File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1361: download - view: text, annotated - select for diffs
Thu Nov 30 15:15:06 2017 UTC (6 years, 7 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6754 LTI Integration: LON-CAPA as LTI Provider
  - Work in progress

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1361 2017/11/30 15:15:06 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: 
   77: 
   78: use Encode;
   79: 
   80: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
   81:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
   82:             %managerstab);
   83: 
   84: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   85:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   86:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   87:     %courseownerbuf, %coursetypebuf,$locknum);
   88: 
   89: use IO::Socket;
   90: use GDBM_File;
   91: use HTML::LCParser;
   92: use Fcntl qw(:flock);
   93: use Storable qw(thaw nfreeze);
   94: use Time::HiRes qw( sleep gettimeofday tv_interval );
   95: use Cache::Memcached;
   96: use Digest::MD5;
   97: use Math::Random;
   98: use File::MMagic;
   99: use LONCAPA qw(:DEFAULT :match);
  100: use LONCAPA::Configuration;
  101: use LONCAPA::lonmetadata;
  102: use LONCAPA::Lond;
  103: use LONCAPA::LWPReq;
  104: 
  105: use File::Copy;
  106: 
  107: my $readit;
  108: my $max_connection_retries = 20;     # Or some such value.
  109: 
  110: require Exporter;
  111: 
  112: our @ISA = qw (Exporter);
  113: our @EXPORT = qw(%env);
  114: 
  115: 
  116: # ------------------------------------ Logging (parameters, docs, slots, roles)
  117: {
  118:     my $logid;
  119:     sub write_log {
  120: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  121:         if ($context eq 'course') {
  122:             if (($cnum eq '') || ($cdom eq '')) {
  123:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  124:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  125:             }
  126:         }
  127: 	$logid ++;
  128:         my $now = time();
  129: 	my $id=$now.'00000'.$$.'00000'.$logid;
  130:         my $logentry = { 
  131:                           $id => {
  132:                                    'exe_uname' => $env{'user.name'},
  133:                                    'exe_udom'  => $env{'user.domain'},
  134:                                    'exe_time'  => $now,
  135:                                    'exe_ip'    => $ENV{'REMOTE_ADDR'},
  136:                                    'delflag'   => $delflag,
  137:                                    'logentry'  => $storehash,
  138:                                    'uname'     => $uname,
  139:                                    'udom'      => $udom,
  140:                                   }
  141:                        };
  142: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
  143:     }
  144: }
  145: 
  146: sub logtouch {
  147:     my $execdir=$perlvar{'lonDaemons'};
  148:     unless (-e "$execdir/logs/lonnet.log") {	
  149: 	open(my $fh,">>","$execdir/logs/lonnet.log");
  150: 	close $fh;
  151:     }
  152:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  153:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  154: }
  155: 
  156: sub logthis {
  157:     my $message=shift;
  158:     my $execdir=$perlvar{'lonDaemons'};
  159:     my $now=time;
  160:     my $local=localtime($now);
  161:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
  162: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  163: 	print $fh $logstring;
  164: 	close($fh);
  165:     }
  166:     return 1;
  167: }
  168: 
  169: sub logperm {
  170:     my $message=shift;
  171:     my $execdir=$perlvar{'lonDaemons'};
  172:     my $now=time;
  173:     my $local=localtime($now);
  174:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
  175: 	print $fh "$now:$message:$local\n";
  176: 	close($fh);
  177:     }
  178:     return 1;
  179: }
  180: 
  181: sub create_connection {
  182:     my ($hostname,$lonid) = @_;
  183:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  184: 				     Type    => SOCK_STREAM,
  185: 				     Timeout => 10);
  186:     return 0 if (!$client);
  187:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  188:     my $result = <$client>;
  189:     chomp($result);
  190:     return 1 if ($result eq 'done');
  191:     return 0;
  192: }
  193: 
  194: sub get_server_timezone {
  195:     my ($cnum,$cdom) = @_;
  196:     my $home=&homeserver($cnum,$cdom);
  197:     if ($home ne 'no_host') {
  198:         my $cachetime = 24*3600;
  199:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  200:         if (defined($cached)) {
  201:             return $timezone;
  202:         } else {
  203:             my $timezone = &reply('servertimezone',$home);
  204:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  205:         }
  206:     }
  207: }
  208: 
  209: sub get_server_distarch {
  210:     my ($lonhost,$ignore_cache) = @_;
  211:     if (defined($lonhost)) {
  212:         if (!defined(&hostname($lonhost))) {
  213:             return;
  214:         }
  215:         my $cachetime = 12*3600;
  216:         if (!$ignore_cache) {
  217:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  218:             if (defined($cached)) {
  219:                 return $distarch;
  220:             }
  221:         }
  222:         my $rep = &reply('serverdistarch',$lonhost);
  223:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  224:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  225:                 $rep eq '') {
  226:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  227:         }
  228:     }
  229:     return;
  230: }
  231: 
  232: sub get_servercerts_info {
  233:     my ($lonhost,$context) = @_;
  234:     my ($rep,$uselocal);
  235:     if (grep { $_ eq $lonhost } &current_machine_ids()) {
  236:         $uselocal = 1;
  237:     }
  238:     if (($context ne 'cgi') && ($uselocal)) {
  239:         my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
  240:         if ($distro eq '') {
  241:             $uselocal = 0;
  242:         } elsif ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
  243:             if ($1 < 6) {
  244:                 $uselocal = 0;
  245:             }
  246:         }  elsif ($distro =~ /^(?:sles)(\d+)$/) {
  247:             if ($1 < 12) {
  248:                 $uselocal = 0;
  249:             }
  250:         }
  251:     }
  252:     if ($uselocal) {
  253:         $rep = LONCAPA::Lond::server_certs(\%perlvar);
  254:     } else {
  255:         $rep=&reply('servercerts',$lonhost);
  256:     }
  257:     my ($result,%returnhash);
  258:     if (defined($lonhost)) {
  259:         if (!defined(&hostname($lonhost))) {
  260:             return;
  261:         }
  262:     }
  263:     if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  264:         ($rep eq 'unknown_cmd')) {
  265:         $result = $rep;
  266:     } else {
  267:         $result = 'ok';
  268:         my @pairs=split(/\&/,$rep);
  269:         foreach my $item (@pairs) {
  270:             my ($key,$value)=split(/=/,$item,2);
  271:             my $what = &unescape($key);
  272:             $returnhash{$what}=&thaw_unescape($value);
  273:         }
  274:     }
  275:     return ($result,\%returnhash);
  276: }
  277: 
  278: sub get_server_loncaparev {
  279:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  280:     if (defined($lonhost)) {
  281:         if (!defined(&hostname($lonhost))) {
  282:             undef($lonhost);
  283:         }
  284:     }
  285:     if (!defined($lonhost)) {
  286:         if (defined(&domain($dom,'primary'))) {
  287:             $lonhost=&domain($dom,'primary');
  288:             if ($lonhost eq 'no_host') {
  289:                 undef($lonhost);
  290:             }
  291:         }
  292:     }
  293:     if (defined($lonhost)) {
  294:         my $cachetime = 12*3600;
  295:         if (!$ignore_cache) {
  296:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  297:             if (defined($cached)) {
  298:                 return $loncaparev;
  299:             }
  300:         }
  301:         my ($answer,$loncaparev);
  302:         my @ids=&current_machine_ids();
  303:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  304:             $answer = $perlvar{'lonVersion'};
  305:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  306:                 $loncaparev = $1;
  307:             }
  308:         } else {
  309:             $answer = &reply('serverloncaparev',$lonhost);
  310:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  311:                 if ($caller eq 'loncron') {
  312:                     my $protocol = $protocol{$lonhost};
  313:                     $protocol = 'http' if ($protocol ne 'https');
  314:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
  315:                     my $request=new HTTP::Request('GET',$url);
  316:                     my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,4,1);
  317:                     unless ($response->is_error()) {
  318:                         my $content = $response->content;
  319:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  320:                             $loncaparev = $1;
  321:                         }
  322:                     }
  323:                 } else {
  324:                     $loncaparev = $loncaparevs{$lonhost};
  325:                 }
  326:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  327:                 $loncaparev = $1;
  328:             }
  329:         }
  330:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  331:     }
  332: }
  333: 
  334: sub get_server_homeID {
  335:     my ($hostname,$ignore_cache,$caller) = @_;
  336:     unless ($ignore_cache) {
  337:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  338:         if (defined($cached)) {
  339:             return $serverhomeID;
  340:         }
  341:     }
  342:     my $cachetime = 12*3600;
  343:     my $serverhomeID;
  344:     if ($caller eq 'loncron') { 
  345:         my @machine_ids = &machine_ids($hostname);
  346:         foreach my $id (@machine_ids) {
  347:             my $response = &reply('serverhomeID',$id);
  348:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  349:                 $serverhomeID = $response;
  350:                 last;
  351:             }
  352:         }
  353:         if ($serverhomeID eq '') {
  354:             $serverhomeID = $machine_ids[-1];
  355:         }
  356:     } else {
  357:         $serverhomeID = $serverhomeIDs{$hostname};
  358:     }
  359:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  360: }
  361: 
  362: sub get_remote_globals {
  363:     my ($lonhost,$whathash,$ignore_cache) = @_;
  364:     my ($result,%returnhash,%whatneeded);
  365:     if (ref($whathash) eq 'HASH') {
  366:         foreach my $what (sort(keys(%{$whathash}))) {
  367:             my $hashid = $lonhost.'-'.$what;
  368:             my ($response,$cached);
  369:             unless ($ignore_cache) {
  370:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  371:             }
  372:             if (defined($cached)) {
  373:                 $returnhash{$what} = $response;
  374:             } else {
  375:                 $whatneeded{$what} = 1;
  376:             }
  377:         }
  378:         if (keys(%whatneeded) == 0) {
  379:             $result = 'ok';
  380:         } else {
  381:             my $requested = &freeze_escape(\%whatneeded);
  382:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  383:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  384:                 ($rep eq 'unknown_cmd')) {
  385:                 $result = $rep;
  386:             } else {
  387:                 $result = 'ok';
  388:                 my @pairs=split(/\&/,$rep);
  389:                 foreach my $item (@pairs) {
  390:                     my ($key,$value)=split(/=/,$item,2);
  391:                     my $what = &unescape($key);
  392:                     my $hashid = $lonhost.'-'.$what;
  393:                     $returnhash{$what}=&thaw_unescape($value);
  394:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  395:                 }
  396:             }
  397:         }
  398:     }
  399:     return ($result,\%returnhash);
  400: }
  401: 
  402: sub remote_devalidate_cache {
  403:     my ($lonhost,$cachekeys) = @_;
  404:     my $items;
  405:     return unless (ref($cachekeys) eq 'ARRAY');
  406:     my $cachestr = join('&',@{$cachekeys});
  407:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
  408:     return $response;
  409: }
  410: 
  411: # -------------------------------------------------- Non-critical communication
  412: sub subreply {
  413:     my ($cmd,$server)=@_;
  414:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  415:     #
  416:     #  With loncnew process trimming, there's a timing hole between lonc server
  417:     #  process exit and the master server picking up the listen on the AF_UNIX
  418:     #  socket.  In that time interval, a lock file will exist:
  419: 
  420:     my $lockfile=$peerfile.".lock";
  421:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  422: 	sleep(0.1);
  423:     }
  424:     # At this point, either a loncnew parent is listening or an old lonc
  425:     # or loncnew child is listening so we can connect or everything's dead.
  426:     #
  427:     #   We'll give the connection a few tries before abandoning it.  If
  428:     #   connection is not possible, we'll con_lost back to the client.
  429:     #   
  430:     my $client;
  431:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  432: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  433: 				      Type    => SOCK_STREAM,
  434: 				      Timeout => 10);
  435: 	if ($client) {
  436: 	    last;		# Connected!
  437: 	} else {
  438: 	    &create_connection(&hostname($server),$server);
  439: 	}
  440:         sleep(0.1);	# Try again later if failed connection.
  441:     }
  442:     my $answer;
  443:     if ($client) {
  444: 	print $client "sethost:$server:$cmd\n";
  445: 	$answer=<$client>;
  446: 	if (!$answer) { $answer="con_lost"; }
  447: 	chomp($answer);
  448:     } else {
  449: 	$answer = 'con_lost';	# Failed connection.
  450:     }
  451:     return $answer;
  452: }
  453: 
  454: sub reply {
  455:     my ($cmd,$server)=@_;
  456:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  457:     my $answer=subreply($cmd,$server);
  458:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  459:        &logthis("<font color=\"blue\">WARNING:".
  460:                 " $cmd to $server returned $answer</font>");
  461:     }
  462:     return $answer;
  463: }
  464: 
  465: # ----------------------------------------------------------- Send USR1 to lonc
  466: 
  467: sub reconlonc {
  468:     my ($lonid) = @_;
  469:     if ($lonid) {
  470:         my $hostname = &hostname($lonid);
  471: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  472: 	if ($hostname && -e $peerfile) {
  473: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  474: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  475: 					     Type    => SOCK_STREAM,
  476: 					     Timeout => 10);
  477: 	    if ($client) {
  478: 		print $client ("reset_retries\n");
  479: 		my $answer=<$client>;
  480: 		#reset just this one.
  481: 	    }
  482: 	}
  483: 	return;
  484:     }
  485: 
  486:     &logthis("Trying to reconnect lonc");
  487:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  488:     if (open(my $fh,"<",$loncfile)) {
  489: 	my $loncpid=<$fh>;
  490:         chomp($loncpid);
  491:         if (kill 0 => $loncpid) {
  492: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  493:             kill USR1 => $loncpid;
  494:             sleep 1;
  495:         } else {
  496: 	    &logthis(
  497:                "<font color=\"blue\">WARNING:".
  498:                " lonc at pid $loncpid not responding, giving up</font>");
  499:         }
  500:     } else {
  501: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  502:     }
  503: }
  504: 
  505: # ------------------------------------------------------ Critical communication
  506: 
  507: sub critical {
  508:     my ($cmd,$server)=@_;
  509:     unless (&hostname($server)) {
  510:         &logthis("<font color=\"blue\">WARNING:".
  511:                " Critical message to unknown server ($server)</font>");
  512:         return 'no_such_host';
  513:     }
  514:     my $answer=reply($cmd,$server);
  515:     if ($answer eq 'con_lost') {
  516: 	&reconlonc($server);
  517: 	my $answer=reply($cmd,$server);
  518:         if ($answer eq 'con_lost') {
  519:             my $now=time;
  520:             my $middlename=$cmd;
  521:             $middlename=substr($middlename,0,16);
  522:             $middlename=~s/\W//g;
  523:             my $dfilename=
  524:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  525:             $dumpcount++;
  526:             {
  527: 		my $dfh;
  528: 		if (open($dfh,">",$dfilename)) {
  529: 		    print $dfh "$cmd\n"; 
  530: 		    close($dfh);
  531: 		}
  532:             }
  533:             sleep 1;
  534:             my $wcmd='';
  535:             {
  536: 		my $dfh;
  537: 		if (open($dfh,"<",$dfilename)) {
  538: 		    $wcmd=<$dfh>; 
  539: 		    close($dfh);
  540: 		}
  541:             }
  542:             chomp($wcmd);
  543:             if ($wcmd eq $cmd) {
  544: 		&logthis("<font color=\"blue\">WARNING: ".
  545:                          "Connection buffer $dfilename: $cmd</font>");
  546:                 &logperm("D:$server:$cmd");
  547: 	        return 'con_delayed';
  548:             } else {
  549:                 &logthis("<font color=\"red\">CRITICAL:"
  550:                         ." Critical connection failed: $server $cmd</font>");
  551:                 &logperm("F:$server:$cmd");
  552:                 return 'con_failed';
  553:             }
  554:         }
  555:     }
  556:     return $answer;
  557: }
  558: 
  559: # ------------------------------------------- check if return value is an error
  560: 
  561: sub error {
  562:     my ($result) = @_;
  563:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  564: 	if ($2 == 2) { return undef; }
  565: 	return $1;
  566:     }
  567:     return undef;
  568: }
  569: 
  570: sub convert_and_load_session_env {
  571:     my ($lonidsdir,$handle)=@_;
  572:     my @profile;
  573:     {
  574: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  575: 	if (!$opened) {
  576: 	    return 0;
  577: 	}
  578: 	flock($idf,LOCK_SH);
  579: 	@profile=<$idf>;
  580: 	close($idf);
  581:     }
  582:     my %temp_env;
  583:     foreach my $line (@profile) {
  584: 	if ($line !~ m/=/) {
  585: 	    return 0;
  586: 	}
  587: 	chomp($line);
  588: 	my ($envname,$envvalue)=split(/=/,$line,2);
  589: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  590:     }
  591:     unlink("$lonidsdir/$handle.id");
  592:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  593: 	    0640)) {
  594: 	%disk_env = %temp_env;
  595: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  596: 	untie(%disk_env);
  597:     }
  598:     return 1;
  599: }
  600: 
  601: # ------------------------------------------- Transfer profile into environment
  602: my $env_loaded;
  603: sub transfer_profile_to_env {
  604:     my ($lonidsdir,$handle,$force_transfer) = @_;
  605:     if (!$force_transfer && $env_loaded) { return; } 
  606: 
  607:     if (!defined($lonidsdir)) {
  608: 	$lonidsdir = $perlvar{'lonIDsDir'};
  609:     }
  610:     if (!defined($handle)) {
  611:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  612:     }
  613: 
  614:     my $convert;
  615:     {
  616:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  617: 	if (!$opened) {
  618: 	    return;
  619: 	}
  620: 	flock($idf,LOCK_SH);
  621: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  622: 		&GDBM_READER(),0640)) {
  623: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  624: 	    untie(%disk_env);
  625: 	} else {
  626: 	    $convert = 1;
  627: 	}
  628:     }
  629:     if ($convert) {
  630: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  631: 	    &logthis("Failed to load session, or convert session.");
  632: 	}
  633:     }
  634: 
  635:     my %remove;
  636:     while ( my $envname = each(%env) ) {
  637:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  638:             if ($time < time-300) {
  639:                 $remove{$key}++;
  640:             }
  641:         }
  642:     }
  643: 
  644:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  645:     $env_loaded=1;
  646:     foreach my $expired_key (keys(%remove)) {
  647:         &delenv($expired_key);
  648:     }
  649: }
  650: 
  651: # ---------------------------------------------------- Check for valid session 
  652: sub check_for_valid_session {
  653:     my ($r,$name,$userhashref,$domref) = @_;
  654:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  655:     my ($linkname,$pubname);
  656:     if ($name eq '') {
  657:         $name = 'lonID';
  658:         $linkname = 'lonLinkID';
  659:         $pubname = 'lonPubID';
  660:     }
  661:     my $lonid=$cookies{$name};
  662:     if (!$lonid) {
  663:         if (($name eq 'lonID') && ($ENV{'SERVER_PORT'} != 443) && ($linkname)) {
  664:             $lonid=$cookies{$linkname};
  665:         }
  666:         if (!$lonid) {
  667:             if (($name eq 'lonID') && ($pubname)) {
  668:                 $lonid=$cookies{$pubname};
  669:             }
  670:         }
  671:     }
  672:     return undef if (!$lonid);
  673: 
  674:     my $handle=&LONCAPA::clean_handle($lonid->value);
  675:     my $lonidsdir;
  676:     if ($name eq 'lonDAV') {
  677:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  678:     } else {
  679:         $lonidsdir=$r->dir_config('lonIDsDir');
  680:     }
  681:     if (!-e "$lonidsdir/$handle.id") {
  682:         if ((ref($domref)) && ($name eq 'lonID') && 
  683:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
  684:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
  685:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
  686:                 $$domref = $possudom;
  687:             }
  688:         }
  689:         return undef;
  690:     }
  691: 
  692:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  693:     return undef if (!$opened);
  694: 
  695:     flock($idf,LOCK_SH);
  696:     my %disk_env;
  697:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  698: 	    &GDBM_READER(),0640)) {
  699: 	return undef;	
  700:     }
  701: 
  702:     if (!defined($disk_env{'user.name'})
  703: 	|| !defined($disk_env{'user.domain'})) {
  704: 	return undef;
  705:     }
  706: 
  707:     if (ref($userhashref) eq 'HASH') {
  708:         $userhashref->{'name'} = $disk_env{'user.name'};
  709:         $userhashref->{'domain'} = $disk_env{'user.domain'};
  710:         $userhashref->{'lti'} = $disk_env{'request.lti.login'};
  711:     }
  712: 
  713:     return $handle;
  714: }
  715: 
  716: sub timed_flock {
  717:     my ($file,$lock_type) = @_;
  718:     my $failed=0;
  719:     eval {
  720: 	local $SIG{__DIE__}='DEFAULT';
  721: 	local $SIG{ALRM}=sub {
  722: 	    $failed=1;
  723: 	    die("failed lock");
  724: 	};
  725: 	alarm(13);
  726: 	flock($file,$lock_type);
  727: 	alarm(0);
  728:     };
  729:     if ($failed) {
  730: 	return undef;
  731:     } else {
  732: 	return 1;
  733:     }
  734: }
  735: 
  736: # ---------------------------------------------------------- Append Environment
  737: 
  738: sub appenv {
  739:     my ($newenv,$roles) = @_;
  740:     if (ref($newenv) eq 'HASH') {
  741:         foreach my $key (keys(%{$newenv})) {
  742:             my $refused = 0;
  743: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  744:                 $refused = 1;
  745:                 if (ref($roles) eq 'ARRAY') {
  746:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
  747:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  748:                         $refused = 0;
  749:                     }
  750:                 }
  751:             }
  752:             if ($refused) {
  753:                 &logthis("<font color=\"blue\">WARNING: ".
  754:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  755:                          .'</font>');
  756: 	        delete($newenv->{$key});
  757:             } else {
  758:                 $env{$key}=$newenv->{$key};
  759:             }
  760:         }
  761:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  762:         if ($opened
  763: 	    && &timed_flock($env_file,LOCK_EX)
  764: 	    &&
  765: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  766: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  767: 	    while (my ($key,$value) = each(%{$newenv})) {
  768: 	        $disk_env{$key} = $value;
  769: 	    }
  770: 	    untie(%disk_env);
  771:         }
  772:     }
  773:     return 'ok';
  774: }
  775: # ----------------------------------------------------- Delete from Environment
  776: 
  777: sub delenv {
  778:     my ($delthis,$regexp,$roles) = @_;
  779:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  780:         my $refused = 1;
  781:         if (ref($roles) eq 'ARRAY') {
  782:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  783:             if (grep(/^\Q$role\E$/,@{$roles})) {
  784:                 $refused = 0;
  785:             }
  786:         }
  787:         if ($refused) {
  788:             &logthis("<font color=\"blue\">WARNING: ".
  789:                      "Attempt to delete from environment ".$delthis);
  790:             return 'error';
  791:         }
  792:     }
  793:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  794:     if ($opened
  795: 	&& &timed_flock($env_file,LOCK_EX)
  796: 	&&
  797: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  798: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  799: 	foreach my $key (keys(%disk_env)) {
  800: 	    if ($regexp) {
  801:                 if ($key=~/^$delthis/) {
  802:                     delete($env{$key});
  803:                     delete($disk_env{$key});
  804:                 } 
  805:             } else {
  806:                 if ($key=~/^\Q$delthis\E/) {
  807: 		    delete($env{$key});
  808: 		    delete($disk_env{$key});
  809: 	        }
  810:             }
  811: 	}
  812: 	untie(%disk_env);
  813:     }
  814:     return 'ok';
  815: }
  816: 
  817: sub get_env_multiple {
  818:     my ($name) = @_;
  819:     my @values;
  820:     if (defined($env{$name})) {
  821:         # exists is it an array
  822:         if (ref($env{$name})) {
  823:             @values=@{ $env{$name} };
  824:         } else {
  825:             $values[0]=$env{$name};
  826:         }
  827:     }
  828:     return(@values);
  829: }
  830: 
  831: # ------------------------------------------------------------------- Locking
  832: 
  833: sub set_lock {
  834:     my ($text)=@_;
  835:     $locknum++;
  836:     my $id=$$.'-'.$locknum;
  837:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  838:              'session.lock.'.$id => $text});
  839:     return $id;
  840: }
  841: 
  842: sub get_locks {
  843:     my $num=0;
  844:     my %texts=();
  845:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  846:        if ($lock=~/\w/) {
  847:           $num++;
  848:           $texts{$lock}=$env{'session.lock.'.$lock};
  849:        }
  850:    }
  851:    return ($num,%texts);
  852: }
  853: 
  854: sub remove_lock {
  855:     my ($id)=@_;
  856:     my $newlocks='';
  857:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  858:        if (($lock=~/\w/) && ($lock ne $id)) {
  859:           $newlocks.=','.$lock;
  860:        }
  861:     }
  862:     &appenv({'session.locks' => $newlocks});
  863:     &delenv('session.lock.'.$id);
  864: }
  865: 
  866: sub remove_all_locks {
  867:     my $activelocks=$env{'session.locks'};
  868:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  869:        if ($lock=~/\w/) {
  870:           &remove_lock($lock);
  871:        }
  872:     }
  873: }
  874: 
  875: 
  876: # ------------------------------------------ Find out current server userload
  877: sub userload {
  878:     my $numusers=0;
  879:     {
  880: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  881: 	my $filename;
  882: 	my $curtime=time;
  883: 	while ($filename=readdir(LONIDS)) {
  884: 	    next if ($filename eq '.' || $filename eq '..');
  885: 	    next if ($filename =~ /publicuser_\d+\.id/);
  886: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  887: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  888: 	}
  889: 	closedir(LONIDS);
  890:     }
  891:     my $userloadpercent=0;
  892:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  893:     if ($maxuserload) {
  894: 	$userloadpercent=100*$numusers/$maxuserload;
  895:     }
  896:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  897:     return $userloadpercent;
  898: }
  899: 
  900: # ------------------------------ Find server with least workload from spare.tab
  901: 
  902: sub spareserver {
  903:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  904:     my $spare_server;
  905:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  906:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  907:                                                      :  $userloadpercent;
  908:     my ($uint_dom,$remotesessions);
  909:     if (($udom ne '') && (&domain($udom) ne '')) {
  910:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  911:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  912:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  913:         $remotesessions = $udomdefaults{'remotesessions'};
  914:     }
  915:     my $spareshash = &this_host_spares($udom);
  916:     if (ref($spareshash) eq 'HASH') {
  917:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  918:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  919:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  920:                                              $try_server));
  921: 	        ($spare_server, $lowest_load) =
  922: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  923:             }
  924:         }
  925: 
  926:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
  927: 
  928:         if (!$found_server) {
  929:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
  930: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
  931:                     next unless (&spare_can_host($udom,$uint_dom,
  932:                                                  $remotesessions,$try_server));
  933: 	            ($spare_server, $lowest_load) =
  934: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
  935:                 }
  936: 	    }
  937:         }
  938:     }
  939: 
  940:     if (!$want_server_name) {
  941:         my $protocol = 'http';
  942:         if ($protocol{$spare_server} eq 'https') {
  943:             $protocol = $protocol{$spare_server};
  944:         }
  945:         if (defined($spare_server)) {
  946:             my $hostname = &hostname($spare_server);
  947:             if (defined($hostname)) {
  948: 	        $spare_server = $protocol.'://'.$hostname;
  949:             }
  950:         }
  951:     }
  952:     return $spare_server;
  953: }
  954: 
  955: sub compare_server_load {
  956:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
  957: 
  958:     if ($required) {
  959:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
  960:         my $remoterev = &get_server_loncaparev(undef,$try_server);
  961:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
  962:         if (($major eq '' && $minor eq '') ||
  963:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
  964:             return ($spare_server,$lowest_load);
  965:         }
  966:     }
  967: 
  968:     my $loadans     = &reply('load',    $try_server);
  969:     my $userloadans = &reply('userload',$try_server);
  970: 
  971:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  972: 	return ($spare_server, $lowest_load); #didn't get a number from the server
  973:     }
  974: 
  975:     my $load;
  976:     if ($loadans =~ /\d/) {
  977: 	if ($userloadans =~ /\d/) {
  978: 	    #both are numbers, pick the bigger one
  979: 	    $load = ($loadans > $userloadans) ? $loadans 
  980: 		                              : $userloadans;
  981: 	} else {
  982: 	    $load = $loadans;
  983: 	}
  984:     } else {
  985: 	$load = $userloadans;
  986:     }
  987: 
  988:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  989: 	$spare_server = $try_server;
  990: 	$lowest_load  = $load;
  991:     }
  992:     return ($spare_server,$lowest_load);
  993: }
  994: 
  995: # --------------------------- ask offload servers if user already has a session
  996: sub find_existing_session {
  997:     my ($udom,$uname) = @_;
  998:     my $spareshash = &this_host_spares($udom);
  999:     if (ref($spareshash) eq 'HASH') {
 1000:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
 1001:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
 1002:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1003:             }
 1004:         }
 1005:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
 1006:             foreach my $try_server (@{ $spareshash->{'default'} }) {
 1007:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1008:             }
 1009:         }
 1010:     }
 1011:     return;
 1012: }
 1013: 
 1014: # -------------------------------- ask if server already has a session for user
 1015: sub has_user_session {
 1016:     my ($lonid,$udom,$uname) = @_;
 1017:     my $result = &reply(join(':','userhassession',
 1018: 			     map {&escape($_)} ($udom,$uname)),$lonid);
 1019:     return 1 if ($result eq 'ok');
 1020: 
 1021:     return 0;
 1022: }
 1023: 
 1024: # --------- determine least loaded server in a user's domain which allows login
 1025: 
 1026: sub choose_server {
 1027:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
 1028:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
 1029:     my %servers = &get_servers($udom);
 1030:     my $lowest_load = 30000;
 1031:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
 1032:     if ($skiploadbal) {
 1033:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
 1034:         unless (defined($cached)) {
 1035:             my $cachetime = 60*60*24;
 1036:             my %domconfig =
 1037:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1038:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1039:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
 1040:                                            $cachetime);
 1041:             }
 1042:         }
 1043:     }
 1044:     foreach my $lonhost (keys(%servers)) {
 1045:         if ($skiploadbal) {
 1046:             if (ref($balancers) eq 'HASH') {
 1047:                 next if (exists($balancers->{$lonhost}));
 1048:             }
 1049:         }   
 1050:         my $loginvia;
 1051:         if ($checkloginvia) {
 1052:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
 1053:             if ($loginvia) {
 1054:                 my ($server,$path) = split(/:/,$loginvia);
 1055:                 ($login_host, $lowest_load) =
 1056:                     &compare_server_load($server, $login_host, $lowest_load, $required);
 1057:                 if ($login_host eq $server) {
 1058:                     $portal_path = $path;
 1059:                     $isredirect = 1;
 1060:                 }
 1061:             } else {
 1062:                 ($login_host, $lowest_load) =
 1063:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1064:                 if ($login_host eq $lonhost) {
 1065:                     $portal_path = '';
 1066:                     $isredirect = ''; 
 1067:                 }
 1068:             }
 1069:         } else {
 1070:             ($login_host, $lowest_load) =
 1071:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1072:         }
 1073:     }
 1074:     if ($login_host ne '') {
 1075:         $hostname = &hostname($login_host);
 1076:     }
 1077:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
 1078: }
 1079: 
 1080: # --------------------------------------------- Try to change a user's password
 1081: 
 1082: sub changepass {
 1083:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
 1084:     $currentpass = &escape($currentpass);
 1085:     $newpass     = &escape($newpass);
 1086:     my $lonhost = $perlvar{'lonHostID'};
 1087:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
 1088: 		       $server);
 1089:     if (! $answer) {
 1090: 	&logthis("No reply on password change request to $server ".
 1091: 		 "by $uname in domain $udom.");
 1092:     } elsif ($answer =~ "^ok") {
 1093:         &logthis("$uname in $udom successfully changed their password ".
 1094: 		 "on $server.");
 1095:     } elsif ($answer =~ "^pwchange_failure") {
 1096: 	&logthis("$uname in $udom was unable to change their password ".
 1097: 		 "on $server.  The action was blocked by either lcpasswd ".
 1098: 		 "or pwchange");
 1099:     } elsif ($answer =~ "^non_authorized") {
 1100:         &logthis("$uname in $udom did not get their password correct when ".
 1101: 		 "attempting to change it on $server.");
 1102:     } elsif ($answer =~ "^auth_mode_error") {
 1103:         &logthis("$uname in $udom attempted to change their password despite ".
 1104: 		 "not being locally or internally authenticated on $server.");
 1105:     } elsif ($answer =~ "^unknown_user") {
 1106:         &logthis("$uname in $udom attempted to change their password ".
 1107: 		 "on $server but were unable to because $server is not ".
 1108: 		 "their home server.");
 1109:     } elsif ($answer =~ "^refused") {
 1110: 	&logthis("$server refused to change $uname in $udom password because ".
 1111: 		 "it was sent an unencrypted request to change the password.");
 1112:     } elsif ($answer =~ "invalid_client") {
 1113:         &logthis("$server refused to change $uname in $udom password because ".
 1114:                  "it was a reset by e-mail originating from an invalid server.");
 1115:     }
 1116:     return $answer;
 1117: }
 1118: 
 1119: # ----------------------- Try to determine user's current authentication scheme
 1120: 
 1121: sub queryauthenticate {
 1122:     my ($uname,$udom)=@_;
 1123:     my $uhome=&homeserver($uname,$udom);
 1124:     if (!$uhome) {
 1125: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1126: 	return 'no_host';
 1127:     }
 1128:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1129:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1130: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1131:     }
 1132:     return $answer;
 1133: }
 1134: 
 1135: # --------- Try to authenticate user from domain's lib servers (first this one)
 1136: 
 1137: sub authenticate {
 1138:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1139:     $upass=&escape($upass);
 1140:     $uname= &LONCAPA::clean_username($uname);
 1141:     my $uhome=&homeserver($uname,$udom,1);
 1142:     my $newhome;
 1143:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1144: # Maybe the machine was offline and only re-appeared again recently?
 1145:         &reconlonc();
 1146: # One more
 1147: 	$uhome=&homeserver($uname,$udom,1);
 1148:         if (($uhome eq 'no_host') && $checkdefauth) {
 1149:             if (defined(&domain($udom,'primary'))) {
 1150:                 $newhome=&domain($udom,'primary');
 1151:             }
 1152:             if ($newhome ne '') {
 1153:                 $uhome = $newhome;
 1154:             }
 1155:         }
 1156: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1157: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1158: 	    return 'no_host';
 1159:         }
 1160:     }
 1161:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1162:     if ($answer eq 'authorized') {
 1163:         if ($newhome) {
 1164:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1165:             return 'no_account_on_host'; 
 1166:         } else {
 1167:             &logthis("User $uname at $udom authorized by $uhome");
 1168:             return $uhome;
 1169:         }
 1170:     }
 1171:     if ($answer eq 'non_authorized') {
 1172: 	&logthis("User $uname at $udom rejected by $uhome");
 1173: 	return 'no_host'; 
 1174:     }
 1175:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1176:     return 'no_host';
 1177: }
 1178: 
 1179: sub can_host_session {
 1180:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1181:     my $canhost = 1;
 1182:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1183:     if (ref($remotesessions) eq 'HASH') {
 1184:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1185:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1186:                 $canhost = 0;
 1187:             } else {
 1188:                 $canhost = 1;
 1189:             }
 1190:         }
 1191:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1192:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1193:                 $canhost = 1;
 1194:             } else {
 1195:                 $canhost = 0;
 1196:             }
 1197:         }
 1198:         if ($canhost) {
 1199:             if ($remotesessions->{'version'} ne '') {
 1200:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1201:                 if ($reqmajor ne '' && $reqminor ne '') {
 1202:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1203:                         my $major = $1;
 1204:                         my $minor = $2;
 1205:                         if (($major < $reqmajor ) ||
 1206:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1207:                             $canhost = 0;
 1208:                         }
 1209:                     } else {
 1210:                         $canhost = 0;
 1211:                     }
 1212:                 }
 1213:             }
 1214:         }
 1215:     }
 1216:     if ($canhost) {
 1217:         if (ref($hostedsessions) eq 'HASH') {
 1218:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1219:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1220:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1221:                 if (($uint_dom ne '') && 
 1222:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1223:                     $canhost = 0;
 1224:                 } else {
 1225:                     $canhost = 1;
 1226:                 }
 1227:             }
 1228:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1229:                 if (($uint_dom ne '') && 
 1230:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1231:                     $canhost = 1;
 1232:                 } else {
 1233:                     $canhost = 0;
 1234:                 }
 1235:             }
 1236:         }
 1237:     }
 1238:     return $canhost;
 1239: }
 1240: 
 1241: sub spare_can_host {
 1242:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1243:     my $canhost=1;
 1244:     my $try_server_hostname = &hostname($try_server);
 1245:     my $serverhomeID = &get_server_homeID($try_server_hostname);
 1246:     my $serverhomedom = &host_domain($serverhomeID);
 1247:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
 1248:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
 1249:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
 1250:             $canhost = 0;
 1251:         }
 1252:     }
 1253:     if (($canhost) && ($uint_dom)) {
 1254:         my @intdoms;
 1255:         my $internet_names = &get_internet_names($try_server);
 1256:         if (ref($internet_names) eq 'ARRAY') {
 1257:             @intdoms = @{$internet_names};
 1258:         }
 1259:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1260:             my $remoterev = &get_server_loncaparev(undef,$try_server);
 1261:             $canhost = &can_host_session($udom,$try_server,$remoterev,
 1262:                                          $remotesessions,
 1263:                                          $defdomdefaults{'hostedsessions'});
 1264:         }
 1265:     }
 1266:     return $canhost;
 1267: }
 1268: 
 1269: sub this_host_spares {
 1270:     my ($dom) = @_;
 1271:     my ($dom_in_use,$lonhost_in_use,$result);
 1272:     my @hosts = &current_machine_ids();
 1273:     foreach my $lonhost (@hosts) {
 1274:         if (&host_domain($lonhost) eq $dom) {
 1275:             $dom_in_use = $dom;
 1276:             $lonhost_in_use = $lonhost;
 1277:             last;
 1278:         }
 1279:     }
 1280:     if ($dom_in_use ne '') {
 1281:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1282:     }
 1283:     if (ref($result) ne 'HASH') {
 1284:         $lonhost_in_use = $perlvar{'lonHostID'};
 1285:         $dom_in_use = &host_domain($lonhost_in_use);
 1286:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1287:         if (ref($result) ne 'HASH') {
 1288:             $result = \%spareid;
 1289:         }
 1290:     }
 1291:     return $result;
 1292: }
 1293: 
 1294: sub spares_for_offload  {
 1295:     my ($dom_in_use,$lonhost_in_use) = @_;
 1296:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1297:     if (defined($cached)) {
 1298:         return $result;
 1299:     } else {
 1300:         my $cachetime = 60*60*24;
 1301:         my %domconfig =
 1302:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1303:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1304:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1305:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1306:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1307:                 }
 1308:             }
 1309:         }
 1310:     }
 1311:     return;
 1312: }
 1313: 
 1314: sub get_lonbalancer_config {
 1315:     my ($servers) = @_;
 1316:     my ($currbalancer,$currtargets);
 1317:     if (ref($servers) eq 'HASH') {
 1318:         foreach my $server (keys(%{$servers})) {
 1319:             my %what = (
 1320:                          spareid => 1,
 1321:                          perlvar => 1,
 1322:                        );
 1323:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1324:             if ($result eq 'ok') {
 1325:                 if (ref($returnhash) eq 'HASH') {
 1326:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1327:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1328:                             $currbalancer = $server;
 1329:                             $currtargets = {};
 1330:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1331:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1332:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1333:                                 }
 1334:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1335:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1336:                                 }
 1337:                             }
 1338:                             last;
 1339:                         }
 1340:                     }
 1341:                 }
 1342:             }
 1343:         }
 1344:     }
 1345:     return ($currbalancer,$currtargets);
 1346: }
 1347: 
 1348: sub check_loadbalancing {
 1349:     my ($uname,$udom,$caller) = @_;
 1350:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1351:         $rule_in_effect,$offloadto,$otherserver);
 1352:     my $lonhost = $perlvar{'lonHostID'};
 1353:     my @hosts = &current_machine_ids();
 1354:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1355:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1356:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1357:     my $serverhomedom = &host_domain($lonhost);
 1358:     my $domneedscache;
 1359:     my $cachetime = 60*60*24;
 1360: 
 1361:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1362:         $dom_in_use = $udom;
 1363:         $homeintdom = 1;
 1364:     } else {
 1365:         $dom_in_use = $serverhomedom;
 1366:     }
 1367:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1368:     unless (defined($cached)) {
 1369:         my %domconfig =
 1370:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1371:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1372:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1373:         } else {
 1374:             $domneedscache = $dom_in_use;
 1375:         }
 1376:     }
 1377:     if (ref($result) eq 'HASH') {
 1378:         ($is_balancer,$currtargets,$currrules) = 
 1379:             &check_balancer_result($result,@hosts);
 1380:         if ($is_balancer) {
 1381:             if (ref($currrules) eq 'HASH') {
 1382:                 if ($homeintdom) {
 1383:                     if ($uname ne '') {
 1384:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1385:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1386:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1387:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1388:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1389:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1390:                             }
 1391:                         }
 1392:                         if ($rule_in_effect eq '') {
 1393:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1394:                             if ($userenv{'inststatus'} ne '') {
 1395:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1396:                                 my ($othertitle,$usertypes,$types) =
 1397:                                     &Apache::loncommon::sorted_inst_types($udom);
 1398:                                 if (ref($types) eq 'ARRAY') {
 1399:                                     foreach my $type (@{$types}) {
 1400:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1401:                                             if (exists($currrules->{$type})) {
 1402:                                                 $rule_in_effect = $currrules->{$type};
 1403:                                             }
 1404:                                         }
 1405:                                     }
 1406:                                 }
 1407:                             } else {
 1408:                                 if (exists($currrules->{'default'})) {
 1409:                                     $rule_in_effect = $currrules->{'default'};
 1410:                                 }
 1411:                             }
 1412:                         }
 1413:                     } else {
 1414:                         if (exists($currrules->{'default'})) {
 1415:                             $rule_in_effect = $currrules->{'default'};
 1416:                         }
 1417:                     }
 1418:                 } else {
 1419:                     if ($currrules->{'_LC_external'} ne '') {
 1420:                         $rule_in_effect = $currrules->{'_LC_external'};
 1421:                     }
 1422:                 }
 1423:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1424:                                                        $uname,$udom);
 1425:             }
 1426:         }
 1427:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1428:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1429:         unless (defined($cached)) {
 1430:             my %domconfig =
 1431:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1432:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1433:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
 1434:             } else {
 1435:                 $domneedscache = $serverhomedom;
 1436:             }
 1437:         }
 1438:         if (ref($result) eq 'HASH') {
 1439:             ($is_balancer,$currtargets,$currrules) = 
 1440:                 &check_balancer_result($result,@hosts);
 1441:             if ($is_balancer) {
 1442:                 if (ref($currrules) eq 'HASH') {
 1443:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1444:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1445:                     }
 1446:                 }
 1447:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1448:                                                        $uname,$udom);
 1449:             }
 1450:         } else {
 1451:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1452:                 $is_balancer = 1;
 1453:                 $offloadto = &this_host_spares($dom_in_use);
 1454:             }
 1455:             unless (defined($cached)) {
 1456:                 $domneedscache = $serverhomedom;
 1457:             }
 1458:         }
 1459:     } else {
 1460:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1461:             $is_balancer = 1;
 1462:             $offloadto = &this_host_spares($dom_in_use);
 1463:         }
 1464:         unless (defined($cached)) {
 1465:             $domneedscache = $serverhomedom;
 1466:         }
 1467:     }
 1468:     if ($domneedscache) {
 1469:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
 1470:     }
 1471:     if ($is_balancer) {
 1472:         my $lowest_load = 30000;
 1473:         if (ref($offloadto) eq 'HASH') {
 1474:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1475:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1476:                     ($otherserver,$lowest_load) =
 1477:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1478:                 }
 1479:             }
 1480:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1481: 
 1482:             if (!$found_server) {
 1483:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1484:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1485:                         ($otherserver,$lowest_load) =
 1486:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1487:                     }
 1488:                 }
 1489:             }
 1490:         } elsif (ref($offloadto) eq 'ARRAY') {
 1491:             if (@{$offloadto} == 1) {
 1492:                 $otherserver = $offloadto->[0];
 1493:             } elsif (@{$offloadto} > 1) {
 1494:                 foreach my $try_server (@{$offloadto}) {
 1495:                     ($otherserver,$lowest_load) =
 1496:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1497:                 }
 1498:             }
 1499:         }
 1500:         unless ($caller eq 'login') {
 1501:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1502:                 $is_balancer = 0;
 1503:                 if ($uname ne '' && $udom ne '') {
 1504:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1505:                     
 1506:                         &appenv({'user.loadbalexempt'     => $lonhost,  
 1507:                                  'user.loadbalcheck.time' => time});
 1508:                     }
 1509:                 }
 1510:             }
 1511:         }
 1512:     }
 1513:     return ($is_balancer,$otherserver);
 1514: }
 1515: 
 1516: sub check_balancer_result {
 1517:     my ($result,@hosts) = @_;
 1518:     my ($is_balancer,$currtargets,$currrules);
 1519:     if (ref($result) eq 'HASH') {
 1520:         if ($result->{'lonhost'} ne '') {
 1521:             my $currbalancer = $result->{'lonhost'};
 1522:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1523:                 $is_balancer = 1;
 1524:                 $currtargets = $result->{'targets'};
 1525:                 $currrules = $result->{'rules'};
 1526:             }
 1527:         } else {
 1528:             foreach my $key (keys(%{$result})) {
 1529:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1530:                     (ref($result->{$key}) eq 'HASH')) {
 1531:                     $is_balancer = 1;
 1532:                     $currrules = $result->{$key}{'rules'};
 1533:                     $currtargets = $result->{$key}{'targets'};
 1534:                     last;
 1535:                 }
 1536:             }
 1537:         }
 1538:     }
 1539:     return ($is_balancer,$currtargets,$currrules);
 1540: }
 1541: 
 1542: sub get_loadbalancer_targets {
 1543:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1544:     my $offloadto;
 1545:     if ($rule_in_effect eq 'none') {
 1546:         return [$perlvar{'lonHostID'}];
 1547:     } elsif ($rule_in_effect eq '') {
 1548:         $offloadto = $currtargets;
 1549:     } else {
 1550:         if ($rule_in_effect eq 'homeserver') {
 1551:             my $homeserver = &homeserver($uname,$udom);
 1552:             if ($homeserver ne 'no_host') {
 1553:                 $offloadto = [$homeserver];
 1554:             }
 1555:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1556:             my %domconfig =
 1557:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1558:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1559:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1560:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1561:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1562:                     }
 1563:                 }
 1564:             } else {
 1565:                 my %servers = &internet_dom_servers($udom);
 1566:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1567:                 if (&hostname($remotebalancer) ne '') {
 1568:                     $offloadto = [$remotebalancer];
 1569:                 }
 1570:             }
 1571:         } elsif (&hostname($rule_in_effect) ne '') {
 1572:             $offloadto = [$rule_in_effect];
 1573:         }
 1574:     }
 1575:     return $offloadto;
 1576: }
 1577: 
 1578: sub internet_dom_servers {
 1579:     my ($dom) = @_;
 1580:     my (%uniqservers,%servers);
 1581:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1582:     my @machinedoms = &machine_domains($primaryserver);
 1583:     foreach my $mdom (@machinedoms) {
 1584:         my %currservers = %servers;
 1585:         my %server = &get_servers($mdom);
 1586:         %servers = (%currservers,%server);
 1587:     }
 1588:     my %by_hostname;
 1589:     foreach my $id (keys(%servers)) {
 1590:         push(@{$by_hostname{$servers{$id}}},$id);
 1591:     }
 1592:     foreach my $hostname (sort(keys(%by_hostname))) {
 1593:         if (@{$by_hostname{$hostname}} > 1) {
 1594:             my $match = 0;
 1595:             foreach my $id (@{$by_hostname{$hostname}}) {
 1596:                 if (&host_domain($id) eq $dom) {
 1597:                     $uniqservers{$id} = $hostname;
 1598:                     $match = 1;
 1599:                 }
 1600:             }
 1601:             unless ($match) {
 1602:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1603:             }
 1604:         } else {
 1605:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1606:         }
 1607:     }
 1608:     return %uniqservers;
 1609: }
 1610: 
 1611: sub trusted_domains {
 1612:     my ($cmdtype,$calldom) = @_;
 1613:     my ($trusted,$untrusted);
 1614:     if (&domain($calldom) eq '') {
 1615:         return ($trusted,$untrusted);
 1616:     }
 1617:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|domroles|catalog|reqcrs|msg)$/) {
 1618:         return ($trusted,$untrusted);
 1619:     }
 1620:     my $callprimary = &domain($calldom,'primary');
 1621:     my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
 1622:     if ($intcalldom eq '') {
 1623:         return ($trusted,$untrusted);
 1624:     }
 1625: 
 1626:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
 1627:     unless (defined($cached)) {
 1628:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
 1629:         &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
 1630:         $trustconfig = $domconfig{'trust'};
 1631:     }
 1632:     if (ref($trustconfig)) {
 1633:         my (%possexc,%possinc,@allexc,@allinc); 
 1634:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
 1635:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
 1636:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
 1637:             }
 1638:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
 1639:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
 1640:             }
 1641:         }
 1642:         if (keys(%possexc)) {
 1643:             if (keys(%possinc)) {
 1644:                 foreach my $key (sort(keys(%possexc))) {
 1645:                     next if ($key eq $intcalldom);
 1646:                     unless ($possinc{$key}) {
 1647:                         push(@allexc,$key);
 1648:                     }
 1649:                 }
 1650:             } else {
 1651:                 @allexc = sort(keys(%possexc));
 1652:             }
 1653:         }
 1654:         if (keys(%possinc)) {
 1655:             $possinc{$intcalldom} = 1;
 1656:             @allinc = sort(keys(%possinc));
 1657:         }
 1658:         if ((@allexc > 0) || (@allinc > 0)) {
 1659:             my %doms_by_intdom;
 1660:             my %allintdoms = &all_host_intdom();
 1661:             my %alldoms = &all_host_domain();
 1662:             foreach my $key (%allintdoms) {
 1663:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
 1664:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
 1665:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
 1666:                     }
 1667:                 } else {
 1668:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
 1669:                 }
 1670:             }
 1671:             foreach my $exc (@allexc) {
 1672:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
 1673:                     $untrusted = $doms_by_intdom{$exc};
 1674:                 }
 1675:             }
 1676:             foreach my $inc (@allinc) {
 1677:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
 1678:                     $trusted = $doms_by_intdom{$inc};
 1679:                 }
 1680:             }
 1681:         }
 1682:     }
 1683:     return ($trusted,$untrusted);
 1684: }
 1685: 
 1686: sub will_trust {
 1687:     my ($cmdtype,$domain,$possdom) = @_;
 1688:     return 1 if ($domain eq $possdom);
 1689:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
 1690:     my $willtrust; 
 1691:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
 1692:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
 1693:             $willtrust = 1;
 1694:         }
 1695:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
 1696:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
 1697:             $willtrust = 1;
 1698:         }
 1699:     } else {
 1700:         $willtrust = 1;
 1701:     }
 1702:     return $willtrust;
 1703: }
 1704: 
 1705: # ---------------------- Find the homebase for a user from domain's lib servers
 1706: 
 1707: my %homecache;
 1708: sub homeserver {
 1709:     my ($uname,$udom,$ignoreBadCache)=@_;
 1710:     my $index="$uname:$udom";
 1711: 
 1712:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1713: 
 1714:     my %servers = &get_servers($udom,'library');
 1715:     foreach my $tryserver (keys(%servers)) {
 1716:         next if ($ignoreBadCache ne 'true' && 
 1717: 		 exists($badServerCache{$tryserver}));
 1718: 
 1719: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1720: 	if ($answer eq 'found') {
 1721: 	    delete($badServerCache{$tryserver}); 
 1722: 	    return $homecache{$index}=$tryserver;
 1723: 	} elsif ($answer eq 'no_host') {
 1724: 	    $badServerCache{$tryserver}=1;
 1725: 	}
 1726:     }    
 1727:     return 'no_host';
 1728: }
 1729: 
 1730: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
 1731: 
 1732: sub idget {
 1733:     my ($udom,$idsref,$namespace)=@_;
 1734:     my %returnhash=();
 1735:     my @ids=(); 
 1736:     if (ref($idsref) eq 'ARRAY') {
 1737:         @ids = @{$idsref};
 1738:     } else {
 1739:         return %returnhash; 
 1740:     }
 1741:     if ($namespace eq '') {
 1742:         $namespace = 'ids';
 1743:     }
 1744:     
 1745:     my %servers = &get_servers($udom,'library');
 1746:     foreach my $tryserver (keys(%servers)) {
 1747: 	my $idlist=join('&', map { &escape($_); } @ids);
 1748: 	if ($namespace eq 'ids') {
 1749: 	    $idlist=~tr/A-Z/a-z/;
 1750: 	}
 1751: 	my $reply;
 1752: 	if ($namespace eq 'ids') {
 1753: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1754: 	} else {
 1755: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
 1756: 	}
 1757: 	my @answer=();
 1758: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1759: 	    @answer=split(/\&/,$reply);
 1760: 	}                    ;
 1761: 	my $i;
 1762: 	for ($i=0;$i<=$#ids;$i++) {
 1763: 	    if ($answer[$i]) {
 1764: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
 1765: 	    }
 1766: 	}
 1767:     }
 1768:     return %returnhash;
 1769: }
 1770: 
 1771: # ------------------------------------- Find the IDs behind a list of usernames
 1772: 
 1773: sub idrget {
 1774:     my ($udom,@unames)=@_;
 1775:     my %returnhash=();
 1776:     foreach my $uname (@unames) {
 1777:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1778:     }
 1779:     return %returnhash;
 1780: }
 1781: 
 1782: # Store away a list of names and associated student/employee IDs or clicker IDs
 1783: 
 1784: sub idput {
 1785:     my ($udom,$idsref,$uhom,$namespace)=@_;
 1786:     my %servers=();
 1787:     my %ids=();
 1788:     my %byid = ();
 1789:     if (ref($idsref) eq 'HASH') {
 1790:         %ids=%{$idsref};
 1791:     }
 1792:     if ($namespace eq '') {
 1793:         $namespace = 'ids'; 
 1794:     }
 1795:     foreach my $uname (keys(%ids)) {
 1796: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1797:         if ($uhom eq '') {
 1798:             $uhom=&homeserver($uname,$udom);
 1799:         }
 1800:         if ($uhom ne 'no_host') {
 1801:             my $esc_unam=&escape($uname);
 1802:             if ($namespace eq 'ids') {
 1803:                 my $id=&escape($ids{$uname});
 1804:                 $id=~tr/A-Z/a-z/;
 1805:                 my $esc_unam=&escape($uname);
 1806:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
 1807:             } else {
 1808:                 my @currids = split(/,/,$ids{$uname});
 1809:                 foreach my $id (@currids) {
 1810:                     $byid{$uhom}{$id} .= $uname.',';
 1811:                 }
 1812:             }
 1813:         }
 1814:     }
 1815:     if ($namespace eq 'clickers') {
 1816:         foreach my $server (keys(%byid)) {
 1817:             if (ref($byid{$server}) eq 'HASH') {
 1818:                 foreach my $id (keys(%{$byid{$server}})) {
 1819:                     $byid{$server} =~ s/,$//;
 1820:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
 1821:                 }
 1822:             }
 1823:         }
 1824:     }
 1825:     foreach my $server (keys(%servers)) {
 1826:         $servers{$server} =~ s/\&$//;
 1827:         if ($namespace eq 'ids') {     
 1828:             &critical('idput:'.$udom.':'.$servers{$server},$server);
 1829:         } else {
 1830:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
 1831:         }
 1832:     }
 1833: }
 1834: 
 1835: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
 1836: 
 1837: sub iddel {
 1838:     my ($udom,$idshashref,$uhome,$namespace)=@_;
 1839:     my %result=();
 1840:     my %ids=();
 1841:     my %byid = ();
 1842:     if (ref($idshashref) eq 'HASH') {
 1843:         %ids=%{$idshashref};
 1844:     } else {
 1845:         return %result;
 1846:     }
 1847:     if ($namespace eq '') {
 1848:         $namespace = 'ids';
 1849:     }
 1850:     my %servers=();
 1851:     while (my ($id,$unamestr) = each(%ids)) {
 1852:         if ($namespace eq 'ids') {
 1853:             my $uhom = $uhome;
 1854:             if ($uhom eq '') { 
 1855:                 $uhom=&homeserver($unamestr,$udom);
 1856:             }
 1857:             if ($uhom ne 'no_host') {
 1858:                 $servers{$uhom}.='&'.&escape($id);
 1859:             }
 1860:          } else {
 1861:             my @curritems = split(/,/,$ids{$id});
 1862:             foreach my $uname (@curritems) {
 1863:                 my $uhom = $uhome;
 1864:                 if ($uhom eq '') {
 1865:                     $uhom=&homeserver($uname,$udom);
 1866:                 }
 1867:                 if ($uhom ne 'no_host') { 
 1868:                     $byid{$uhom}{$id} .= $uname.',';
 1869:                 }
 1870:             }
 1871:         }
 1872:     }
 1873:     if ($namespace eq 'clickers') {
 1874:         foreach my $server (keys(%byid)) {
 1875:             if (ref($byid{$server}) eq 'HASH') {
 1876:                 foreach my $id (keys(%{$byid{$server}})) {
 1877:                     $byid{$server}{$id} =~ s/,$//;
 1878:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
 1879:                 }
 1880:             }
 1881:         }
 1882:     }
 1883:     foreach my $server (keys(%servers)) {
 1884:         $servers{$server} =~ s/\&$//;
 1885:         if ($namespace eq 'ids') {
 1886:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
 1887:         } elsif ($namespace eq 'clickers') {
 1888:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
 1889:         }
 1890:     }
 1891:     return %result;
 1892: }
 1893: 
 1894: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
 1895: 
 1896: sub updateclickers {
 1897:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
 1898:     my %clickers;
 1899:     if (ref($idshashref) eq 'HASH') {
 1900:         %clickers=%{$idshashref};
 1901:     } else {
 1902:         return;
 1903:     }
 1904:     my $items='';
 1905:     foreach my $item (keys(%clickers)) {
 1906:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
 1907:     }
 1908:     $items=~s/\&$//;
 1909:     my $request = "updateclickers:$udom:$action:$items";
 1910:     if ($critical) {
 1911:         return &critical($request,$uhome);
 1912:     } else {
 1913:         return &reply($request,$uhome);
 1914:     }
 1915: }
 1916: 
 1917: # ------------------------------dump from db file owned by domainconfig user
 1918: sub dump_dom {
 1919:     my ($namespace, $udom, $regexp) = @_;
 1920: 
 1921:     $udom ||= $env{'user.domain'};
 1922: 
 1923:     return () unless $udom;
 1924: 
 1925:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 1926: }
 1927: 
 1928: # ------------------------------------------ get items from domain db files   
 1929: 
 1930: sub get_dom {
 1931:     my ($namespace,$storearr,$udom,$uhome)=@_;
 1932:     return if ($udom eq 'public');
 1933:     my $items='';
 1934:     foreach my $item (@$storearr) {
 1935:         $items.=&escape($item).'&';
 1936:     }
 1937:     $items=~s/\&$//;
 1938:     if (!$udom) {
 1939:         $udom=$env{'user.domain'};
 1940:         return if ($udom eq 'public');
 1941:         if (defined(&domain($udom,'primary'))) {
 1942:             $uhome=&domain($udom,'primary');
 1943:         } else {
 1944:             undef($uhome);
 1945:         }
 1946:     } else {
 1947:         if (!$uhome) {
 1948:             if (defined(&domain($udom,'primary'))) {
 1949:                 $uhome=&domain($udom,'primary');
 1950:             }
 1951:         }
 1952:     }
 1953:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1954:         my $rep;
 1955:         if ($namespace =~ /^enc/) {
 1956:             $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
 1957:         } else {
 1958:             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 1959:         }
 1960:         my %returnhash;
 1961:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 1962:             return %returnhash;
 1963:         }
 1964:         my @pairs=split(/\&/,$rep);
 1965:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1966:             return @pairs;
 1967:         }
 1968:         my $i=0;
 1969:         foreach my $item (@$storearr) {
 1970:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 1971:             $i++;
 1972:         }
 1973:         return %returnhash;
 1974:     } else {
 1975:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1976:     }
 1977: }
 1978: 
 1979: # -------------------------------------------- put items in domain db files 
 1980: 
 1981: sub put_dom {
 1982:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1983:     if (!$udom) {
 1984:         $udom=$env{'user.domain'};
 1985:         if (defined(&domain($udom,'primary'))) {
 1986:             $uhome=&domain($udom,'primary');
 1987:         } else {
 1988:             undef($uhome);
 1989:         }
 1990:     } else {
 1991:         if (!$uhome) {
 1992:             if (defined(&domain($udom,'primary'))) {
 1993:                 $uhome=&domain($udom,'primary');
 1994:             }
 1995:         }
 1996:     } 
 1997:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1998:         my $items='';
 1999:         foreach my $item (keys(%$storehash)) {
 2000:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 2001:         }
 2002:         $items=~s/\&$//;
 2003:         if ($namespace =~ /^enc/) {
 2004:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
 2005:         } else {
 2006:             return &reply("putdom:$udom:$namespace:$items",$uhome);
 2007:         }
 2008:     } else {
 2009:         &logthis("put_dom failed - no homeserver and/or domain");
 2010:     }
 2011: }
 2012: 
 2013: # --------------------- newput for items in db file owned by domainconfig user
 2014: sub newput_dom {
 2015:     my ($namespace,$storehash,$udom) = @_;
 2016:     my $result;
 2017:     if (!$udom) {
 2018:         $udom=$env{'user.domain'};
 2019:     }
 2020:     if ($udom) {
 2021:         my $uname = &get_domainconfiguser($udom);
 2022:         $result = &newput($namespace,$storehash,$udom,$uname);
 2023:     }
 2024:     return $result;
 2025: }
 2026: 
 2027: # --------------------- delete for items in db file owned by domainconfig user
 2028: sub del_dom {
 2029:     my ($namespace,$storearr,$udom)=@_;
 2030:     if (ref($storearr) eq 'ARRAY') {
 2031:         if (!$udom) {
 2032:             $udom=$env{'user.domain'};
 2033:         }
 2034:         if ($udom) {
 2035:             my $uname = &get_domainconfiguser($udom); 
 2036:             return &del($namespace,$storearr,$udom,$uname);
 2037:         }
 2038:     }
 2039: }
 2040: 
 2041: # ----------------------------------construct domainconfig user for a domain 
 2042: sub get_domainconfiguser {
 2043:     my ($udom) = @_;
 2044:     return $udom.'-domainconfig';
 2045: }
 2046: 
 2047: sub retrieve_inst_usertypes {
 2048:     my ($udom) = @_;
 2049:     my (%returnhash,@order);
 2050:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 2051:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 2052:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 2053:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
 2054:     } else {
 2055:         if (defined(&domain($udom,'primary'))) {
 2056:             my $uhome=&domain($udom,'primary');
 2057:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 2058:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 2059:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
 2060:                 return (\%returnhash,\@order);
 2061:             }
 2062:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 2063:             my @pairs=split(/\&/,$hashitems);
 2064:             foreach my $item (@pairs) {
 2065:                 my ($key,$value)=split(/=/,$item,2);
 2066:                 $key = &unescape($key);
 2067:                 next if ($key =~ /^error: 2 /);
 2068:                 $returnhash{$key}=&thaw_unescape($value);
 2069:             }
 2070:             my @esc_order = split(/\&/,$orderitems);
 2071:             foreach my $item (@esc_order) {
 2072:                 push(@order,&unescape($item));
 2073:             }
 2074:         } else {
 2075:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
 2076:         }
 2077:         return (\%returnhash,\@order);
 2078:     }
 2079: }
 2080: 
 2081: sub is_domainimage {
 2082:     my ($url) = @_;
 2083:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
 2084:         if (&domain($1) ne '') {
 2085:             return '1';
 2086:         }
 2087:     }
 2088:     return;
 2089: }
 2090: 
 2091: sub inst_directory_query {
 2092:     my ($srch) = @_;
 2093:     my $udom = $srch->{'srchdomain'};
 2094:     my %results;
 2095:     my $homeserver = &domain($udom,'primary');
 2096:     my $outcome;
 2097:     if ($homeserver ne '') {
 2098:         unless ($homeserver eq $perlvar{'lonHostID'}) {
 2099:             if ($srch->{'srchby'} eq 'email') {
 2100:                 my $lcrev = &get_server_loncaparev(undef,$homeserver);
 2101:                 my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2102:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
 2103:                     (($major == 2) && ($minor < 12))) {
 2104:                     return;
 2105:                 }
 2106:             }
 2107:         }
 2108: 	my $queryid=&reply("querysend:instdirsearch:".
 2109: 			   &escape($srch->{'srchby'}).':'.
 2110: 			   &escape($srch->{'srchterm'}).':'.
 2111: 			   &escape($srch->{'srchtype'}),$homeserver);
 2112: 	my $host=&hostname($homeserver);
 2113: 	if ($queryid !~/^\Q$host\E\_/) {
 2114: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
 2115: 	    return;
 2116: 	}
 2117: 	my $response = &get_query_reply($queryid);
 2118: 	my $maxtries = 5;
 2119: 	my $tries = 1;
 2120: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2121: 	    $response = &get_query_reply($queryid);
 2122: 	    $tries ++;
 2123: 	}
 2124: 
 2125:         if (!&error($response) && $response ne 'refused') {
 2126:             if ($response eq 'unavailable') {
 2127:                 $outcome = $response;
 2128:             } else {
 2129:                 $outcome = 'ok';
 2130:                 my @matches = split(/\n/,$response);
 2131:                 foreach my $match (@matches) {
 2132:                     my ($key,$value) = split(/=/,$match);
 2133:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 2134:                 }
 2135:             }
 2136:         }
 2137:     }
 2138:     return ($outcome,%results);
 2139: }
 2140: 
 2141: sub usersearch {
 2142:     my ($srch) = @_;
 2143:     my $dom = $srch->{'srchdomain'};
 2144:     my %results;
 2145:     my %libserv = &all_library();
 2146:     my $query = 'usersearch';
 2147:     foreach my $tryserver (keys(%libserv)) {
 2148:         if (&host_domain($tryserver) eq $dom) {
 2149:             unless ($tryserver eq $perlvar{'lonHostID'}) {
 2150:                 if ($srch->{'srchby'} eq 'email') {
 2151:                     my $lcrev = &get_server_loncaparev(undef,$tryserver);
 2152:                     my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2153:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
 2154:                              (($major == 2) && ($minor < 12)));
 2155:                 }
 2156:             }
 2157:             my $host=&hostname($tryserver);
 2158:             my $queryid=
 2159:                 &reply("querysend:".&escape($query).':'.
 2160:                        &escape($srch->{'srchby'}).':'.
 2161:                        &escape($srch->{'srchtype'}).':'.
 2162:                        &escape($srch->{'srchterm'}),$tryserver);
 2163:             if ($queryid !~/^\Q$host\E\_/) {
 2164:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 2165:                 next;
 2166:             }
 2167:             my $reply = &get_query_reply($queryid);
 2168:             my $maxtries = 1;
 2169:             my $tries = 1;
 2170:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 2171:                 $reply = &get_query_reply($queryid);
 2172:                 $tries ++;
 2173:             }
 2174:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 2175:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 2176:             } else {
 2177:                 my @matches;
 2178:                 if ($reply =~ /\n/) {
 2179:                     @matches = split(/\n/,$reply);
 2180:                 } else {
 2181:                     @matches = split(/\&/,$reply);
 2182:                 }
 2183:                 foreach my $match (@matches) {
 2184:                     my ($uname,$udom,%userhash);
 2185:                     foreach my $entry (split(/:/,$match)) {
 2186:                         my ($key,$value) =
 2187:                             map {&unescape($_);} split(/=/,$entry);
 2188:                         $userhash{$key} = $value;
 2189:                         if ($key eq 'username') {
 2190:                             $uname = $value;
 2191:                         } elsif ($key eq 'domain') {
 2192:                             $udom = $value;
 2193:                         }
 2194:                     }
 2195:                     $results{$uname.':'.$udom} = \%userhash;
 2196:                 }
 2197:             }
 2198:         }
 2199:     }
 2200:     return %results;
 2201: }
 2202: 
 2203: sub get_instuser {
 2204:     my ($udom,$uname,$id) = @_;
 2205:     my $homeserver = &domain($udom,'primary');
 2206:     my ($outcome,%results);
 2207:     if ($homeserver ne '') {
 2208:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 2209:                            &escape($id).':'.&escape($udom),$homeserver);
 2210:         my $host=&hostname($homeserver);
 2211:         if ($queryid !~/^\Q$host\E\_/) {
 2212:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 2213:             return;
 2214:         }
 2215:         my $response = &get_query_reply($queryid);
 2216:         my $maxtries = 5;
 2217:         my $tries = 1;
 2218:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2219:             $response = &get_query_reply($queryid);
 2220:             $tries ++;
 2221:         }
 2222:         if (!&error($response) && $response ne 'refused') {
 2223:             if ($response eq 'unavailable') {
 2224:                 $outcome = $response;
 2225:             } else {
 2226:                 $outcome = 'ok';
 2227:                 my @matches = split(/\n/,$response);
 2228:                 foreach my $match (@matches) {
 2229:                     my ($key,$value) = split(/=/,$match);
 2230:                     $results{&unescape($key)} = &thaw_unescape($value);
 2231:                 }
 2232:             }
 2233:         }
 2234:     }
 2235:     my %userinfo;
 2236:     if (ref($results{$uname}) eq 'HASH') {
 2237:         %userinfo = %{$results{$uname}};
 2238:     } 
 2239:     return ($outcome,%userinfo);
 2240: }
 2241: 
 2242: sub get_multiple_instusers {
 2243:     my ($udom,$users,$caller) = @_;
 2244:     my ($outcome,$results);
 2245:     if (ref($users) eq 'HASH') {
 2246:         my $count = keys(%{$users}); 
 2247:         my $requested = &freeze_escape($users);
 2248:         my $homeserver = &domain($udom,'primary');
 2249:         if ($homeserver ne '') {
 2250:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
 2251:             my $host=&hostname($homeserver);
 2252:             if ($queryid !~/^\Q$host\E\_/) {
 2253:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
 2254:                          ' for host: '.$homeserver.'in domain '.$udom);
 2255:                 return ($outcome,$results);
 2256:             }
 2257:             my $response = &get_query_reply($queryid);
 2258:             my $maxtries = 5;
 2259:             if ($count > 100) {
 2260:                 $maxtries = 1+int($count/20);
 2261:             }
 2262:             my $tries = 1;
 2263:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
 2264:                 $response = &get_query_reply($queryid);
 2265:                 $tries ++;
 2266:             }
 2267:             if ($response eq '') {
 2268:                 $results = {};
 2269:                 foreach my $key (keys(%{$users})) {
 2270:                     my ($uname,$id);
 2271:                     if ($caller eq 'id') {
 2272:                         $id = $key;
 2273:                     } else {
 2274:                         $uname = $key;
 2275:                     }
 2276:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
 2277:                     $outcome = $resp;
 2278:                     if ($resp eq 'ok') {
 2279:                         %{$results} = (%{$results}, %info);
 2280:                     } else {
 2281:                         last;
 2282:                     }
 2283:                 }
 2284:             } elsif(!&error($response) && ($response ne 'refused')) {
 2285:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
 2286:                     $outcome = $response;
 2287:                 } else {
 2288:                     ($outcome,my $userdata) = split(/=/,$response,2);
 2289:                     if ($outcome eq 'ok') {
 2290:                         $results = &thaw_unescape($userdata); 
 2291:                     }
 2292:                 }
 2293:             }
 2294:         }
 2295:     }
 2296:     return ($outcome,$results);
 2297: }
 2298: 
 2299: sub inst_rulecheck {
 2300:     my ($udom,$uname,$id,$item,$rules) = @_;
 2301:     my %returnhash;
 2302:     if ($udom ne '') {
 2303:         if (ref($rules) eq 'ARRAY') {
 2304:             @{$rules} = map {&escape($_);} (@{$rules});
 2305:             my $rulestr = join(':',@{$rules});
 2306:             my $homeserver=&domain($udom,'primary');
 2307:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2308:                 my $response;
 2309:                 if ($item eq 'username') {                
 2310:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 2311:                                               ':'.&escape($uname).':'.$rulestr,
 2312:                                               $homeserver));
 2313:                 } elsif ($item eq 'id') {
 2314:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 2315:                                               ':'.&escape($id).':'.$rulestr,
 2316:                                               $homeserver));
 2317:                 } elsif ($item eq 'selfcreate') {
 2318:                     $response=&unescape(&reply('instselfcreatecheck:'.
 2319:                                                &escape($udom).':'.&escape($uname).
 2320:                                               ':'.$rulestr,$homeserver));
 2321:                 }
 2322:                 if ($response ne 'refused') {
 2323:                     my @pairs=split(/\&/,$response);
 2324:                     foreach my $item (@pairs) {
 2325:                         my ($key,$value)=split(/=/,$item,2);
 2326:                         $key = &unescape($key);
 2327:                         next if ($key =~ /^error: 2 /);
 2328:                         $returnhash{$key}=&thaw_unescape($value);
 2329:                     }
 2330:                 }
 2331:             }
 2332:         }
 2333:     }
 2334:     return %returnhash;
 2335: }
 2336: 
 2337: sub inst_userrules {
 2338:     my ($udom,$check) = @_;
 2339:     my (%ruleshash,@ruleorder);
 2340:     if ($udom ne '') {
 2341:         my $homeserver=&domain($udom,'primary');
 2342:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2343:             my $response;
 2344:             if ($check eq 'id') {
 2345:                 $response=&reply('instidrules:'.&escape($udom),
 2346:                                  $homeserver);
 2347:             } elsif ($check eq 'email') {
 2348:                 $response=&reply('instemailrules:'.&escape($udom),
 2349:                                  $homeserver);
 2350:             } else {
 2351:                 $response=&reply('instuserrules:'.&escape($udom),
 2352:                                  $homeserver);
 2353:             }
 2354:             if (($response ne 'refused') && ($response ne 'error') && 
 2355:                 ($response ne 'unknown_cmd') && 
 2356:                 ($response ne 'no_such_host')) {
 2357:                 my ($hashitems,$orderitems) = split(/:/,$response);
 2358:                 my @pairs=split(/\&/,$hashitems);
 2359:                 foreach my $item (@pairs) {
 2360:                     my ($key,$value)=split(/=/,$item,2);
 2361:                     $key = &unescape($key);
 2362:                     next if ($key =~ /^error: 2 /);
 2363:                     $ruleshash{$key}=&thaw_unescape($value);
 2364:                 }
 2365:                 my @esc_order = split(/\&/,$orderitems);
 2366:                 foreach my $item (@esc_order) {
 2367:                     push(@ruleorder,&unescape($item));
 2368:                 }
 2369:             }
 2370:         }
 2371:     }
 2372:     return (\%ruleshash,\@ruleorder);
 2373: }
 2374: 
 2375: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 2376: 
 2377: sub get_domain_defaults {
 2378:     my ($domain,$ignore_cache) = @_;
 2379:     return if (($domain eq '') || ($domain eq 'public'));
 2380:     my $cachetime = 60*60*24;
 2381:     unless ($ignore_cache) {
 2382:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 2383:         if (defined($cached)) {
 2384:             if (ref($result) eq 'HASH') {
 2385:                 return %{$result};
 2386:             }
 2387:         }
 2388:     }
 2389:     my %domdefaults;
 2390:     my %domconfig =
 2391:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 2392:                                   'requestcourses','inststatus',
 2393:                                   'coursedefaults','usersessions',
 2394:                                   'requestauthor','selfenrollment',
 2395:                                   'coursecategories','ssl','autoenroll',
 2396:                                   'trust','helpsettings'],$domain);
 2397:     my @coursetypes = ('official','unofficial','community','textbook','placement');
 2398:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2399:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2400:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2401:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2402:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2403:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2404:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2405:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
 2406:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
 2407:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
 2408:     } else {
 2409:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2410:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2411:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2412:     }
 2413:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2414:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2415:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2416:         } else {
 2417:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2418:         }
 2419:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2420:         foreach my $item (@usertools) {
 2421:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2422:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2423:             }
 2424:         }
 2425:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2426:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2427:         }
 2428:     }
 2429:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2430:         foreach my $item ('official','unofficial','community','textbook','placement') {
 2431:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2432:         }
 2433:     }
 2434:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2435:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2436:     }
 2437:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2438:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
 2439:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2440:         }
 2441:     }
 2442:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2443:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
 2444:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
 2445:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
 2446:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
 2447:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
 2448:         }
 2449:         foreach my $type (@coursetypes) {
 2450:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2451:                 unless ($type eq 'community') {
 2452:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
 2453:                 }
 2454:             }
 2455:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2456:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
 2457:             }
 2458:             if ($domdefaults{'postsubmit'} eq 'on') {
 2459:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
 2460:                     $domdefaults{$type.'postsubtimeout'} = 
 2461:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
 2462:                 }
 2463:             }
 2464:         }
 2465:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
 2466:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
 2467:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
 2468:                 if (@clonecodes) {
 2469:                     $domdefaults{'canclone'} = join('+',@clonecodes);
 2470:                 }
 2471:             }
 2472:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
 2473:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
 2474:         }
 2475:         if ($domconfig{'coursedefaults'}{'texengine'}) {
 2476:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
 2477:         } 
 2478:     }
 2479:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2480:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2481:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2482:         }
 2483:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2484:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2485:         }
 2486:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
 2487:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
 2488:         }
 2489:     }
 2490:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
 2491:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
 2492:             my @settings = ('types','registered','enroll_dates','access_dates','section',
 2493:                             'approval','limit');
 2494:             foreach my $type (@coursetypes) {
 2495:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
 2496:                     my @mgrdc = ();
 2497:                     foreach my $item (@settings) {
 2498:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
 2499:                             push(@mgrdc,$item);
 2500:                         }
 2501:                     }
 2502:                     if (@mgrdc) {
 2503:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
 2504:                     }
 2505:                 }
 2506:             }
 2507:         }
 2508:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
 2509:             foreach my $type (@coursetypes) {
 2510:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
 2511:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
 2512:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
 2513:                     }
 2514:                 }
 2515:             }
 2516:         }
 2517:     }
 2518:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2519:         $domdefaults{'catauth'} = 'std';
 2520:         $domdefaults{'catunauth'} = 'std';
 2521:         if ($domconfig{'coursecategories'}{'auth'}) { 
 2522:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
 2523:         }
 2524:         if ($domconfig{'coursecategories'}{'unauth'}) {
 2525:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
 2526:         }
 2527:     }
 2528:     if (ref($domconfig{'ssl'}) eq 'HASH') {
 2529:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
 2530:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
 2531:         }
 2532:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
 2533:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
 2534:         }
 2535:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
 2536:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
 2537:         }
 2538:     }
 2539:     if (ref($domconfig{'trust'}) eq 'HASH') {
 2540:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
 2541:         foreach my $prefix (@prefixes) {
 2542:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
 2543:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
 2544:             }
 2545:         }
 2546:     }
 2547:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 2548:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
 2549:     }
 2550:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 2551:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
 2552:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 2553:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
 2554:         }
 2555:     }
 2556:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2557:     return %domdefaults;
 2558: }
 2559: 
 2560: sub course_portal_url {
 2561:     my ($cnum,$cdom) = @_;
 2562:     my $chome = &homeserver($cnum,$cdom);
 2563:     my $hostname = &hostname($chome);
 2564:     my $protocol = $protocol{$chome};
 2565:     $protocol = 'http' if ($protocol ne 'https');
 2566:     my %domdefaults = &get_domain_defaults($cdom);
 2567:     my $firsturl;
 2568:     if ($domdefaults{'portal_def'}) {
 2569:         $firsturl = $domdefaults{'portal_def'};
 2570:     } else {
 2571:         $firsturl = $protocol.'://'.$hostname;
 2572:     }
 2573:     return $firsturl;
 2574: }
 2575: 
 2576: # --------------------------------------------------- Assign a key to a student
 2577: 
 2578: sub assign_access_key {
 2579: #
 2580: # a valid key looks like uname:udom#comments
 2581: # comments are being appended
 2582: #
 2583:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2584:     $kdom=
 2585:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2586:     $knum=
 2587:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2588:     $cdom=
 2589:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2590:     $cnum=
 2591:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2592:     $udom=$env{'user.name'} unless (defined($udom));
 2593:     $uname=$env{'user.domain'} unless (defined($uname));
 2594:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2595:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2596:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2597:                                                   # assigned to this person
 2598:                                                   # - this should not happen,
 2599:                                                   # unless something went wrong
 2600:                                                   # the first time around
 2601: # ready to assign
 2602:         $logentry=$1.'; '.$logentry;
 2603:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2604:                                                  $kdom,$knum) eq 'ok') {
 2605: # key now belongs to user
 2606: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2607:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2608:                 &appenv({'environment.'.$envkey => $ckey});
 2609:                 return 'ok';
 2610:             } else {
 2611:                 return 
 2612:   'error: Count not permanently assign key, will need to be re-entered later.';
 2613: 	    }
 2614:         } else {
 2615:             return 'error: Could not assign key, try again later.';
 2616:         }
 2617:     } elsif (!$existing{$ckey}) {
 2618: # the key does not exist
 2619: 	return 'error: The key does not exist';
 2620:     } else {
 2621: # the key is somebody else's
 2622: 	return 'error: The key is already in use';
 2623:     }
 2624: }
 2625: 
 2626: # ------------------------------------------ put an additional comment on a key
 2627: 
 2628: sub comment_access_key {
 2629: #
 2630: # a valid key looks like uname:udom#comments
 2631: # comments are being appended
 2632: #
 2633:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2634:     $cdom=
 2635:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2636:     $cnum=
 2637:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2638:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2639:     if ($existing{$ckey}) {
 2640:         $existing{$ckey}.='; '.$logentry;
 2641: # ready to assign
 2642:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2643:                                                  $cdom,$cnum) eq 'ok') {
 2644: 	    return 'ok';
 2645:         } else {
 2646: 	    return 'error: Count not store comment.';
 2647:         }
 2648:     } else {
 2649: # the key does not exist
 2650: 	return 'error: The key does not exist';
 2651:     }
 2652: }
 2653: 
 2654: # ------------------------------------------------------ Generate a set of keys
 2655: 
 2656: sub generate_access_keys {
 2657:     my ($number,$cdom,$cnum,$logentry)=@_;
 2658:     $cdom=
 2659:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2660:     $cnum=
 2661:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2662:     unless (&allowed('mky',$cdom)) { return 0; }
 2663:     unless (($cdom) && ($cnum)) { return 0; }
 2664:     if ($number>10000) { return 0; }
 2665:     sleep(2); # make sure don't get same seed twice
 2666:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2667:     my $total=0;
 2668:     for (my $i=1;$i<=$number;$i++) {
 2669:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2670:                   sprintf("%lx",int(100000*rand)).'-'.
 2671:                   sprintf("%lx",int(100000*rand));
 2672:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2673:        $newkey=~s/0/h/g; # and also 0 and O
 2674:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2675:        if ($existing{$newkey}) {
 2676:            $i--;
 2677:        } else {
 2678: 	  if (&put('accesskeys',
 2679:               { $newkey => '# generated '.localtime().
 2680:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2681:                            '; '.$logentry },
 2682: 		   $cdom,$cnum) eq 'ok') {
 2683:               $total++;
 2684: 	  }
 2685:        }
 2686:     }
 2687:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2688:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2689:     return $total;
 2690: }
 2691: 
 2692: # ------------------------------------------------------- Validate an accesskey
 2693: 
 2694: sub validate_access_key {
 2695:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2696:     $cdom=
 2697:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2698:     $cnum=
 2699:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2700:     $udom=$env{'user.domain'} unless (defined($udom));
 2701:     $uname=$env{'user.name'} unless (defined($uname));
 2702:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2703:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2704: }
 2705: 
 2706: # ------------------------------------- Find the section of student in a course
 2707: sub devalidate_getsection_cache {
 2708:     my ($udom,$unam,$courseid)=@_;
 2709:     my $hashid="$udom:$unam:$courseid";
 2710:     &devalidate_cache_new('getsection',$hashid);
 2711: }
 2712: 
 2713: sub courseid_to_courseurl {
 2714:     my ($courseid) = @_;
 2715:     #already url style courseid
 2716:     return $courseid if ($courseid =~ m{^/});
 2717: 
 2718:     if (exists($env{'course.'.$courseid.'.num'})) {
 2719: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2720: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2721: 	return "/$cdom/$cnum";
 2722:     }
 2723: 
 2724:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2725:     if (exists($courseinfo{'num'})) {
 2726: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2727:     }
 2728: 
 2729:     return undef;
 2730: }
 2731: 
 2732: sub getsection {
 2733:     my ($udom,$unam,$courseid)=@_;
 2734:     my $cachetime=1800;
 2735: 
 2736:     my $hashid="$udom:$unam:$courseid";
 2737:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2738:     if (defined($cached)) { return $result; }
 2739: 
 2740:     my %Pending; 
 2741:     my %Expired;
 2742:     #
 2743:     # Each role can either have not started yet (pending), be active, 
 2744:     #    or have expired.
 2745:     #
 2746:     # If there is an active role, we are done.
 2747:     #
 2748:     # If there is more than one role which has not started yet, 
 2749:     #     choose the one which will start sooner
 2750:     # If there is one role which has not started yet, return it.
 2751:     #
 2752:     # If there is more than one expired role, choose the one which ended last.
 2753:     # If there is a role which has expired, return it.
 2754:     #
 2755:     $courseid = &courseid_to_courseurl($courseid);
 2756:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 2757:     foreach my $key (keys(%roleshash)) {
 2758:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2759:         my $section=$1;
 2760:         if ($key eq $courseid.'_st') { $section=''; }
 2761:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2762:         my $now=time;
 2763:         if (defined($end) && $end && ($now > $end)) {
 2764:             $Expired{$end}=$section;
 2765:             next;
 2766:         }
 2767:         if (defined($start) && $start && ($now < $start)) {
 2768:             $Pending{$start}=$section;
 2769:             next;
 2770:         }
 2771:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2772:     }
 2773:     #
 2774:     # Presumedly there will be few matching roles from the above
 2775:     # loop and the sorting time will be negligible.
 2776:     if (scalar(keys(%Pending))) {
 2777:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2778:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2779:     } 
 2780:     if (scalar(keys(%Expired))) {
 2781:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2782:         my $time = pop(@sorted);
 2783:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2784:     }
 2785:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2786: }
 2787: 
 2788: sub save_cache {
 2789:     &purge_remembered();
 2790:     #&Apache::loncommon::validate_page();
 2791:     undef(%env);
 2792:     undef($env_loaded);
 2793: }
 2794: 
 2795: my $to_remember=-1;
 2796: my %remembered;
 2797: my %accessed;
 2798: my $kicks=0;
 2799: my $hits=0;
 2800: sub make_key {
 2801:     my ($name,$id) = @_;
 2802:     if (length($id) > 65 
 2803: 	&& length(&escape($id)) > 200) {
 2804: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2805:     }
 2806:     return &escape($name.':'.$id);
 2807: }
 2808: 
 2809: sub devalidate_cache_new {
 2810:     my ($name,$id,$debug) = @_;
 2811:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2812:     my $remembered_id=$name.':'.$id;
 2813:     $id=&make_key($name,$id);
 2814:     $memcache->delete($id);
 2815:     delete($remembered{$remembered_id});
 2816:     delete($accessed{$remembered_id});
 2817: }
 2818: 
 2819: sub is_cached_new {
 2820:     my ($name,$id,$debug) = @_;
 2821:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
 2822:     if (exists($remembered{$remembered_id})) {
 2823: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
 2824: 	$accessed{$remembered_id}=[&gettimeofday()];
 2825: 	$hits++;
 2826: 	return ($remembered{$remembered_id},1);
 2827:     }
 2828:     $id=&make_key($name,$id);
 2829:     my $value = $memcache->get($id);
 2830:     if (!(defined($value))) {
 2831: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2832: 	return (undef,undef);
 2833:     }
 2834:     if ($value eq '__undef__') {
 2835: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2836: 	$value=undef;
 2837:     }
 2838:     &make_room($remembered_id,$value,$debug);
 2839:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2840:     return ($value,1);
 2841: }
 2842: 
 2843: sub do_cache_new {
 2844:     my ($name,$id,$value,$time,$debug) = @_;
 2845:     my $remembered_id=$name.':'.$id;
 2846:     $id=&make_key($name,$id);
 2847:     my $setvalue=$value;
 2848:     if (!defined($setvalue)) {
 2849: 	$setvalue='__undef__';
 2850:     }
 2851:     if (!defined($time) ) {
 2852: 	$time=600;
 2853:     }
 2854:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 2855:     my $result = $memcache->set($id,$setvalue,$time);
 2856:     if (! $result) {
 2857: 	&logthis("caching of id -> $id  failed");
 2858: 	$memcache->disconnect_all();
 2859:     }
 2860:     # need to make a copy of $value
 2861:     &make_room($remembered_id,$value,$debug);
 2862:     return $value;
 2863: }
 2864: 
 2865: sub make_room {
 2866:     my ($remembered_id,$value,$debug)=@_;
 2867: 
 2868:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
 2869:                                     : $value;
 2870:     if ($to_remember<0) { return; }
 2871:     $accessed{$remembered_id}=[&gettimeofday()];
 2872:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 2873:     my $to_kick;
 2874:     my $max_time=0;
 2875:     foreach my $other (keys(%accessed)) {
 2876: 	if (&tv_interval($accessed{$other}) > $max_time) {
 2877: 	    $to_kick=$other;
 2878: 	    $max_time=&tv_interval($accessed{$other});
 2879: 	}
 2880:     }
 2881:     delete($remembered{$to_kick});
 2882:     delete($accessed{$to_kick});
 2883:     $kicks++;
 2884:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 2885:     return;
 2886: }
 2887: 
 2888: sub purge_remembered {
 2889:     #&logthis("Tossing ".scalar(keys(%remembered)));
 2890:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 2891:     undef(%remembered);
 2892:     undef(%accessed);
 2893: }
 2894: # ------------------------------------- Read an entry from a user's environment
 2895: 
 2896: sub userenvironment {
 2897:     my ($udom,$unam,@what)=@_;
 2898:     my $items;
 2899:     foreach my $item (@what) {
 2900:         $items.=&escape($item).'&';
 2901:     }
 2902:     $items=~s/\&$//;
 2903:     my %returnhash=();
 2904:     my $uhome = &homeserver($unam,$udom);
 2905:     unless ($uhome eq 'no_host') {
 2906:         my @answer=split(/\&/, 
 2907:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 2908:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 2909:             return %returnhash;
 2910:         }
 2911:         my $i;
 2912:         for ($i=0;$i<=$#what;$i++) {
 2913: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 2914:         }
 2915:     }
 2916:     return %returnhash;
 2917: }
 2918: 
 2919: # ---------------------------------------------------------- Get a studentphoto
 2920: sub studentphoto {
 2921:     my ($udom,$unam,$ext) = @_;
 2922:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2923:     if (defined($env{'request.course.id'})) {
 2924:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 2925:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 2926:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 2927:             } else {
 2928:                 my ($result,$perm_reqd)=
 2929: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2930:                 if ($result eq 'ok') {
 2931:                     if (!($perm_reqd eq 'yes')) {
 2932:                         return(&retrievestudentphoto($udom,$unam,$ext));
 2933:                     }
 2934:                 }
 2935:             }
 2936:         }
 2937:     } else {
 2938:         my ($result,$perm_reqd) = 
 2939: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2940:         if ($result eq 'ok') {
 2941:             if (!($perm_reqd eq 'yes')) {
 2942:                 return(&retrievestudentphoto($udom,$unam,$ext));
 2943:             }
 2944:         }
 2945:     }
 2946:     return '/adm/lonKaputt/lonlogo_broken.gif';
 2947: }
 2948: 
 2949: sub retrievestudentphoto {
 2950:     my ($udom,$unam,$ext,$type) = @_;
 2951:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2952:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 2953:     if ($ret eq 'ok') {
 2954:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 2955:         if ($type eq 'thumbnail') {
 2956:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 2957:         }
 2958:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 2959:         return $tokenurl;
 2960:     } else {
 2961:         if ($type eq 'thumbnail') {
 2962:             return '/adm/lonKaputt/genericstudent_tn.gif';
 2963:         } else { 
 2964:             return '/adm/lonKaputt/lonlogo_broken.gif';
 2965:         }
 2966:     }
 2967: }
 2968: 
 2969: # -------------------------------------------------------------------- New chat
 2970: 
 2971: sub chatsend {
 2972:     my ($newentry,$anon,$group)=@_;
 2973:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 2974:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2975:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 2976:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 2977: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 2978: 		   &escape($newentry)).':'.$group,$chome);
 2979: }
 2980: 
 2981: # ------------------------------------------ Find current version of a resource
 2982: 
 2983: sub getversion {
 2984:     my $fname=&clutter(shift);
 2985:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 2986:     return &currentversion(&filelocation('',$fname));
 2987: }
 2988: 
 2989: sub currentversion {
 2990:     my $fname=shift;
 2991:     my $author=$fname;
 2992:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2993:     my ($udom,$uname)=split(/\//,$author);
 2994:     my $home=&homeserver($uname,$udom);
 2995:     if ($home eq 'no_host') { 
 2996:         return -1; 
 2997:     }
 2998:     my $answer=&reply("currentversion:$fname",$home);
 2999:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3000: 	return -1;
 3001:     }
 3002:     return $answer;
 3003: }
 3004: 
 3005: #
 3006: # Return special version number of resource if set by override, empty otherwise
 3007: #
 3008: sub usedversion {
 3009:     my $fname=shift;
 3010:     unless ($fname) { $fname=$env{'request.uri'}; }
 3011:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 3012:     if ($urlversion) { return $urlversion; }
 3013:     return '';
 3014: }
 3015: 
 3016: # ----------------------------- Subscribe to a resource, return URL if possible
 3017: 
 3018: sub subscribe {
 3019:     my $fname=shift;
 3020:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 3021:     $fname=~s/[\n\r]//g;
 3022:     my $author=$fname;
 3023:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3024:     my ($udom,$uname)=split(/\//,$author);
 3025:     my $home=homeserver($uname,$udom);
 3026:     if ($home eq 'no_host') {
 3027:         return 'not_found';
 3028:     }
 3029:     my $answer=reply("sub:$fname",$home);
 3030:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3031: 	$answer.=' by '.$home;
 3032:     }
 3033:     return $answer;
 3034: }
 3035:     
 3036: # -------------------------------------------------------------- Replicate file
 3037: 
 3038: sub repcopy {
 3039:     my $filename=shift;
 3040:     $filename=~s/\/+/\//g;
 3041:     my $londocroot = $perlvar{'lonDocRoot'};
 3042:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 3043:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 3044:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 3045: 	$filename=~m{^/*(uploaded|editupload)/}) {
 3046: 	return &repcopy_userfile($filename);
 3047:     }
 3048:     $filename=~s/[\n\r]//g;
 3049:     my $transname="$filename.in.transfer";
 3050: # FIXME: this should flock
 3051:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 3052:     my $remoteurl=subscribe($filename);
 3053:     if ($remoteurl =~ /^con_lost by/) {
 3054: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3055:            return 'unavailable';
 3056:     } elsif ($remoteurl eq 'not_found') {
 3057: 	   #&logthis("Subscribe returned not_found: $filename");
 3058: 	   return 'not_found';
 3059:     } elsif ($remoteurl =~ /^rejected by/) {
 3060: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3061:            return 'forbidden';
 3062:     } elsif ($remoteurl eq 'directory') {
 3063:            return 'ok';
 3064:     } else {
 3065:         my $author=$filename;
 3066:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3067:         my ($udom,$uname)=split(/\//,$author);
 3068:         my $home=homeserver($uname,$udom);
 3069:         unless ($home eq $perlvar{'lonHostID'}) {
 3070:            my @parts=split(/\//,$filename);
 3071:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 3072:            if ($path ne "$londocroot/res") {
 3073:                &logthis("Malconfiguration for replication: $filename");
 3074: 	       return 'bad_request';
 3075:            }
 3076:            my $count;
 3077:            for ($count=5;$count<$#parts;$count++) {
 3078:                $path.="/$parts[$count]";
 3079:                if ((-e $path)!=1) {
 3080: 		   mkdir($path,0777);
 3081:                }
 3082:            }
 3083:            my $request=new HTTP::Request('GET',"$remoteurl");
 3084:            my $response;
 3085:            if ($remoteurl =~ m{/raw/}) {
 3086:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
 3087:            } else {
 3088:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
 3089:            }
 3090:            if ($response->is_error()) {
 3091: 	       unlink($transname);
 3092:                my $message=$response->status_line;
 3093:                &logthis("<font color=\"blue\">WARNING:"
 3094:                        ." LWP get: $message: $filename</font>");
 3095:                return 'unavailable';
 3096:            } else {
 3097: 	       if ($remoteurl!~/\.meta$/) {
 3098:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 3099:                   my $mresponse;
 3100:                   if ($remoteurl =~ m{/raw/}) {
 3101:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
 3102:                   } else {
 3103:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
 3104:                   }
 3105:                   if ($mresponse->is_error()) {
 3106: 		      unlink($filename.'.meta');
 3107:                       &logthis(
 3108:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 3109:                   }
 3110: 	       }
 3111:                rename($transname,$filename);
 3112:                return 'ok';
 3113:            }
 3114:        }
 3115:     }
 3116: }
 3117: 
 3118: # ------------------------------------------------ Get server side include body
 3119: sub ssi_body {
 3120:     my ($filelink,%form)=@_;
 3121:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 3122:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 3123:     }
 3124:     my $output='';
 3125:     my $response;
 3126:     if ($filelink=~/^https?\:/) {
 3127:        ($output,$response)=&externalssi($filelink);
 3128:     } else {
 3129:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 3130:        $filelink .= 'inhibitmenu=yes';
 3131:        ($output,$response)=&ssi($filelink,%form);
 3132:     }
 3133:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 3134:     $output=~s/^.*?\<body[^\>]*\>//si;
 3135:     $output=~s/\<\/body\s*\>.*?$//si;
 3136:     if (wantarray) {
 3137:         return ($output, $response);
 3138:     } else {
 3139:         return $output;
 3140:     }
 3141: }
 3142: 
 3143: # --------------------------------------------------------- Server Side Include
 3144: 
 3145: sub absolute_url {
 3146:     my ($host_name) = @_;
 3147:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 3148:     if ($host_name eq '') {
 3149: 	$host_name = $ENV{'SERVER_NAME'};
 3150:     }
 3151:     return $protocol.$host_name;
 3152: }
 3153: 
 3154: #
 3155: #   Server side include.
 3156: # Parameters:
 3157: #  fn     Possibly encrypted resource name/id.
 3158: #  form   Hash that describes how the rendering should be done
 3159: #         and other things.
 3160: # Returns:
 3161: #   Scalar context: The content of the response.
 3162: #   Array context:  2 element list of the content and the full response object.
 3163: #     
 3164: sub ssi {
 3165: 
 3166:     my ($fn,%form)=@_;
 3167:     my $request;
 3168: 
 3169:     $form{'no_update_last_known'}=1;
 3170:     &Apache::lonenc::check_encrypt(\$fn);
 3171:     if (%form) {
 3172:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 3173:       $request->content(join('&',map { 
 3174:             my $name = escape($_);
 3175:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
 3176:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
 3177:             : &escape($form{$_}) );    
 3178:         } keys(%form)));
 3179:     } else {
 3180:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 3181:     }
 3182: 
 3183:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 3184:     my $lonhost = $perlvar{'lonHostID'};
 3185:     my $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar);
 3186: 
 3187:     if (wantarray) {
 3188: 	return ($response->content, $response);
 3189:     } else {
 3190: 	return $response->content;
 3191:     }
 3192: }
 3193: 
 3194: sub externalssi {
 3195:     my ($url)=@_;
 3196:     my $request=new HTTP::Request('GET',$url);
 3197:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
 3198:     if (wantarray) {
 3199:         return ($response->content, $response);
 3200:     } else {
 3201:         return $response->content;
 3202:     }
 3203: }
 3204: 
 3205: 
 3206: # If the local copy of a replicated resource is outdated, trigger a  
 3207: # connection from the homeserver to flush the delayed queue. If no update 
 3208: # happens, remove local copies of outdated resource (and corresponding
 3209: # metadata file).
 3210: 
 3211: sub remove_stale_resfile {
 3212:     my ($url) = @_;
 3213:     my $removed;
 3214:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
 3215:         my $audom = $1;
 3216:         my $auname = $2;
 3217:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
 3218:             my $homeserver = &homeserver($auname,$audom);
 3219:             unless (($homeserver eq 'no_host') ||
 3220:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
 3221:                 my $fname = &filelocation('',$url);
 3222:                 if (-e $fname) {
 3223:                     my $protocol = $protocol{$homeserver};
 3224:                     $protocol = 'http' if ($protocol ne 'https');
 3225:                     my $hostname = &hostname($homeserver);
 3226:                     if ($hostname) {
 3227:                         my $uri = &declutter($url);
 3228:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
 3229:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
 3230:                         if ($response->is_success()) {
 3231:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
 3232:                             my $locmodtime = (stat($fname))[9];
 3233:                             if ($locmodtime < $remmodtime) {
 3234:                                 my $stale;
 3235:                                 my $answer = &reply('pong',$homeserver);
 3236:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
 3237:                                     sleep(0.2);
 3238:                                     $locmodtime = (stat($fname))[9];
 3239:                                     if ($locmodtime < $remmodtime) {
 3240:                                         my $posstransfer = $fname.'.in.transfer';
 3241:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
 3242:                                             $removed = 1;
 3243:                                         } else {
 3244:                                             $stale = 1;
 3245:                                         }
 3246:                                     } else {
 3247:                                         $removed = 1;
 3248:                                     }
 3249:                                 } else {
 3250:                                     $stale = 1;
 3251:                                 }
 3252:                                 if ($stale) {
 3253:                                     unlink($fname);
 3254:                                     if ($uri!~/\.meta$/) {
 3255:                                         unlink($fname.'.meta');
 3256:                                     }
 3257:                                     &reply("unsub:$fname",$homeserver);
 3258:                                     $removed = 1;
 3259:                                 }
 3260:                             }
 3261:                         }
 3262:                     }
 3263:                 }
 3264:             }
 3265:         }
 3266:     }
 3267:     return $removed;
 3268: }
 3269: 
 3270: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 3271: 
 3272: sub allowuploaded {
 3273:     my ($srcurl,$url)=@_;
 3274:     $url=&clutter(&declutter($url));
 3275:     my $dir=$url;
 3276:     $dir=~s/\/[^\/]+$//;
 3277:     my %httpref=();
 3278:     my $httpurl=&hreflocation('',$url);
 3279:     $httpref{'httpref.'.$httpurl}=$srcurl;
 3280:     &Apache::lonnet::appenv(\%httpref);
 3281: }
 3282: 
 3283: #
 3284: # Determine if the current user should be able to edit a particular resource,
 3285: # when viewing in course context.
 3286: # (a) When viewing resource used to determine if "Edit" item is included in 
 3287: #     Functions.
 3288: # (b) When displaying folder contents in course editor, used to determine if
 3289: #     "Edit" link will be displayed alongside resource.
 3290: #
 3291: #  input: six args -- filename (decluttered), course number, course domain,
 3292: #                   url, symb (if registered) and group (if this is a group
 3293: #                   item -- e.g., bulletin board, group page etc.).
 3294: #  output: array of five scalars -- 
 3295: #          $cfile -- url for file editing if editable on current server
 3296: #          $home -- homeserver of resource (i.e., for author if published,
 3297: #                                           or course if uploaded.).
 3298: #          $switchserver --  1 if server switch will be needed.
 3299: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 3300: #          $forceview -- 1 if icon/link should be to go to view mode
 3301: #
 3302: 
 3303: sub can_edit_resource {
 3304:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 3305:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 3306: #
 3307: # For aboutme pages user can only edit his/her own.
 3308: #
 3309:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 3310:         my ($sdom,$sname) = ($1,$2);
 3311:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 3312:             $home = $env{'user.home'};
 3313:             $cfile = $resurl;
 3314:             if ($env{'form.forceedit'}) {
 3315:                 $forceview = 1;
 3316:             } else {
 3317:                 $forceedit = 1;
 3318:             }
 3319:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3320:         } else {
 3321:             return;
 3322:         }
 3323:     }
 3324: 
 3325:     if ($env{'request.course.id'}) {
 3326:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 3327:         if ($group ne '') {
 3328: # if this is a group homepage or group bulletin board, check group privs
 3329:             my $allowed = 0;
 3330:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 3331:                 if ((&allowed('mdg',$env{'request.course.id'}.
 3332:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3333:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3334:                     $allowed = 1;
 3335:                 }
 3336:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 3337:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3338:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3339:                     $allowed = 1;
 3340:                 }
 3341:             }
 3342:             if ($allowed) {
 3343:                 $home=&homeserver($cnum,$cdom);
 3344:                 if ($env{'form.forceedit'}) {
 3345:                     $forceview = 1;
 3346:                 } else {
 3347:                     $forceedit = 1;
 3348:                 }
 3349:                 $cfile = $resurl;
 3350:             } else {
 3351:                 return;
 3352:             }
 3353:         } else {
 3354:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 3355:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 3356:                     return;
 3357:                 }
 3358:             } elsif (!$crsedit) {
 3359: #
 3360: # No edit allowed where CC has switched to student role.
 3361: #
 3362:                 return;
 3363:             }
 3364:         }
 3365:     }
 3366: 
 3367:     if ($file ne '') {
 3368:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 3369:             if (&is_course_upload($file,$cnum,$cdom)) {
 3370:                 $uploaded = 1;
 3371:                 $incourse = 1;
 3372:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 3373:                     $cfile = &hreflocation('',$file);
 3374:                     if ($env{'form.forceedit'}) {
 3375:                         $forceview = 1;
 3376:                     } else {
 3377:                         $forceedit = 1;
 3378:                     }
 3379:                 }
 3380:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 3381:                 $incourse = 1;
 3382:                 if ($env{'form.forceedit'}) {
 3383:                     $forceview = 1;
 3384:                 } else {
 3385:                     $forceedit = 1;
 3386:                 }
 3387:                 $cfile = $resurl;
 3388:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 3389:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 3390:                     $incourse = 1;
 3391:                     if ($env{'form.forceedit'}) {
 3392:                         $forceview = 1;
 3393:                     } else {
 3394:                         $forceedit = 1;
 3395:                     }
 3396:                     $cfile = $resurl;
 3397:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 3398:                     $incourse = 1;
 3399:                     $cfile = $resurl.'/smpedit';
 3400:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 3401:                     $incourse = 1;
 3402:                     if ($env{'form.forceedit'}) {
 3403:                         $forceview = 1;
 3404:                     } else {
 3405:                         $forceedit = 1;
 3406:                     }
 3407:                     $cfile = $resurl;
 3408:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3409:                     $incourse = 1;
 3410:                     if ($env{'form.forceedit'}) {
 3411:                         $forceview = 1;
 3412:                     } else {
 3413:                         $forceedit = 1;
 3414:                     }
 3415:                     $cfile = $resurl;
 3416:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3417:                     $incourse = 1;
 3418:                     if ($env{'form.forceedit'}) {
 3419:                         $forceview = 1;
 3420:                     } else {
 3421:                         $forceedit = 1;
 3422:                     }
 3423:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3424:                 }
 3425:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 3426:                 my $template = '/res/lib/templates/simpleproblem.problem';
 3427:                 if (&is_on_map($template)) { 
 3428:                     $incourse = 1;
 3429:                     $forceview = 1;
 3430:                     $cfile = $template;
 3431:                 }
 3432:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3433:                     $incourse = 1;
 3434:                     if ($env{'form.forceedit'}) {
 3435:                         $forceview = 1;
 3436:                     } else {
 3437:                         $forceedit = 1;
 3438:                     }
 3439:                     $cfile = $resurl;
 3440:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3441:                 $incourse = 1;
 3442:                 if ($env{'form.forceedit'}) {
 3443:                     $forceview = 1;
 3444:                 } else {
 3445:                     $forceedit = 1;
 3446:                 }
 3447:                 $cfile = $resurl;
 3448:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 3449:                 $incourse = 1;
 3450:                 $forceview = 1;
 3451:                 if ($symb) {
 3452:                     my ($map,$id,$res)=&decode_symb($symb);
 3453:                     $env{'request.symb'} = $symb;
 3454:                     $cfile = &clutter($res);
 3455:                 } else {
 3456:                     $cfile = $env{'form.suppurl'};
 3457:                     my $escfile = &unescape($cfile);
 3458:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3459:                         $cfile = '/adm/wrapper'.$escfile;
 3460:                     } else {
 3461:                         $escfile =~ s{^http://}{};
 3462:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
 3463:                     }
 3464:                 }
 3465:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3466:                 if ($env{'form.forceedit'}) {
 3467:                     $forceview = 1;
 3468:                 } else {
 3469:                     $forceedit = 1;
 3470:                 }
 3471:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3472:             }
 3473:         }
 3474:         if ($uploaded || $incourse) {
 3475:             $home=&homeserver($cnum,$cdom);
 3476:         } elsif ($file !~ m{/$}) {
 3477:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 3478:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 3479:             # Check that the user has permission to edit this resource
 3480:             my $setpriv = 1;
 3481:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 3482:             if (defined($cfudom)) {
 3483:                 $home=&homeserver($cfuname,$cfudom);
 3484:                 $cfile=$file;
 3485:             }
 3486:         }
 3487:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 3488:             (($home ne '') && ($home ne 'no_host'))) {
 3489:             my @ids=&current_machine_ids();
 3490:             unless (grep(/^\Q$home\E$/,@ids)) {
 3491:                 $switchserver=1;
 3492:             }
 3493:         }
 3494:     }
 3495:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3496: }
 3497: 
 3498: sub is_course_upload {
 3499:     my ($file,$cnum,$cdom) = @_;
 3500:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 3501:     $uploadpath =~ s{^\/}{};
 3502:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 3503:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 3504:         return 1;
 3505:     }
 3506:     return;
 3507: }
 3508: 
 3509: sub in_course {
 3510:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 3511:     if ($hideprivileged) {
 3512:         my $skipuser;
 3513:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 3514:         my @possdoms = ($cdom);  
 3515:         if ($coursehash{'checkforpriv'}) { 
 3516:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 3517:         }
 3518:         if (&privileged($uname,$udom,\@possdoms)) {
 3519:             $skipuser = 1;
 3520:             if ($coursehash{'nothideprivileged'}) {
 3521:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3522:                     my $user;
 3523:                     if ($item =~ /:/) {
 3524:                         $user = $item;
 3525:                     } else {
 3526:                         $user = join(':',split(/[\@]/,$item));
 3527:                     }
 3528:                     if ($user eq $uname.':'.$udom) {
 3529:                         undef($skipuser);
 3530:                         last;
 3531:                     }
 3532:                 }
 3533:             }
 3534:             if ($skipuser) {
 3535:                 return 0;
 3536:             }
 3537:         }
 3538:     }
 3539:     $type ||= 'any';
 3540:     if (!defined($cdom) || !defined($cnum)) {
 3541:         my $cid  = $env{'request.course.id'};
 3542:         $cdom = $env{'course.'.$cid.'.domain'};
 3543:         $cnum = $env{'course.'.$cid.'.num'};
 3544:     }
 3545:     my $typesref;
 3546:     if (($type eq 'any') || ($type eq 'all')) {
 3547:         $typesref = ['active','previous','future'];
 3548:     } elsif ($type eq 'previous' || $type eq 'future') {
 3549:         $typesref = [$type];
 3550:     }
 3551:     my %roles = &get_my_roles($uname,$udom,'userroles',
 3552:                               $typesref,undef,[$cdom]);
 3553:     my ($tmp) = keys(%roles);
 3554:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 3555:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 3556:     if (@course_roles > 0) {
 3557:         return 1;
 3558:     }
 3559:     return 0;
 3560: }
 3561: 
 3562: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 3563: # input: action, courseID, current domain, intended
 3564: #        path to file, source of file, instruction to parse file for objects,
 3565: #        ref to hash for embedded objects,
 3566: #        ref to hash for codebase of java objects.
 3567: #        reference to scalar to accommodate mime type determined
 3568: #          from File::MMagic if $parser = parse.
 3569: #
 3570: # output: url to file (if action was uploaddoc), 
 3571: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 3572: #
 3573: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 3574: # course.
 3575: #
 3576: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3577: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 3578: #          course's home server.
 3579: #
 3580: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 3581: #          be copied from $source (current location) to 
 3582: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3583: #         and will then be copied to
 3584: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 3585: #         course's home server.
 3586: #
 3587: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3588: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 3589: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3590: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 3591: #         in course's home server.
 3592: #
 3593: 
 3594: sub process_coursefile {
 3595:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 3596:         $mimetype)=@_;
 3597:     my $fetchresult;
 3598:     my $home=&homeserver($docuname,$docudom);
 3599:     if ($action eq 'propagate') {
 3600:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3601: 			     $home);
 3602:     } else {
 3603:         my $fpath = '';
 3604:         my $fname = $file;
 3605:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3606:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3607:         my $filepath = &build_filepath($fpath);
 3608:         if ($action eq 'copy') {
 3609:             if ($source eq '') {
 3610:                 $fetchresult = 'no source file';
 3611:                 return $fetchresult;
 3612:             } else {
 3613:                 my $destination = $filepath.'/'.$fname;
 3614:                 rename($source,$destination);
 3615:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3616:                                  $home);
 3617:             }
 3618:         } elsif ($action eq 'uploaddoc') {
 3619:             open(my $fh,'>',$filepath.'/'.$fname);
 3620:             print $fh $env{'form.'.$source};
 3621:             close($fh);
 3622:             if ($parser eq 'parse') {
 3623:                 my $mm = new File::MMagic;
 3624:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 3625:                 if ($type eq 'text/html') {
 3626:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 3627:                     unless ($parse_result eq 'ok') {
 3628:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 3629:                     }
 3630:                 }
 3631:                 if (ref($mimetype)) {
 3632:                     $$mimetype = $type;
 3633:                 } 
 3634:             }
 3635:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3636:                                  $home);
 3637:             if ($fetchresult eq 'ok') {
 3638:                 return '/uploaded/'.$fpath.'/'.$fname;
 3639:             } else {
 3640:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3641:                         ' to host '.$home.': '.$fetchresult);
 3642:                 return '/adm/notfound.html';
 3643:             }
 3644:         }
 3645:     }
 3646:     unless ( $fetchresult eq 'ok') {
 3647:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3648:              ' to host '.$home.': '.$fetchresult);
 3649:     }
 3650:     return $fetchresult;
 3651: }
 3652: 
 3653: sub build_filepath {
 3654:     my ($fpath) = @_;
 3655:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 3656:     unless ($fpath eq '') {
 3657:         my @parts=split('/',$fpath);
 3658:         foreach my $part (@parts) {
 3659:             $filepath.= '/'.$part;
 3660:             if ((-e $filepath)!=1) {
 3661:                 mkdir($filepath,0777);
 3662:             }
 3663:         }
 3664:     }
 3665:     return $filepath;
 3666: }
 3667: 
 3668: sub store_edited_file {
 3669:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 3670:     my $file = $primary_url;
 3671:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 3672:     my $fpath = '';
 3673:     my $fname = $file;
 3674:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3675:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3676:     my $filepath = &build_filepath($fpath);
 3677:     open(my $fh,'>',$filepath.'/'.$fname);
 3678:     print $fh $content;
 3679:     close($fh);
 3680:     my $home=&homeserver($docuname,$docudom);
 3681:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3682: 			  $home);
 3683:     if ($$fetchresult eq 'ok') {
 3684:         return '/uploaded/'.$fpath.'/'.$fname;
 3685:     } else {
 3686:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3687: 		 ' to host '.$home.': '.$$fetchresult);
 3688:         return '/adm/notfound.html';
 3689:     }
 3690: }
 3691: 
 3692: sub clean_filename {
 3693:     my ($fname,$args)=@_;
 3694: # Replace Windows backslashes by forward slashes
 3695:     $fname=~s/\\/\//g;
 3696:     if (!$args->{'keep_path'}) {
 3697:         # Get rid of everything but the actual filename
 3698: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 3699:     }
 3700: # Replace spaces by underscores
 3701:     $fname=~s/\s+/\_/g;
 3702: # Replace all other weird characters by nothing
 3703:     $fname=~s{[^/\w\.\-]}{}g;
 3704: # Replace all .\d. sequences with _\d. so they no longer look like version
 3705: # numbers
 3706:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 3707:     return $fname;
 3708: }
 3709: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 3710: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 3711: # image with the same aspect ratio as the original, but with dimensions which do 
 3712: # not exceed $resizewidth and $resizeheight.
 3713:  
 3714: sub resizeImage {
 3715:     my ($img_path,$resizewidth,$resizeheight) = @_;
 3716:     my $ima = Image::Magick->new;
 3717:     my $resized;
 3718:     if (-e $img_path) {
 3719:         $ima->Read($img_path);
 3720:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 3721:             my $width = $ima->Get('width');
 3722:             my $height = $ima->Get('height');
 3723:             if ($width > $resizewidth) {
 3724: 	        my $factor = $width/$resizewidth;
 3725:                 my $newheight = $height/$factor;
 3726:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 3727:                 $resized = 1;
 3728:             }
 3729:         }
 3730:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 3731:             my $width = $ima->Get('width');
 3732:             my $height = $ima->Get('height');
 3733:             if ($height > $resizeheight) {
 3734:                 my $factor = $height/$resizeheight;
 3735:                 my $newwidth = $width/$factor;
 3736:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 3737:                 $resized = 1;
 3738:             }
 3739:         }
 3740:         if ($resized) {
 3741:             $ima->Write($img_path);
 3742:         }
 3743:     }
 3744:     return;
 3745: }
 3746: 
 3747: # --------------- Take an uploaded file and put it into the userfiles directory
 3748: # input: $formname - the contents of the file are in $env{"form.$formname"}
 3749: #                    the desired filename is in $env{"form.$formname.filename"}
 3750: #        $context - possible values: coursedoc, existingfile, overwrite, 
 3751: #                                    canceloverwrite, or ''. 
 3752: #                   if 'coursedoc': upload to the current course
 3753: #                   if 'existingfile': write file to tmp/overwrites directory 
 3754: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 3755: #                   $context is passed as argument to &finishuserfileupload
 3756: #        $subdir - directory in userfile to store the file into
 3757: #        $parser - instruction to parse file for objects ($parser = parse)    
 3758: #        $allfiles - reference to hash for embedded objects
 3759: #        $codebase - reference to hash for codebase of java objects
 3760: #        $desuname - username for permanent storage of uploaded file
 3761: #        $dsetudom - domain for permanaent storage of uploaded file
 3762: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 3763: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 3764: #        $resizewidth - width (pixels) to which to resize uploaded image
 3765: #        $resizeheight - height (pixels) to which to resize uploaded image
 3766: #        $mimetype - reference to scalar to accommodate mime type determined
 3767: #                    from File::MMagic.
 3768: # 
 3769: # output: url of file in userspace, or error: <message> 
 3770: #             or /adm/notfound.html if failure to upload occurse
 3771: 
 3772: sub userfileupload {
 3773:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 3774:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 3775:     if (!defined($subdir)) { $subdir='unknown'; }
 3776:     my $fname=$env{'form.'.$formname.'.filename'};
 3777:     $fname=&clean_filename($fname);
 3778:     # See if there is anything left
 3779:     unless ($fname) { return 'error: no uploaded file'; }
 3780:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 3781:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 3782:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 3783:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3784:         my $now = time;
 3785:         my $filepath;
 3786:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 3787:              $filepath = 'tmp/helprequests/'.$now;
 3788:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 3789:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 3790:                          '_'.$env{'user.domain'}.'/pending';
 3791:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3792:             my ($docuname,$docudom);
 3793:             if ($destudom =~ /^$match_domain$/) {
 3794:                 $docudom = $destudom;
 3795:             } else {
 3796:                 $docudom = $env{'user.domain'};
 3797:             }
 3798:             if ($destuname =~ /^$match_username$/) {
 3799:                 $docuname = $destuname;
 3800:             } else {
 3801:                 $docuname = $env{'user.name'};
 3802:             }
 3803:             if (exists($env{'form.group'})) {
 3804:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3805:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3806:             }
 3807:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 3808:             if ($context eq 'canceloverwrite') {
 3809:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 3810:                 if (-e  $tempfile) {
 3811:                     my @info = stat($tempfile);
 3812:                     if ($info[9] eq $env{'form.timestamp'}) {
 3813:                         unlink($tempfile);
 3814:                     }
 3815:                 }
 3816:                 return;
 3817:             }
 3818:         }
 3819:         # Create the directory if not present
 3820:         my @parts=split(/\//,$filepath);
 3821:         my $fullpath = $perlvar{'lonDaemons'};
 3822:         for (my $i=0;$i<@parts;$i++) {
 3823:             $fullpath .= '/'.$parts[$i];
 3824:             if ((-e $fullpath)!=1) {
 3825:                 mkdir($fullpath,0777);
 3826:             }
 3827:         }
 3828:         open(my $fh,'>',$fullpath.'/'.$fname);
 3829:         print $fh $env{'form.'.$formname};
 3830:         close($fh);
 3831:         if ($context eq 'existingfile') {
 3832:             my @info = stat($fullpath.'/'.$fname);
 3833:             return ($fullpath.'/'.$fname,$info[9]);
 3834:         } else {
 3835:             return $fullpath.'/'.$fname;
 3836:         }
 3837:     }
 3838:     if ($subdir eq 'scantron') {
 3839:         $fname = 'scantron_orig_'.$fname;
 3840:     } else {
 3841:         $fname="$subdir/$fname";
 3842:     }
 3843:     if ($context eq 'coursedoc') {
 3844: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3845: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3846:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 3847:             return &finishuserfileupload($docuname,$docudom,
 3848: 					 $formname,$fname,$parser,$allfiles,
 3849: 					 $codebase,$thumbwidth,$thumbheight,
 3850:                                          $resizewidth,$resizeheight,$context,$mimetype);
 3851:         } else {
 3852:             if ($env{'form.folder'}) {
 3853:                 $fname=$env{'form.folder'}.'/'.$fname;
 3854:             }
 3855:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 3856: 				       $fname,$formname,$parser,
 3857: 				       $allfiles,$codebase,$mimetype);
 3858:         }
 3859:     } elsif (defined($destuname)) {
 3860:         my $docuname=$destuname;
 3861:         my $docudom=$destudom;
 3862: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3863: 				     $parser,$allfiles,$codebase,
 3864:                                      $thumbwidth,$thumbheight,
 3865:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3866:     } else {
 3867:         my $docuname=$env{'user.name'};
 3868:         my $docudom=$env{'user.domain'};
 3869:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 3870:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3871:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3872:         }
 3873: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3874: 				     $parser,$allfiles,$codebase,
 3875:                                      $thumbwidth,$thumbheight,
 3876:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3877:     }
 3878: }
 3879: 
 3880: sub finishuserfileupload {
 3881:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 3882:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 3883:     my $path=$docudom.'/'.$docuname.'/';
 3884:     my $filepath=$perlvar{'lonDocRoot'};
 3885:   
 3886:     my ($fnamepath,$file,$fetchthumb);
 3887:     $file=$fname;
 3888:     if ($fname=~m|/|) {
 3889:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 3890: 	$path.=$fnamepath.'/';
 3891:     }
 3892:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 3893:     my $count;
 3894:     for ($count=4;$count<=$#parts;$count++) {
 3895:         $filepath.="/$parts[$count]";
 3896:         if ((-e $filepath)!=1) {
 3897: 	    mkdir($filepath,0777);
 3898:         }
 3899:     }
 3900: 
 3901: # Save the file
 3902:     {
 3903: 	if (!open(FH,'>',$filepath.'/'.$file)) {
 3904: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 3905: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 3906: 	    return '/adm/notfound.html';
 3907: 	}
 3908:         if ($context eq 'overwrite') {
 3909:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 3910:             my $target = $filepath.'/'.$file;
 3911:             if (-e $source) {
 3912:                 my @info = stat($source);
 3913:                 if ($info[9] eq $env{'form.timestamp'}) {   
 3914:                     unless (&File::Copy::move($source,$target)) {
 3915:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 3916:                         return "Moving from $source failed";
 3917:                     }
 3918:                 } else {
 3919:                     return "Temporary file: $source had unexpected date/time for last modification";
 3920:                 }
 3921:             } else {
 3922:                 return "Temporary file: $source missing";
 3923:             }
 3924:         } elsif (!print FH ($env{'form.'.$formname})) {
 3925: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 3926: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 3927: 	    return '/adm/notfound.html';
 3928: 	}
 3929: 	close(FH);
 3930:         if ($resizewidth && $resizeheight) {
 3931:             my $mm = new File::MMagic;
 3932:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 3933:             if ($mime_type =~ m{^image/}) {
 3934: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 3935:             }  
 3936: 	}
 3937:     }
 3938:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 3939:         if (ref($mimetype)) {
 3940:             if ($$mimetype eq '') {
 3941:                 my $mm = new File::MMagic;
 3942:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 3943:                 $$mimetype = $type;
 3944:             }
 3945:         }
 3946:     }
 3947:     if ($parser eq 'parse') {
 3948:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 3949:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 3950:                                                        $allfiles,$codebase);
 3951:             unless ($parse_result eq 'ok') {
 3952:                 &logthis('Failed to parse '.$filepath.$file.
 3953: 	   	         ' for embedded media: '.$parse_result); 
 3954:             }
 3955:         }
 3956:     }
 3957:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 3958:         my $input = $filepath.'/'.$file;
 3959:         my $output = $filepath.'/'.'tn-'.$file;
 3960:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 3961:         my @args = ('convert','-sample',$thumbsize,$input,$output);
 3962:         system({$args[0]} @args);
 3963:         if (-e $filepath.'/'.'tn-'.$file) {
 3964:             $fetchthumb  = 1; 
 3965:         }
 3966:     }
 3967:  
 3968: # Notify homeserver to grep it
 3969: #
 3970:     my $docuhome=&homeserver($docuname,$docudom);	
 3971:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 3972:     if ($fetchresult eq 'ok') {
 3973:         if ($fetchthumb) {
 3974:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 3975:             if ($thumbresult ne 'ok') {
 3976:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 3977:                          $docuhome.': '.$thumbresult);
 3978:             }
 3979:         }
 3980: #
 3981: # Return the URL to it
 3982:         return '/uploaded/'.$path.$file;
 3983:     } else {
 3984:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 3985: 		 ': '.$fetchresult);
 3986:         return '/adm/notfound.html';
 3987:     }
 3988: }
 3989: 
 3990: sub extract_embedded_items {
 3991:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 3992:     my @state = ();
 3993:     my (%lastids,%related,%shockwave,%flashvars);
 3994:     my %javafiles = (
 3995:                       codebase => '',
 3996:                       code => '',
 3997:                       archive => ''
 3998:                     );
 3999:     my %mediafiles = (
 4000:                       src => '',
 4001:                       movie => '',
 4002:                      );
 4003:     my $p;
 4004:     if ($content) {
 4005:         $p = HTML::LCParser->new($content);
 4006:     } else {
 4007:         $p = HTML::LCParser->new($fullpath);
 4008:     }
 4009:     while (my $t=$p->get_token()) {
 4010: 	if ($t->[0] eq 'S') {
 4011: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 4012: 	    push(@state, $tagname);
 4013:             if (lc($tagname) eq 'allow') {
 4014:                 &add_filetype($allfiles,$attr->{'src'},'src');
 4015:             }
 4016: 	    if (lc($tagname) eq 'img') {
 4017: 		&add_filetype($allfiles,$attr->{'src'},'src');
 4018: 	    }
 4019: 	    if (lc($tagname) eq 'a') {
 4020:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 4021:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4022:                 }
 4023: 	    }
 4024:             if (lc($tagname) eq 'script') {
 4025:                 my $src;
 4026:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 4027:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 4028:                 } else {
 4029:                     if ($attr->{'src'} ne '') {
 4030:                         $src = $attr->{'src'};
 4031:                         &add_filetype($allfiles,$src,'src');
 4032:                     }
 4033:                 }
 4034:                 my $text = $p->get_trimmed_text();
 4035:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 4036:                     my @swfargs = split(/,/,$1);
 4037:                     foreach my $item (@swfargs) {
 4038:                         $item =~ s/["']//g;
 4039:                         $item =~ s/^\s+//;
 4040:                         $item =~ s/\s+$//;
 4041:                     }
 4042:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 4043:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 4044:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 4045:                         } else {
 4046:                             $related{$swfargs[0]} = [$swfargs[2]];
 4047:                         }
 4048:                     }
 4049:                 }
 4050:             }
 4051:             if (lc($tagname) eq 'link') {
 4052:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 4053:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4054:                 }
 4055:             }
 4056: 	    if (lc($tagname) eq 'object' ||
 4057: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 4058: 		foreach my $item (keys(%javafiles)) {
 4059: 		    $javafiles{$item} = '';
 4060: 		}
 4061:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 4062:                     $lastids{lc($tagname)} = $attr->{'id'};
 4063:                 }
 4064: 	    }
 4065: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 4066: 		my $name = lc($attr->{'name'});
 4067: 		foreach my $item (keys(%javafiles)) {
 4068: 		    if ($name eq $item) {
 4069: 			$javafiles{$item} = $attr->{'value'};
 4070: 			last;
 4071: 		    }
 4072: 		}
 4073:                 my $pathfrom;
 4074: 		foreach my $item (keys(%mediafiles)) {
 4075: 		    if ($name eq $item) {
 4076:                         $pathfrom = $attr->{'value'};
 4077:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 4078: 			&add_filetype($allfiles,$pathfrom,$name);
 4079: 			last;
 4080: 		    }
 4081: 		}
 4082:                 if ($name eq 'flashvars') {
 4083:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 4084:                 }
 4085:                 if ($pathfrom ne '') {
 4086:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 4087:                                          $pathfrom);
 4088:                 }
 4089: 	    }
 4090: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 4091: 		foreach my $item (keys(%javafiles)) {
 4092: 		    if ($attr->{$item}) {
 4093: 			$javafiles{$item} = $attr->{$item};
 4094: 			last;
 4095: 		    }
 4096: 		}
 4097: 		foreach my $item (keys(%mediafiles)) {
 4098: 		    if ($attr->{$item}) {
 4099: 			&add_filetype($allfiles,$attr->{$item},$item);
 4100: 			last;
 4101: 		    }
 4102: 		}
 4103:                 if (lc($tagname) eq 'embed') {
 4104:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 4105:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 4106:                                              $attr->{'src'});
 4107:                     }
 4108:                 }
 4109: 	    }
 4110:             if (lc($tagname) eq 'iframe') {
 4111:                 my $src = $attr->{'src'} ;
 4112:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 4113:                     &add_filetype($allfiles,$src,'src');
 4114:                 } elsif ($src =~ m{^/}) {
 4115:                     if ($env{'request.course.id'}) {
 4116:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4117:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4118:                         my $url = &hreflocation('',$fullpath);
 4119:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 4120:                             my $relpath = $1;
 4121:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 4122:                                 &add_filetype($allfiles,$1,'src');
 4123:                             }
 4124:                         }
 4125:                     }
 4126:                 }
 4127:             }
 4128:             if ($t->[4] =~ m{/>$}) {
 4129:                 pop(@state);
 4130:             }
 4131: 	} elsif ($t->[0] eq 'E') {
 4132: 	    my ($tagname) = ($t->[1]);
 4133: 	    if ($javafiles{'codebase'} ne '') {
 4134: 		$javafiles{'codebase'} .= '/';
 4135: 	    }  
 4136: 	    if (lc($tagname) eq 'applet' ||
 4137: 		lc($tagname) eq 'object' ||
 4138: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 4139: 		) {
 4140: 		foreach my $item (keys(%javafiles)) {
 4141: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 4142: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 4143: 			&add_filetype($allfiles,$file,$item);
 4144: 		    }
 4145: 		}
 4146: 	    } 
 4147: 	    pop @state;
 4148: 	}
 4149:     }
 4150:     foreach my $id (sort(keys(%flashvars))) {
 4151:         if ($shockwave{$id} ne '') {
 4152:             my @pairs = split(/\&/,$flashvars{$id});
 4153:             foreach my $pair (@pairs) {
 4154:                 my ($key,$value) = split(/\=/,$pair);
 4155:                 if ($key eq 'thumb') {
 4156:                     &add_filetype($allfiles,$value,$key);
 4157:                 } elsif ($key eq 'content') {
 4158:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 4159:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 4160:                     if ($ext ne '') {
 4161:                         &add_filetype($allfiles,$path.$value,$ext);
 4162:                     }
 4163:                 }
 4164:             }
 4165:         }
 4166:     }
 4167:     return 'ok';
 4168: }
 4169: 
 4170: sub add_filetype {
 4171:     my ($allfiles,$file,$type)=@_;
 4172:     if (exists($allfiles->{$file})) {
 4173: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 4174: 	    push(@{$allfiles->{$file}}, &escape($type));
 4175: 	}
 4176:     } else {
 4177: 	@{$allfiles->{$file}} = (&escape($type));
 4178:     }
 4179: }
 4180: 
 4181: sub embedded_dependency {
 4182:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 4183:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 4184:         if (($identifier ne '') &&
 4185:             (ref($related->{$identifier}) eq 'ARRAY') &&
 4186:             ($pathfrom ne '')) {
 4187:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 4188:             foreach my $dep (@{$related->{$identifier}}) {
 4189:                 &add_filetype($allfiles,$path.$dep,'object');
 4190:             }
 4191:         }
 4192:     }
 4193:     return;
 4194: }
 4195: 
 4196: sub removeuploadedurl {
 4197:     my ($url)=@_;	
 4198:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 4199:     return &removeuserfile($uname,$udom,$fname);
 4200: }
 4201: 
 4202: sub removeuserfile {
 4203:     my ($docuname,$docudom,$fname)=@_;
 4204:     my $home=&homeserver($docuname,$docudom);    
 4205:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 4206:     if ($result eq 'ok') {	
 4207:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 4208:             my $metafile = $fname.'.meta';
 4209:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 4210: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 4211:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 4212:             my $sqlresult = 
 4213:                 &update_portfolio_table($docuname,$docudom,$file,
 4214:                                         'portfolio_metadata',$group,
 4215:                                         'delete');
 4216:         }
 4217:     }
 4218:     return $result;
 4219: }
 4220: 
 4221: sub mkdiruserfile {
 4222:     my ($docuname,$docudom,$dir)=@_;
 4223:     my $home=&homeserver($docuname,$docudom);
 4224:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 4225: }
 4226: 
 4227: sub renameuserfile {
 4228:     my ($docuname,$docudom,$old,$new)=@_;
 4229:     my $home=&homeserver($docuname,$docudom);
 4230:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 4231:                         &escape("$old").':'.&escape("$new"),$home);
 4232:     if ($result eq 'ok') {
 4233:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 4234:             my $oldmeta = $old.'.meta';
 4235:             my $newmeta = $new.'.meta';
 4236:             my $metaresult = 
 4237:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 4238: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 4239:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 4240:             my $sqlresult = 
 4241:                 &update_portfolio_table($docuname,$docudom,$file,
 4242:                                         'portfolio_metadata',$group,
 4243:                                         'delete');
 4244:         }
 4245:     }
 4246:     return $result;
 4247: }
 4248: 
 4249: # ------------------------------------------------------------------------- Log
 4250: 
 4251: sub log {
 4252:     my ($dom,$nam,$hom,$what)=@_;
 4253:     return critical("log:$dom:$nam:$what",$hom);
 4254: }
 4255: 
 4256: # ------------------------------------------------------------------ Course Log
 4257: #
 4258: # This routine flushes several buffers of non-mission-critical nature
 4259: #
 4260: 
 4261: sub flushcourselogs {
 4262:     &logthis('Flushing log buffers');
 4263: #
 4264: # course logs
 4265: # This is a log of all transactions in a course, which can be used
 4266: # for data mining purposes
 4267: #
 4268: # It also collects the courseid database, which lists last transaction
 4269: # times and course titles for all courseids
 4270: #
 4271:     my %courseidbuffer=();
 4272:     foreach my $crsid (keys(%courselogs)) {
 4273:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 4274: 		          &escape($courselogs{$crsid}),
 4275: 		          $coursehombuf{$crsid}) eq 'ok') {
 4276: 	    delete $courselogs{$crsid};
 4277:         } else {
 4278:             &logthis('Failed to flush log buffer for '.$crsid);
 4279:             if (length($courselogs{$crsid})>40000) {
 4280:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 4281:                         " exceeded maximum size, deleting.</font>");
 4282:                delete $courselogs{$crsid};
 4283:             }
 4284:         }
 4285:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 4286:             'description' => $coursedescrbuf{$crsid},
 4287:             'inst_code'    => $courseinstcodebuf{$crsid},
 4288:             'type'        => $coursetypebuf{$crsid},
 4289:             'owner'       => $courseownerbuf{$crsid},
 4290:         };
 4291:     }
 4292: #
 4293: # Write course id database (reverse lookup) to homeserver of courses 
 4294: # Is used in pickcourse
 4295: #
 4296:     foreach my $crs_home (keys(%courseidbuffer)) {
 4297:         my $response = &courseidput(&host_domain($crs_home),
 4298:                                     $courseidbuffer{$crs_home},
 4299:                                     $crs_home,'timeonly');
 4300:     }
 4301: #
 4302: # File accesses
 4303: # Writes to the dynamic metadata of resources to get hit counts, etc.
 4304: #
 4305:     foreach my $entry (keys(%accesshash)) {
 4306:         if ($entry =~ /___count$/) {
 4307:             my ($dom,$name);
 4308:             ($dom,$name,undef)=
 4309: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 4310:             if (! defined($dom) || $dom eq '' || 
 4311:                 ! defined($name) || $name eq '') {
 4312:                 my $cid = $env{'request.course.id'};
 4313:                 $dom  = $env{'request.'.$cid.'.domain'};
 4314:                 $name = $env{'request.'.$cid.'.num'};
 4315:             }
 4316:             my $value = $accesshash{$entry};
 4317:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 4318:             my %temphash=($url => $value);
 4319:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 4320:             if ($result eq 'ok') {
 4321:                 delete $accesshash{$entry};
 4322:             }
 4323:         } else {
 4324:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 4325:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 4326:             my %temphash=($entry => $accesshash{$entry});
 4327:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 4328:                 delete $accesshash{$entry};
 4329:             }
 4330:         }
 4331:     }
 4332: #
 4333: # Roles
 4334: # Reverse lookup of user roles for course faculty/staff and co-authorship
 4335: #
 4336:     foreach my $entry (keys(%userrolehash)) {
 4337:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 4338: 	    split(/\:/,$entry);
 4339:         if (&Apache::lonnet::put('nohist_userroles',
 4340:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 4341:                 $rudom,$runame) eq 'ok') {
 4342: 	    delete $userrolehash{$entry};
 4343:         }
 4344:     }
 4345: #
 4346: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
 4347: #
 4348:     my %domrolebuffer = ();
 4349:     foreach my $entry (keys(%domainrolehash)) {
 4350:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 4351:         if ($domrolebuffer{$rudom}) {
 4352:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 4353:                       '='.&escape($domainrolehash{$entry});
 4354:         } else {
 4355:             $domrolebuffer{$rudom}.=&escape($entry).
 4356:                       '='.&escape($domainrolehash{$entry});
 4357:         }
 4358:         delete $domainrolehash{$entry};
 4359:     }
 4360:     foreach my $dom (keys(%domrolebuffer)) {
 4361: 	my %servers;
 4362: 	if (defined(&domain($dom,'primary'))) {
 4363: 	    my $primary=&domain($dom,'primary');
 4364: 	    my $hostname=&hostname($primary);
 4365: 	    $servers{$primary} = $hostname;
 4366: 	} else { 
 4367: 	    %servers = &get_servers($dom,'library');
 4368: 	}
 4369: 	foreach my $tryserver (keys(%servers)) {
 4370: 	    if (&reply('domroleput:'.$dom.':'.
 4371: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
 4372: 		last;
 4373: 	    } else {  
 4374: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 4375: 	    }
 4376:         }
 4377:     }
 4378:     $dumpcount++;
 4379: }
 4380: 
 4381: sub courselog {
 4382:     my $what=shift;
 4383:     $what=time.':'.$what;
 4384:     unless ($env{'request.course.id'}) { return ''; }
 4385:     $coursedombuf{$env{'request.course.id'}}=
 4386:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 4387:     $coursenumbuf{$env{'request.course.id'}}=
 4388:        $env{'course.'.$env{'request.course.id'}.'.num'};
 4389:     $coursehombuf{$env{'request.course.id'}}=
 4390:        $env{'course.'.$env{'request.course.id'}.'.home'};
 4391:     $coursedescrbuf{$env{'request.course.id'}}=
 4392:        $env{'course.'.$env{'request.course.id'}.'.description'};
 4393:     $courseinstcodebuf{$env{'request.course.id'}}=
 4394:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 4395:     $courseownerbuf{$env{'request.course.id'}}=
 4396:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 4397:     $coursetypebuf{$env{'request.course.id'}}=
 4398:        $env{'course.'.$env{'request.course.id'}.'.type'};
 4399:     if (defined $courselogs{$env{'request.course.id'}}) {
 4400: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 4401:     } else {
 4402: 	$courselogs{$env{'request.course.id'}}.=$what;
 4403:     }
 4404:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 4405: 	&flushcourselogs();
 4406:     }
 4407: }
 4408: 
 4409: sub courseacclog {
 4410:     my $fnsymb=shift;
 4411:     unless ($env{'request.course.id'}) { return ''; }
 4412:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 4413:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 4414:         $what.=':POST';
 4415:         # FIXME: Probably ought to escape things....
 4416: 	foreach my $key (keys(%env)) {
 4417:             if ($key=~/^form\.(.*)/) {
 4418:                 my $formitem = $1;
 4419:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 4420:                     $what.=':'.$formitem.'='.$env{$key};
 4421:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 4422:                     $what.=':'.$formitem.'='.$env{$key};
 4423:                 }
 4424:             }
 4425:         }
 4426:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 4427:         # FIXME: We should not be depending on a form parameter that someone
 4428:         # editing lonsearchcat.pm might change in the future.
 4429:         if ($env{'form.phase'} eq 'course_search') {
 4430:             $what.= ':POST';
 4431:             # FIXME: Probably ought to escape things....
 4432:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 4433:                                  'crsdiscuss') {
 4434:                 $what.=':'.$element.'='.$env{'form.'.$element};
 4435:             }
 4436:         }
 4437:     }
 4438:     &courselog($what);
 4439: }
 4440: 
 4441: sub countacc {
 4442:     my $url=&declutter(shift);
 4443:     return if (! defined($url) || $url eq '');
 4444:     unless ($env{'request.course.id'}) { return ''; }
 4445: #
 4446: # Mark that this url was used in this course
 4447: #
 4448:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 4449: #
 4450: # Increase the access count for this resource in this child process
 4451: #
 4452:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 4453:     $accesshash{$key}++;
 4454: }
 4455: 
 4456: sub linklog {
 4457:     my ($from,$to)=@_;
 4458:     $from=&declutter($from);
 4459:     $to=&declutter($to);
 4460:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 4461:     $accesshash{$to.'___'.$from.'___goto'}=1;
 4462: }
 4463: 
 4464: sub statslog {
 4465:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 4466:     if ($users<2) { return; }
 4467:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 4468:             'course'       => $env{'request.course.id'},
 4469:             'sections'     => '"all"',
 4470:             'num_students' => $users,
 4471:             'part'         => $part,
 4472:             'symb'         => $symb,
 4473:             'mean_tries'   => $av_attempts,
 4474:             'deg_of_diff'  => $degdiff});
 4475:     foreach my $key (keys(%dynstore)) {
 4476:         $accesshash{$key}=$dynstore{$key};
 4477:     }
 4478: }
 4479:   
 4480: sub userrolelog {
 4481:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 4482:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 4483:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4484:        $userrolehash
 4485:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4486:                     =$tend.':'.$tstart;
 4487:     }
 4488:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 4489:        $userrolehash
 4490:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 4491:                     =$tend.':'.$tstart;
 4492:     }
 4493:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
 4494:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4495:        $domainrolehash
 4496:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4497:                     = $tend.':'.$tstart;
 4498:     }
 4499: }
 4500: 
 4501: sub courserolelog {
 4502:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 4503:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 4504:         my $cdom = $1;
 4505:         my $cnum = $2;
 4506:         my $sec = $3;
 4507:         my $namespace = 'rolelog';
 4508:         my %storehash = (
 4509:                            role    => $trole,
 4510:                            start   => $tstart,
 4511:                            end     => $tend,
 4512:                            selfenroll => $selfenroll,
 4513:                            context    => $context,
 4514:                         );
 4515:         if ($trole eq 'gr') {
 4516:             $namespace = 'groupslog';
 4517:             $storehash{'group'} = $sec;
 4518:         } else {
 4519:             $storehash{'section'} = $sec;
 4520:         }
 4521:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 4522:                    $domain,$cnum,$cdom);
 4523:         if (($trole ne 'st') || ($sec ne '')) {
 4524:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 4525:         }
 4526:     }
 4527:     return;
 4528: }
 4529: 
 4530: sub domainrolelog {
 4531:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4532:     if ($area =~ m{^/($match_domain)/$}) {
 4533:         my $cdom = $1;
 4534:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 4535:         my $namespace = 'rolelog';
 4536:         my %storehash = (
 4537:                            role    => $trole,
 4538:                            start   => $tstart,
 4539:                            end     => $tend,
 4540:                            context => $context,
 4541:                         );
 4542:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 4543:                    $domain,$domconfiguser,$cdom);
 4544:     }
 4545:     return;
 4546: 
 4547: }
 4548: 
 4549: sub coauthorrolelog {
 4550:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4551:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 4552:         my $audom = $1;
 4553:         my $auname = $2;
 4554:         my $namespace = 'rolelog';
 4555:         my %storehash = (
 4556:                            role    => $trole,
 4557:                            start   => $tstart,
 4558:                            end     => $tend,
 4559:                            context => $context,
 4560:                         );
 4561:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 4562:                    $domain,$auname,$audom);
 4563:     }
 4564:     return;
 4565: }
 4566: 
 4567: sub get_course_adv_roles {
 4568:     my ($cid,$codes) = @_;
 4569:     $cid=$env{'request.course.id'} unless (defined($cid));
 4570:     my %coursehash=&coursedescription($cid);
 4571:     my $crstype = &Apache::loncommon::course_type($cid);
 4572:     my %nothide=();
 4573:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4574:         if ($user !~ /:/) {
 4575: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 4576:         } else {
 4577:             $nothide{$user}=1;
 4578:         }
 4579:     }
 4580:     my @possdoms = ($coursehash{'domain'});
 4581:     if ($coursehash{'checkforpriv'}) {
 4582:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 4583:     }
 4584:     my %returnhash=();
 4585:     my %dumphash=
 4586:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 4587:     my $now=time;
 4588:     my %privileged;
 4589:     foreach my $entry (keys(%dumphash)) {
 4590: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4591:         if (($tstart) && ($tstart<0)) { next; }
 4592:         if (($tend) && ($tend<$now)) { next; }
 4593:         if (($tstart) && ($now<$tstart)) { next; }
 4594:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 4595: 	if ($username eq '' || $domain eq '') { next; }
 4596:         if ((&privileged($username,$domain,\@possdoms)) &&
 4597:             (!$nothide{$username.':'.$domain})) { next; }
 4598: 	if ($role eq 'cr') { next; }
 4599:         if ($codes) {
 4600:             if ($section) { $role .= ':'.$section; }
 4601:             if ($returnhash{$role}) {
 4602:                 $returnhash{$role}.=','.$username.':'.$domain;
 4603:             } else {
 4604:                 $returnhash{$role}=$username.':'.$domain;
 4605:             }
 4606:         } else {
 4607:             my $key=&plaintext($role,$crstype);
 4608:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 4609:             if ($returnhash{$key}) {
 4610: 	        $returnhash{$key}.=','.$username.':'.$domain;
 4611:             } else {
 4612:                 $returnhash{$key}=$username.':'.$domain;
 4613:             }
 4614:         }
 4615:     }
 4616:     return %returnhash;
 4617: }
 4618: 
 4619: sub get_my_roles {
 4620:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 4621:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 4622:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 4623:     my (%dumphash,%nothide);
 4624:     if ($context eq 'userroles') {
 4625:         %dumphash = &dump('roles',$udom,$uname);
 4626:     } else {
 4627:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 4628:         if ($hidepriv) {
 4629:             my %coursehash=&coursedescription($udom.'_'.$uname);
 4630:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4631:                 if ($user !~ /:/) {
 4632:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 4633:                 } else {
 4634:                     $nothide{$user} = 1;
 4635:                 }
 4636:             }
 4637:         }
 4638:     }
 4639:     my %returnhash=();
 4640:     my $now=time;
 4641:     my %privileged;
 4642:     foreach my $entry (keys(%dumphash)) {
 4643:         my ($role,$tend,$tstart);
 4644:         if ($context eq 'userroles') {
 4645:             next if ($entry =~ /^rolesdef/);
 4646: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 4647:         } else {
 4648:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4649:         }
 4650:         if (($tstart) && ($tstart<0)) { next; }
 4651:         my $status = 'active';
 4652:         if (($tend) && ($tend<=$now)) {
 4653:             $status = 'previous';
 4654:         } 
 4655:         if (($tstart) && ($now<$tstart)) {
 4656:             $status = 'future';
 4657:         }
 4658:         if (ref($types) eq 'ARRAY') {
 4659:             if (!grep(/^\Q$status\E$/,@{$types})) {
 4660:                 next;
 4661:             } 
 4662:         } else {
 4663:             if ($status ne 'active') {
 4664:                 next;
 4665:             }
 4666:         }
 4667:         my ($rolecode,$username,$domain,$section,$area);
 4668:         if ($context eq 'userroles') {
 4669:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 4670:             (undef,$domain,$username,$section) = split(/\//,$area);
 4671:         } else {
 4672:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 4673:         }
 4674:         if (ref($roledoms) eq 'ARRAY') {
 4675:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 4676:                 next;
 4677:             }
 4678:         }
 4679:         if (ref($roles) eq 'ARRAY') {
 4680:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 4681:                 if ($role =~ /^cr\//) {
 4682:                     if (!grep(/^cr$/,@{$roles})) {
 4683:                         next;
 4684:                     }
 4685:                 } elsif ($role =~ /^gr\//) {
 4686:                     if (!grep(/^gr$/,@{$roles})) {
 4687:                         next;
 4688:                     }
 4689:                 } else {
 4690:                     next;
 4691:                 }
 4692:             }
 4693:         }
 4694:         if ($hidepriv) {
 4695:             my @privroles = ('dc','su');
 4696:             if ($context eq 'userroles') {
 4697:                 next if (grep(/^\Q$role\E$/,@privroles));
 4698:             } else {
 4699:                 my $possdoms = [$domain];
 4700:                 if (ref($roledoms) eq 'ARRAY') {
 4701:                    push(@{$possdoms},@{$roledoms}); 
 4702:                 }
 4703:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 4704:                     if (!$nothide{$username.':'.$domain}) {
 4705:                         next;
 4706:                     }
 4707:                 }
 4708:             }
 4709:         }
 4710:         if ($withsec) {
 4711:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 4712:                 $tstart.':'.$tend;
 4713:         } else {
 4714:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 4715:         }
 4716:     }
 4717:     return %returnhash;
 4718: }
 4719: 
 4720: sub get_all_adhocroles {
 4721:     my ($dom) = @_;
 4722:     my @roles_by_num = ();
 4723:     my %domdefaults = &get_domain_defaults($dom);
 4724:     my (%description,%access_in_dom,%access_info);
 4725:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
 4726:         my $count = 0;
 4727:         my %domcurrent = %{$domdefaults{'adhocroles'}};
 4728:         my %ordered;
 4729:         foreach my $role (sort(keys(%domcurrent))) {
 4730:             my ($order,$desc,$access_in_dom);
 4731:             if (ref($domcurrent{$role}) eq 'HASH') {
 4732:                 $order = $domcurrent{$role}{'order'};
 4733:                 $desc = $domcurrent{$role}{'desc'};
 4734:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
 4735:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
 4736:             }
 4737:             if ($order eq '') {
 4738:                 $order = $count;
 4739:             }
 4740:             $ordered{$order} = $role;
 4741:             if ($desc ne '') {
 4742:                 $description{$role} = $desc;
 4743:             } else {
 4744:                 $description{$role}= $role;
 4745:             }
 4746:             $count++;
 4747:         }
 4748:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 4749:             push(@roles_by_num,$ordered{$item});
 4750:         }
 4751:     }
 4752:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
 4753: }
 4754: 
 4755: sub get_my_adhocroles {
 4756:     my ($cid,$checkreg) = @_;
 4757:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
 4758:     if ($env{'request.course.id'} eq $cid) {
 4759:         $cdom = $env{'course.'.$cid.'.domain'};
 4760:         $cnum = $env{'course.'.$cid.'.num'};
 4761:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
 4762:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
 4763:         $cdom = $1;
 4764:         $cnum = $2;
 4765:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
 4766:                                      $cdom,$cnum);
 4767:     }
 4768:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
 4769:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
 4770:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
 4771:         if ($rosterhash{$user} ne '') {
 4772:             my $type = (split(/:/,$rosterhash{$user}))[5];
 4773:             return ([],{}) if ($type eq 'auto');
 4774:         }
 4775:     }
 4776:     if (($cdom ne '') && ($cnum ne ''))  {
 4777:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
 4778:             my $then=$env{'user.login.time'};
 4779:             my $update=$env{'user.update.time'};
 4780:             if (!$update) {
 4781:                 $update = $then;
 4782:             }
 4783:             my @liveroles;
 4784:             foreach my $role ('dh','da') {
 4785:                 if ($env{"user.role.$role./$cdom/"}) {
 4786:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
 4787:                     my $limit = $update;
 4788:                     if ($env{'request.role'} eq "$role./$cdom/") {
 4789:                         $limit = $then;
 4790:                     }
 4791:                     my $activerole = 1;
 4792:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
 4793:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
 4794:                     if ($activerole) {
 4795:                         push(@liveroles,$role);
 4796:                     }
 4797:                 }
 4798:             }
 4799:             if (@liveroles) {
 4800:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
 4801:                     my ($accessref,$accessinfo,%access_in_dom);
 4802:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
 4803:                     if (ref($roles_by_num) eq 'ARRAY') {
 4804:                         if (@{$roles_by_num}) {
 4805:                             my %settings;
 4806:                             if ($env{'request.course.id'} eq $cid) {
 4807:                                 foreach my $envkey (keys(%env)) {
 4808:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
 4809:                                         $settings{$1} = $env{$envkey};
 4810:                                     }
 4811:                                 }
 4812:                             } else {
 4813:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
 4814:                             }
 4815:                             my %setincrs;
 4816:                             if ($settings{'internal.adhocaccess'}) {
 4817:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
 4818:                             }
 4819:                             my @statuses;
 4820:                             if ($env{'environment.inststatus'}) {
 4821:                                 @statuses = split(/,/,$env{'environment.inststatus'});
 4822:                             }
 4823:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
 4824:                             if (ref($accessref) eq 'HASH') {
 4825:                                 %access_in_dom = %{$accessref};
 4826:                             }
 4827:                             foreach my $role (@{$roles_by_num}) {
 4828:                                 my ($curraccess,@okstatus,@personnel);
 4829:                                 if ($setincrs{$role}) {
 4830:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
 4831:                                     if ($curraccess eq 'status') {
 4832:                                         @okstatus = split(/\&/,$rest);
 4833:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 4834:                                         @personnel = split(/\&/,$rest);
 4835:                                     }
 4836:                                 } else {
 4837:                                     $curraccess = $access_in_dom{$role};
 4838:                                     if (ref($accessinfo) eq 'HASH') {
 4839:                                         if ($curraccess eq 'status') {
 4840:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 4841:                                                 @okstatus = @{$accessinfo->{$role}};
 4842:                                             }
 4843:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 4844:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 4845:                                                 @personnel = @{$accessinfo->{$role}};
 4846:                                             }
 4847:                                         }
 4848:                                     }
 4849:                                 }
 4850:                                 if ($curraccess eq 'none') {
 4851:                                     next;
 4852:                                 } elsif ($curraccess eq 'all') {
 4853:                                     push(@possroles,$role);
 4854:                                 } elsif ($curraccess eq 'dh') {
 4855:                                     if (grep(/^dh$/,@liveroles)) {
 4856:                                         push(@possroles,$role);
 4857:                                     } else {
 4858:                                         next;
 4859:                                     }
 4860:                                 } elsif ($curraccess eq 'da') {
 4861:                                     if (grep(/^da$/,@liveroles)) {
 4862:                                         push(@possroles,$role);
 4863:                                     } else {
 4864:                                         next;
 4865:                                     }
 4866:                                 } elsif ($curraccess eq 'status') {
 4867:                                     if (@okstatus) {
 4868:                                         if (!@statuses) {
 4869:                                             if (grep(/^default$/,@okstatus)) {
 4870:                                                 push(@possroles,$role);
 4871:                                             }
 4872:                                         } else {
 4873:                                             foreach my $status (@okstatus) {
 4874:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
 4875:                                                     push(@possroles,$role);
 4876:                                                     last;
 4877:                                                 }
 4878:                                             }
 4879:                                         }
 4880:                                     }
 4881:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 4882:                                     if (grep(/^\Q$user\E$/,@personnel)) {
 4883:                                         if ($curraccess eq 'exc') {
 4884:                                             push(@possroles,$role);
 4885:                                         }
 4886:                                     } elsif ($curraccess eq 'inc') {
 4887:                                         push(@possroles,$role);
 4888:                                     }
 4889:                                 }
 4890:                             }
 4891:                         }
 4892:                     }
 4893:                 }
 4894:             }
 4895:         }
 4896:     }
 4897:     unless (ref($description) eq 'HASH') {
 4898:         if (ref($roles_by_num) eq 'ARRAY') {
 4899:             my %desc;
 4900:             map { $desc{$_} = $_; } (@{$roles_by_num});
 4901:             $description = \%desc;
 4902:         } else {
 4903:             $description = {};
 4904:         }
 4905:     }
 4906:     return (\@possroles,$description);
 4907: }
 4908: 
 4909: # ----------------------------------------------------- Frontpage Announcements
 4910: #
 4911: #
 4912: 
 4913: sub postannounce {
 4914:     my ($server,$text)=@_;
 4915:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 4916:     unless ($text=~/\w/) { $text=''; }
 4917:     return &reply('setannounce:'.&escape($text),$server);
 4918: }
 4919: 
 4920: sub getannounce {
 4921: 
 4922:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 4923: 	my $announcement='';
 4924: 	while (my $line = <$fh>) { $announcement .= $line; }
 4925: 	close($fh);
 4926: 	if ($announcement=~/\w/) { 
 4927: 	    return 
 4928:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 4929:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 4930: 	} else {
 4931: 	    return '';
 4932: 	}
 4933:     } else {
 4934: 	return '';
 4935:     }
 4936: }
 4937: 
 4938: # ---------------------------------------------------------- Course ID routines
 4939: # Deal with domain's nohist_courseid.db files
 4940: #
 4941: 
 4942: sub courseidput {
 4943:     my ($domain,$storehash,$coursehome,$caller) = @_;
 4944:     return unless (ref($storehash) eq 'HASH');
 4945:     my $outcome;
 4946:     if ($caller eq 'timeonly') {
 4947:         my $cids = '';
 4948:         foreach my $item (keys(%$storehash)) {
 4949:             $cids.=&escape($item).'&';
 4950:         }
 4951:         $cids=~s/\&$//;
 4952:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 4953:                           $coursehome);       
 4954:     } else {
 4955:         my $items = '';
 4956:         foreach my $item (keys(%$storehash)) {
 4957:             $items.= &escape($item).'='.
 4958:                      &freeze_escape($$storehash{$item}).'&';
 4959:         }
 4960:         $items=~s/\&$//;
 4961:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 4962:                           $coursehome);
 4963:     }
 4964:     if ($outcome eq 'unknown_cmd') {
 4965:         my $what;
 4966:         foreach my $cid (keys(%$storehash)) {
 4967:             $what .= &escape($cid).'=';
 4968:             foreach my $item ('description','inst_code','owner','type') {
 4969:                 $what .= &escape($storehash->{$cid}{$item}).':';
 4970:             }
 4971:             $what =~ s/\:$/&/;
 4972:         }
 4973:         $what =~ s/\&$//;  
 4974:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 4975:     } else {
 4976:         return $outcome;
 4977:     }
 4978: }
 4979: 
 4980: sub courseiddump {
 4981:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 4982:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 4983:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 4984:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 4985:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
 4986:     my $as_hash = 1;
 4987:     my %returnhash;
 4988:     if (!$domfilter) { $domfilter=''; }
 4989:     my %libserv = &all_library();
 4990:     foreach my $tryserver (keys(%libserv)) {
 4991:         if ( (  $hostidflag == 1 
 4992: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 4993: 	     || (!defined($hostidflag)) ) {
 4994: 
 4995: 	    if (($domfilter eq '') ||
 4996: 		(&host_domain($tryserver) eq $domfilter)) {
 4997:                 my $rep;
 4998:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 4999:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 5000:                         join(":", (&host_domain($tryserver), $sincefilter, 
 5001:                                 &escape($descfilter), &escape($instcodefilter), 
 5002:                                 &escape($ownerfilter), &escape($coursefilter),
 5003:                                 &escape($typefilter), &escape($regexp_ok), 
 5004:                                 $as_hash, &escape($selfenrollonly), 
 5005:                                 &escape($catfilter), $showhidden, $caller, 
 5006:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 5007:                                 &escape($createdbefore), &escape($createdafter), 
 5008:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
 5009:                                 $reqcrsdom,&escape($reqinstcode))));
 5010:                 } else {
 5011:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 5012:                              $sincefilter.':'.&escape($descfilter).':'.
 5013:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 5014:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 5015:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 5016:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 5017:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 5018:                              &escape($cc_clone).':'.$cloneonly.':'.
 5019:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 5020:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
 5021:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
 5022:                 }
 5023:                      
 5024:                 my @pairs=split(/\&/,$rep);
 5025:                 foreach my $item (@pairs) {
 5026:                     my ($key,$value)=split(/\=/,$item,2);
 5027:                     $key = &unescape($key);
 5028:                     next if ($key =~ /^error: 2 /);
 5029:                     my $result = &thaw_unescape($value);
 5030:                     if (ref($result) eq 'HASH') {
 5031:                         $returnhash{$key}=$result;
 5032:                     } else {
 5033:                         my @responses = split(/:/,$value);
 5034:                         my @items = ('description','inst_code','owner','type');
 5035:                         for (my $i=0; $i<@responses; $i++) {
 5036:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 5037:                         }
 5038:                     }
 5039:                 }
 5040:             }
 5041:         }
 5042:     }
 5043:     return %returnhash;
 5044: }
 5045: 
 5046: sub courselastaccess {
 5047:     my ($cdom,$cnum,$hostidref) = @_;
 5048:     my %returnhash;
 5049:     if ($cdom && $cnum) {
 5050:         my $chome = &homeserver($cnum,$cdom);
 5051:         if ($chome ne 'no_host') {
 5052:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 5053:             &extract_lastaccess(\%returnhash,$rep);
 5054:         }
 5055:     } else {
 5056:         if (!$cdom) { $cdom=''; }
 5057:         my %libserv = &all_library();
 5058:         foreach my $tryserver (keys(%libserv)) {
 5059:             if (ref($hostidref) eq 'ARRAY') {
 5060:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 5061:             } 
 5062:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 5063:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 5064:                 &extract_lastaccess(\%returnhash,$rep);
 5065:             }
 5066:         }
 5067:     }
 5068:     return %returnhash;
 5069: }
 5070: 
 5071: sub extract_lastaccess {
 5072:     my ($returnhash,$rep) = @_;
 5073:     if (ref($returnhash) eq 'HASH') {
 5074:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 5075:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 5076:                  $rep eq '') {
 5077:             my @pairs=split(/\&/,$rep);
 5078:             foreach my $item (@pairs) {
 5079:                 my ($key,$value)=split(/\=/,$item,2);
 5080:                 $key = &unescape($key);
 5081:                 next if ($key =~ /^error: 2 /);
 5082:                 $returnhash->{$key} = &thaw_unescape($value);
 5083:             }
 5084:         }
 5085:     }
 5086:     return;
 5087: }
 5088: 
 5089: # ---------------------------------------------------------- DC e-mail
 5090: 
 5091: sub dcmailput {
 5092:     my ($domain,$msgid,$message,$server)=@_;
 5093:     my $status = &Apache::lonnet::critical(
 5094:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 5095:        &escape($message),$server);
 5096:     return $status;
 5097: }
 5098: 
 5099: sub dcmaildump {
 5100:     my ($dom,$startdate,$enddate,$senders) = @_;
 5101:     my %returnhash=();
 5102: 
 5103:     if (defined(&domain($dom,'primary'))) {
 5104:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 5105:                                                          &escape($enddate).':';
 5106: 	my @esc_senders=map { &escape($_)} @$senders;
 5107: 	$cmd.=&escape(join('&',@esc_senders));
 5108: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 5109:             my ($key,$value) = split(/\=/,$line,2);
 5110:             if (($key) && ($value)) {
 5111:                 $returnhash{&unescape($key)} = &unescape($value);
 5112:             }
 5113:         }
 5114:     }
 5115:     return %returnhash;
 5116: }
 5117: # ---------------------------------------------------------- Domain roles
 5118: 
 5119: sub get_domain_roles {
 5120:     my ($dom,$roles,$startdate,$enddate)=@_;
 5121:     if ((!defined($startdate)) || ($startdate eq '')) {
 5122:         $startdate = '.';
 5123:     }
 5124:     if ((!defined($enddate)) || ($enddate eq '')) {
 5125:         $enddate = '.';
 5126:     }
 5127:     my $rolelist;
 5128:     if (ref($roles) eq 'ARRAY') {
 5129:         $rolelist = join('&',@{$roles});
 5130:     }
 5131:     my %personnel = ();
 5132: 
 5133:     my %servers = &get_servers($dom,'library');
 5134:     foreach my $tryserver (keys(%servers)) {
 5135: 	%{$personnel{$tryserver}}=();
 5136: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 5137: 					    &escape($startdate).':'.
 5138: 					    &escape($enddate).':'.
 5139: 					    &escape($rolelist), $tryserver))) {
 5140: 	    my ($key,$value) = split(/\=/,$line,2);
 5141: 	    if (($key) && ($value)) {
 5142: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 5143: 	    }
 5144: 	}
 5145:     }
 5146:     return %personnel;
 5147: }
 5148: 
 5149: sub get_active_domroles {
 5150:     my ($dom,$roles) = @_;
 5151:     return () unless (ref($roles) eq 'ARRAY');
 5152:     my $now = time;
 5153:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
 5154:     my %domroles;
 5155:     foreach my $server (keys(%dompersonnel)) {
 5156:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
 5157:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
 5158:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
 5159:         }
 5160:     }
 5161:     return %domroles;
 5162: }
 5163: 
 5164: # ----------------------------------------------------------- Interval timing 
 5165: 
 5166: {
 5167: # Caches needed for speedup of navmaps
 5168: # We don't want to cache this for very long at all (5 seconds at most)
 5169: # 
 5170: # The user for whom we cache
 5171: my $cachedkey='';
 5172: # The cached times for this user
 5173: my %cachedtimes=();
 5174: # When this was last done
 5175: my $cachedtime='';
 5176: 
 5177: sub load_all_first_access {
 5178:     my ($uname,$udom,$ignorecache)=@_;
 5179:     if (($cachedkey eq $uname.':'.$udom) &&
 5180:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
 5181:         (!$ignorecache)) {
 5182:         return;
 5183:     }
 5184:     $cachedtime=time;
 5185:     $cachedkey=$uname.':'.$udom;
 5186:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 5187: }
 5188: 
 5189: sub get_first_access {
 5190:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
 5191:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5192:     if ($argsymb) { $symb=$argsymb; }
 5193:     my ($map,$id,$res)=&decode_symb($symb);
 5194:     if ($argmap) { $map = $argmap; }
 5195:     if ($type eq 'course') {
 5196: 	$res='course';
 5197:     } elsif ($type eq 'map') {
 5198: 	$res=&symbread($map);
 5199:     } else {
 5200: 	$res=$symb;
 5201:     }
 5202:     &load_all_first_access($uname,$udom,$ignorecache);
 5203:     return $cachedtimes{"$courseid\0$res"};
 5204: }
 5205: 
 5206: sub set_first_access {
 5207:     my ($type,$interval)=@_;
 5208:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5209:     my ($map,$id,$res)=&decode_symb($symb);
 5210:     if ($type eq 'course') {
 5211: 	$res='course';
 5212:     } elsif ($type eq 'map') {
 5213: 	$res=&symbread($map);
 5214:     } else {
 5215: 	$res=$symb;
 5216:     }
 5217:     $cachedkey='';
 5218:     my $firstaccess=&get_first_access($type,$symb,$map);
 5219:     if (!$firstaccess) {
 5220:         my $start = time;
 5221: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 5222:                           $udom,$uname);
 5223:         if ($putres eq 'ok') {
 5224:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 5225:                  $udom,$uname); 
 5226:             &appenv(
 5227:                      {
 5228:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 5229:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 5230:                      }
 5231:                   );
 5232:         }
 5233:         return $putres;
 5234:     }
 5235:     return 'already_set';
 5236: }
 5237: }
 5238: 
 5239: # --------------------------------------------- Set Expire Date for Spreadsheet
 5240: 
 5241: sub expirespread {
 5242:     my ($uname,$udom,$stype,$usymb)=@_;
 5243:     my $cid=$env{'request.course.id'}; 
 5244:     if ($cid) {
 5245:        my $now=time;
 5246:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 5247:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 5248:                             $env{'course.'.$cid.'.num'}.
 5249: 	        	    ':nohist_expirationdates:'.
 5250:                             &escape($key).'='.$now,
 5251:                             $env{'course.'.$cid.'.home'})
 5252:     }
 5253:     return 'ok';
 5254: }
 5255: 
 5256: # ----------------------------------------------------- Devalidate Spreadsheets
 5257: 
 5258: sub devalidate {
 5259:     my ($symb,$uname,$udom)=@_;
 5260:     my $cid=$env{'request.course.id'}; 
 5261:     if ($cid) {
 5262:         # delete the stored spreadsheets for
 5263:         # - the student level sheet of this user in course's homespace
 5264:         # - the assessment level sheet for this resource 
 5265:         #   for this user in user's homespace
 5266: 	# - current conditional state info
 5267: 	my $key=$uname.':'.$udom.':';
 5268:         my $status=
 5269: 	    &del('nohist_calculatedsheets',
 5270: 		 [$key.'studentcalc:'],
 5271: 		 $env{'course.'.$cid.'.domain'},
 5272: 		 $env{'course.'.$cid.'.num'})
 5273: 		.' '.
 5274: 	    &del('nohist_calculatedsheets_'.$cid,
 5275: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 5276:         unless ($status eq 'ok ok') {
 5277:            &logthis('Could not devalidate spreadsheet '.
 5278:                     $uname.' at '.$udom.' for '.
 5279: 		    $symb.': '.$status);
 5280:         }
 5281: 	&delenv('user.state.'.$cid);
 5282:     }
 5283: }
 5284: 
 5285: sub get_scalar {
 5286:     my ($string,$end) = @_;
 5287:     my $value;
 5288:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 5289: 	$value = $1;
 5290:     } elsif ($$string =~ s/^([^&]*?)&//) {
 5291: 	$value = $1;
 5292:     }
 5293:     return &unescape($value);
 5294: }
 5295: 
 5296: sub array2str {
 5297:   my (@array) = @_;
 5298:   my $result=&arrayref2str(\@array);
 5299:   $result=~s/^__ARRAY_REF__//;
 5300:   $result=~s/__END_ARRAY_REF__$//;
 5301:   return $result;
 5302: }
 5303: 
 5304: sub arrayref2str {
 5305:   my ($arrayref) = @_;
 5306:   my $result='__ARRAY_REF__';
 5307:   foreach my $elem (@$arrayref) {
 5308:     if(ref($elem) eq 'ARRAY') {
 5309:       $result.=&arrayref2str($elem).'&';
 5310:     } elsif(ref($elem) eq 'HASH') {
 5311:       $result.=&hashref2str($elem).'&';
 5312:     } elsif(ref($elem)) {
 5313:       #print("Got a ref of ".(ref($elem))." skipping.");
 5314:     } else {
 5315:       $result.=&escape($elem).'&';
 5316:     }
 5317:   }
 5318:   $result=~s/\&$//;
 5319:   $result .= '__END_ARRAY_REF__';
 5320:   return $result;
 5321: }
 5322: 
 5323: sub hash2str {
 5324:   my (%hash) = @_;
 5325:   my $result=&hashref2str(\%hash);
 5326:   $result=~s/^__HASH_REF__//;
 5327:   $result=~s/__END_HASH_REF__$//;
 5328:   return $result;
 5329: }
 5330: 
 5331: sub hashref2str {
 5332:   my ($hashref)=@_;
 5333:   my $result='__HASH_REF__';
 5334:   foreach my $key (sort(keys(%$hashref))) {
 5335:     if (ref($key) eq 'ARRAY') {
 5336:       $result.=&arrayref2str($key).'=';
 5337:     } elsif (ref($key) eq 'HASH') {
 5338:       $result.=&hashref2str($key).'=';
 5339:     } elsif (ref($key)) {
 5340:       $result.='=';
 5341:       #print("Got a ref of ".(ref($key))." skipping.");
 5342:     } else {
 5343: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 5344:     }
 5345: 
 5346:     if(ref($hashref->{$key}) eq 'ARRAY') {
 5347:       $result.=&arrayref2str($hashref->{$key}).'&';
 5348:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 5349:       $result.=&hashref2str($hashref->{$key}).'&';
 5350:     } elsif(ref($hashref->{$key})) {
 5351:        $result.='&';
 5352:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 5353:     } else {
 5354:       $result.=&escape($hashref->{$key}).'&';
 5355:     }
 5356:   }
 5357:   $result=~s/\&$//;
 5358:   $result .= '__END_HASH_REF__';
 5359:   return $result;
 5360: }
 5361: 
 5362: sub str2hash {
 5363:     my ($string)=@_;
 5364:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 5365:     return %$hash;
 5366: }
 5367: 
 5368: sub str2hashref {
 5369:   my ($string) = @_;
 5370: 
 5371:   my %hash;
 5372: 
 5373:   if($string !~ /^__HASH_REF__/) {
 5374:       if (! ($string eq '' || !defined($string))) {
 5375: 	  $hash{'error'}='Not hash reference';
 5376:       }
 5377:       return (\%hash, $string);
 5378:   }
 5379: 
 5380:   $string =~ s/^__HASH_REF__//;
 5381: 
 5382:   while($string !~ /^__END_HASH_REF__/) {
 5383:       #key
 5384:       my $key='';
 5385:       if($string =~ /^__HASH_REF__/) {
 5386:           ($key, $string)=&str2hashref($string);
 5387:           if(defined($key->{'error'})) {
 5388:               $hash{'error'}='Bad data';
 5389:               return (\%hash, $string);
 5390:           }
 5391:       } elsif($string =~ /^__ARRAY_REF__/) {
 5392:           ($key, $string)=&str2arrayref($string);
 5393:           if($key->[0] eq 'Array reference error') {
 5394:               $hash{'error'}='Bad data';
 5395:               return (\%hash, $string);
 5396:           }
 5397:       } else {
 5398:           $string =~ s/^(.*?)=//;
 5399: 	  $key=&unescape($1);
 5400:       }
 5401:       $string =~ s/^=//;
 5402: 
 5403:       #value
 5404:       my $value='';
 5405:       if($string =~ /^__HASH_REF__/) {
 5406:           ($value, $string)=&str2hashref($string);
 5407:           if(defined($value->{'error'})) {
 5408:               $hash{'error'}='Bad data';
 5409:               return (\%hash, $string);
 5410:           }
 5411:       } elsif($string =~ /^__ARRAY_REF__/) {
 5412:           ($value, $string)=&str2arrayref($string);
 5413:           if($value->[0] eq 'Array reference error') {
 5414:               $hash{'error'}='Bad data';
 5415:               return (\%hash, $string);
 5416:           }
 5417:       } else {
 5418: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 5419:       }
 5420:       $string =~ s/^&//;
 5421: 
 5422:       $hash{$key}=$value;
 5423:   }
 5424: 
 5425:   $string =~ s/^__END_HASH_REF__//;
 5426: 
 5427:   return (\%hash, $string);
 5428: }
 5429: 
 5430: sub str2array {
 5431:     my ($string)=@_;
 5432:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 5433:     return @$array;
 5434: }
 5435: 
 5436: sub str2arrayref {
 5437:   my ($string) = @_;
 5438:   my @array;
 5439: 
 5440:   if($string !~ /^__ARRAY_REF__/) {
 5441:       if (! ($string eq '' || !defined($string))) {
 5442: 	  $array[0]='Array reference error';
 5443:       }
 5444:       return (\@array, $string);
 5445:   }
 5446: 
 5447:   $string =~ s/^__ARRAY_REF__//;
 5448: 
 5449:   while($string !~ /^__END_ARRAY_REF__/) {
 5450:       my $value='';
 5451:       if($string =~ /^__HASH_REF__/) {
 5452:           ($value, $string)=&str2hashref($string);
 5453:           if(defined($value->{'error'})) {
 5454:               $array[0] ='Array reference error';
 5455:               return (\@array, $string);
 5456:           }
 5457:       } elsif($string =~ /^__ARRAY_REF__/) {
 5458:           ($value, $string)=&str2arrayref($string);
 5459:           if($value->[0] eq 'Array reference error') {
 5460:               $array[0] ='Array reference error';
 5461:               return (\@array, $string);
 5462:           }
 5463:       } else {
 5464: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 5465:       }
 5466:       $string =~ s/^&//;
 5467: 
 5468:       push(@array, $value);
 5469:   }
 5470: 
 5471:   $string =~ s/^__END_ARRAY_REF__//;
 5472: 
 5473:   return (\@array, $string);
 5474: }
 5475: 
 5476: # -------------------------------------------------------------------Temp Store
 5477: 
 5478: sub tmpreset {
 5479:   my ($symb,$namespace,$domain,$stuname) = @_;
 5480:   if (!$symb) {
 5481:     $symb=&symbread();
 5482:     if (!$symb) { $symb= $env{'request.url'}; }
 5483:   }
 5484:   $symb=escape($symb);
 5485: 
 5486:   if (!$namespace) { $namespace=$env{'request.state'}; }
 5487:   $namespace=~s/\//\_/g;
 5488:   $namespace=~s/\W//g;
 5489: 
 5490:   if (!$domain) { $domain=$env{'user.domain'}; }
 5491:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5492:   if ($domain eq 'public' && $stuname eq 'public') {
 5493:       $stuname=$ENV{'REMOTE_ADDR'};
 5494:   }
 5495:   my $path=LONCAPA::tempdir();
 5496:   my %hash;
 5497:   if (tie(%hash,'GDBM_File',
 5498: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5499: 	  &GDBM_WRCREAT(),0640)) {
 5500:     foreach my $key (keys(%hash)) {
 5501:       if ($key=~ /:$symb/) {
 5502: 	delete($hash{$key});
 5503:       }
 5504:     }
 5505:   }
 5506: }
 5507: 
 5508: sub tmpstore {
 5509:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 5510: 
 5511:   if (!$symb) {
 5512:     $symb=&symbread();
 5513:     if (!$symb) { $symb= $env{'request.url'}; }
 5514:   }
 5515:   $symb=escape($symb);
 5516: 
 5517:   if (!$namespace) {
 5518:     # I don't think we would ever want to store this for a course.
 5519:     # it seems this will only be used if we don't have a course.
 5520:     #$namespace=$env{'request.course.id'};
 5521:     #if (!$namespace) {
 5522:       $namespace=$env{'request.state'};
 5523:     #}
 5524:   }
 5525:   $namespace=~s/\//\_/g;
 5526:   $namespace=~s/\W//g;
 5527:   if (!$domain) { $domain=$env{'user.domain'}; }
 5528:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5529:   if ($domain eq 'public' && $stuname eq 'public') {
 5530:       $stuname=$ENV{'REMOTE_ADDR'};
 5531:   }
 5532:   my $now=time;
 5533:   my %hash;
 5534:   my $path=LONCAPA::tempdir();
 5535:   if (tie(%hash,'GDBM_File',
 5536: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5537: 	  &GDBM_WRCREAT(),0640)) {
 5538:     $hash{"version:$symb"}++;
 5539:     my $version=$hash{"version:$symb"};
 5540:     my $allkeys=''; 
 5541:     foreach my $key (keys(%$storehash)) {
 5542:       $allkeys.=$key.':';
 5543:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 5544:     }
 5545:     $hash{"$version:$symb:timestamp"}=$now;
 5546:     $allkeys.='timestamp';
 5547:     $hash{"$version:keys:$symb"}=$allkeys;
 5548:     if (untie(%hash)) {
 5549:       return 'ok';
 5550:     } else {
 5551:       return "error:$!";
 5552:     }
 5553:   } else {
 5554:     return "error:$!";
 5555:   }
 5556: }
 5557: 
 5558: # -----------------------------------------------------------------Temp Restore
 5559: 
 5560: sub tmprestore {
 5561:   my ($symb,$namespace,$domain,$stuname) = @_;
 5562: 
 5563:   if (!$symb) {
 5564:     $symb=&symbread();
 5565:     if (!$symb) { $symb= $env{'request.url'}; }
 5566:   }
 5567:   $symb=escape($symb);
 5568: 
 5569:   if (!$namespace) { $namespace=$env{'request.state'}; }
 5570: 
 5571:   if (!$domain) { $domain=$env{'user.domain'}; }
 5572:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5573:   if ($domain eq 'public' && $stuname eq 'public') {
 5574:       $stuname=$ENV{'REMOTE_ADDR'};
 5575:   }
 5576:   my %returnhash;
 5577:   $namespace=~s/\//\_/g;
 5578:   $namespace=~s/\W//g;
 5579:   my %hash;
 5580:   my $path=LONCAPA::tempdir();
 5581:   if (tie(%hash,'GDBM_File',
 5582: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5583: 	  &GDBM_READER(),0640)) {
 5584:     my $version=$hash{"version:$symb"};
 5585:     $returnhash{'version'}=$version;
 5586:     my $scope;
 5587:     for ($scope=1;$scope<=$version;$scope++) {
 5588:       my $vkeys=$hash{"$scope:keys:$symb"};
 5589:       my @keys=split(/:/,$vkeys);
 5590:       my $key;
 5591:       $returnhash{"$scope:keys"}=$vkeys;
 5592:       foreach $key (@keys) {
 5593: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 5594: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 5595:       }
 5596:     }
 5597:     if (!(untie(%hash))) {
 5598:       return "error:$!";
 5599:     }
 5600:   } else {
 5601:     return "error:$!";
 5602:   }
 5603:   return %returnhash;
 5604: }
 5605: 
 5606: # ----------------------------------------------------------------------- Store
 5607: 
 5608: sub store {
 5609:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 5610:     my $home='';
 5611: 
 5612:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 5613: 
 5614:     $symb=&symbclean($symb);
 5615:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 5616: 
 5617:     if (!$domain) { $domain=$env{'user.domain'}; }
 5618:     if (!$stuname) { $stuname=$env{'user.name'}; }
 5619: 
 5620:     &devalidate($symb,$stuname,$domain);
 5621: 
 5622:     $symb=escape($symb);
 5623:     if (!$namespace) { 
 5624:        unless ($namespace=$env{'request.course.id'}) { 
 5625:           return ''; 
 5626:        } 
 5627:     }
 5628:     if (!$home) { $home=$env{'user.home'}; }
 5629: 
 5630:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 5631:     $$storehash{'host'}=$perlvar{'lonHostID'};
 5632: 
 5633:     my $namevalue='';
 5634:     foreach my $key (keys(%$storehash)) {
 5635:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5636:     }
 5637:     $namevalue=~s/\&$//;
 5638:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 5639:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 5640: }
 5641: 
 5642: # -------------------------------------------------------------- Critical Store
 5643: 
 5644: sub cstore {
 5645:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 5646:     my $home='';
 5647: 
 5648:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 5649: 
 5650:     $symb=&symbclean($symb);
 5651:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 5652: 
 5653:     if (!$domain) { $domain=$env{'user.domain'}; }
 5654:     if (!$stuname) { $stuname=$env{'user.name'}; }
 5655: 
 5656:     &devalidate($symb,$stuname,$domain);
 5657: 
 5658:     $symb=escape($symb);
 5659:     if (!$namespace) { 
 5660:        unless ($namespace=$env{'request.course.id'}) { 
 5661:           return ''; 
 5662:        } 
 5663:     }
 5664:     if (!$home) { $home=$env{'user.home'}; }
 5665: 
 5666:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 5667:     $$storehash{'host'}=$perlvar{'lonHostID'};
 5668: 
 5669:     my $namevalue='';
 5670:     foreach my $key (keys(%$storehash)) {
 5671:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5672:     }
 5673:     $namevalue=~s/\&$//;
 5674:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 5675:     return critical
 5676:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 5677: }
 5678: 
 5679: # --------------------------------------------------------------------- Restore
 5680: 
 5681: sub restore {
 5682:     my ($symb,$namespace,$domain,$stuname) = @_;
 5683:     my $home='';
 5684: 
 5685:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 5686: 
 5687:     if (!$symb) {
 5688:         return if ($namespace eq 'courserequests');
 5689:         unless ($symb=escape(&symbread())) { return ''; }
 5690:     } else {
 5691:         unless ($namespace eq 'courserequests') {
 5692:             $symb=&escape(&symbclean($symb));
 5693:         }
 5694:     }
 5695:     if (!$namespace) { 
 5696:        unless ($namespace=$env{'request.course.id'}) { 
 5697:           return ''; 
 5698:        } 
 5699:     }
 5700:     if (!$domain) { $domain=$env{'user.domain'}; }
 5701:     if (!$stuname) { $stuname=$env{'user.name'}; }
 5702:     if (!$home) { $home=$env{'user.home'}; }
 5703:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 5704: 
 5705:     my %returnhash=();
 5706:     foreach my $line (split(/\&/,$answer)) {
 5707: 	my ($name,$value)=split(/\=/,$line);
 5708:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 5709:     }
 5710:     my $version;
 5711:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 5712:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 5713:           $returnhash{$item}=$returnhash{$version.':'.$item};
 5714:        }
 5715:     }
 5716:     return %returnhash;
 5717: }
 5718: 
 5719: # ---------------------------------------------------------- Course Description
 5720: #
 5721: #  
 5722: 
 5723: sub coursedescription {
 5724:     my ($courseid,$args)=@_;
 5725:     $courseid=~s/^\///;
 5726:     $courseid=~s/\_/\//g;
 5727:     my ($cdomain,$cnum)=split(/\//,$courseid);
 5728:     my $chome=&homeserver($cnum,$cdomain);
 5729:     my $normalid=$cdomain.'_'.$cnum;
 5730:     # need to always cache even if we get errors otherwise we keep 
 5731:     # trying and trying and trying to get the course description.
 5732:     my %envhash=();
 5733:     my %returnhash=();
 5734:     
 5735:     my $expiretime=600;
 5736:     if ($env{'request.course.id'} eq $normalid) {
 5737: 	$expiretime=120;
 5738:     }
 5739: 
 5740:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 5741:     if (!$args->{'freshen_cache'}
 5742: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 5743: 	foreach my $key (keys(%env)) {
 5744: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 5745: 	    my ($setting) = $1;
 5746: 	    $returnhash{$setting} = $env{$key};
 5747: 	}
 5748: 	return %returnhash;
 5749:     }
 5750: 
 5751:     # get the data again
 5752: 
 5753:     if (!$args->{'one_time'}) {
 5754: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 5755:     }
 5756: 
 5757:     if ($chome ne 'no_host') {
 5758:        %returnhash=&dump('environment',$cdomain,$cnum);
 5759:        if (!exists($returnhash{'con_lost'})) {
 5760: 	   my $username = $env{'user.name'}; # Defult username
 5761: 	   if(defined $args->{'user'}) {
 5762: 	       $username = $args->{'user'};
 5763: 	   }
 5764:            $returnhash{'home'}= $chome;
 5765: 	   $returnhash{'domain'} = $cdomain;
 5766: 	   $returnhash{'num'} = $cnum;
 5767:            if (!defined($returnhash{'type'})) {
 5768:                $returnhash{'type'} = 'Course';
 5769:            }
 5770:            while (my ($name,$value) = each %returnhash) {
 5771:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 5772:            }
 5773:            $returnhash{'url'}=&clutter($returnhash{'url'});
 5774:            $returnhash{'fn'}=LONCAPA::tempdir() .
 5775: 	       $username.'_'.$cdomain.'_'.$cnum;
 5776:            $envhash{'course.'.$normalid.'.home'}=$chome;
 5777:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 5778:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 5779:        }
 5780:     }
 5781:     if (!$args->{'one_time'}) {
 5782: 	&appenv(\%envhash);
 5783:     }
 5784:     return %returnhash;
 5785: }
 5786: 
 5787: sub update_released_required {
 5788:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 5789:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 5790:         $cid = $env{'request.course.id'};
 5791:         $cdom = $env{'course.'.$cid.'.domain'};
 5792:         $cnum = $env{'course.'.$cid.'.num'};
 5793:         $chome = $env{'course.'.$cid.'.home'};
 5794:     }
 5795:     if ($needsrelease) {
 5796:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 5797:         my $needsupdate;
 5798:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 5799:             $needsupdate = 1;
 5800:         } else {
 5801:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 5802:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 5803:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 5804:                 $needsupdate = 1;
 5805:             }
 5806:         }
 5807:         if ($needsupdate) {
 5808:             my %needshash = (
 5809:                              'internal.releaserequired' => $needsrelease,
 5810:                             );
 5811:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 5812:             if ($putresult eq 'ok') {
 5813:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 5814:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 5815:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 5816:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 5817:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 5818:                 }
 5819:             }
 5820:         }
 5821:     }
 5822:     return;
 5823: }
 5824: 
 5825: # -------------------------------------------------See if a user is privileged
 5826: 
 5827: sub privileged {
 5828:     my ($username,$domain,$possdomains,$possroles)=@_;
 5829:     my $now = time;
 5830:     my $roles;
 5831:     if (ref($possroles) eq 'ARRAY') {
 5832:         $roles = $possroles; 
 5833:     } else {
 5834:         $roles = ['dc','su'];
 5835:     }
 5836:     if (ref($possdomains) eq 'ARRAY') {
 5837:         my %privileged = &privileged_by_domain($possdomains,$roles);
 5838:         foreach my $dom (@{$possdomains}) {
 5839:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 5840:                 (ref($privileged{$dom}) eq 'HASH')) {
 5841:                 foreach my $role (@{$roles}) {
 5842:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5843:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 5844:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 5845:                             return 1 unless (($end && $end < $now) ||
 5846:                                              ($start && $start > $now));
 5847:                         }
 5848:                     }
 5849:                 }
 5850:             }
 5851:         }
 5852:     } else {
 5853:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 5854:         my $now = time;
 5855: 
 5856:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
 5857:             my ($trole, $tend, $tstart) = split(/_/, $role);
 5858:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 5859:                 return 1 unless ($tend && $tend < $now) 
 5860:                         or ($tstart && $tstart > $now);
 5861:             }
 5862:         }
 5863:     }
 5864:     return 0;
 5865: }
 5866: 
 5867: sub privileged_by_domain {
 5868:     my ($domains,$roles) = @_;
 5869:     my %privileged = ();
 5870:     my $cachetime = 60*60*24;
 5871:     my $now = time;
 5872:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 5873:         return %privileged;
 5874:     }
 5875:     foreach my $dom (@{$domains}) {
 5876:         next if (ref($privileged{$dom}) eq 'HASH');
 5877:         my $needroles;
 5878:         foreach my $role (@{$roles}) {
 5879:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 5880:             if (defined($cached)) {
 5881:                 if (ref($result) eq 'HASH') {
 5882:                     $privileged{$dom}{$role} = $result;
 5883:                 }
 5884:             } else {
 5885:                 $needroles = 1;
 5886:             }
 5887:         }
 5888:         if ($needroles) {
 5889:             my %dompersonnel = &get_domain_roles($dom,$roles);
 5890:             $privileged{$dom} = {};
 5891:             foreach my $server (keys(%dompersonnel)) {
 5892:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 5893:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 5894:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 5895:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 5896:                         next if ($end && $end < $now);
 5897:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 5898:                             $dompersonnel{$server}{$item};
 5899:                     }
 5900:                 }
 5901:             }
 5902:             if (ref($privileged{$dom}) eq 'HASH') {
 5903:                 foreach my $role (@{$roles}) {
 5904:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5905:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 5906:                     } else {
 5907:                         my %hash = ();
 5908:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 5909:                     }
 5910:                 }
 5911:             }
 5912:         }
 5913:     }
 5914:     return %privileged;
 5915: }
 5916: 
 5917: # -------------------------------------------------------- Get user privileges
 5918: 
 5919: sub rolesinit {
 5920:     my ($domain, $username) = @_;
 5921:     my %userroles = ('user.login.time' => time);
 5922:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 5923: 
 5924:     # firstaccess and timerinterval are related to timed maps/resources. 
 5925:     # also, blocking can be triggered by an activating timer
 5926:     # it's saved in the user's %env.
 5927:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 5928:     my %timerinterval = &dump('timerinterval', $domain, $username);
 5929:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 5930:         %timerintchk, %timerintenv);
 5931: 
 5932:     foreach my $key (keys(%firstaccess)) {
 5933:         my ($cid, $rest) = split(/\0/, $key);
 5934:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 5935:     }
 5936: 
 5937:     foreach my $key (keys(%timerinterval)) {
 5938:         my ($cid,$rest) = split(/\0/,$key);
 5939:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 5940:     }
 5941: 
 5942:     my %allroles=();
 5943:     my %allgroups=();
 5944: 
 5945:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
 5946:         my $role = $rolesdump{$area};
 5947:         $area =~ s/\_\w\w$//;
 5948: 
 5949:         my ($trole, $tend, $tstart, $group_privs);
 5950: 
 5951:         if ($role =~ /^cr/) {
 5952:         # Custom role, defined by a user 
 5953:         # e.g., user.role.cr/msu/smith/mynewrole
 5954:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 5955:                 $trole = $1;
 5956:                 ($tend, $tstart) = split('_', $2);
 5957:             } else {
 5958:                 $trole = $role;
 5959:             }
 5960:         } elsif ($role =~ m|^gr/|) {
 5961:         # Role of member in a group, defined within a course/community
 5962:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 5963:             ($trole, $tend, $tstart) = split(/_/, $role);
 5964:             next if $tstart eq '-1';
 5965:             ($trole, $group_privs) = split(/\//, $trole);
 5966:             $group_privs = &unescape($group_privs);
 5967:         } else {
 5968:         # Just a normal role, defined in roles.tab
 5969:             ($trole, $tend, $tstart) = split(/_/,$role);
 5970:         }
 5971: 
 5972:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 5973:                  $username);
 5974:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 5975: 
 5976:         # role expired or not available yet?
 5977:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 5978:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 5979: 
 5980:         next if $area eq '' or $trole eq '';
 5981: 
 5982:         my $spec = "$trole.$area";
 5983:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 5984: 
 5985:         if ($trole =~ /^cr\//) {
 5986:         # Custom role, defined by a user
 5987:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 5988:         } elsif ($trole eq 'gr') {
 5989:         # Role of a member in a group, defined within a course/community
 5990:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 5991:             next;
 5992:         } else {
 5993:         # Normal role, defined in roles.tab
 5994:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 5995:         }
 5996: 
 5997:         my $cid = $tdomain.'_'.$trest;
 5998:         unless ($firstaccchk{$cid}) {
 5999:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 6000:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 6001:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 6002:                         $coursetimerstarts{$cid}{$item}; 
 6003:                 }
 6004:             }
 6005:             $firstaccchk{$cid} = 1;
 6006:         }
 6007:         unless ($timerintchk{$cid}) {
 6008:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 6009:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 6010:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 6011:                        $coursetimerintervals{$cid}{$item};
 6012:                 }
 6013:             }
 6014:             $timerintchk{$cid} = 1;
 6015:         }
 6016:     }
 6017: 
 6018:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
 6019:                                                           \%allroles, \%allgroups);
 6020:     $env{'user.adv'} = $userroles{'user.adv'};
 6021:     $env{'user.rar'} = $userroles{'user.rar'};
 6022: 
 6023:     return (\%userroles,\%firstaccenv,\%timerintenv);
 6024: }
 6025: 
 6026: sub set_arearole {
 6027:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 6028:     unless ($nolog) {
 6029: # log the associated role with the area
 6030:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 6031:     }
 6032:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 6033: }
 6034: 
 6035: sub custom_roleprivs {
 6036:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 6037:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 6038:     my $homsvr = &homeserver($rauthor,$rdomain);
 6039:     if (&hostname($homsvr) ne '') {
 6040:         my ($rdummy,$roledef)=
 6041:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 6042:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 6043:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 6044:             if (defined($syspriv)) {
 6045:                 if ($trest =~ /^$match_community$/) {
 6046:                     $syspriv =~ s/bre\&S//; 
 6047:                 }
 6048:                 $$allroles{'cm./'}.=':'.$syspriv;
 6049:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 6050:             }
 6051:             if ($tdomain ne '') {
 6052:                 if (defined($dompriv)) {
 6053:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 6054:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 6055:                 }
 6056:                 if (($trest ne '') && (defined($coursepriv))) {
 6057:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
 6058:                         my $rolename = $1;
 6059:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
 6060:                     }
 6061:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 6062:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 6063:                 }
 6064:             }
 6065:         }
 6066:     }
 6067: }
 6068: 
 6069: sub course_adhocrole_privs {
 6070:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
 6071:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
 6072:     if ($overrides{"internal.adhocpriv.$rolename"}) {
 6073:         my (%currprivs,%storeprivs);
 6074:         foreach my $item (split(/:/,$coursepriv)) {
 6075:             my ($priv,$restrict) = split(/\&/,$item);
 6076:             $currprivs{$priv} = $restrict;
 6077:         }
 6078:         my (%possadd,%possremove,%full);
 6079:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 6080:             my ($priv,$restrict)=split(/\&/,$item);
 6081:             $full{$priv} = $restrict;
 6082:         }
 6083:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
 6084:              next if ($item eq '');
 6085:              my ($rule,$rest) = split(/=/,$item);
 6086:              next unless (($rule eq 'off') || ($rule eq 'on'));
 6087:              foreach my $priv (split(/:/,$rest)) {
 6088:                  if ($priv ne '') {
 6089:                      if ($rule eq 'off') {
 6090:                          $possremove{$priv} = 1;
 6091:                      } else {
 6092:                          $possadd{$priv} = 1;
 6093:                      }
 6094:                  }
 6095:              }
 6096:          }
 6097:          foreach my $priv (sort(keys(%full))) {
 6098:              if (exists($currprivs{$priv})) {
 6099:                  unless (exists($possremove{$priv})) {
 6100:                      $storeprivs{$priv} = $currprivs{$priv};
 6101:                  }
 6102:              } elsif (exists($possadd{$priv})) {
 6103:                  $storeprivs{$priv} = $full{$priv};
 6104:              }
 6105:          }
 6106:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
 6107:      }
 6108:      return $coursepriv;
 6109: }
 6110: 
 6111: sub group_roleprivs {
 6112:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 6113:     my $access = 1;
 6114:     my $now = time;
 6115:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 6116:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 6117:     if ($access) {
 6118:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 6119:         $$allgroups{$course}{$group} .=':'.$group_privs;
 6120:     }
 6121: }
 6122: 
 6123: sub standard_roleprivs {
 6124:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 6125:     if (defined($pr{$trole.':s'})) {
 6126:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 6127:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 6128:     }
 6129:     if ($tdomain ne '') {
 6130:         if (defined($pr{$trole.':d'})) {
 6131:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6132:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6133:         }
 6134:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 6135:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 6136:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 6137:         }
 6138:     }
 6139: }
 6140: 
 6141: sub set_userprivs {
 6142:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 6143:     my $author=0;
 6144:     my $adv=0;
 6145:     my $rar=0;
 6146:     my %grouproles = ();
 6147:     if (keys(%{$allgroups}) > 0) {
 6148:         my @groupkeys; 
 6149:         foreach my $role (keys(%{$allroles})) {
 6150:             push(@groupkeys,$role);
 6151:         }
 6152:         if (ref($groups_roles) eq 'HASH') {
 6153:             foreach my $key (keys(%{$groups_roles})) {
 6154:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 6155:                     push(@groupkeys,$key);
 6156:                 }
 6157:             }
 6158:         }
 6159:         if (@groupkeys > 0) {
 6160:             foreach my $role (@groupkeys) {
 6161:                 my ($trole,$area,$sec,$extendedarea);
 6162:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 6163:                     $trole = $1;
 6164:                     $area = $2;
 6165:                     $sec = $3;
 6166:                     $extendedarea = $area.$sec;
 6167:                     if (exists($$allgroups{$area})) {
 6168:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 6169:                             my $spec = $trole.'.'.$extendedarea;
 6170:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 6171:                                                 $$allgroups{$area}{$group};
 6172:                         }
 6173:                     }
 6174:                 }
 6175:             }
 6176:         }
 6177:     }
 6178:     foreach my $group (keys(%grouproles)) {
 6179:         $$allroles{$group} = $grouproles{$group};
 6180:     }
 6181:     foreach my $role (keys(%{$allroles})) {
 6182:         my %thesepriv;
 6183:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 6184:         foreach my $item (split(/:/,$$allroles{$role})) {
 6185:             if ($item ne '') {
 6186:                 my ($privilege,$restrictions)=split(/&/,$item);
 6187:                 if ($restrictions eq '') {
 6188:                     $thesepriv{$privilege}='F';
 6189:                 } elsif ($thesepriv{$privilege} ne 'F') {
 6190:                     $thesepriv{$privilege}.=$restrictions;
 6191:                 }
 6192:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 6193:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
 6194:             }
 6195:         }
 6196:         my $thesestr='';
 6197:         foreach my $priv (sort(keys(%thesepriv))) {
 6198: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 6199: 	}
 6200:         $userroles->{'user.priv.'.$role} = $thesestr;
 6201:     }
 6202:     return ($author,$adv,$rar);
 6203: }
 6204: 
 6205: sub role_status {
 6206:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 6207:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 6208:         my ($one,$two) = split(m{\./},$rolekey,2);
 6209:         (undef,undef,$$role) = split(/\./,$one,3);
 6210:         unless (!defined($$role) || $$role eq '') {
 6211:             $$where = '/'.$two;
 6212:             $$trolecode=$$role.'.'.$$where;
 6213:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 6214:             $$tstatus='is';
 6215:             if ($$tstart && $$tstart>$update) {
 6216:                 $$tstatus='future';
 6217:                 if ($$tstart<$now) {
 6218:                     if ($$tstart && $$tstart>$refresh) {
 6219:                         if (($$where ne '') && ($$role ne '')) {
 6220:                             my (%allroles,%allgroups,$group_privs,
 6221:                                 %groups_roles,@rolecodes);
 6222:                             my %userroles = (
 6223:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 6224:                             );
 6225:                             @rolecodes = ('cm'); 
 6226:                             my $spec=$$role.'.'.$$where;
 6227:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 6228:                             if ($$role =~ /^cr\//) {
 6229:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 6230:                                 push(@rolecodes,'cr');
 6231:                             } elsif ($$role eq 'gr') {
 6232:                                 push(@rolecodes,$$role);
 6233:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 6234:                                                     $env{'user.name'});
 6235:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 6236:                                 (undef,my $group_privs) = split(/\//,$trole);
 6237:                                 $group_privs = &unescape($group_privs);
 6238:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 6239:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 6240:                                 &get_groups_roles($tdomain,$trest,
 6241:                                                   \%course_roles,\@rolecodes,
 6242:                                                   \%groups_roles);
 6243:                             } else {
 6244:                                 push(@rolecodes,$$role);
 6245:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 6246:                             }
 6247:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
 6248:                                                                    \%groups_roles);
 6249:                             &appenv(\%userroles,\@rolecodes);
 6250:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6251:                         }
 6252:                     }
 6253:                     $$tstatus = 'is';
 6254:                 }
 6255:             }
 6256:             if ($$tend) {
 6257:                 if ($$tend<$update) {
 6258:                     $$tstatus='expired';
 6259:                 } elsif ($$tend<$now) {
 6260:                     $$tstatus='will_not';
 6261:                 }
 6262:             }
 6263:         }
 6264:     }
 6265: }
 6266: 
 6267: sub get_groups_roles {
 6268:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 6269:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 6270:                   (ref($rolecodes) eq 'ARRAY') && 
 6271:                   (ref($groups_roles) eq 'HASH')); 
 6272:     if (keys(%{$cdom_courseroles}) > 0) {
 6273:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 6274:         if ($cdom ne '' && $cnum ne '') {
 6275:             foreach my $key (keys(%{$cdom_courseroles})) {
 6276:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 6277:                     my $crsrole = $1;
 6278:                     my $crssec = $2;
 6279:                     if ($crsrole =~ /^cr/) {
 6280:                         unless (grep(/^cr$/,@{$rolecodes})) {
 6281:                             push(@{$rolecodes},'cr');
 6282:                         }
 6283:                     } else {
 6284:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 6285:                             push(@{$rolecodes},$crsrole);
 6286:                         }
 6287:                     }
 6288:                     my $rolekey = "$crsrole./$cdom/$cnum";
 6289:                     if ($crssec ne '') {
 6290:                         $rolekey .= "/$crssec";
 6291:                     }
 6292:                     $rolekey .= './';
 6293:                     $groups_roles->{$rolekey} = $rolecodes;
 6294:                 }
 6295:             }
 6296:         }
 6297:     }
 6298:     return;
 6299: }
 6300: 
 6301: sub delete_env_groupprivs {
 6302:     my ($where,$courseroles,$possroles) = @_;
 6303:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 6304:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 6305:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 6306:         %{$courseroles->{$udom}} =
 6307:             &get_my_roles('','','userroles',['active'],
 6308:                           $possroles,[$udom],1);
 6309:     }
 6310:     if (ref($courseroles->{$udom}) eq 'HASH') {
 6311:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 6312:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 6313:             my $area = '/'.$cdom.'/'.$cnum;
 6314:             my $privkey = "user.priv.$crsrole.$area";
 6315:             if ($crssec ne '') {
 6316:                 $privkey .= '/'.$crssec;
 6317:             }
 6318:             $privkey .= ".$area/$group";
 6319:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 6320:         }
 6321:     }
 6322:     return;
 6323: }
 6324: 
 6325: sub check_adhoc_privs {
 6326:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
 6327:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 6328:     if ($sec) {
 6329:         $cckey .= '/'.$sec;
 6330:     } 
 6331:     my $setprivs;
 6332:     if ($env{$cckey}) {
 6333:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 6334:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 6335:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 6336:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6337:             $setprivs = 1;
 6338:         }
 6339:     } else {
 6340:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6341:         $setprivs = 1;
 6342:     }
 6343:     return $setprivs;
 6344: }
 6345: 
 6346: sub set_adhoc_privileges {
 6347: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
 6348:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
 6349:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 6350:     if ($sec ne '') {
 6351:         $area .= '/'.$sec;
 6352:     }
 6353:     my $spec = $role.'.'.$area;
 6354:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 6355:                                   $env{'user.name'},1);
 6356:     my %rolehash = ();
 6357:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
 6358:         my $rolename = $1;
 6359:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
 6360:         my %domdef = &get_domain_defaults($dcdom);
 6361:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
 6362:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
 6363:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
 6364:             }
 6365:         }
 6366:     } else {
 6367:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
 6368:     }
 6369:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
 6370:     &appenv(\%userroles,[$role,'cm']);
 6371:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6372:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 6373:         &appenv( {'request.role'        => $spec,
 6374:                   'request.role.domain' => $dcdom,
 6375:                   'request.course.sec'  => $sec,
 6376:                  }
 6377:                );
 6378:         my $tadv=0;
 6379:         if (&allowed('adv') eq 'F') { $tadv=1; }
 6380:         &appenv({'request.role.adv'    => $tadv});
 6381:     }
 6382: }
 6383: 
 6384: # --------------------------------------------------------------- get interface
 6385: 
 6386: sub get {
 6387:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6388:    my $items='';
 6389:    foreach my $item (@$storearr) {
 6390:        $items.=&escape($item).'&';
 6391:    }
 6392:    $items=~s/\&$//;
 6393:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6394:    if (!$uname) { $uname=$env{'user.name'}; }
 6395:    my $uhome=&homeserver($uname,$udomain);
 6396: 
 6397:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 6398:    my @pairs=split(/\&/,$rep);
 6399:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 6400:      return @pairs;
 6401:    }
 6402:    my %returnhash=();
 6403:    my $i=0;
 6404:    foreach my $item (@$storearr) {
 6405:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 6406:       $i++;
 6407:    }
 6408:    return %returnhash;
 6409: }
 6410: 
 6411: # --------------------------------------------------------------- del interface
 6412: 
 6413: sub del {
 6414:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6415:    my $items='';
 6416:    foreach my $item (@$storearr) {
 6417:        $items.=&escape($item).'&';
 6418:    }
 6419: 
 6420:    $items=~s/\&$//;
 6421:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6422:    if (!$uname) { $uname=$env{'user.name'}; }
 6423:    my $uhome=&homeserver($uname,$udomain);
 6424:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 6425: }
 6426: 
 6427: # -------------------------------------------------------------- dump interface
 6428: 
 6429: sub unserialize {
 6430:     my ($rep, $escapedkeys) = @_;
 6431: 
 6432:     return {} if $rep =~ /^error/;
 6433: 
 6434:     my %returnhash=();
 6435: 	foreach my $item (split(/\&/,$rep)) {
 6436: 	    my ($key, $value) = split(/=/, $item, 2);
 6437: 	    $key = unescape($key) unless $escapedkeys;
 6438: 	    next if $key =~ /^error: 2 /;
 6439: 	    $returnhash{$key} = &thaw_unescape($value);
 6440: 	}
 6441:     #return %returnhash;
 6442:     return \%returnhash;
 6443: }        
 6444: 
 6445: # see Lond::dump_with_regexp
 6446: # if $escapedkeys hash keys won't get unescaped.
 6447: sub dump {
 6448:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 6449:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6450:     if (!$uname) { $uname=$env{'user.name'}; }
 6451:     my $uhome=&homeserver($uname,$udomain);
 6452: 
 6453:     if ($regexp) {
 6454:         $regexp=&escape($regexp);
 6455:     } else {
 6456:         $regexp='.';
 6457:     }
 6458:     if (grep { $_ eq $uhome } current_machine_ids()) {
 6459:         # user is hosted on this machine
 6460:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 6461:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 6462:         return %{unserialize($reply, $escapedkeys)};
 6463:     }
 6464:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 6465:     my @pairs=split(/\&/,$rep);
 6466:     my %returnhash=();
 6467:     if (!($rep =~ /^error/ )) {
 6468: 	foreach my $item (@pairs) {
 6469: 	    my ($key,$value)=split(/=/,$item,2);
 6470:         $key = unescape($key) unless $escapedkeys;
 6471:         #$key = &unescape($key);
 6472: 	    next if ($key =~ /^error: 2 /);
 6473: 	    $returnhash{$key}=&thaw_unescape($value);
 6474: 	}
 6475:     }
 6476:     return %returnhash;
 6477: }
 6478: 
 6479: 
 6480: # --------------------------------------------------------- dumpstore interface
 6481: 
 6482: sub dumpstore {
 6483:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 6484:    # same as dump but keys must be escaped. They may contain colon separated
 6485:    # lists of values that may themself contain colons (e.g. symbs).
 6486:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 6487: }
 6488: 
 6489: # -------------------------------------------------------------- keys interface
 6490: 
 6491: sub getkeys {
 6492:    my ($namespace,$udomain,$uname)=@_;
 6493:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6494:    if (!$uname) { $uname=$env{'user.name'}; }
 6495:    my $uhome=&homeserver($uname,$udomain);
 6496:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 6497:    my @keyarray=();
 6498:    foreach my $key (split(/\&/,$rep)) {
 6499:       next if ($key =~ /^error: 2 /);
 6500:       push(@keyarray,&unescape($key));
 6501:    }
 6502:    return @keyarray;
 6503: }
 6504: 
 6505: # --------------------------------------------------------------- currentdump
 6506: sub currentdump {
 6507:    my ($courseid,$sdom,$sname)=@_;
 6508:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 6509:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 6510:    $sname    = $env{'user.name'}         if (! defined($sname));
 6511:    my $uhome = &homeserver($sname,$sdom);
 6512:    my $rep;
 6513: 
 6514:    if (grep { $_ eq $uhome } current_machine_ids()) {
 6515:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 6516:                    $courseid)));
 6517:    } else {
 6518:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 6519:    }
 6520: 
 6521:    return if ($rep =~ /^(error:|no_such_host)/);
 6522:    #
 6523:    my %returnhash=();
 6524:    #
 6525:    if ($rep eq 'unknown_cmd') {
 6526:        # an old lond will not know currentdump
 6527:        # Do a dump and make it look like a currentdump
 6528:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 6529:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 6530:        my %hash = @tmp;
 6531:        @tmp=();
 6532:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 6533:    } else {
 6534:        my @pairs=split(/\&/,$rep);
 6535:        foreach my $pair (@pairs) {
 6536:            my ($key,$value)=split(/=/,$pair,2);
 6537:            my ($symb,$param) = split(/:/,$key);
 6538:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 6539:                                                         &thaw_unescape($value);
 6540:        }
 6541:    }
 6542:    return %returnhash;
 6543: }
 6544: 
 6545: sub convert_dump_to_currentdump{
 6546:     my %hash = %{shift()};
 6547:     my %returnhash;
 6548:     # Code ripped from lond, essentially.  The only difference
 6549:     # here is the unescaping done by lonnet::dump().  Conceivably
 6550:     # we might run in to problems with parameter names =~ /^v\./
 6551:     while (my ($key,$value) = each(%hash)) {
 6552:         my ($v,$symb,$param) = split(/:/,$key);
 6553: 	$symb  = &unescape($symb);
 6554: 	$param = &unescape($param);
 6555:         next if ($v eq 'version' || $symb eq 'keys');
 6556:         next if (exists($returnhash{$symb}) &&
 6557:                  exists($returnhash{$symb}->{$param}) &&
 6558:                  $returnhash{$symb}->{'v.'.$param} > $v);
 6559:         $returnhash{$symb}->{$param}=$value;
 6560:         $returnhash{$symb}->{'v.'.$param}=$v;
 6561:     }
 6562:     #
 6563:     # Remove all of the keys in the hashes which keep track of
 6564:     # the version of the parameter.
 6565:     while (my ($symb,$param_hash) = each(%returnhash)) {
 6566:         # use a foreach because we are going to delete from the hash.
 6567:         foreach my $key (keys(%$param_hash)) {
 6568:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 6569:         }
 6570:     }
 6571:     return \%returnhash;
 6572: }
 6573: 
 6574: # ------------------------------------------------------ critical inc interface
 6575: 
 6576: sub cinc {
 6577:     return &inc(@_,'critical');
 6578: }
 6579: 
 6580: # --------------------------------------------------------------- inc interface
 6581: 
 6582: sub inc {
 6583:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 6584:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6585:     if (!$uname) { $uname=$env{'user.name'}; }
 6586:     my $uhome=&homeserver($uname,$udomain);
 6587:     my $items='';
 6588:     if (! ref($store)) {
 6589:         # got a single value, so use that instead
 6590:         $items = &escape($store).'=&';
 6591:     } elsif (ref($store) eq 'SCALAR') {
 6592:         $items = &escape($$store).'=&';        
 6593:     } elsif (ref($store) eq 'ARRAY') {
 6594:         $items = join('=&',map {&escape($_);} @{$store});
 6595:     } elsif (ref($store) eq 'HASH') {
 6596:         while (my($key,$value) = each(%{$store})) {
 6597:             $items.= &escape($key).'='.&escape($value).'&';
 6598:         }
 6599:     }
 6600:     $items=~s/\&$//;
 6601:     if ($critical) {
 6602: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 6603:     } else {
 6604: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 6605:     }
 6606: }
 6607: 
 6608: # --------------------------------------------------------------- put interface
 6609: 
 6610: sub put {
 6611:    my ($namespace,$storehash,$udomain,$uname)=@_;
 6612:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6613:    if (!$uname) { $uname=$env{'user.name'}; }
 6614:    my $uhome=&homeserver($uname,$udomain);
 6615:    my $items='';
 6616:    foreach my $item (keys(%$storehash)) {
 6617:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 6618:    }
 6619:    $items=~s/\&$//;
 6620:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 6621: }
 6622: 
 6623: # ------------------------------------------------------------ newput interface
 6624: 
 6625: sub newput {
 6626:    my ($namespace,$storehash,$udomain,$uname)=@_;
 6627:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6628:    if (!$uname) { $uname=$env{'user.name'}; }
 6629:    my $uhome=&homeserver($uname,$udomain);
 6630:    my $items='';
 6631:    foreach my $key (keys(%$storehash)) {
 6632:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6633:    }
 6634:    $items=~s/\&$//;
 6635:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 6636: }
 6637: 
 6638: # ---------------------------------------------------------  putstore interface
 6639: 
 6640: sub putstore {
 6641:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
 6642:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6643:    if (!$uname) { $uname=$env{'user.name'}; }
 6644:    my $uhome=&homeserver($uname,$udomain);
 6645:    my $items='';
 6646:    foreach my $key (keys(%$storehash)) {
 6647:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 6648:    }
 6649:    $items=~s/\&$//;
 6650:    my $esc_symb=&escape($symb);
 6651:    my $esc_v=&escape($version);
 6652:    my $reply =
 6653:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 6654: 	      $uhome);
 6655:    if (($tolog) && ($reply eq 'ok')) {
 6656:        my $namevalue='';
 6657:        foreach my $key (keys(%{$storehash})) {
 6658:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 6659:        }
 6660:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
 6661:                      '&host='.&escape($perlvar{'lonHostID'}).
 6662:                      '&version='.$esc_v.
 6663:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
 6664:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
 6665:    }
 6666:    if ($reply eq 'unknown_cmd') {
 6667:        # gfall back to way things use to be done
 6668:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 6669: 			    $uname);
 6670:    }
 6671:    return $reply;
 6672: }
 6673: 
 6674: sub old_putstore {
 6675:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 6676:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6677:     if (!$uname) { $uname=$env{'user.name'}; }
 6678:     my $uhome=&homeserver($uname,$udomain);
 6679:     my %newstorehash;
 6680:     foreach my $item (keys(%$storehash)) {
 6681: 	my $key = $version.':'.&escape($symb).':'.$item;
 6682: 	$newstorehash{$key} = $storehash->{$item};
 6683:     }
 6684:     my $items='';
 6685:     my %allitems = ();
 6686:     foreach my $item (keys(%newstorehash)) {
 6687: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 6688: 	    my $key = $1.':keys:'.$2;
 6689: 	    $allitems{$key} .= $3.':';
 6690: 	}
 6691: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 6692:     }
 6693:     foreach my $item (keys(%allitems)) {
 6694: 	$allitems{$item} =~ s/\:$//;
 6695: 	$items.= $item.'='.$allitems{$item}.'&';
 6696:     }
 6697:     $items=~s/\&$//;
 6698:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 6699: }
 6700: 
 6701: # ------------------------------------------------------ critical put interface
 6702: 
 6703: sub cput {
 6704:    my ($namespace,$storehash,$udomain,$uname)=@_;
 6705:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6706:    if (!$uname) { $uname=$env{'user.name'}; }
 6707:    my $uhome=&homeserver($uname,$udomain);
 6708:    my $items='';
 6709:    foreach my $item (keys(%$storehash)) {
 6710:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 6711:    }
 6712:    $items=~s/\&$//;
 6713:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 6714: }
 6715: 
 6716: # -------------------------------------------------------------- eget interface
 6717: 
 6718: sub eget {
 6719:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6720:    my $items='';
 6721:    foreach my $item (@$storearr) {
 6722:        $items.=&escape($item).'&';
 6723:    }
 6724:    $items=~s/\&$//;
 6725:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6726:    if (!$uname) { $uname=$env{'user.name'}; }
 6727:    my $uhome=&homeserver($uname,$udomain);
 6728:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 6729:    my @pairs=split(/\&/,$rep);
 6730:    my %returnhash=();
 6731:    my $i=0;
 6732:    foreach my $item (@$storearr) {
 6733:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 6734:       $i++;
 6735:    }
 6736:    return %returnhash;
 6737: }
 6738: 
 6739: # ------------------------------------------------------------ tmpput interface
 6740: sub tmpput {
 6741:     my ($storehash,$server,$context)=@_;
 6742:     my $items='';
 6743:     foreach my $item (keys(%$storehash)) {
 6744: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 6745:     }
 6746:     $items=~s/\&$//;
 6747:     if (defined($context)) {
 6748:         $items .= ':'.&escape($context);
 6749:     }
 6750:     return &reply("tmpput:$items",$server);
 6751: }
 6752: 
 6753: # ------------------------------------------------------------ tmpget interface
 6754: sub tmpget {
 6755:     my ($token,$server)=@_;
 6756:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 6757:     my $rep=&reply("tmpget:$token",$server);
 6758:     my %returnhash;
 6759:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
 6760:         return %returnhash;
 6761:     }
 6762:     foreach my $item (split(/\&/,$rep)) {
 6763: 	my ($key,$value)=split(/=/,$item);
 6764: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 6765:     }
 6766:     return %returnhash;
 6767: }
 6768: 
 6769: # ------------------------------------------------------------ tmpdel interface
 6770: sub tmpdel {
 6771:     my ($token,$server)=@_;
 6772:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 6773:     return &reply("tmpdel:$token",$server);
 6774: }
 6775: 
 6776: # ------------------------------------------------------------ get_timebased_id 
 6777: 
 6778: sub get_timebased_id {
 6779:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 6780:         $maxtries) = @_;
 6781:     my ($newid,$error,$dellock);
 6782:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 6783:         return ('','ok','invalid call to get suffix');
 6784:     }
 6785: 
 6786: # set defaults for any optional args for which values were not supplied
 6787:     if ($who eq '') {
 6788:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 6789:     }
 6790:     if (!$locktries) {
 6791:         $locktries = 3;
 6792:     }
 6793:     if (!$maxtries) {
 6794:         $maxtries = 10;
 6795:     }
 6796:     
 6797:     if (($cdom eq '') || ($cnum eq '')) {
 6798:         if ($env{'request.course.id'}) {
 6799:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6800:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6801:         }
 6802:         if (($cdom eq '') || ($cnum eq '')) {
 6803:             return ('','ok','call to get suffix not in course context');
 6804:         }
 6805:     }
 6806: 
 6807: # construct locking item
 6808:     my $lockhash = {
 6809:                       $prefix."\0".'locked_'.$keyid => $who,
 6810:                    };
 6811:     my $tries = 0;
 6812: 
 6813: # attempt to get lock on nohist_$namespace file
 6814:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 6815:     while (($gotlock ne 'ok') && $tries <$locktries) {
 6816:         $tries ++;
 6817:         sleep 1;
 6818:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 6819:     }
 6820: 
 6821: # attempt to get unique identifier, based on current timestamp
 6822:     if ($gotlock eq 'ok') {
 6823:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 6824:         my $id = time;
 6825:         $newid = $id;
 6826:         if ($idtype eq 'addcode') {
 6827:             $newid .= &sixnum_code();
 6828:         }
 6829:         my $idtries = 0;
 6830:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 6831:             if ($idtype eq 'concat') {
 6832:                 $newid = $id.$idtries;
 6833:             } elsif ($idtype eq 'addcode') {
 6834:                 $newid = $newid.&sixnum_code();
 6835:             } else {
 6836:                 $newid ++;
 6837:             }
 6838:             $idtries ++;
 6839:         }
 6840:         if (!exists($inuse{$prefix."\0".$newid})) {
 6841:             my %new_item =  (
 6842:                               $prefix."\0".$newid => $who,
 6843:                             );
 6844:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 6845:                                                  $cdom,$cnum);
 6846:             if ($putresult ne 'ok') {
 6847:                 undef($newid);
 6848:                 $error = 'error saving new item: '.$putresult;
 6849:             }
 6850:         } else {
 6851:              undef($newid);
 6852:              $error = ('error: no unique suffix available for the new item ');
 6853:         }
 6854: #  remove lock
 6855:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 6856:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 6857:     } else {
 6858:         $error = "error: could not obtain lockfile\n";
 6859:         $dellock = 'ok';
 6860:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
 6861:             $dellock = 'nolock';
 6862:         }
 6863:     }
 6864:     return ($newid,$dellock,$error);
 6865: }
 6866: 
 6867: sub sixnum_code {
 6868:     my $code;
 6869:     for (0..6) {
 6870:         $code .= int( rand(9) );
 6871:     }
 6872:     return $code;
 6873: }
 6874: 
 6875: # -------------------------------------------------- portfolio access checking
 6876: 
 6877: sub portfolio_access {
 6878:     my ($requrl,$clientip) = @_;
 6879:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 6880:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
 6881:     if ($result) {
 6882:         my %setters;
 6883:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 6884:             my ($startblock,$endblock) =
 6885:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 6886:             if ($startblock && $endblock) {
 6887:                 return 'B';
 6888:             }
 6889:         } else {
 6890:             my ($startblock,$endblock) =
 6891:                 &Apache::loncommon::blockcheck(\%setters,'port');
 6892:             if ($startblock && $endblock) {
 6893:                 return 'B';
 6894:             }
 6895:         }
 6896:     }
 6897:     if ($result eq 'ok') {
 6898:        return 'F';
 6899:     } elsif ($result =~ /^[^:]+:guest_/) {
 6900:        return 'A';
 6901:     }
 6902:     return '';
 6903: }
 6904: 
 6905: sub get_portfolio_access {
 6906:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
 6907: 
 6908:     if (!ref($access_hash)) {
 6909: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 6910: 	my %access_controls = &get_access_controls($current_perms,$group,
 6911: 						   $file_name);
 6912: 	$access_hash = $access_controls{$file_name};
 6913:     }
 6914: 
 6915:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
 6916:     my $now = time;
 6917:     if (ref($access_hash) eq 'HASH') {
 6918:         foreach my $key (keys(%{$access_hash})) {
 6919:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 6920:             if ($start > $now) {
 6921:                 next;
 6922:             }
 6923:             if ($end && $end<$now) {
 6924:                 next;
 6925:             }
 6926:             if ($scope eq 'public') {
 6927:                 $public = $key;
 6928:                 last;
 6929:             } elsif ($scope eq 'guest') {
 6930:                 $guest = $key;
 6931:             } elsif ($scope eq 'domains') {
 6932:                 push(@domains,$key);
 6933:             } elsif ($scope eq 'users') {
 6934:                 push(@users,$key);
 6935:             } elsif ($scope eq 'course') {
 6936:                 push(@courses,$key);
 6937:             } elsif ($scope eq 'group') {
 6938:                 push(@groups,$key);
 6939:             } elsif ($scope eq 'ip') {
 6940:                 push(@ips,$key);
 6941:             }
 6942:         }
 6943:         if ($public) {
 6944:             return 'ok';
 6945:         } elsif (@ips > 0) {
 6946:             my $allowed;
 6947:             foreach my $ipkey (@ips) {
 6948:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
 6949:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
 6950:                         $allowed = 1;
 6951:                         last; 
 6952:                     }
 6953:                 }
 6954:             }
 6955:             if ($allowed) {
 6956:                 return 'ok';
 6957:             }
 6958:         }
 6959:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 6960:             if ($guest) {
 6961:                 return $guest;
 6962:             }
 6963:         } else {
 6964:             if (@domains > 0) {
 6965:                 foreach my $domkey (@domains) {
 6966:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 6967:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 6968:                             return 'ok';
 6969:                         }
 6970:                     }
 6971:                 }
 6972:             }
 6973:             if (@users > 0) {
 6974:                 foreach my $userkey (@users) {
 6975:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 6976:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 6977:                             if (ref($item) eq 'HASH') {
 6978:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 6979:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 6980:                                     return 'ok';
 6981:                                 }
 6982:                             }
 6983:                         }
 6984:                     } 
 6985:                 }
 6986:             }
 6987:             my %roleshash;
 6988:             my @courses_and_groups = @courses;
 6989:             push(@courses_and_groups,@groups); 
 6990:             if (@courses_and_groups > 0) {
 6991:                 my (%allgroups,%allroles); 
 6992:                 my ($start,$end,$role,$sec,$group);
 6993:                 foreach my $envkey (%env) {
 6994:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 6995:                         my $cid = $2.'_'.$3; 
 6996:                         if ($1 eq 'gr') {
 6997:                             $group = $4;
 6998:                             $allgroups{$cid}{$group} = $env{$envkey};
 6999:                         } else {
 7000:                             if ($4 eq '') {
 7001:                                 $sec = 'none';
 7002:                             } else {
 7003:                                 $sec = $4;
 7004:                             }
 7005:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7006:                         }
 7007:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7008:                         my $cid = $2.'_'.$3;
 7009:                         if ($4 eq '') {
 7010:                             $sec = 'none';
 7011:                         } else {
 7012:                             $sec = $4;
 7013:                         }
 7014:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7015:                     }
 7016:                 }
 7017:                 if (keys(%allroles) == 0) {
 7018:                     return;
 7019:                 }
 7020:                 foreach my $key (@courses_and_groups) {
 7021:                     my %content = %{$$access_hash{$key}};
 7022:                     my $cnum = $content{'number'};
 7023:                     my $cdom = $content{'domain'};
 7024:                     my $cid = $cdom.'_'.$cnum;
 7025:                     if (!exists($allroles{$cid})) {
 7026:                         next;
 7027:                     }    
 7028:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 7029:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 7030:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 7031:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 7032:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 7033:                         foreach my $role (keys(%{$allroles{$cid}})) {
 7034:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 7035:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 7036:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 7037:                                         if (grep/^all$/,@sections) {
 7038:                                             return 'ok';
 7039:                                         } else {
 7040:                                             if (grep/^$sec$/,@sections) {
 7041:                                                 return 'ok';
 7042:                                             }
 7043:                                         }
 7044:                                     }
 7045:                                 }
 7046:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 7047:                                     if (grep/^none$/,@groups) {
 7048:                                         return 'ok';
 7049:                                     }
 7050:                                 } else {
 7051:                                     if (grep/^all$/,@groups) {
 7052:                                         return 'ok';
 7053:                                     } 
 7054:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 7055:                                         if (grep/^$group$/,@groups) {
 7056:                                             return 'ok';
 7057:                                         }
 7058:                                     }
 7059:                                 } 
 7060:                             }
 7061:                         }
 7062:                     }
 7063:                 }
 7064:             }
 7065:             if ($guest) {
 7066:                 return $guest;
 7067:             }
 7068:         }
 7069:     }
 7070:     return;
 7071: }
 7072: 
 7073: sub course_group_datechecker {
 7074:     my ($dates,$now,$status) = @_;
 7075:     my ($start,$end) = split(/\./,$dates);
 7076:     if (!$start && !$end) {
 7077:         return 'ok';
 7078:     }
 7079:     if (grep/^active$/,@{$status}) {
 7080:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 7081:             return 'ok';
 7082:         }
 7083:     }
 7084:     if (grep/^previous$/,@{$status}) {
 7085:         if ($end > $now ) {
 7086:             return 'ok';
 7087:         }
 7088:     }
 7089:     if (grep/^future$/,@{$status}) {
 7090:         if ($start > $now) {
 7091:             return 'ok';
 7092:         }
 7093:     }
 7094:     return; 
 7095: }
 7096: 
 7097: sub parse_portfolio_url {
 7098:     my ($url) = @_;
 7099: 
 7100:     my ($type,$udom,$unum,$group,$file_name);
 7101:     
 7102:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 7103: 	$type = 1;
 7104:         $udom = $1;
 7105:         $unum = $2;
 7106:         $file_name = $3;
 7107:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 7108: 	$type = 2;
 7109:         $udom = $1;
 7110:         $unum = $2;
 7111:         $group = $3;
 7112:         $file_name = $3.'/'.$4;
 7113:     }
 7114:     if (wantarray) {
 7115: 	return ($type,$udom,$unum,$file_name,$group);
 7116:     }
 7117:     return $type;
 7118: }
 7119: 
 7120: sub is_portfolio_url {
 7121:     my ($url) = @_;
 7122:     return scalar(&parse_portfolio_url($url));
 7123: }
 7124: 
 7125: sub is_portfolio_file {
 7126:     my ($file) = @_;
 7127:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 7128:         return 1;
 7129:     }
 7130:     return;
 7131: }
 7132: 
 7133: sub usertools_access {
 7134:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 7135:     my ($access,%tools);
 7136:     if ($context eq '') {
 7137:         $context = 'tools';
 7138:     }
 7139:     if ($context eq 'requestcourses') {
 7140:         %tools = (
 7141:                       official   => 1,
 7142:                       unofficial => 1,
 7143:                       community  => 1,
 7144:                       textbook   => 1,
 7145:                       placement  => 1,
 7146:                  );
 7147:     } elsif ($context eq 'requestauthor') {
 7148:         %tools = (
 7149:                       requestauthor => 1,
 7150:                  );
 7151:     } else {
 7152:         %tools = (
 7153:                       aboutme   => 1,
 7154:                       blog      => 1,
 7155:                       webdav    => 1,
 7156:                       portfolio => 1,
 7157:                  );
 7158:     }
 7159:     return if (!defined($tools{$tool}));
 7160: 
 7161:     if (($udom eq '') || ($uname eq '')) {
 7162:         $udom = $env{'user.domain'};
 7163:         $uname = $env{'user.name'};
 7164:     }
 7165: 
 7166:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7167:         if ($action ne 'reload') {
 7168:             if ($context eq 'requestcourses') {
 7169:                 return $env{'environment.canrequest.'.$tool};
 7170:             } elsif ($context eq 'requestauthor') {
 7171:                 return $env{'environment.canrequest.author'};
 7172:             } else {
 7173:                 return $env{'environment.availabletools.'.$tool};
 7174:             }
 7175:         }
 7176:     }
 7177: 
 7178:     my ($toolstatus,$inststatus,$envkey);
 7179:     if ($context eq 'requestauthor') {
 7180:         $envkey = $context; 
 7181:     } else {
 7182:         $envkey = $context.'.'.$tool;
 7183:     }
 7184: 
 7185:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 7186:          ($action ne 'reload')) {
 7187:         $toolstatus = $env{'environment.'.$envkey};
 7188:         $inststatus = $env{'environment.inststatus'};
 7189:     } else {
 7190:         if (ref($userenvref) eq 'HASH') {
 7191:             $toolstatus = $userenvref->{$envkey};
 7192:             $inststatus = $userenvref->{'inststatus'};
 7193:         } else {
 7194:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 7195:             $toolstatus = $userenv{$envkey};
 7196:             $inststatus = $userenv{'inststatus'};
 7197:         }
 7198:     }
 7199: 
 7200:     if ($toolstatus ne '') {
 7201:         if ($toolstatus) {
 7202:             $access = 1;
 7203:         } else {
 7204:             $access = 0;
 7205:         }
 7206:         return $access;
 7207:     }
 7208: 
 7209:     my ($is_adv,%domdef);
 7210:     if (ref($is_advref) eq 'HASH') {
 7211:         $is_adv = $is_advref->{'is_adv'};
 7212:     } else {
 7213:         $is_adv = &is_advanced_user($udom,$uname);
 7214:     }
 7215:     if (ref($domdefref) eq 'HASH') {
 7216:         %domdef = %{$domdefref};
 7217:     } else {
 7218:         %domdef = &get_domain_defaults($udom);
 7219:     }
 7220:     if (ref($domdef{$tool}) eq 'HASH') {
 7221:         if ($is_adv) {
 7222:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 7223:                 if ($domdef{$tool}{'_LC_adv'}) { 
 7224:                     $access = 1;
 7225:                 } else {
 7226:                     $access = 0;
 7227:                 }
 7228:                 return $access;
 7229:             }
 7230:         }
 7231:         if ($inststatus ne '') {
 7232:             my ($hasaccess,$hasnoaccess);
 7233:             foreach my $affiliation (split(/:/,$inststatus)) {
 7234:                 if ($domdef{$tool}{$affiliation} ne '') { 
 7235:                     if ($domdef{$tool}{$affiliation}) {
 7236:                         $hasaccess = 1;
 7237:                     } else {
 7238:                         $hasnoaccess = 1;
 7239:                     }
 7240:                 }
 7241:             }
 7242:             if ($hasaccess || $hasnoaccess) {
 7243:                 if ($hasaccess) {
 7244:                     $access = 1;
 7245:                 } elsif ($hasnoaccess) {
 7246:                     $access = 0; 
 7247:                 }
 7248:                 return $access;
 7249:             }
 7250:         } else {
 7251:             if ($domdef{$tool}{'default'} ne '') {
 7252:                 if ($domdef{$tool}{'default'}) {
 7253:                     $access = 1;
 7254:                 } elsif ($domdef{$tool}{'default'} == 0) {
 7255:                     $access = 0;
 7256:                 }
 7257:                 return $access;
 7258:             }
 7259:         }
 7260:     } else {
 7261:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 7262:             $access = 1;
 7263:         } else {
 7264:             $access = 0;
 7265:         }
 7266:         return $access;
 7267:     }
 7268: }
 7269: 
 7270: sub is_course_owner {
 7271:     my ($cdom,$cnum,$udom,$uname) = @_;
 7272:     if (($udom eq '') || ($uname eq '')) {
 7273:         $udom = $env{'user.domain'};
 7274:         $uname = $env{'user.name'};
 7275:     }
 7276:     unless (($udom eq '') || ($uname eq '')) {
 7277:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 7278:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 7279:                 return 1;
 7280:             } else {
 7281:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 7282:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 7283:                     return 1;
 7284:                 }
 7285:             }
 7286:         }
 7287:     }
 7288:     return;
 7289: }
 7290: 
 7291: sub is_advanced_user {
 7292:     my ($udom,$uname) = @_;
 7293:     if ($udom ne '' && $uname ne '') {
 7294:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7295:             if (wantarray) {
 7296:                 return ($env{'user.adv'},$env{'user.author'});
 7297:             } else {
 7298:                 return $env{'user.adv'};
 7299:             }
 7300:         }
 7301:     }
 7302:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 7303:     my %allroles;
 7304:     my ($is_adv,$is_author);
 7305:     foreach my $role (keys(%roleshash)) {
 7306:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 7307:         my $area = '/'.$tdomain.'/'.$trest;
 7308:         if ($sec ne '') {
 7309:             $area .= '/'.$sec;
 7310:         }
 7311:         if (($area ne '') && ($trole ne '')) {
 7312:             my $spec=$trole.'.'.$area;
 7313:             if ($trole =~ /^cr\//) {
 7314:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 7315:             } elsif ($trole ne 'gr') {
 7316:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 7317:             }
 7318:             if ($trole eq 'au') {
 7319:                 $is_author = 1;
 7320:             }
 7321:         }
 7322:     }
 7323:     foreach my $role (keys(%allroles)) {
 7324:         last if ($is_adv);
 7325:         foreach my $item (split(/:/,$allroles{$role})) {
 7326:             if ($item ne '') {
 7327:                 my ($privilege,$restrictions)=split(/&/,$item);
 7328:                 if ($privilege eq 'adv') {
 7329:                     $is_adv = 1;
 7330:                     last;
 7331:                 }
 7332:             }
 7333:         }
 7334:     }
 7335:     if (wantarray) {
 7336:         return ($is_adv,$is_author);
 7337:     }
 7338:     return $is_adv;
 7339: }
 7340: 
 7341: sub check_can_request {
 7342:     my ($dom,$can_request,$request_domains) = @_;
 7343:     my $canreq = 0;
 7344:     my ($types,$typename) = &Apache::loncommon::course_types();
 7345:     my @options = ('approval','validate','autolimit');
 7346:     my $optregex = join('|',@options);
 7347:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 7348:         foreach my $type (@{$types}) {
 7349:             if (&usertools_access($env{'user.name'},
 7350:                                   $env{'user.domain'},
 7351:                                   $type,undef,'requestcourses')) {
 7352:                 $canreq ++;
 7353:                 if (ref($request_domains) eq 'HASH') {
 7354:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 7355:                 }
 7356:                 if ($dom eq $env{'user.domain'}) {
 7357:                     $can_request->{$type} = 1;
 7358:                 }
 7359:             }
 7360:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 7361:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 7362:                 if (@curr > 0) {
 7363:                     foreach my $item (@curr) {
 7364:                         if (ref($request_domains) eq 'HASH') {
 7365:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 7366:                             if ($otherdom ne '') {
 7367:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 7368:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 7369:                                         push(@{$request_domains->{$type}},$otherdom);
 7370:                                     }
 7371:                                 } else {
 7372:                                     push(@{$request_domains->{$type}},$otherdom);
 7373:                                 }
 7374:                             }
 7375:                         }
 7376:                     }
 7377:                     unless($dom eq $env{'user.domain'}) {
 7378:                         $canreq ++;
 7379:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 7380:                             $can_request->{$type} = 1;
 7381:                         }
 7382:                     }
 7383:                 }
 7384:             }
 7385:         }
 7386:     }
 7387:     return $canreq;
 7388: }
 7389: 
 7390: # ---------------------------------------------- Custom access rule evaluation
 7391: 
 7392: sub customaccess {
 7393:     my ($priv,$uri)=@_;
 7394:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 7395:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 7396:     $udom = &LONCAPA::clean_domain($udom);
 7397:     $ucrs = &LONCAPA::clean_username($ucrs);
 7398:     my $access=0;
 7399:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 7400: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 7401: 	if ($type eq 'user') {
 7402: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 7403: 		my ($tdom,$tuname)=split(m{/},$scope);
 7404: 		if ($tdom) {
 7405: 		    if ($tdom ne $env{'user.domain'}) { next; }
 7406: 		}
 7407: 		if ($tuname) {
 7408: 		    if ($tuname ne $env{'user.name'}) { next; }
 7409: 		}
 7410: 		$access=($effect eq 'allow');
 7411: 		last;
 7412: 	    }
 7413: 	} else {
 7414: 	    if ($role) {
 7415: 		if ($role ne $urole) { next; }
 7416: 	    }
 7417: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 7418: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 7419: 		if ($tdom) {
 7420: 		    if ($tdom ne $udom) { next; }
 7421: 		}
 7422: 		if ($tcrs) {
 7423: 		    if ($tcrs ne $ucrs) { next; }
 7424: 		}
 7425: 		if ($tsec) {
 7426: 		    if ($tsec ne $usec) { next; }
 7427: 		}
 7428: 		$access=($effect eq 'allow');
 7429: 		last;
 7430: 	    }
 7431: 	    if ($realm eq '' && $role eq '') {
 7432: 		$access=($effect eq 'allow');
 7433: 	    }
 7434: 	}
 7435:     }
 7436:     return $access;
 7437: }
 7438: 
 7439: # ------------------------------------------------- Check for a user privilege
 7440: 
 7441: sub allowed {
 7442:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
 7443:     my $ver_orguri=$uri;
 7444:     $uri=&deversion($uri);
 7445:     my $orguri=$uri;
 7446:     $uri=&declutter($uri);
 7447: 
 7448:     if ($priv eq 'evb') {
 7449: # Evade communication block restrictions for specified role in a course
 7450:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 7451:             return $1;
 7452:         } else {
 7453:             return;
 7454:         }
 7455:     }
 7456: 
 7457:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 7458: # Free bre access to adm and meta resources
 7459:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$})) 
 7460: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 7461: 	&& ($priv eq 'bre')) {
 7462: 	return 'F';
 7463:     }
 7464: 
 7465: # Free bre access to user's own portfolio contents
 7466:     my ($space,$domain,$name,@dir)=split('/',$uri);
 7467:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 7468: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 7469:         my %setters;
 7470:         my ($startblock,$endblock) = 
 7471:             &Apache::loncommon::blockcheck(\%setters,'port');
 7472:         if ($startblock && $endblock) {
 7473:             return 'B';
 7474:         } else {
 7475:             return 'F';
 7476:         }
 7477:     }
 7478: 
 7479: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 7480:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 7481:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 7482:         if (exists($env{'request.course.id'})) {
 7483:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7484:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7485:             if (($domain eq $cdom) && ($name eq $cnum)) {
 7486:                 my $courseprivid=$env{'request.course.id'};
 7487:                 $courseprivid=~s/\_/\//;
 7488:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 7489:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 7490:                     return $1; 
 7491:                 } else {
 7492:                     if ($env{'request.course.sec'}) {
 7493:                         $courseprivid.='/'.$env{'request.course.sec'};
 7494:                     }
 7495:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 7496:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 7497:                         return $2;
 7498:                     }
 7499:                 }
 7500:             }
 7501:         }
 7502:     }
 7503: 
 7504: # Free bre to public access
 7505: 
 7506:     if ($priv eq 'bre') {
 7507:         my $copyright=&metadata($uri,'copyright');
 7508: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 7509:            return 'F'; 
 7510:         }
 7511:         if ($copyright eq 'priv') {
 7512:             $uri=~/([^\/]+)\/([^\/]+)\//;
 7513: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 7514: 		return '';
 7515:             }
 7516:         }
 7517:         if ($copyright eq 'domain') {
 7518:             $uri=~/([^\/]+)\/([^\/]+)\//;
 7519: 	    unless (($env{'user.domain'} eq $1) ||
 7520:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 7521: 		return '';
 7522:             }
 7523:         }
 7524:         if ($env{'request.role'}=~ /li\.\//) {
 7525:             # Library role, so allow browsing of resources in this domain.
 7526:             return 'F';
 7527:         }
 7528:         if ($copyright eq 'custom') {
 7529: 	    unless (&customaccess($priv,$uri)) { return ''; }
 7530:         }
 7531:     }
 7532:     # Domain coordinator is trying to create a course
 7533:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 7534:         # uri is the requested domain in this case.
 7535:         # comparison to 'request.role.domain' shows if the user has selected
 7536:         # a role of dc for the domain in question.
 7537:         return 'F' if ($uri eq $env{'request.role.domain'});
 7538:     }
 7539: 
 7540:     my $thisallowed='';
 7541:     my $statecond=0;
 7542:     my $courseprivid='';
 7543: 
 7544:     my $ownaccess;
 7545:     # Community Coordinator or Assistant Co-author browsing resource space.
 7546:     if (($priv eq 'bro') && ($env{'user.author'})) {
 7547:         if ($uri eq '') {
 7548:             $ownaccess = 1;
 7549:         } else {
 7550:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 7551:                 my $udom = $env{'user.domain'};
 7552:                 my $uname = $env{'user.name'};
 7553:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 7554:                     $ownaccess = 1;
 7555:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 7556:                     unless ($uri =~ m{\.\./}) {
 7557:                         $ownaccess = 1;
 7558:                     }
 7559:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 7560:                     my $now = time;
 7561:                     if ($uri =~ m{^([^/]+)/?$}) {
 7562:                         my $adom = $1;
 7563:                         foreach my $key (keys(%env)) {
 7564:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 7565:                                 my ($start,$end) = split('.',$env{$key});
 7566:                                 if (($now >= $start) && (!$end || $end < $now)) {
 7567:                                     $ownaccess = 1;
 7568:                                     last;
 7569:                                 }
 7570:                             }
 7571:                         }
 7572:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 7573:                         my $adom = $1;
 7574:                         my $aname = $2;
 7575:                         foreach my $role ('ca','aa') { 
 7576:                             if ($env{"user.role.$role./$adom/$aname"}) {
 7577:                                 my ($start,$end) =
 7578:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 7579:                                 if (($now >= $start) && (!$end || $end < $now)) {
 7580:                                     $ownaccess = 1;
 7581:                                     last;
 7582:                                 }
 7583:                             }
 7584:                         }
 7585:                     }
 7586:                 }
 7587:             }
 7588:         }
 7589:     }
 7590: 
 7591: # Course
 7592: 
 7593:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 7594:         unless (($priv eq 'bro') && (!$ownaccess)) {
 7595:             $thisallowed.=$1;
 7596:         }
 7597:     }
 7598: 
 7599: # Domain
 7600: 
 7601:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 7602:        =~/\Q$priv\E\&([^\:]*)/) {
 7603:         unless (($priv eq 'bro') && (!$ownaccess)) {
 7604:             $thisallowed.=$1;
 7605:         }
 7606:     }
 7607: 
 7608: # User who is not author or co-author might still be able to edit
 7609: # resource of an author in the domain (e.g., if Domain Coordinator).
 7610:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 7611:         (&allowed('mdc',$env{'request.course.id'}))) {
 7612:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 7613:             $thisallowed.=$1;
 7614:         }
 7615:     }
 7616: 
 7617: # Course: uri itself is a course
 7618:     my $courseuri=$uri;
 7619:     $courseuri=~s/\_(\d)/\/$1/;
 7620:     $courseuri=~s/^([^\/])/\/$1/;
 7621: 
 7622:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 7623:        =~/\Q$priv\E\&([^\:]*)/) {
 7624:         unless (($priv eq 'bro') && (!$ownaccess)) {
 7625:             $thisallowed.=$1;
 7626:         }
 7627:     }
 7628: 
 7629: # URI is an uploaded document for this course, default permissions don't matter
 7630: # not allowing 'edit' access (editupload) to uploaded course docs
 7631:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 7632: 	$thisallowed='';
 7633:         my ($match)=&is_on_map($uri);
 7634:         if ($match) {
 7635:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 7636:                   =~/\Q$priv\E\&([^\:]*)/) {
 7637:                 my $value = $1;
 7638:                 if ($noblockcheck) {
 7639:                     $thisallowed.=$value;
 7640:                 } else {
 7641:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
 7642:                     if (@blockers > 0) {
 7643:                         $thisallowed = 'B';
 7644:                     } else {
 7645:                         $thisallowed.=$value;
 7646:                     }
 7647:                 }
 7648:             }
 7649:         } else {
 7650:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 7651:             if ($refuri) {
 7652:                 if ($refuri =~ m|^/adm/|) {
 7653:                     $thisallowed='F';
 7654:                 } else {
 7655:                     $refuri=&declutter($refuri);
 7656:                     my ($match) = &is_on_map($refuri);
 7657:                     if ($match) {
 7658:                         if ($noblockcheck) {
 7659:                             $thisallowed='F';
 7660:                         } else {
 7661:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 7662:                             if (@blockers > 0) {
 7663:                                 $thisallowed = 'B';
 7664:                             } else {
 7665:                                 $thisallowed='F';
 7666:                             }
 7667:                         }
 7668:                     }
 7669:                 }
 7670:             }
 7671:         }
 7672:     }
 7673: 
 7674:     if ($priv eq 'bre'
 7675: 	&& $thisallowed ne 'F' 
 7676: 	&& $thisallowed ne '2'
 7677: 	&& &is_portfolio_url($uri)) {
 7678: 	$thisallowed = &portfolio_access($uri,$clientip);
 7679:     }
 7680: 
 7681: # Full access at system, domain or course-wide level? Exit.
 7682:     if ($thisallowed=~/F/) {
 7683: 	return 'F';
 7684:     }
 7685: 
 7686: # If this is generating or modifying users, exit with special codes
 7687: 
 7688:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 7689: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 7690: 	    my ($audom,$auname)=split('/',$uri);
 7691: # no author name given, so this just checks on the general right to make a co-author in this domain
 7692: 	    unless ($auname) { return $thisallowed; }
 7693: # an author name is given, so we are about to actually make a co-author for a certain account
 7694: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 7695: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 7696: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 7697: 	}
 7698: 	return $thisallowed;
 7699:     }
 7700: #
 7701: # Gathered so far: system, domain and course wide privileges
 7702: #
 7703: # Course: See if uri or referer is an individual resource that is part of 
 7704: # the course
 7705: 
 7706:     if ($env{'request.course.id'}) {
 7707: 
 7708:        $courseprivid=$env{'request.course.id'};
 7709:        if ($env{'request.course.sec'}) {
 7710:           $courseprivid.='/'.$env{'request.course.sec'};
 7711:        }
 7712:        $courseprivid=~s/\_/\//;
 7713:        my $checkreferer=1;
 7714:        my ($match,$cond)=&is_on_map($uri);
 7715:        if ($match) {
 7716:            $statecond=$cond;
 7717:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 7718:                =~/\Q$priv\E\&([^\:]*)/) {
 7719:                my $value = $1;
 7720:                if ($priv eq 'bre') {
 7721:                    if ($noblockcheck) {
 7722:                        $thisallowed.=$value;
 7723:                    } else {
 7724:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
 7725:                        if (@blockers > 0) {
 7726:                            $thisallowed = 'B';
 7727:                        } else {
 7728:                            $thisallowed.=$value;
 7729:                        }
 7730:                    }
 7731:                } else {
 7732:                    $thisallowed.=$value;
 7733:                }
 7734:                $checkreferer=0;
 7735:            }
 7736:        }
 7737:        
 7738:        if ($checkreferer) {
 7739: 	  my $refuri=$env{'httpref.'.$orguri};
 7740:             unless ($refuri) {
 7741:                 foreach my $key (keys(%env)) {
 7742: 		    if ($key=~/^httpref\..*\*/) {
 7743: 			my $pattern=$key;
 7744:                         $pattern=~s/^httpref\.\/res\///;
 7745:                         $pattern=~s/\*/\[\^\/\]\+/g;
 7746:                         $pattern=~s/\//\\\//g;
 7747:                         if ($orguri=~/$pattern/) {
 7748: 			    $refuri=$env{$key};
 7749:                         }
 7750:                     }
 7751:                 }
 7752:             }
 7753: 
 7754:          if ($refuri) { 
 7755: 	  $refuri=&declutter($refuri);
 7756:           my ($match,$cond)=&is_on_map($refuri);
 7757:             if ($match) {
 7758:               my $refstatecond=$cond;
 7759:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 7760:                   =~/\Q$priv\E\&([^\:]*)/) {
 7761:                   my $value = $1;
 7762:                   if ($priv eq 'bre') {
 7763:                       if ($noblockcheck) {
 7764:                           $thisallowed.=$value;
 7765:                       } else {
 7766:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 7767:                           if (@blockers > 0) {
 7768:                               $thisallowed = 'B';
 7769:                           } else {
 7770:                               $thisallowed.=$value;
 7771:                           }
 7772:                       }
 7773:                   } else {
 7774:                       $thisallowed.=$value;
 7775:                   }
 7776:                   $uri=$refuri;
 7777:                   $statecond=$refstatecond;
 7778:               }
 7779:           }
 7780:         }
 7781:        }
 7782:    }
 7783: 
 7784: #
 7785: # Gathered now: all privileges that could apply, and condition number
 7786: # 
 7787: #
 7788: # Full or no access?
 7789: #
 7790: 
 7791:     if ($thisallowed=~/F/) {
 7792: 	return 'F';
 7793:     }
 7794: 
 7795:     unless ($thisallowed) {
 7796:         return '';
 7797:     }
 7798: 
 7799: # Restrictions exist, deal with them
 7800: #
 7801: #   C:according to course preferences
 7802: #   R:according to resource settings
 7803: #   L:unless locked
 7804: #   X:according to user session state
 7805: #
 7806: 
 7807: # Possibly locked functionality, check all courses
 7808: # Locks might take effect only after 10 minutes cache expiration for other
 7809: # courses, and 2 minutes for current course
 7810: 
 7811:     my $envkey;
 7812:     if ($thisallowed=~/L/) {
 7813:         foreach $envkey (keys(%env)) {
 7814:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 7815:                my $courseid=$2;
 7816:                my $roleid=$1.'.'.$2;
 7817:                $courseid=~s/^\///;
 7818:                my $expiretime=600;
 7819:                if ($env{'request.role'} eq $roleid) {
 7820: 		  $expiretime=120;
 7821:                }
 7822: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 7823:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 7824:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 7825: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 7826:                }
 7827:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 7828:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 7829: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 7830:                        &log($env{'user.domain'},$env{'user.name'},
 7831:                             $env{'user.home'},
 7832:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 7833:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 7834:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 7835: 		       return '';
 7836:                    }
 7837:                }
 7838:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 7839:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 7840: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 7841:                        &log($env{'user.domain'},$env{'user.name'},
 7842:                             $env{'user.home'},
 7843:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 7844:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 7845:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 7846: 		       return '';
 7847:                    }
 7848:                }
 7849: 	   }
 7850:        }
 7851:     }
 7852:    
 7853: #
 7854: # Rest of the restrictions depend on selected course
 7855: #
 7856: 
 7857:     unless ($env{'request.course.id'}) {
 7858: 	if ($thisallowed eq 'A') {
 7859: 	    return 'A';
 7860:         } elsif ($thisallowed eq 'B') {
 7861:             return 'B';
 7862: 	} else {
 7863: 	    return '1';
 7864: 	}
 7865:     }
 7866: 
 7867: #
 7868: # Now user is definitely in a course
 7869: #
 7870: 
 7871: 
 7872: # Course preferences
 7873: 
 7874:    if ($thisallowed=~/C/) {
 7875:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 7876:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 7877:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 7878: 	   =~/\Q$rolecode\E/) {
 7879: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 7880: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 7881: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 7882: 			$env{'request.course.id'});
 7883: 	   }
 7884:            return '';
 7885:        }
 7886: 
 7887:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 7888: 	   =~/\Q$unamedom\E/) {
 7889: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 7890: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 7891: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 7892: 			$env{'request.course.id'});
 7893: 	   }
 7894:            return '';
 7895:        }
 7896:    }
 7897: 
 7898: # Resource preferences
 7899: 
 7900:    if ($thisallowed=~/R/) {
 7901:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 7902:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 7903: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 7904: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 7905: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 7906: 	   }
 7907: 	   return '';
 7908:        }
 7909:    }
 7910: 
 7911: # Restricted by state or randomout?
 7912: 
 7913:    if ($thisallowed=~/X/) {
 7914:       if ($env{'acc.randomout'}) {
 7915: 	 if (!$symb) { $symb=&symbread($uri,1); }
 7916:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 7917:             return ''; 
 7918:          }
 7919:       }
 7920:       if (&condval($statecond)) {
 7921: 	 return '2';
 7922:       } else {
 7923:          return '';
 7924:       }
 7925:    }
 7926: 
 7927:     if ($thisallowed eq 'A') {
 7928: 	return 'A';
 7929:     } elsif ($thisallowed eq 'B') {
 7930:         return 'B';
 7931:     }
 7932:    return 'F';
 7933: }
 7934: 
 7935: # ------------------------------------------- Check construction space access
 7936: 
 7937: sub constructaccess {
 7938:     my ($url,$setpriv)=@_;
 7939: 
 7940: # We do not allow editing of previous versions of files
 7941:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 7942: 
 7943: # Get username and domain from URL
 7944:     my ($ownername,$ownerdomain,$ownerhome);
 7945: 
 7946:     ($ownerdomain,$ownername) =
 7947:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
 7948: 
 7949: # The URL does not really point to any authorspace, forget it
 7950:     unless (($ownername) && ($ownerdomain)) { return ''; }
 7951: 
 7952: # Now we need to see if the user has access to the authorspace of
 7953: # $ownername at $ownerdomain
 7954: 
 7955:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 7956: # Real author for this?
 7957:        $ownerhome = $env{'user.home'};
 7958:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 7959:           return ($ownername,$ownerdomain,$ownerhome);
 7960:        }
 7961:     } else {
 7962: # Co-author for this?
 7963:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 7964:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 7965:             $ownerhome = &homeserver($ownername,$ownerdomain);
 7966:             return ($ownername,$ownerdomain,$ownerhome);
 7967:         }
 7968:         if ($env{'request.course.id'}) {
 7969:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
 7970:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
 7971:                 if (&allowed('mdc',$env{'request.course.id'})) {
 7972:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
 7973:                     return ($ownername,$ownerdomain,$ownerhome);
 7974:                 }
 7975:             }
 7976:         }
 7977:     }
 7978: 
 7979: # We don't have any access right now. If we are not possibly going to do anything about this,
 7980: # we might as well leave
 7981:    unless ($setpriv) { return ''; }
 7982: 
 7983: # Backdoor access?
 7984:     my $allowed=&allowed('eco',$ownerdomain);
 7985: # Nope
 7986:     unless ($allowed) { return ''; }
 7987: # Looks like we may have access, but could be locked by the owner of the construction space
 7988:     if ($allowed eq 'U') {
 7989:         my %blocked=&get('environment',['domcoord.author'],
 7990:                          $ownerdomain,$ownername);
 7991: # Is blocked by owner
 7992:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 7993:     }
 7994:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 7995: # Grant temporary access
 7996:         my $then=$env{'user.login.time'};
 7997:         my $update=$env{'user.update.time'};
 7998:         if (!$update) { $update = $then; }
 7999:         my $refresh=$env{'user.refresh.time'};
 8000:         if (!$refresh) { $refresh = $update; }
 8001:         my $now = time;
 8002:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 8003:                            $now,'ca','constructaccess');
 8004:         $ownerhome = &homeserver($ownername,$ownerdomain);
 8005:         return($ownername,$ownerdomain,$ownerhome);
 8006:     }
 8007: # No business here
 8008:     return '';
 8009: }
 8010: 
 8011: # ----------------------------------------------------------- Content Blocking
 8012: 
 8013: {
 8014: # Caches for faster Course Contents display where content blocking
 8015: # is in operation (i.e., interval param set) for timed quiz.
 8016: #
 8017: # User for whom data are being temporarily cached.
 8018: my $cacheduser='';
 8019: # Cached blockers for this user (a hash of blocking items). 
 8020: my %cachedblockers=();
 8021: # When the data were last cached.
 8022: my $cachedlast='';
 8023: 
 8024: sub load_all_blockers {
 8025:     my ($uname,$udom,$blocks)=@_;
 8026:     if (($uname ne '') && ($udom ne '')) { 
 8027:         if (($cacheduser eq $uname.':'.$udom) &&
 8028:             (abs($cachedlast-time)<5)) {
 8029:             return;
 8030:         }
 8031:     }
 8032:     $cachedlast=time;
 8033:     $cacheduser=$uname.':'.$udom;
 8034:     %cachedblockers = &get_commblock_resources($blocks);
 8035: }
 8036: 
 8037: sub get_comm_blocks {
 8038:     my ($cdom,$cnum) = @_;
 8039:     if ($cdom eq '' || $cnum eq '') {
 8040:         return unless ($env{'request.course.id'});
 8041:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8042:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8043:     }
 8044:     my %commblocks;
 8045:     my $hashid=$cdom.'_'.$cnum;
 8046:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 8047:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 8048:         %commblocks = %{$blocksref};
 8049:     } else {
 8050:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 8051:         my $cachetime = 600;
 8052:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 8053:     }
 8054:     return %commblocks;
 8055: }
 8056: 
 8057: sub get_commblock_resources {
 8058:     my ($blocks) = @_;
 8059:     my %blockers = ();
 8060:     return %blockers unless ($env{'request.course.id'});
 8061:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8062:     my %commblocks;
 8063:     if (ref($blocks) eq 'HASH') {
 8064:         %commblocks = %{$blocks};
 8065:     } else {
 8066:         %commblocks = &get_comm_blocks();
 8067:     }
 8068:     return %blockers unless (keys(%commblocks) > 0); 
 8069:     my $navmap = Apache::lonnavmaps::navmap->new();
 8070:     return %blockers unless (ref($navmap));
 8071:     my $now = time;
 8072:     foreach my $block (keys(%commblocks)) {
 8073:         if ($block =~ /^(\d+)____(\d+)$/) {
 8074:             my ($start,$end) = ($1,$2);
 8075:             if ($start <= $now && $end >= $now) {
 8076:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8077:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8078:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8079:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8080:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
 8081:                             }
 8082:                         }
 8083:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8084:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8085:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8086:                             }
 8087:                         }
 8088:                     }
 8089:                 }
 8090:             }
 8091:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 8092:             my $item = $1;
 8093:             my @to_test;
 8094:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8095:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8096:                     my @interval;
 8097:                     my $type = 'map';
 8098:                     if ($item eq 'course') {
 8099:                         $type = 'course';
 8100:                         @interval=&EXT("resource.0.interval");
 8101:                     } else {
 8102:                         if ($item =~ /___\d+___/) {
 8103:                             $type = 'resource';
 8104:                             @interval=&EXT("resource.0.interval",$item);
 8105:                             if (ref($navmap)) {                        
 8106:                                 my $res = $navmap->getBySymb($item); 
 8107:                                 push(@to_test,$res);
 8108:                             }
 8109:                         } else {
 8110:                             my $mapsymb = &symbread($item,1);
 8111:                             if ($mapsymb) {
 8112:                                 if (ref($navmap)) {
 8113:                                     my $mapres = $navmap->getBySymb($mapsymb);
 8114:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
 8115:                                     foreach my $res (@to_test) {
 8116:                                         my $symb = $res->symb();
 8117:                                         next if ($symb eq $mapsymb);
 8118:                                         if ($symb ne '') {
 8119:                                             @interval=&EXT("resource.0.interval",$symb);
 8120:                                             if ($interval[1] eq 'map') {
 8121:                                                 last;
 8122:                                             }
 8123:                                         }
 8124:                                     }
 8125:                                 }
 8126:                             }
 8127:                         }
 8128:                     }
 8129:                     if ($interval[0] =~ /^(\d+)/) {
 8130:                         my $timelimit = $1; 
 8131:                         my $first_access;
 8132:                         if ($type eq 'resource') {
 8133:                             $first_access=&get_first_access($interval[1],$item);
 8134:                         } elsif ($type eq 'map') {
 8135:                             $first_access=&get_first_access($interval[1],undef,$item);
 8136:                         } else {
 8137:                             $first_access=&get_first_access($interval[1]);
 8138:                         }
 8139:                         if ($first_access) {
 8140:                             my $timesup = $first_access+$timelimit;
 8141:                             if ($timesup > $now) {
 8142:                                 my $activeblock;
 8143:                                 foreach my $res (@to_test) {
 8144:                                     if ($res->answerable()) {
 8145:                                         $activeblock = 1;
 8146:                                         last;
 8147:                                     }
 8148:                                 }
 8149:                                 if ($activeblock) {
 8150:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8151:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8152:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 8153:                                          }
 8154:                                     }
 8155:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8156:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8157:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8158:                                         }
 8159:                                     }
 8160:                                 }
 8161:                             }
 8162:                         }
 8163:                     }
 8164:                 }
 8165:             }
 8166:         }
 8167:     }
 8168:     return %blockers;
 8169: }
 8170: 
 8171: sub has_comm_blocking {
 8172:     my ($priv,$symb,$uri,$blocks) = @_;
 8173:     my @blockers;
 8174:     return unless ($env{'request.course.id'});
 8175:     return unless ($priv eq 'bre');
 8176:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8177:     return if ($env{'request.state'} eq 'construct');
 8178:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
 8179:     return unless (keys(%cachedblockers) > 0);
 8180:     my (%possibles,@symbs);
 8181:     if (!$symb) {
 8182:         $symb = &symbread($uri,1,1,1,\%possibles);
 8183:     }
 8184:     if ($symb) {
 8185:         @symbs = ($symb);
 8186:     } elsif (keys(%possibles)) { 
 8187:         @symbs = keys(%possibles);
 8188:     }
 8189:     my $noblock;
 8190:     foreach my $symb (@symbs) {
 8191:         last if ($noblock);
 8192:         my ($map,$resid,$resurl)=&decode_symb($symb);
 8193:         foreach my $block (keys(%cachedblockers)) {
 8194:             if ($block =~ /^firstaccess____(.+)$/) {
 8195:                 my $item = $1;
 8196:                 if (($item eq $map) || ($item eq $symb)) {
 8197:                     $noblock = 1;
 8198:                     last;
 8199:                 }
 8200:             }
 8201:             if (ref($cachedblockers{$block}) eq 'HASH') {
 8202:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
 8203:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
 8204:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 8205:                             push(@blockers,$block);
 8206:                         }
 8207:                     }
 8208:                 }
 8209:             }
 8210:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
 8211:                 if ($cachedblockers{$block}{'maps'}{$map}) {
 8212:                     unless (grep(/^\Q$block\E$/,@blockers)) {
 8213:                         push(@blockers,$block);
 8214:                     }
 8215:                 }
 8216:             }
 8217:         }
 8218:     }
 8219:     return if ($noblock);
 8220:     return @blockers;
 8221: }
 8222: }
 8223: 
 8224: # -------------------------------- Deversion and split uri into path an filename   
 8225: 
 8226: #
 8227: #   Removes the version from a URI and
 8228: #   splits it in to its filename and path to the filename.
 8229: #   Seems like File::Basename could have done this more clearly.
 8230: #   Parameters:
 8231: #      $uri   - input URI
 8232: #   Returns:
 8233: #     Two element list consisting of 
 8234: #     $pathname  - the URI up to and excluding the trailing /
 8235: #     $filename  - The part of the URI following the last /
 8236: #  NOTE:
 8237: #    Another realization of this is simply:
 8238: #    use File::Basename;
 8239: #    ...
 8240: #    $uri = shift;
 8241: #    $filename = basename($uri);
 8242: #    $path     = dirname($uri);
 8243: #    return ($filename, $path);
 8244: #
 8245: #     The implementation below is probably faster however.
 8246: #
 8247: sub split_uri_for_cond {
 8248:     my $uri=&deversion(&declutter(shift));
 8249:     my @uriparts=split(/\//,$uri);
 8250:     my $filename=pop(@uriparts);
 8251:     my $pathname=join('/',@uriparts);
 8252:     return ($pathname,$filename);
 8253: }
 8254: # --------------------------------------------------- Is a resource on the map?
 8255: 
 8256: sub is_on_map {
 8257:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 8258:     #Trying to find the conditional for the file
 8259:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 8260: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 8261:     if ($match) {
 8262: 	return (1,$1);
 8263:     } else {
 8264: 	return (0,0);
 8265:     }
 8266: }
 8267: 
 8268: # --------------------------------------------------------- Get symb from alias
 8269: 
 8270: sub get_symb_from_alias {
 8271:     my $symb=shift;
 8272:     my ($map,$resid,$url)=&decode_symb($symb);
 8273: # Already is a symb
 8274:     if ($url) { return $symb; }
 8275: # Must be an alias
 8276:     my $aliassymb='';
 8277:     my %bighash;
 8278:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8279:                             &GDBM_READER(),0640)) {
 8280:         my $rid=$bighash{'mapalias_'.$symb};
 8281: 	if ($rid) {
 8282: 	    my ($mapid,$resid)=split(/\./,$rid);
 8283: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 8284: 				    $resid,$bighash{'src_'.$rid});
 8285: 	}
 8286:         untie %bighash;
 8287:     }
 8288:     return $aliassymb;
 8289: }
 8290: 
 8291: # ----------------------------------------------------------------- Define Role
 8292: 
 8293: sub definerole {
 8294:   if (allowed('mcr','/')) {
 8295:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
 8296:     foreach my $role (split(':',$sysrole)) {
 8297: 	my ($crole,$cqual)=split(/\&/,$role);
 8298:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 8299:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 8300: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 8301:                return "refused:s:$crole&$cqual"; 
 8302:             }
 8303:         }
 8304:     }
 8305:     foreach my $role (split(':',$domrole)) {
 8306: 	my ($crole,$cqual)=split(/\&/,$role);
 8307:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 8308:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 8309: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 8310:                return "refused:d:$crole&$cqual"; 
 8311:             }
 8312:         }
 8313:     }
 8314:     foreach my $role (split(':',$courole)) {
 8315: 	my ($crole,$cqual)=split(/\&/,$role);
 8316:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 8317:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 8318: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 8319:                return "refused:c:$crole&$cqual"; 
 8320:             }
 8321:         }
 8322:     }
 8323:     my $uhome;
 8324:     if (($uname ne '') && ($udom ne '')) {
 8325:         $uhome = &homeserver($uname,$udom);
 8326:         return $uhome if ($uhome eq 'no_host');
 8327:     } else {
 8328:         $uname = $env{'user.name'};
 8329:         $udom = $env{'user.domain'};
 8330:         $uhome = $env{'user.home'};
 8331:     }
 8332:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 8333:                 "$udom:$uname:rolesdef_$rolename=".
 8334:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 8335:     return reply($command,$uhome);
 8336:   } else {
 8337:     return 'refused';
 8338:   }
 8339: }
 8340: 
 8341: # ---------------- Make a metadata query against the network of library servers
 8342: 
 8343: sub metadata_query {
 8344:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 8345:     my %rhash;
 8346:     my %libserv = &all_library();
 8347:     my @server_list = (defined($server_array) ? @$server_array
 8348:                                               : keys(%libserv) );
 8349:     for my $server (@server_list) {
 8350:         my $domains = ''; 
 8351:         if (ref($domains_hash) eq 'HASH') {
 8352:             $domains = $domains_hash->{$server}; 
 8353:         }
 8354: 	unless ($custom or $customshow) {
 8355: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 8356: 	    $rhash{$server}=$reply;
 8357: 	}
 8358: 	else {
 8359: 	    my $reply=&reply("querysend:".&escape($query).':'.
 8360: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 8361: 			     $server);
 8362: 	    $rhash{$server}=$reply;
 8363: 	}
 8364:     }
 8365:     return \%rhash;
 8366: }
 8367: 
 8368: # ----------------------------------------- Send log queries and wait for reply
 8369: 
 8370: sub log_query {
 8371:     my ($uname,$udom,$query,%filters)=@_;
 8372:     my $uhome=&homeserver($uname,$udom);
 8373:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 8374:     my $uhost=&hostname($uhome);
 8375:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 8376:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 8377:                        $uhome);
 8378:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 8379:     return get_query_reply($queryid);
 8380: }
 8381: 
 8382: # -------------------------- Update MySQL table for portfolio file
 8383: 
 8384: sub update_portfolio_table {
 8385:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 8386:     if ($group ne '') {
 8387:         $file_name =~s /^\Q$group\E//;
 8388:     }
 8389:     my $homeserver = &homeserver($uname,$udom);
 8390:     my $queryid=
 8391:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 8392:                ':'.&escape($file_name).':'.$action,$homeserver);
 8393:     my $reply = &get_query_reply($queryid);
 8394:     return $reply;
 8395: }
 8396: 
 8397: # -------------------------- Update MySQL allusers table
 8398: 
 8399: sub update_allusers_table {
 8400:     my ($uname,$udom,$names) = @_;
 8401:     my $homeserver = &homeserver($uname,$udom);
 8402:     my $queryid=
 8403:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 8404:                'lastname='.&escape($names->{'lastname'}).'%%'.
 8405:                'firstname='.&escape($names->{'firstname'}).'%%'.
 8406:                'middlename='.&escape($names->{'middlename'}).'%%'.
 8407:                'generation='.&escape($names->{'generation'}).'%%'.
 8408:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 8409:                'id='.&escape($names->{'id'}),$homeserver);
 8410:     return;
 8411: }
 8412: 
 8413: # ------- Request retrieval of institutional classlists for course(s)
 8414: 
 8415: sub fetch_enrollment_query {
 8416:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 8417:     my ($homeserver,$sleep,$loopmax);
 8418:     my $maxtries = 1;
 8419:     if ($context eq 'automated') {
 8420:         $homeserver = $perlvar{'lonHostID'};
 8421:         $sleep = 2;
 8422:         $loopmax = 100;
 8423:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 8424:     } else {
 8425:         $homeserver = &homeserver($cnum,$dom);
 8426:     }
 8427:     my $host=&hostname($homeserver);
 8428:     my $cmd = '';
 8429:     foreach my $affiliate (keys(%{$affiliatesref})) {
 8430:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 8431:     }
 8432:     $cmd =~ s/%%$//;
 8433:     $cmd = &escape($cmd);
 8434:     my $query = 'fetchenrollment';
 8435:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 8436:     unless ($queryid=~/^\Q$host\E\_/) { 
 8437:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 8438:         return 'error: '.$queryid;
 8439:     }
 8440:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
 8441:     my $tries = 1;
 8442:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 8443:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
 8444:         $tries ++;
 8445:     }
 8446:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 8447:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 8448:     } else {
 8449:         my @responses = split(/:/,$reply);
 8450:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
 8451:             foreach my $line (@responses) {
 8452:                 my ($key,$value) = split(/=/,$line,2);
 8453:                 $$replyref{$key} = $value;
 8454:             }
 8455:         } else {
 8456:             my $pathname = LONCAPA::tempdir();
 8457:             foreach my $line (@responses) {
 8458:                 my ($key,$value) = split(/=/,$line);
 8459:                 $$replyref{$key} = $value;
 8460:                 if ($value > 0) {
 8461:                     foreach my $item (@{$$affiliatesref{$key}}) {
 8462:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 8463:                         my $destname = $pathname.'/'.$filename;
 8464:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 8465:                         if ($xml_classlist =~ /^error/) {
 8466:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 8467:                         } else {
 8468:                             if ( open(FILE,">",$destname) ) {
 8469:                                 print FILE &unescape($xml_classlist);
 8470:                                 close(FILE);
 8471:                             } else {
 8472:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 8473:                             }
 8474:                         }
 8475:                     }
 8476:                 }
 8477:             }
 8478:         }
 8479:         return 'ok';
 8480:     }
 8481:     return 'error';
 8482: }
 8483: 
 8484: sub get_query_reply {
 8485:     my ($queryid,$sleep,$loopmax) = @_;;
 8486:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
 8487:         $sleep = 0.2;
 8488:     }
 8489:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
 8490:         $loopmax = 100;
 8491:     }
 8492:     my $replyfile=LONCAPA::tempdir().$queryid;
 8493:     my $reply='';
 8494:     for (1..$loopmax) {
 8495: 	sleep($sleep);
 8496:         if (-e $replyfile.'.end') {
 8497: 	    if (open(my $fh,"<",$replyfile)) {
 8498: 		$reply = join('',<$fh>);
 8499: 		close($fh);
 8500: 	   } else { return 'error: reply_file_error'; }
 8501:            return &unescape($reply);
 8502: 	}
 8503:     }
 8504:     return 'timeout:'.$queryid;
 8505: }
 8506: 
 8507: sub courselog_query {
 8508: #
 8509: # possible filters:
 8510: # url: url or symb
 8511: # username
 8512: # domain
 8513: # action: view, submit, grade
 8514: # start: timestamp
 8515: # end: timestamp
 8516: #
 8517:     my (%filters)=@_;
 8518:     unless ($env{'request.course.id'}) { return 'no_course'; }
 8519:     if ($filters{'url'}) {
 8520: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 8521:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 8522:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 8523:     }
 8524:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 8525:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8526:     return &log_query($cname,$cdom,'courselog',%filters);
 8527: }
 8528: 
 8529: sub userlog_query {
 8530: #
 8531: # possible filters:
 8532: # action: log check role
 8533: # start: timestamp
 8534: # end: timestamp
 8535: #
 8536:     my ($uname,$udom,%filters)=@_;
 8537:     return &log_query($uname,$udom,'userlog',%filters);
 8538: }
 8539: 
 8540: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 8541: 
 8542: sub auto_run {
 8543:     my ($cnum,$cdom) = @_;
 8544:     my $response = 0;
 8545:     my $settings;
 8546:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 8547:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 8548:         $settings = $domconfig{'autoenroll'};
 8549:         if ($settings->{'run'} eq '1') {
 8550:             $response = 1;
 8551:         }
 8552:     } else {
 8553:         my $homeserver;
 8554:         if (&is_course($cdom,$cnum)) {
 8555:             $homeserver = &homeserver($cnum,$cdom);
 8556:         } else {
 8557:             $homeserver = &domain($cdom,'primary');
 8558:         }
 8559:         if ($homeserver ne 'no_host') {
 8560:             $response = &reply('autorun:'.$cdom,$homeserver);
 8561:         }
 8562:     }
 8563:     return $response;
 8564: }
 8565: 
 8566: sub auto_get_sections {
 8567:     my ($cnum,$cdom,$inst_coursecode) = @_;
 8568:     my $homeserver;
 8569:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 8570:         $homeserver = &homeserver($cnum,$cdom);
 8571:     }
 8572:     if (!defined($homeserver)) { 
 8573:         if ($cdom =~ /^$match_domain$/) {
 8574:             $homeserver = &domain($cdom,'primary');
 8575:         }
 8576:     }
 8577:     my @secs;
 8578:     if (defined($homeserver)) {
 8579:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 8580:         unless ($response eq 'refused') {
 8581:             @secs = split(/:/,$response);
 8582:         }
 8583:     }
 8584:     return @secs;
 8585: }
 8586: 
 8587: sub auto_new_course {
 8588:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 8589:     my $homeserver = &homeserver($cnum,$cdom);
 8590:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 8591:     return $response;
 8592: }
 8593: 
 8594: sub auto_validate_courseID {
 8595:     my ($cnum,$cdom,$inst_course_id) = @_;
 8596:     my $homeserver = &homeserver($cnum,$cdom);
 8597:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 8598:     return $response;
 8599: }
 8600: 
 8601: sub auto_validate_instcode {
 8602:     my ($cnum,$cdom,$instcode,$owner) = @_;
 8603:     my ($homeserver,$response);
 8604:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 8605:         $homeserver = &homeserver($cnum,$cdom);
 8606:     }
 8607:     if (!defined($homeserver)) {
 8608:         if ($cdom =~ /^$match_domain$/) {
 8609:             $homeserver = &domain($cdom,'primary');
 8610:         }
 8611:     }
 8612:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 8613:                         &escape($instcode).':'.&escape($owner),$homeserver));
 8614:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 8615:     return ($outcome,$description,$defaultcredits);
 8616: }
 8617: 
 8618: sub auto_create_password {
 8619:     my ($cnum,$cdom,$authparam,$udom) = @_;
 8620:     my ($homeserver,$response);
 8621:     my $create_passwd = 0;
 8622:     my $authchk = '';
 8623:     if ($udom =~ /^$match_domain$/) {
 8624:         $homeserver = &domain($udom,'primary');
 8625:     }
 8626:     if ($homeserver eq '') {
 8627:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 8628:             $homeserver = &homeserver($cnum,$cdom);
 8629:         }
 8630:     }
 8631:     if ($homeserver eq '') {
 8632:         $authchk = 'nodomain';
 8633:     } else {
 8634:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 8635:         if ($response eq 'refused') {
 8636:             $authchk = 'refused';
 8637:         } else {
 8638:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 8639:         }
 8640:     }
 8641:     return ($authparam,$create_passwd,$authchk);
 8642: }
 8643: 
 8644: sub auto_photo_permission {
 8645:     my ($cnum,$cdom,$students) = @_;
 8646:     my $homeserver = &homeserver($cnum,$cdom);
 8647:     my ($outcome,$perm_reqd,$conditions) = 
 8648: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 8649:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 8650: 	return (undef,undef);
 8651:     }
 8652:     return ($outcome,$perm_reqd,$conditions);
 8653: }
 8654: 
 8655: sub auto_checkphotos {
 8656:     my ($uname,$udom,$pid) = @_;
 8657:     my $homeserver = &homeserver($uname,$udom);
 8658:     my ($result,$resulttype);
 8659:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 8660: 				   &escape($uname).':'.&escape($pid),
 8661: 				   $homeserver));
 8662:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 8663: 	return (undef,undef);
 8664:     }
 8665:     if ($outcome) {
 8666:         ($result,$resulttype) = split(/:/,$outcome);
 8667:     } 
 8668:     return ($result,$resulttype);
 8669: }
 8670: 
 8671: sub auto_photochoice {
 8672:     my ($cnum,$cdom) = @_;
 8673:     my $homeserver = &homeserver($cnum,$cdom);
 8674:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 8675: 						       &escape($cdom),
 8676: 						       $homeserver)));
 8677:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 8678: 	return (undef,undef);
 8679:     }
 8680:     return ($update,$comment);
 8681: }
 8682: 
 8683: sub auto_photoupdate {
 8684:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 8685:     my $homeserver = &homeserver($cnum,$dom);
 8686:     my $host=&hostname($homeserver);
 8687:     my $cmd = '';
 8688:     my $maxtries = 1;
 8689:     foreach my $affiliate (keys(%{$affiliatesref})) {
 8690:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 8691:     }
 8692:     $cmd =~ s/%%$//;
 8693:     $cmd = &escape($cmd);
 8694:     my $query = 'institutionalphotos';
 8695:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 8696:     unless ($queryid=~/^\Q$host\E\_/) {
 8697:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 8698:         return 'error: '.$queryid;
 8699:     }
 8700:     my $reply = &get_query_reply($queryid);
 8701:     my $tries = 1;
 8702:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 8703:         $reply = &get_query_reply($queryid);
 8704:         $tries ++;
 8705:     }
 8706:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 8707:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 8708:     } else {
 8709:         my @responses = split(/:/,$reply);
 8710:         my $outcome = shift(@responses); 
 8711:         foreach my $item (@responses) {
 8712:             my ($key,$value) = split(/=/,$item);
 8713:             $$photo{$key} = $value;
 8714:         }
 8715:         return $outcome;
 8716:     }
 8717:     return 'error';
 8718: }
 8719: 
 8720: sub auto_instcode_format {
 8721:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 8722: 	$cat_order) = @_;
 8723:     my $courses = '';
 8724:     my @homeservers;
 8725:     if ($caller eq 'global') {
 8726: 	my %servers = &get_servers($codedom,'library');
 8727: 	foreach my $tryserver (keys(%servers)) {
 8728: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 8729: 		push(@homeservers,$tryserver);
 8730: 	    }
 8731:         }
 8732:     } elsif ($caller eq 'requests') {
 8733:         if ($codedom =~ /^$match_domain$/) {
 8734:             my $chome = &domain($codedom,'primary');
 8735:             unless ($chome eq 'no_host') {
 8736:                 push(@homeservers,$chome);
 8737:             }
 8738:         }
 8739:     } else {
 8740:         push(@homeservers,&homeserver($caller,$codedom));
 8741:     }
 8742:     foreach my $code (keys(%{$instcodes})) {
 8743:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 8744:     }
 8745:     chop($courses);
 8746:     my $ok_response = 0;
 8747:     my $response;
 8748:     while (@homeservers > 0 && $ok_response == 0) {
 8749:         my $server = shift(@homeservers); 
 8750:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 8751:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 8752:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 8753: 		split(/:/,$response);
 8754:             %{$codes} = (%{$codes},&str2hash($codes_str));
 8755:             push(@{$codetitles},&str2array($codetitles_str));
 8756:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 8757:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 8758:             $ok_response = 1;
 8759:         }
 8760:     }
 8761:     if ($ok_response) {
 8762:         return 'ok';
 8763:     } else {
 8764:         return $response;
 8765:     }
 8766: }
 8767: 
 8768: sub auto_instcode_defaults {
 8769:     my ($domain,$returnhash,$code_order) = @_;
 8770:     my @homeservers;
 8771: 
 8772:     my %servers = &get_servers($domain,'library');
 8773:     foreach my $tryserver (keys(%servers)) {
 8774: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 8775: 	    push(@homeservers,$tryserver);
 8776: 	}
 8777:     }
 8778: 
 8779:     my $response;
 8780:     foreach my $server (@homeservers) {
 8781:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 8782:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 8783: 	
 8784: 	foreach my $pair (split(/\&/,$response)) {
 8785: 	    my ($name,$value)=split(/\=/,$pair);
 8786: 	    if ($name eq 'code_order') {
 8787: 		@{$code_order} = split(/\&/,&unescape($value));
 8788: 	    } else {
 8789: 		$returnhash->{&unescape($name)}=&unescape($value);
 8790: 	    }
 8791: 	}
 8792: 	return 'ok';
 8793:     }
 8794: 
 8795:     return $response;
 8796: }
 8797: 
 8798: sub auto_possible_instcodes {
 8799:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 8800:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 8801:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 8802:         return;
 8803:     }
 8804:     my (@homeservers,$uhome);
 8805:     if (defined(&domain($domain,'primary'))) {
 8806:         $uhome=&domain($domain,'primary');
 8807:         push(@homeservers,&domain($domain,'primary'));
 8808:     } else {
 8809:         my %servers = &get_servers($domain,'library');
 8810:         foreach my $tryserver (keys(%servers)) {
 8811:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 8812:                 push(@homeservers,$tryserver);
 8813:             }
 8814:         }
 8815:     }
 8816:     my $response;
 8817:     foreach my $server (@homeservers) {
 8818:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 8819:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 8820:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 8821:             split(':',$response);
 8822:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 8823:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 8824:         foreach my $item (split('&',$cat_title)) {   
 8825:             my ($name,$value)=split('=',$item);
 8826:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 8827:         }
 8828:         foreach my $item (split('&',$cat_order)) {
 8829:             my ($name,$value)=split('=',$item);
 8830:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 8831:         }
 8832:         return 'ok';
 8833:     }
 8834:     return $response;
 8835: }
 8836: 
 8837: sub auto_courserequest_checks {
 8838:     my ($dom) = @_;
 8839:     my ($homeserver,%validations);
 8840:     if ($dom =~ /^$match_domain$/) {
 8841:         $homeserver = &domain($dom,'primary');
 8842:     }
 8843:     unless ($homeserver eq 'no_host') {
 8844:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 8845:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 8846:             my @items = split(/&/,$response);
 8847:             foreach my $item (@items) {
 8848:                 my ($key,$value) = split('=',$item);
 8849:                 $validations{&unescape($key)} = &thaw_unescape($value);
 8850:             }
 8851:         }
 8852:     }
 8853:     return %validations; 
 8854: }
 8855: 
 8856: sub auto_courserequest_validation {
 8857:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
 8858:     my ($homeserver,$response);
 8859:     if ($dom =~ /^$match_domain$/) {
 8860:         $homeserver = &domain($dom,'primary');
 8861:     }
 8862:     unless ($homeserver eq 'no_host') {
 8863:         my $customdata;
 8864:         if (ref($custominfo) eq 'HASH') {
 8865:             $customdata = &freeze_escape($custominfo);
 8866:         }
 8867:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 8868:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 8869:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
 8870:                                     $customdata,$homeserver));
 8871:     }
 8872:     return $response;
 8873: }
 8874: 
 8875: sub auto_validate_class_sec {
 8876:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 8877:     my $homeserver = &homeserver($cnum,$cdom);
 8878:     my $ownerlist;
 8879:     if (ref($owners) eq 'ARRAY') {
 8880:         $ownerlist = join(',',@{$owners});
 8881:     } else {
 8882:         $ownerlist = $owners;
 8883:     }
 8884:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 8885:                         &escape($ownerlist).':'.$cdom,$homeserver);
 8886:     return $response;
 8887: }
 8888: 
 8889: sub auto_crsreq_update {
 8890:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
 8891:         $code,$accessstart,$accessend,$inbound) = @_;
 8892:     my ($homeserver,%crsreqresponse);
 8893:     if ($cdom =~ /^$match_domain$/) {
 8894:         $homeserver = &domain($cdom,'primary');
 8895:     }
 8896:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 8897:         my $info;
 8898:         if (ref($inbound) eq 'HASH') {
 8899:             $info = &freeze_escape($inbound);
 8900:         }
 8901:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
 8902:                             ':'.&escape($action).':'.&escape($ownername).':'.
 8903:                             &escape($ownerdomain).':'.&escape($fullname).':'.
 8904:                             &escape($title).':'.&escape($code).':'.
 8905:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
 8906:                             $homeserver);
 8907:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 8908:             my @items = split(/&/,$response);
 8909:             foreach my $item (@items) {
 8910:                 my ($key,$value) = split('=',$item);
 8911:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
 8912:             }
 8913:         }
 8914:     }
 8915:     return \%crsreqresponse;
 8916: }
 8917: 
 8918: sub auto_export_grades {
 8919:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
 8920:     my ($homeserver,%exportresponse);
 8921:     if ($cdom =~ /^$match_domain$/) {
 8922:         $homeserver = &domain($cdom,'primary');
 8923:     }
 8924:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 8925:         my $info;
 8926:         if (ref($inforef) eq 'HASH') {
 8927:             $info = &freeze_escape($inforef);
 8928:         }
 8929:         if (ref($gradesref) eq 'HASH') {
 8930:             my $grades = &freeze_escape($gradesref);
 8931:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
 8932:                                 $info.':'.$grades,$homeserver);
 8933:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
 8934:                 my @items = split(/&/,$response);
 8935:                 foreach my $item (@items) {
 8936:                     my ($key,$value) = split('=',$item);
 8937:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
 8938:                 }
 8939:             }
 8940:         }
 8941:     }
 8942:     return \%exportresponse;
 8943: }
 8944: 
 8945: sub check_instcode_cloning {
 8946:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
 8947:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 8948:         return;
 8949:     }
 8950:     my $canclone;
 8951:     if (@{$code_order} > 0) {
 8952:         my $instcoderegexp ='^';
 8953:         my @clonecodes = split(/\&/,$cloner);
 8954:         foreach my $item (@{$code_order}) {
 8955:             if (grep(/^\Q$item\E=/,@clonecodes)) {
 8956:                 foreach my $pair (@clonecodes) {
 8957:                     my ($key,$val) = split(/\=/,$pair,2);
 8958:                     $val = &unescape($val);
 8959:                     if ($key eq $item) {
 8960:                         $instcoderegexp .= '('.$val.')';
 8961:                         last;
 8962:                     }
 8963:                 }
 8964:             } else {
 8965:                 $instcoderegexp .= $codedefaults->{$item};
 8966:             }
 8967:         }
 8968:         $instcoderegexp .= '$';
 8969:         my (@from,@to);
 8970:         eval {
 8971:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
 8972:                (@to) = ($clonetocode =~ /$instcoderegexp/);
 8973:         };
 8974:         if ((@from > 0) && (@to > 0)) {
 8975:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 8976:             if (!@diffs) {
 8977:                 $canclone = 1;
 8978:             }
 8979:         }
 8980:     }
 8981:     return $canclone;
 8982: }
 8983: 
 8984: sub default_instcode_cloning {
 8985:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
 8986:     my (%codedefaults,@code_order,$canclone);
 8987:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
 8988:         %codedefaults = %{$codedefaultsref};
 8989:         @code_order = @{$codeorderref};
 8990:     } elsif ($clonedom) {
 8991:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
 8992:     }
 8993:     if (($domdefclone) && (@code_order)) {
 8994:         my @clonecodes = split(/\+/,$domdefclone);
 8995:         my $instcoderegexp ='^';
 8996:         foreach my $item (@code_order) {
 8997:             if (grep(/^\Q$item\E$/,@clonecodes)) {
 8998:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
 8999:             } else {
 9000:                 $instcoderegexp .= $codedefaults{$item};
 9001:             }
 9002:         }
 9003:         $instcoderegexp .= '$';
 9004:         my (@from,@to);
 9005:         eval {
 9006:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9007:             (@to) = ($clonetocode =~ /$instcoderegexp/);
 9008:         };
 9009:         if ((@from > 0) && (@to > 0)) {
 9010:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9011:             if (!@diffs) {
 9012:                 $canclone = 1;
 9013:             }
 9014:         }
 9015:     }
 9016:     return $canclone;
 9017: }
 9018: 
 9019: # ------------------------------------------------------- Course Group routines
 9020: 
 9021: sub get_coursegroups {
 9022:     my ($cdom,$cnum,$group,$namespace) = @_;
 9023:     return(&dump($namespace,$cdom,$cnum,$group));
 9024: }
 9025: 
 9026: sub modify_coursegroup {
 9027:     my ($cdom,$cnum,$groupsettings) = @_;
 9028:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 9029: }
 9030: 
 9031: sub toggle_coursegroup_status {
 9032:     my ($cdom,$cnum,$group,$action) = @_;
 9033:     my ($from_namespace,$to_namespace);
 9034:     if ($action eq 'delete') {
 9035:         $from_namespace = 'coursegroups';
 9036:         $to_namespace = 'deleted_groups';
 9037:     } else {
 9038:         $from_namespace = 'deleted_groups';
 9039:         $to_namespace = 'coursegroups';
 9040:     }
 9041:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 9042:     if (my $tmp = &error(%curr_group)) {
 9043:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 9044:         return ('read error',$tmp);
 9045:     } else {
 9046:         my %savedsettings = %curr_group; 
 9047:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 9048:         my $deloutcome;
 9049:         if ($result eq 'ok') {
 9050:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 9051:         } else {
 9052:             return ('write error',$result);
 9053:         }
 9054:         if ($deloutcome eq 'ok') {
 9055:             return 'ok';
 9056:         } else {
 9057:             return ('delete error',$deloutcome);
 9058:         }
 9059:     }
 9060: }
 9061: 
 9062: sub modify_group_roles {
 9063:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 9064:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 9065:     my $role = 'gr/'.&escape($userprivs);
 9066:     my ($uname,$udom) = split(/:/,$user);
 9067:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 9068:     if ($result eq 'ok') {
 9069:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 9070:     }
 9071:     return $result;
 9072: }
 9073: 
 9074: sub modify_coursegroup_membership {
 9075:     my ($cdom,$cnum,$membership) = @_;
 9076:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 9077:     return $result;
 9078: }
 9079: 
 9080: sub get_active_groups {
 9081:     my ($udom,$uname,$cdom,$cnum) = @_;
 9082:     my $now = time;
 9083:     my %groups = ();
 9084:     foreach my $key (keys(%env)) {
 9085:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 9086:             my ($start,$end) = split(/\./,$env{$key});
 9087:             if (($end!=0) && ($end<$now)) { next; }
 9088:             if (($start!=0) && ($start>$now)) { next; }
 9089:             if ($1 eq $cdom && $2 eq $cnum) {
 9090:                 $groups{$3} = $env{$key} ;
 9091:             }
 9092:         }
 9093:     }
 9094:     return %groups;
 9095: }
 9096: 
 9097: sub get_group_membership {
 9098:     my ($cdom,$cnum,$group) = @_;
 9099:     return(&dump('groupmembership',$cdom,$cnum,$group));
 9100: }
 9101: 
 9102: sub get_users_groups {
 9103:     my ($udom,$uname,$courseid) = @_;
 9104:     my @usersgroups;
 9105:     my $cachetime=1800;
 9106: 
 9107:     my $hashid="$udom:$uname:$courseid";
 9108:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 9109:     if (defined($cached)) {
 9110:         @usersgroups = split(/:/,$grouplist);
 9111:     } else {  
 9112:         $grouplist = '';
 9113:         my $courseurl = &courseid_to_courseurl($courseid);
 9114:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 9115:         my $access_end = $env{'course.'.$courseid.
 9116:                               '.default_enrollment_end_date'};
 9117:         my $now = time;
 9118:         foreach my $key (keys(%roleshash)) {
 9119:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 9120:                 my $group = $1;
 9121:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 9122:                     my $start = $2;
 9123:                     my $end = $1;
 9124:                     if ($start == -1) { next; } # deleted from group
 9125:                     if (($start!=0) && ($start>$now)) { next; }
 9126:                     if (($end!=0) && ($end<$now)) {
 9127:                         if ($access_end && $access_end < $now) {
 9128:                             if ($access_end - $end < 86400) {
 9129:                                 push(@usersgroups,$group);
 9130:                             }
 9131:                         }
 9132:                         next;
 9133:                     }
 9134:                     push(@usersgroups,$group);
 9135:                 }
 9136:             }
 9137:         }
 9138:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 9139:         $grouplist = join(':',@usersgroups);
 9140:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 9141:     }
 9142:     return @usersgroups;
 9143: }
 9144: 
 9145: sub devalidate_getgroups_cache {
 9146:     my ($udom,$uname,$cdom,$cnum)=@_;
 9147:     my $courseid = $cdom.'_'.$cnum;
 9148: 
 9149:     my $hashid="$udom:$uname:$courseid";
 9150:     &devalidate_cache_new('getgroups',$hashid);
 9151: }
 9152: 
 9153: # ------------------------------------------------------------------ Plain Text
 9154: 
 9155: sub plaintext {
 9156:     my ($short,$type,$cid,$forcedefault) = @_;
 9157:     if ($short =~ m{^cr/}) {
 9158: 	return (split('/',$short))[-1];
 9159:     }
 9160:     if (!defined($cid)) {
 9161:         $cid = $env{'request.course.id'};
 9162:     }
 9163:     my %rolenames = (
 9164:                       Course    => 'std',
 9165:                       Community => 'alt1',
 9166:                       Placement => 'std',
 9167:                     );
 9168:     if ($cid ne '') {
 9169:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 9170:             unless ($forcedefault) {
 9171:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 9172:                 &Apache::lonlocal::mt_escape(\$roletext);
 9173:                 return &Apache::lonlocal::mt($roletext);
 9174:             }
 9175:         }
 9176:     }
 9177:     if ((defined($type)) && (defined($rolenames{$type})) &&
 9178:         (defined($rolenames{$type})) && 
 9179:         (defined($prp{$short}{$rolenames{$type}}))) {
 9180:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 9181:     } elsif ($cid ne '') {
 9182:         my $crstype = $env{'course.'.$cid.'.type'};
 9183:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 9184:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 9185:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 9186:         }
 9187:     }
 9188:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 9189: }
 9190: 
 9191: # ----------------------------------------------------------------- Assign Role
 9192: 
 9193: sub assignrole {
 9194:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 9195:         $context)=@_;
 9196:     my $mrole;
 9197:     if ($role =~ /^cr\//) {
 9198:         my $cwosec=$url;
 9199:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 9200: 	unless (&allowed('ccr',$cwosec)) {
 9201:            my $refused = 1;
 9202:            if ($context eq 'requestcourses') {
 9203:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 9204:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 9205:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 9206:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 9207:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9208:                            if ($crsenv{'internal.courseowner'} eq
 9209:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 9210:                                $refused = '';
 9211:                            }
 9212:                        }
 9213:                    }
 9214:                }
 9215:            }
 9216:            if ($refused) {
 9217:                &logthis('Refused custom assignrole: '.
 9218:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 9219:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 9220:                return 'refused';
 9221:            }
 9222:         }
 9223:         $mrole='cr';
 9224:     } elsif ($role =~ /^gr\//) {
 9225:         my $cwogrp=$url;
 9226:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 9227:         unless (&allowed('mdg',$cwogrp)) {
 9228:             &logthis('Refused group assignrole: '.
 9229:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 9230:                     $env{'user.name'}.' at '.$env{'user.domain'});
 9231:             return 'refused';
 9232:         }
 9233:         $mrole='gr';
 9234:     } else {
 9235:         my $cwosec=$url;
 9236:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 9237:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 9238:             my $refused;
 9239:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 9240:                 if (!(&allowed('c'.$role,$url))) {
 9241:                     $refused = 1;
 9242:                 }
 9243:             } else {
 9244:                 $refused = 1;
 9245:             }
 9246:             if ($refused) {
 9247:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 9248:                 if (!$selfenroll && $context eq 'course') {
 9249:                     my %crsenv;
 9250:                     if ($role eq 'cc' || $role eq 'co') {
 9251:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9252:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 9253:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 9254:                                 if ($crsenv{'internal.courseowner'} eq 
 9255:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 9256:                                     $refused = '';
 9257:                                 }
 9258:                             }
 9259:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 9260:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 9261:                                 if ($crsenv{'internal.courseowner'} eq 
 9262:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 9263:                                     $refused = '';
 9264:                                 }
 9265:                             }
 9266:                         }
 9267:                     }
 9268:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 9269:                     $refused = '';
 9270:                 } elsif ($context eq 'requestcourses') {
 9271:                     my @possroles = ('st','ta','ep','in','cc','co');
 9272:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 9273:                         my $wrongcc;
 9274:                         if ($cnum =~ /^$match_community$/) {
 9275:                             $wrongcc = 1 if ($role eq 'cc');
 9276:                         } else {
 9277:                             $wrongcc = 1 if ($role eq 'co');
 9278:                         }
 9279:                         unless ($wrongcc) {
 9280:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9281:                             if ($crsenv{'internal.courseowner'} eq 
 9282:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 9283:                                 $refused = '';
 9284:                             }
 9285:                         }
 9286:                     }
 9287:                 } elsif ($context eq 'requestauthor') {
 9288:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
 9289:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 9290:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 9291:                             $refused = '';
 9292:                         } else {
 9293:                             my %domdefaults = &get_domain_defaults($udom);
 9294:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 9295:                                 my $checkbystatus;
 9296:                                 if ($env{'user.adv'}) { 
 9297:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 9298:                                     if ($disposition eq 'automatic') {
 9299:                                         $refused = '';
 9300:                                     } elsif ($disposition eq '') {
 9301:                                         $checkbystatus = 1;
 9302:                                     } 
 9303:                                 } else {
 9304:                                     $checkbystatus = 1;
 9305:                                 }
 9306:                                 if ($checkbystatus) {
 9307:                                     if ($env{'environment.inststatus'}) {
 9308:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 9309:                                         foreach my $type (@inststatuses) {
 9310:                                             if (($type ne '') &&
 9311:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 9312:                                                 $refused = '';
 9313:                                             }
 9314:                                         }
 9315:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 9316:                                         $refused = '';
 9317:                                     }
 9318:                                 }
 9319:                             }
 9320:                         }
 9321:                     }
 9322:                 }
 9323:                 if ($refused) {
 9324:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 9325:                              ' '.$role.' '.$end.' '.$start.' by '.
 9326: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 9327:                     return 'refused';
 9328:                 }
 9329:             }
 9330:         } elsif ($role eq 'au') {
 9331:             if ($url ne '/'.$udom.'/') {
 9332:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 9333:                          ' to assign author role for '.$uname.':'.$udom.
 9334:                          ' in domain: '.$url.' refused (wrong domain).');
 9335:                 return 'refused';
 9336:             }
 9337:         }
 9338:         $mrole=$role;
 9339:     }
 9340:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 9341:                 "$udom:$uname:$url".'_'."$mrole=$role";
 9342:     if ($end) { $command.='_'.$end; }
 9343:     if ($start) {
 9344: 	if ($end) { 
 9345:            $command.='_'.$start; 
 9346:         } else {
 9347:            $command.='_0_'.$start;
 9348:         }
 9349:     }
 9350:     my $origstart = $start;
 9351:     my $origend = $end;
 9352:     my $delflag;
 9353: # actually delete
 9354:     if ($deleteflag) {
 9355: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 9356: # modify command to delete the role
 9357:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 9358:                 "$udom:$uname:$url".'_'."$mrole";
 9359: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 9360: # set start and finish to negative values for userrolelog
 9361:            $start=-1;
 9362:            $end=-1;
 9363:            $delflag = 1;
 9364:         }
 9365:     }
 9366: # send command
 9367:     my $answer=&reply($command,&homeserver($uname,$udom));
 9368: # log new user role if status is ok
 9369:     if ($answer eq 'ok') {
 9370: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 9371:         if (($role eq 'cc') || ($role eq 'in') ||
 9372:             ($role eq 'ep') || ($role eq 'ad') ||
 9373:             ($role eq 'ta') || ($role eq 'st') ||
 9374:             ($role=~/^cr/) || ($role eq 'gr') ||
 9375:             ($role eq 'co')) {
 9376: # for course roles, perform group memberships changes triggered by role change.
 9377:             unless ($role =~ /^gr/) {
 9378:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 9379:                                                  $origstart,$selfenroll,$context);
 9380:             }
 9381:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9382:                            $selfenroll,$context);
 9383:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
 9384:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
 9385:                  ($role eq 'da')) {
 9386:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9387:                            $context);
 9388:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
 9389:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9390:                              $context); 
 9391:         }
 9392:         if ($role eq 'cc') {
 9393:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 9394:         }
 9395:     }
 9396:     return $answer;
 9397: }
 9398: 
 9399: sub autoupdate_coowners {
 9400:     my ($url,$end,$start,$uname,$udom) = @_;
 9401:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 9402:     if (($cdom ne '') && ($cnum ne '')) {
 9403:         my $now = time;
 9404:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 9405:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 9406:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 9407:             my $instcode = $coursehash{'internal.coursecode'};
 9408:             if ($instcode ne '') {
 9409:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 9410:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 9411:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 9412:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 9413:                         if ($result eq 'valid') {
 9414:                             if ($coursehash{'internal.co-owners'}) {
 9415:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 9416:                                     push(@newcoowners,$coowner);
 9417:                                 }
 9418:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 9419:                                     push(@newcoowners,$uname.':'.$udom);
 9420:                                 }
 9421:                                 @newcoowners = sort(@newcoowners);
 9422:                             } else {
 9423:                                 push(@newcoowners,$uname.':'.$udom);
 9424:                             }
 9425:                         } else {
 9426:                             if ($coursehash{'internal.co-owners'}) {
 9427:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 9428:                                     unless ($coowner eq $uname.':'.$udom) {
 9429:                                         push(@newcoowners,$coowner);
 9430:                                     }
 9431:                                 }
 9432:                                 unless (@newcoowners > 0) {
 9433:                                     $delcoowners = 1;
 9434:                                     $coowners = '';
 9435:                                 }
 9436:                             }
 9437:                         }
 9438:                         if (@newcoowners || $delcoowners) {
 9439:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 9440:                                             $delcoowners,@newcoowners);
 9441:                         }
 9442:                     }
 9443:                 }
 9444:             }
 9445:         }
 9446:     }
 9447: }
 9448: 
 9449: sub store_coowners {
 9450:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 9451:     my $cid = $cdom.'_'.$cnum;
 9452:     my ($coowners,$delresult,$putresult);
 9453:     if (@newcoowners) {
 9454:         $coowners = join(',',@newcoowners);
 9455:         my %coownershash = (
 9456:                             'internal.co-owners' => $coowners,
 9457:                            );
 9458:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 9459:         if ($putresult eq 'ok') {
 9460:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 9461:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 9462:             }
 9463:         }
 9464:     }
 9465:     if ($delcoowners) {
 9466:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 9467:         if ($delresult eq 'ok') {
 9468:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 9469:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 9470:             }
 9471:         }
 9472:     }
 9473:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 9474:         my %crsinfo =
 9475:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 9476:         if (ref($crsinfo{$cid}) eq 'HASH') {
 9477:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 9478:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 9479:         }
 9480:     }
 9481: }
 9482: 
 9483: # -------------------------------------------------- Modify user authentication
 9484: # Overrides without validation
 9485: 
 9486: sub modifyuserauth {
 9487:     my ($udom,$uname,$umode,$upass)=@_;
 9488:     my $uhome=&homeserver($uname,$udom);
 9489:     unless (&allowed('mau',$udom)) { return 'refused'; }
 9490:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 9491:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 9492:              ' in domain '.$env{'request.role.domain'});  
 9493:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 9494: 		     &escape($upass),$uhome);
 9495:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 9496:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 9497:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 9498:     &log($udom,,$uname,$uhome,
 9499:         'Authentication changed by '.$env{'user.domain'}.', '.
 9500:                                      $env{'user.name'}.', '.$umode.
 9501:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 9502:     unless ($reply eq 'ok') {
 9503:         &logthis('Authentication mode error: '.$reply);
 9504: 	return 'error: '.$reply;
 9505:     }   
 9506:     return 'ok';
 9507: }
 9508: 
 9509: # --------------------------------------------------------------- Modify a user
 9510: 
 9511: sub modifyuser {
 9512:     my ($udom,    $uname, $uid,
 9513:         $umode,   $upass, $first,
 9514:         $middle,  $last,  $gene,
 9515:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 9516:     $udom= &LONCAPA::clean_domain($udom);
 9517:     $uname=&LONCAPA::clean_username($uname);
 9518:     my $showcandelete = 'none';
 9519:     if (ref($candelete) eq 'ARRAY') {
 9520:         if (@{$candelete} > 0) {
 9521:             $showcandelete = join(', ',@{$candelete});
 9522:         }
 9523:     }
 9524:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 9525:              $umode.', '.$first.', '.$middle.', '.
 9526: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 9527:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 9528:                                      ' desiredhome not specified'). 
 9529:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 9530:              ' in domain '.$env{'request.role.domain'});
 9531:     my $uhome=&homeserver($uname,$udom,'true');
 9532:     my $newuser;
 9533:     if ($uhome eq 'no_host') {
 9534:         $newuser = 1;
 9535:     }
 9536: # ----------------------------------------------------------------- Create User
 9537:     if (($uhome eq 'no_host') && 
 9538: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 9539:         my $unhome='';
 9540:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 9541:             $unhome = $desiredhome;
 9542: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 9543: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 9544:         } else { # load balancing routine for determining $unhome
 9545:             my $loadm=10000000;
 9546: 	    my %servers = &get_servers($udom,'library');
 9547: 	    foreach my $tryserver (keys(%servers)) {
 9548: 		my $answer=reply('load',$tryserver);
 9549: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 9550: 		    $loadm=$answer;
 9551: 		    $unhome=$tryserver;
 9552: 		}
 9553: 	    }
 9554:         }
 9555:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 9556: 	    return 'error: unable to find a home server for '.$uname.
 9557:                    ' in domain '.$udom;
 9558:         }
 9559:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 9560:                          &escape($upass),$unhome);
 9561: 	unless ($reply eq 'ok') {
 9562:             return 'error: '.$reply;
 9563:         }   
 9564:         $uhome=&homeserver($uname,$udom,'true');
 9565:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 9566: 	    return 'error: unable verify users home machine.';
 9567:         }
 9568:     }   # End of creation of new user
 9569: # ---------------------------------------------------------------------- Add ID
 9570:     if ($uid) {
 9571:        $uid=~tr/A-Z/a-z/;
 9572:        my %uidhash=&idrget($udom,$uname);
 9573:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 9574:          && (!$forceid)) {
 9575: 	  unless ($uid eq $uidhash{$uname}) {
 9576: 	      return 'error: user id "'.$uid.'" does not match '.
 9577:                   'current user id "'.$uidhash{$uname}.'".';
 9578:           }
 9579:        } else {
 9580: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
 9581:        }
 9582:     }
 9583: # -------------------------------------------------------------- Add names, etc
 9584:     my @tmp=&get('environment',
 9585: 		   ['firstname','middlename','lastname','generation','id',
 9586:                     'permanentemail','inststatus'],
 9587: 		   $udom,$uname);
 9588:     my (%names,%oldnames);
 9589:     if ($tmp[0] =~ m/^error:.*/) { 
 9590:         %names=(); 
 9591:     } else {
 9592:         %names = @tmp;
 9593:         %oldnames = %names;
 9594:     }
 9595: #
 9596: # If name, email and/or uid are blank (e.g., because an uploaded file
 9597: # of users did not contain them), do not overwrite existing values
 9598: # unless field is in $candelete array ref.  
 9599: #
 9600: 
 9601:     my @fields = ('firstname','middlename','lastname','generation',
 9602:                   'permanentemail','id');
 9603:     my %newvalues;
 9604:     if (ref($candelete) eq 'ARRAY') {
 9605:         foreach my $field (@fields) {
 9606:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 9607:                 if ($field eq 'firstname') {
 9608:                     $names{$field} = $first;
 9609:                 } elsif ($field eq 'middlename') {
 9610:                     $names{$field} = $middle;
 9611:                 } elsif ($field eq 'lastname') {
 9612:                     $names{$field} = $last;
 9613:                 } elsif ($field eq 'generation') { 
 9614:                     $names{$field} = $gene;
 9615:                 } elsif ($field eq 'permanentemail') {
 9616:                     $names{$field} = $email;
 9617:                 } elsif ($field eq 'id') {
 9618:                     $names{$field}  = $uid;
 9619:                 }
 9620:             }
 9621:         }
 9622:     }
 9623:     if ($first)  { $names{'firstname'}  = $first; }
 9624:     if (defined($middle)) { $names{'middlename'} = $middle; }
 9625:     if ($last)   { $names{'lastname'}   = $last; }
 9626:     if (defined($gene))   { $names{'generation'} = $gene; }
 9627:     if ($email) {
 9628:        $email=~s/[^\w\@\.\-\,]//gs;
 9629:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 9630:     }
 9631:     if ($uid) { $names{'id'}  = $uid; }
 9632:     if (defined($inststatus)) {
 9633:         $names{'inststatus'} = '';
 9634:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 9635:         if (ref($usertypes) eq 'HASH') {
 9636:             my @okstatuses; 
 9637:             foreach my $item (split(/:/,$inststatus)) {
 9638:                 if (defined($usertypes->{$item})) {
 9639:                     push(@okstatuses,$item);  
 9640:                 }
 9641:             }
 9642:             if (@okstatuses) {
 9643:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 9644:             }
 9645:         }
 9646:     }
 9647:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 9648:                  $umode.', '.$first.', '.$middle.', '.
 9649:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 9650:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 9651:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 9652:     } else {
 9653:         $logmsg .= ' during self creation';
 9654:     }
 9655:     my $changed;
 9656:     if ($newuser) {
 9657:         $changed = 1;
 9658:     } else {
 9659:         foreach my $field (@fields) {
 9660:             if ($names{$field} ne $oldnames{$field}) {
 9661:                 $changed = 1;
 9662:                 last;
 9663:             }
 9664:         }
 9665:     }
 9666:     unless ($changed) {
 9667:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 9668:         &logthis($logmsg);
 9669:         return 'ok';
 9670:     }
 9671:     my $reply = &put('environment', \%names, $udom,$uname);
 9672:     if ($reply ne 'ok') { 
 9673:         return 'error: '.$reply;
 9674:     }
 9675:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
 9676:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
 9677:     }
 9678:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 9679:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 9680:     $logmsg = 'Success modifying user '.$logmsg;
 9681:     &logthis($logmsg);
 9682:     return 'ok';
 9683: }
 9684: 
 9685: # -------------------------------------------------------------- Modify student
 9686: 
 9687: sub modifystudent {
 9688:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 9689:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 9690:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
 9691:     if (!$cid) {
 9692: 	unless ($cid=$env{'request.course.id'}) {
 9693: 	    return 'not_in_class';
 9694: 	}
 9695:     }
 9696: # --------------------------------------------------------------- Make the user
 9697:     my $reply=&modifyuser
 9698: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 9699:          $desiredhome,$email,$inststatus);
 9700:     unless ($reply eq 'ok') { return $reply; }
 9701:     # This will cause &modify_student_enrollment to get the uid from the
 9702:     # student's environment
 9703:     $uid = undef if (!$forceid);
 9704:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 9705:                                         $gene,$usec,$end,$start,$type,$locktype,
 9706:                                         $cid,$selfenroll,$context,$credits,$instsec);
 9707:     return $reply;
 9708: }
 9709: 
 9710: sub modify_student_enrollment {
 9711:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
 9712:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
 9713:     my ($cdom,$cnum,$chome);
 9714:     if (!$cid) {
 9715: 	unless ($cid=$env{'request.course.id'}) {
 9716: 	    return 'not_in_class';
 9717: 	}
 9718: 	$cdom=$env{'course.'.$cid.'.domain'};
 9719: 	$cnum=$env{'course.'.$cid.'.num'};
 9720:     } else {
 9721: 	($cdom,$cnum)=split(/_/,$cid);
 9722:     }
 9723:     $chome=$env{'course.'.$cid.'.home'};
 9724:     if (!$chome) {
 9725: 	$chome=&homeserver($cnum,$cdom);
 9726:     }
 9727:     if (!$chome) { return 'unknown_course'; }
 9728:     # Make sure the user exists
 9729:     my $uhome=&homeserver($uname,$udom);
 9730:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 9731: 	return 'error: no such user';
 9732:     }
 9733:     # Get student data if we were not given enough information
 9734:     if (!defined($first)  || $first  eq '' || 
 9735:         !defined($last)   || $last   eq '' || 
 9736:         !defined($uid)    || $uid    eq '' || 
 9737:         !defined($middle) || $middle eq '' || 
 9738:         !defined($gene)   || $gene   eq '') {
 9739:         # They did not supply us with enough data to enroll the student, so
 9740:         # we need to pick up more information.
 9741:         my %tmp = &get('environment',
 9742:                        ['firstname','middlename','lastname', 'generation','id']
 9743:                        ,$udom,$uname);
 9744: 
 9745:         #foreach my $key (keys(%tmp)) {
 9746:         #    &logthis("key $key = ".$tmp{$key});
 9747:         #}
 9748:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 9749:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 9750:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 9751:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 9752:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 9753:     }
 9754:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 9755:     my $user = "$uname:$udom";
 9756:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
 9757:     my $reply=cput('classlist',
 9758: 		   {$user => 
 9759: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
 9760: 		   $cdom,$cnum);
 9761:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
 9762:         &devalidate_getsection_cache($udom,$uname,$cid);
 9763:     } else { 
 9764: 	return 'error: '.$reply;
 9765:     }
 9766:     # Add student role to user
 9767:     my $uurl='/'.$cid;
 9768:     $uurl=~s/\_/\//g;
 9769:     if ($usec) {
 9770: 	$uurl.='/'.$usec;
 9771:     }
 9772:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
 9773:                              $selfenroll,$context);
 9774:     if ($result ne 'ok') {
 9775:         if ($old_entry{$user} ne '') {
 9776:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
 9777:         } else {
 9778:             $reply = &del('classlist',[$user],$cdom,$cnum);
 9779:         }
 9780:     }
 9781:     return $result; 
 9782: }
 9783: 
 9784: sub format_name {
 9785:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 9786:     my $name;
 9787:     if ($first ne 'lastname') {
 9788: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 9789:     } else {
 9790: 	if ($lastname=~/\S/) {
 9791: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 9792: 	    $name=~s/\s+,/,/;
 9793: 	} else {
 9794: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 9795: 	}
 9796:     }
 9797:     $name=~s/^\s+//;
 9798:     $name=~s/\s+$//;
 9799:     $name=~s/\s+/ /g;
 9800:     return $name;
 9801: }
 9802: 
 9803: # ------------------------------------------------- Write to course preferences
 9804: 
 9805: sub writecoursepref {
 9806:     my ($courseid,%prefs)=@_;
 9807:     $courseid=~s/^\///;
 9808:     $courseid=~s/\_/\//g;
 9809:     my ($cdomain,$cnum)=split(/\//,$courseid);
 9810:     my $chome=homeserver($cnum,$cdomain);
 9811:     if (($chome eq '') || ($chome eq 'no_host')) { 
 9812: 	return 'error: no such course';
 9813:     }
 9814:     my $cstring='';
 9815:     foreach my $pref (keys(%prefs)) {
 9816: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 9817:     }
 9818:     $cstring=~s/\&$//;
 9819:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 9820: }
 9821: 
 9822: # ---------------------------------------------------------- Make/modify course
 9823: 
 9824: sub createcourse {
 9825:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 9826:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 9827:     $url=&declutter($url);
 9828:     my $cid='';
 9829:     if ($context eq 'requestcourses') {
 9830:         my $can_create = 0;
 9831:         my ($ownername,$ownerdom) = split(':',$course_owner);
 9832:         if ($udom eq $ownerdom) {
 9833:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 9834:                                   $context)) {
 9835:                 $can_create = 1;
 9836:             }
 9837:         } else {
 9838:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 9839:                                            $category);
 9840:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 9841:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 9842:                 if (@curr > 0) {
 9843:                     my @options = qw(approval validate autolimit);
 9844:                     my $optregex = join('|',@options);
 9845:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 9846:                         $can_create = 1;
 9847:                     }
 9848:                 }
 9849:             }
 9850:         }
 9851:         if ($can_create) {
 9852:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 9853:                 unless (&allowed('ccc',$udom)) {
 9854:                     return 'refused'; 
 9855:                 }
 9856:             }
 9857:         } else {
 9858:             return 'refused';
 9859:         }
 9860:     } elsif (!&allowed('ccc',$udom)) {
 9861:         return 'refused';
 9862:     }
 9863: # --------------------------------------------------------------- Get Unique ID
 9864:     my $uname;
 9865:     if ($cnum =~ /^$match_courseid$/) {
 9866:         my $chome=&homeserver($cnum,$udom,'true');
 9867:         if (($chome eq '') || ($chome eq 'no_host')) {
 9868:             $uname = $cnum;
 9869:         } else {
 9870:             $uname = &generate_coursenum($udom,$crstype);
 9871:         }
 9872:     } else {
 9873:         $uname = &generate_coursenum($udom,$crstype);
 9874:     }
 9875:     return $uname if ($uname =~ /^error/);
 9876: # -------------------------------------------------- Check supplied server name
 9877:     if (!defined($course_server)) {
 9878:         if (defined(&domain($udom,'primary'))) {
 9879:             $course_server = &domain($udom,'primary');
 9880:         } else {
 9881:             $course_server = $env{'user.home'}; 
 9882:         }
 9883:     }
 9884:     my %host_servers =
 9885:         &Apache::lonnet::get_servers($udom,'library');
 9886:     unless ($host_servers{$course_server}) {
 9887:         return 'error: invalid home server for course: '.$course_server;
 9888:     }
 9889: # ------------------------------------------------------------- Make the course
 9890:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 9891:                       $course_server);
 9892:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 9893:     my $uhome=&homeserver($uname,$udom,'true');
 9894:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 9895: 	return 'error: no such course';
 9896:     }
 9897: # ----------------------------------------------------------------- Course made
 9898: # log existence
 9899:     my $now = time;
 9900:     my $newcourse = {
 9901:                     $udom.'_'.$uname => {
 9902:                                      description => $description,
 9903:                                      inst_code   => $inst_code,
 9904:                                      owner       => $course_owner,
 9905:                                      type        => $crstype,
 9906:                                      creator     => $env{'user.name'}.':'.
 9907:                                                     $env{'user.domain'},
 9908:                                      created     => $now,
 9909:                                      context     => $context,
 9910:                                                 },
 9911:                     };
 9912:     &courseidput($udom,$newcourse,$uhome,'notime');
 9913: # set toplevel url
 9914:     my $topurl=$url;
 9915:     unless ($nonstandard) {
 9916: # ------------------------------------------ For standard courses, make top url
 9917:         my $mapurl=&clutter($url);
 9918:         if ($mapurl eq '/res/') { $mapurl=''; }
 9919:         $env{'form.initmap'}=(<<ENDINITMAP);
 9920: <map>
 9921: <resource id="1" type="start"></resource>
 9922: <resource id="2" src="$mapurl"></resource>
 9923: <resource id="3" type="finish"></resource>
 9924: <link index="1" from="1" to="2"></link>
 9925: <link index="2" from="2" to="3"></link>
 9926: </map>
 9927: ENDINITMAP
 9928:         $topurl=&declutter(
 9929:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 9930:                           );
 9931:     }
 9932: # ----------------------------------------------------------- Write preferences
 9933:     &writecoursepref($udom.'_'.$uname,
 9934:                      ('description'              => $description,
 9935:                       'url'                      => $topurl,
 9936:                       'internal.creator'         => $env{'user.name'}.':'.
 9937:                                                     $env{'user.domain'},
 9938:                       'internal.created'         => $now,
 9939:                       'internal.creationcontext' => $context)
 9940:                     );
 9941:     return '/'.$udom.'/'.$uname;
 9942: }
 9943: 
 9944: # ------------------------------------------------------------------- Create ID
 9945: sub generate_coursenum {
 9946:     my ($udom,$crstype) = @_;
 9947:     my $domdesc = &domain($udom);
 9948:     return 'error: invalid domain' if ($domdesc eq '');
 9949:     my $first;
 9950:     if ($crstype eq 'Community') {
 9951:         $first = '0';
 9952:     } else {
 9953:         $first = int(1+rand(9)); 
 9954:     } 
 9955:     my $uname=$first.
 9956:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 9957:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
 9958:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 9959: # ----------------------------------------------- Make sure that does not exist
 9960:     my $uhome=&homeserver($uname,$udom,'true');
 9961:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
 9962:         if ($crstype eq 'Community') {
 9963:             $first = '0';
 9964:         } else {
 9965:             $first = int(1+rand(9));
 9966:         }
 9967:         $uname=$first.
 9968:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 9969:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
 9970:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 9971:         $uhome=&homeserver($uname,$udom,'true');
 9972:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
 9973:             return 'error: unable to generate unique course-ID';
 9974:         }
 9975:     }
 9976:     return $uname;
 9977: }
 9978: 
 9979: sub is_course {
 9980:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
 9981:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
 9982: 
 9983:     return unless $cdom and $cnum;
 9984: 
 9985:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
 9986:         '.');
 9987: 
 9988:     return unless(exists($courses{$cdom.'_'.$cnum}));
 9989:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
 9990: }
 9991: 
 9992: sub store_userdata {
 9993:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
 9994:     my $result;
 9995:     if ($datakey ne '') {
 9996:         if (ref($storehash) eq 'HASH') {
 9997:             if ($udom eq '' || $uname eq '') {
 9998:                 $udom = $env{'user.domain'};
 9999:                 $uname = $env{'user.name'};
10000:             }
10001:             my $uhome=&homeserver($uname,$udom);
10002:             if (($uhome eq '') || ($uhome eq 'no_host')) {
10003:                 $result = 'error: no_host';
10004:             } else {
10005:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
10006:                 $storehash->{'host'} = $perlvar{'lonHostID'};
10007: 
10008:                 my $namevalue='';
10009:                 foreach my $key (keys(%{$storehash})) {
10010:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
10011:                 }
10012:                 $namevalue=~s/\&$//;
10013:                 unless ($namespace eq 'courserequests') {
10014:                     $datakey = &escape($datakey);
10015:                 }
10016:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
10017:                                   $namevalue,$uhome);
10018:             }
10019:         } else {
10020:             $result = 'error: data to store was not a hash reference'; 
10021:         }
10022:     } else {
10023:         $result= 'error: invalid requestkey'; 
10024:     }
10025:     return $result;
10026: }
10027: 
10028: # ---------------------------------------------------------- Assign Custom Role
10029: 
10030: sub assigncustomrole {
10031:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
10032:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
10033:                        $end,$start,$deleteflag,$selfenroll,$context);
10034: }
10035: 
10036: # ----------------------------------------------------------------- Revoke Role
10037: 
10038: sub revokerole {
10039:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
10040:     my $now=time;
10041:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
10042: }
10043: 
10044: # ---------------------------------------------------------- Revoke Custom Role
10045: 
10046: sub revokecustomrole {
10047:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
10048:     my $now=time;
10049:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
10050:            $deleteflag,$selfenroll,$context);
10051: }
10052: 
10053: # ------------------------------------------------------------ Disk usage
10054: sub diskusage {
10055:     my ($udom,$uname,$directorypath,$getpropath)=@_;
10056:     $directorypath =~ s/\/$//;
10057:     my $listing=&reply('du2:'.&escape($directorypath).':'
10058:                        .&escape($getpropath).':'.&escape($uname).':'
10059:                        .&escape($udom),homeserver($uname,$udom));
10060:     if ($listing eq 'unknown_cmd') {
10061:         if ($getpropath) {
10062:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
10063:         }
10064:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
10065:     }
10066:     return $listing;
10067: }
10068: 
10069: sub is_locked {
10070:     my ($file_name, $domain, $user, $which) = @_;
10071:     my @check;
10072:     my $is_locked;
10073:     push (@check,$file_name);
10074:     my %locked = &get('file_permissions',\@check,
10075: 		      $env{'user.domain'},$env{'user.name'});
10076:     my ($tmp)=keys(%locked);
10077:     if ($tmp=~/^error:/) { undef(%locked); }
10078:     
10079:     if (ref($locked{$file_name}) eq 'ARRAY') {
10080:         $is_locked = 'false';
10081:         foreach my $entry (@{$locked{$file_name}}) {
10082:            if (ref($entry) eq 'ARRAY') {
10083:                $is_locked = 'true';
10084:                if (ref($which) eq 'ARRAY') {
10085:                    push(@{$which},$entry);
10086:                } else {
10087:                    last;
10088:                }
10089:            }
10090:        }
10091:     } else {
10092:         $is_locked = 'false';
10093:     }
10094:     return $is_locked;
10095: }
10096: 
10097: sub declutter_portfile {
10098:     my ($file) = @_;
10099:     $file =~ s{^(/portfolio/|portfolio/)}{/};
10100:     return $file;
10101: }
10102: 
10103: # ------------------------------------------------------------- Mark as Read Only
10104: 
10105: sub mark_as_readonly {
10106:     my ($domain,$user,$files,$what) = @_;
10107:     my %current_permissions = &dump('file_permissions',$domain,$user);
10108:     my ($tmp)=keys(%current_permissions);
10109:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10110:     foreach my $file (@{$files}) {
10111: 	$file = &declutter_portfile($file);
10112:         push(@{$current_permissions{$file}},$what);
10113:     }
10114:     &put('file_permissions',\%current_permissions,$domain,$user);
10115:     return;
10116: }
10117: 
10118: # ------------------------------------------------------------Save Selected Files
10119: 
10120: sub save_selected_files {
10121:     my ($user, $path, @files) = @_;
10122:     my $filename = $user."savedfiles";
10123:     my @other_files = &files_not_in_path($user, $path);
10124:     open (OUT,'>',LONCAPA::tempdir().$filename);
10125:     foreach my $file (@files) {
10126:         print (OUT $env{'form.currentpath'}.$file."\n");
10127:     }
10128:     foreach my $file (@other_files) {
10129:         print (OUT $file."\n");
10130:     }
10131:     close (OUT);
10132:     return 'ok';
10133: }
10134: 
10135: sub clear_selected_files {
10136:     my ($user) = @_;
10137:     my $filename = $user."savedfiles";
10138:     open (OUT,'>',LONCAPA::tempdir().$filename);
10139:     print (OUT undef);
10140:     close (OUT);
10141:     return ("ok");    
10142: }
10143: 
10144: sub files_in_path {
10145:     my ($user, $path) = @_;
10146:     my $filename = $user."savedfiles";
10147:     my %return_files;
10148:     open (IN,'<',LONCAPA::tempdir().$filename);
10149:     while (my $line_in = <IN>) {
10150:         chomp ($line_in);
10151:         my @paths_and_file = split (m!/!, $line_in);
10152:         my $file_part = pop (@paths_and_file);
10153:         my $path_part = join ('/', @paths_and_file);
10154:         $path_part.='/';
10155:         my $path_and_file = $path_part.$file_part;
10156:         if ($path_part eq $path) {
10157:             $return_files{$file_part}= 'selected';
10158:         }
10159:     }
10160:     close (IN);
10161:     return (\%return_files);
10162: }
10163: 
10164: # called in portfolio select mode, to show files selected NOT in current directory
10165: sub files_not_in_path {
10166:     my ($user, $path) = @_;
10167:     my $filename = $user."savedfiles";
10168:     my @return_files;
10169:     my $path_part;
10170:     open(IN, '<',LONCAPA::tempdir().$filename);
10171:     while (my $line = <IN>) {
10172:         #ok, I know it's clunky, but I want it to work
10173:         my @paths_and_file = split(m|/|, $line);
10174:         my $file_part = pop(@paths_and_file);
10175:         chomp($file_part);
10176:         my $path_part = join('/', @paths_and_file);
10177:         $path_part .= '/';
10178:         my $path_and_file = $path_part.$file_part;
10179:         if ($path_part ne $path) {
10180:             push(@return_files, ($path_and_file));
10181:         }
10182:     }
10183:     close(OUT);
10184:     return (@return_files);
10185: }
10186: 
10187: #------------------------------Submitted/Handedback Portfolio Files Versioning
10188:  
10189: sub portfiles_versioning {
10190:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
10191:     my $portfolio_root = '/userfiles/portfolio';
10192:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
10193:     foreach my $file (@{$portfiles}) {
10194:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
10195:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
10196:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
10197:         my $getpropath = 1;
10198:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
10199:                                              $stu_name,$getpropath);
10200:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
10201:         my $new_answer = 
10202:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
10203:         if ($new_answer ne 'problem getting file') {
10204:             push(@{$versioned_portfiles}, $directory.$new_answer);
10205:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
10206:                               [$symb,$env{'request.course.id'},'graded']);
10207:         }
10208:     }
10209: }
10210: 
10211: sub get_next_version {
10212:     my ($answer_name, $answer_ext, $dir_list) = @_;
10213:     my $version;
10214:     if (ref($dir_list) eq 'ARRAY') {
10215:         foreach my $row (@{$dir_list}) {
10216:             my ($file) = split(/\&/,$row,2);
10217:             my ($file_name,$file_version,$file_ext) =
10218:                 &file_name_version_ext($file);
10219:             if (($file_name eq $answer_name) &&
10220:                 ($file_ext eq $answer_ext)) {
10221:                      # gets here if filename and extension match,
10222:                      # regardless of version
10223:                 if ($file_version ne '') {
10224:                     # a versioned file is found  so save it for later
10225:                     if ($file_version > $version) {
10226:                         $version = $file_version;
10227:                     }
10228:                 }
10229:             }
10230:         }
10231:     }
10232:     $version ++;
10233:     return($version);
10234: }
10235: 
10236: sub version_selected_portfile {
10237:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
10238:     my ($answer_name,$answer_ver,$answer_ext) =
10239:         &file_name_version_ext($file_name);
10240:     my $new_answer;
10241:     $env{'form.copy'} =
10242:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
10243:     if($env{'form.copy'} eq '-1') {
10244:         $new_answer = 'problem getting file';
10245:     } else {
10246:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
10247:         my $copy_result = 
10248:             &finishuserfileupload($stu_name,$domain,'copy',
10249:                                   '/portfolio'.$directory.$new_answer);
10250:     }
10251:     undef($env{'form.copy'});
10252:     return ($new_answer);
10253: }
10254: 
10255: sub file_name_version_ext {
10256:     my ($file)=@_;
10257:     my @file_parts = split(/\./, $file);
10258:     my ($name,$version,$ext);
10259:     if (@file_parts > 1) {
10260:         $ext=pop(@file_parts);
10261:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
10262:             $version=pop(@file_parts);
10263:         }
10264:         $name=join('.',@file_parts);
10265:     } else {
10266:         $name=join('.',@file_parts);
10267:     }
10268:     return($name,$version,$ext);
10269: }
10270: 
10271: #----------------------------------------------Get portfolio file permissions
10272: 
10273: sub get_portfile_permissions {
10274:     my ($domain,$user) = @_;
10275:     my %current_permissions = &dump('file_permissions',$domain,$user);
10276:     my ($tmp)=keys(%current_permissions);
10277:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10278:     return \%current_permissions;
10279: }
10280: 
10281: #---------------------------------------------Get portfolio file access controls
10282: 
10283: sub get_access_controls {
10284:     my ($current_permissions,$group,$file) = @_;
10285:     my %access;
10286:     my $real_file = $file;
10287:     $file =~ s/\.meta$//;
10288:     if (defined($file)) {
10289:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
10290:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
10291:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
10292:             }
10293:         }
10294:     } else {
10295:         foreach my $key (keys(%{$current_permissions})) {
10296:             if ($key =~ /\0accesscontrol$/) {
10297:                 if (defined($group)) {
10298:                     if ($key !~ m-^\Q$group\E/-) {
10299:                         next;
10300:                     }
10301:                 }
10302:                 my ($fullpath) = split(/\0/,$key);
10303:                 if (ref($$current_permissions{$key}) eq 'HASH') {
10304:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
10305:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
10306:                     }
10307:                 }
10308:             }
10309:         }
10310:     }
10311:     return %access;
10312: }
10313: 
10314: sub modify_access_controls {
10315:     my ($file_name,$changes,$domain,$user)=@_;
10316:     my ($outcome,$deloutcome);
10317:     my %store_permissions;
10318:     my %new_values;
10319:     my %new_control;
10320:     my %translation;
10321:     my @deletions = ();
10322:     my $now = time;
10323:     if (exists($$changes{'activate'})) {
10324:         if (ref($$changes{'activate'}) eq 'HASH') {
10325:             my @newitems = sort(keys(%{$$changes{'activate'}}));
10326:             my $numnew = scalar(@newitems);
10327:             for (my $i=0; $i<$numnew; $i++) {
10328:                 my $newkey = $newitems[$i];
10329:                 my $newid = &Apache::loncommon::get_cgi_id();
10330:                 if ($newkey =~ /^\d+:/) { 
10331:                     $newkey =~ s/^(\d+)/$newid/;
10332:                     $translation{$1} = $newid;
10333:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
10334:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
10335:                     $translation{$1} = $newid;
10336:                 }
10337:                 $new_values{$file_name."\0".$newkey} = 
10338:                                           $$changes{'activate'}{$newitems[$i]};
10339:                 $new_control{$newkey} = $now;
10340:             }
10341:         }
10342:     }
10343:     my %todelete;
10344:     my %changed_items;
10345:     foreach my $action ('delete','update') {
10346:         if (exists($$changes{$action})) {
10347:             if (ref($$changes{$action}) eq 'HASH') {
10348:                 foreach my $key (keys(%{$$changes{$action}})) {
10349:                     my ($itemnum) = ($key =~ /^([^:]+):/);
10350:                     if ($action eq 'delete') { 
10351:                         $todelete{$itemnum} = 1;
10352:                     } else {
10353:                         $changed_items{$itemnum} = $key;
10354:                     }
10355:                 }
10356:             }
10357:         }
10358:     }
10359:     # get lock on access controls for file.
10360:     my $lockhash = {
10361:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
10362:                                                        ':'.$env{'user.domain'},
10363:                    }; 
10364:     my $tries = 0;
10365:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10366:    
10367:     while (($gotlock ne 'ok') && $tries < 10) {
10368:         $tries ++;
10369:         sleep(0.1);
10370:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10371:     }
10372:     if ($gotlock eq 'ok') {
10373:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
10374:         my ($tmp)=keys(%curr_permissions);
10375:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
10376:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
10377:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
10378:             if (ref($curr_controls) eq 'HASH') {
10379:                 foreach my $control_item (keys(%{$curr_controls})) {
10380:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
10381:                     if (defined($todelete{$itemnum})) {
10382:                         push(@deletions,$file_name."\0".$control_item);
10383:                     } else {
10384:                         if (defined($changed_items{$itemnum})) {
10385:                             $new_control{$changed_items{$itemnum}} = $now;
10386:                             push(@deletions,$file_name."\0".$control_item);
10387:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
10388:                         } else {
10389:                             $new_control{$control_item} = $$curr_controls{$control_item};
10390:                         }
10391:                     }
10392:                 }
10393:             }
10394:         }
10395:         my ($group);
10396:         if (&is_course($domain,$user)) {
10397:             ($group,my $file) = split(/\//,$file_name,2);
10398:         }
10399:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
10400:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
10401:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
10402:         #  remove lock
10403:         my @del_lock = ($file_name."\0".'locked_access_records');
10404:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
10405:         my $sqlresult =
10406:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
10407:                                     $group);
10408:     } else {
10409:         $outcome = "error: could not obtain lockfile\n";  
10410:     }
10411:     return ($outcome,$deloutcome,\%new_values,\%translation);
10412: }
10413: 
10414: sub make_public_indefinitely {
10415:     my (@requrl) = @_;
10416:     return &automated_portfile_access('public',\@requrl);
10417: }
10418: 
10419: sub automated_portfile_access {
10420:     my ($accesstype,$addsref,$delsref,$info) = @_;
10421:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
10422:         return 'invalid';
10423:     }
10424:     my %urls;
10425:     if (ref($addsref) eq 'ARRAY') {
10426:         foreach my $requrl (@{$addsref}) {
10427:             if (&is_portfolio_url($requrl)) {
10428:                 unless (exists($urls{$requrl})) {
10429:                     $urls{$requrl} = 'add';
10430:                 }
10431:             }
10432:         }
10433:     }
10434:     if (ref($delsref) eq 'ARRAY') {
10435:         foreach my $requrl (@{$delsref}) { 
10436:             if (&is_portfolio_url($requrl)) {
10437:                 unless (exists($urls{$requrl})) {
10438:                     $urls{$requrl} = 'delete'; 
10439:                 }
10440:             }
10441:         }
10442:     }
10443:     unless (keys(%urls)) {
10444:         return 'invalid';
10445:     }
10446:     my $ip;
10447:     if ($accesstype eq 'ip') {
10448:         if (ref($info) eq 'HASH') {
10449:             if ($info->{'ip'} ne '') {
10450:                 $ip = $info->{'ip'};
10451:             }
10452:         }
10453:         if ($ip eq '') {
10454:             return 'invalid';
10455:         }
10456:     }
10457:     my $errors;
10458:     my $now = time;
10459:     my %current_perms;
10460:     foreach my $requrl (sort(keys(%urls))) {
10461:         my $action;
10462:         if ($urls{$requrl} eq 'add') {
10463:             $action = 'activate';
10464:         } else {
10465:             $action = 'none';
10466:         }
10467:         my $aclnum = 0;
10468:         my (undef,$udom,$unum,$file_name,$group) =
10469:             &parse_portfolio_url($requrl);
10470:         unless (exists($current_perms{$unum.':'.$udom})) {
10471:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
10472:         }
10473:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
10474:                                                    $group,$file_name);
10475:         foreach my $key (keys(%{$access_controls{$file_name}})) {
10476:             my ($num,$scope,$end,$start) = 
10477:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
10478:             if ($scope eq $accesstype) {
10479:                 if (($start <= $now) && ($end == 0)) {
10480:                     if ($accesstype eq 'ip') {
10481:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
10482:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
10483:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
10484:                                     if ($urls{$requrl} eq 'add') {
10485:                                         $action = 'none';
10486:                                         last;
10487:                                     } else {
10488:                                         $action = 'delete';
10489:                                         $aclnum = $num;
10490:                                         last;
10491:                                     }
10492:                                 }
10493:                             }
10494:                         }
10495:                     } elsif ($accesstype eq 'public') {
10496:                         if ($urls{$requrl} eq 'add') {
10497:                             $action = 'none';
10498:                             last;
10499:                         } else {
10500:                             $action = 'delete';
10501:                             $aclnum = $num;
10502:                             last;
10503:                         }
10504:                     }
10505:                 } elsif ($accesstype eq 'public') {
10506:                     $action = 'update';
10507:                     $aclnum = $num;
10508:                     last;
10509:                 }
10510:             }
10511:         }
10512:         if ($action eq 'none') {
10513:             next;
10514:         } else {
10515:             my %changes;
10516:             my $newend = 0;
10517:             my $newstart = $now;
10518:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
10519:             $changes{$action}{$newkey} = {
10520:                 type => $accesstype,
10521:                 time => {
10522:                     start => $newstart,
10523:                     end   => $newend,
10524:                 },
10525:             };
10526:             if ($accesstype eq 'ip') {
10527:                 $changes{$action}{$newkey}{'ip'} = [$ip];
10528:             }
10529:             my ($outcome,$deloutcome,$new_values,$translation) =
10530:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
10531:             unless ($outcome eq 'ok') {
10532:                 $errors .= $outcome.' ';
10533:             }
10534:         }
10535:     }
10536:     if ($errors) {
10537:         $errors =~ s/\s$//;
10538:         return $errors;
10539:     } else {
10540:         return 'ok';
10541:     }
10542: }
10543: 
10544: #------------------------------------------------------Get Marked as Read Only
10545: 
10546: sub get_marked_as_readonly {
10547:     my ($domain,$user,$what,$group) = @_;
10548:     my $current_permissions = &get_portfile_permissions($domain,$user);
10549:     my @readonly_files;
10550:     my $cmp1=$what;
10551:     if (ref($what)) { $cmp1=join('',@{$what}) };
10552:     while (my ($file_name,$value) = each(%{$current_permissions})) {
10553:         if (defined($group)) {
10554:             if ($file_name !~ m-^\Q$group\E/-) {
10555:                 next;
10556:             }
10557:         }
10558:         if (ref($value) eq "ARRAY"){
10559:             foreach my $stored_what (@{$value}) {
10560:                 my $cmp2=$stored_what;
10561:                 if (ref($stored_what) eq 'ARRAY') {
10562:                     $cmp2=join('',@{$stored_what});
10563:                 }
10564:                 if ($cmp1 eq $cmp2) {
10565:                     push(@readonly_files, $file_name);
10566:                     last;
10567:                 } elsif (!defined($what)) {
10568:                     push(@readonly_files, $file_name);
10569:                     last;
10570:                 }
10571:             }
10572:         }
10573:     }
10574:     return @readonly_files;
10575: }
10576: #-----------------------------------------------------------Get Marked as Read Only Hash
10577: 
10578: sub get_marked_as_readonly_hash {
10579:     my ($current_permissions,$group,$what) = @_;
10580:     my %readonly_files;
10581:     while (my ($file_name,$value) = each(%{$current_permissions})) {
10582:         if (defined($group)) {
10583:             if ($file_name !~ m-^\Q$group\E/-) {
10584:                 next;
10585:             }
10586:         }
10587:         if (ref($value) eq "ARRAY"){
10588:             foreach my $stored_what (@{$value}) {
10589:                 if (ref($stored_what) eq 'ARRAY') {
10590:                     foreach my $lock_descriptor(@{$stored_what}) {
10591:                         if ($lock_descriptor eq 'graded') {
10592:                             $readonly_files{$file_name} = 'graded';
10593:                         } elsif ($lock_descriptor eq 'handback') {
10594:                             $readonly_files{$file_name} = 'handback';
10595:                         } else {
10596:                             if (!exists($readonly_files{$file_name})) {
10597:                                 $readonly_files{$file_name} = 'locked';
10598:                             }
10599:                         }
10600:                     }
10601:                 } 
10602:             }
10603:         } 
10604:     }
10605:     return %readonly_files;
10606: }
10607: # ------------------------------------------------------------ Unmark as Read Only
10608: 
10609: sub unmark_as_readonly {
10610:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
10611:     # for portfolio submissions, $what contains [$symb,$crsid] 
10612:     my ($domain,$user,$what,$file_name,$group) = @_;
10613:     $file_name = &declutter_portfile($file_name);
10614:     my $symb_crs = $what;
10615:     if (ref($what)) { $symb_crs=join('',@$what); }
10616:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
10617:     my ($tmp)=keys(%current_permissions);
10618:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10619:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
10620:     foreach my $file (@readonly_files) {
10621: 	my $clean_file = &declutter_portfile($file);
10622: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
10623: 	my $current_locks = $current_permissions{$file};
10624:         my @new_locks;
10625:         my @del_keys;
10626:         if (ref($current_locks) eq "ARRAY"){
10627:             foreach my $locker (@{$current_locks}) {
10628:                 my $compare=$locker;
10629:                 if (ref($locker) eq 'ARRAY') {
10630:                     $compare=join('',@{$locker});
10631:                     if ($compare ne $symb_crs) {
10632:                         push(@new_locks, $locker);
10633:                     }
10634:                 }
10635:             }
10636:             if (scalar(@new_locks) > 0) {
10637:                 $current_permissions{$file} = \@new_locks;
10638:             } else {
10639:                 push(@del_keys, $file);
10640:                 &del('file_permissions',\@del_keys, $domain, $user);
10641:                 delete($current_permissions{$file});
10642:             }
10643:         }
10644:     }
10645:     &put('file_permissions',\%current_permissions,$domain,$user);
10646:     return;
10647: }
10648: 
10649: # ------------------------------------------------------------ Directory lister
10650: 
10651: sub dirlist {
10652:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
10653:     $uri=~s/^\///;
10654:     $uri=~s/\/$//;
10655:     my ($udom, $uname);
10656:     if ($getuserdir) {
10657:         $udom = $userdomain;
10658:         $uname = $username;
10659:     } else {
10660:         (undef,$udom,$uname)=split(/\//,$uri);
10661:         if(defined($userdomain)) {
10662:             $udom = $userdomain;
10663:         }
10664:         if(defined($username)) {
10665:             $uname = $username;
10666:         }
10667:     }
10668:     my ($dirRoot,$listing,@listing_results);
10669: 
10670:     $dirRoot = $perlvar{'lonDocRoot'};
10671:     if (defined($getpropath)) {
10672:         $dirRoot = &propath($udom,$uname);
10673:         $dirRoot =~ s/\/$//;
10674:     } elsif (defined($getuserdir)) {
10675:         my $subdir=$uname.'__';
10676:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
10677:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
10678:                    ."/$udom/$subdir/$uname";
10679:     } elsif (defined($alternateRoot)) {
10680:         $dirRoot = $alternateRoot;
10681:     }
10682: 
10683:     if($udom) {
10684:         if($uname) {
10685:             my $uhome = &homeserver($uname,$udom);
10686:             if ($uhome eq 'no_host') {
10687:                 return ([],'no_host');
10688:             }
10689:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
10690:                               .$getuserdir.':'.&escape($dirRoot)
10691:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
10692:             if ($listing eq 'unknown_cmd') {
10693:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
10694:             } else {
10695:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
10696:             }
10697:             if ($listing eq 'unknown_cmd') {
10698:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
10699:                 @listing_results = split(/:/,$listing);
10700:             } else {
10701:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
10702:             }
10703:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
10704:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
10705:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10706:                 return ([],$listing);
10707:             } else {
10708:                 return (\@listing_results);
10709:             }
10710:         } elsif(!$alternateRoot) {
10711:             my (%allusers,%listerror);
10712: 	    my %servers = &get_servers($udom,'library');
10713:  	    foreach my $tryserver (keys(%servers)) {
10714:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
10715:                                   &escape($udom),$tryserver);
10716:                 if ($listing eq 'unknown_cmd') {
10717: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
10718: 				      $udom, $tryserver);
10719:                 } else {
10720:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
10721:                 }
10722: 		if ($listing eq 'unknown_cmd') {
10723: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
10724: 				      $udom, $tryserver);
10725: 		    @listing_results = split(/:/,$listing);
10726: 		} else {
10727: 		    @listing_results =
10728: 			map { &unescape($_); } split(/:/,$listing);
10729: 		}
10730:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
10731:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
10732:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10733:                     $listerror{$tryserver} = $listing;
10734:                 } else {
10735: 		    foreach my $line (@listing_results) {
10736: 			my ($entry) = split(/&/,$line,2);
10737: 			$allusers{$entry} = 1;
10738: 		    }
10739: 		}
10740:             }
10741:             my @alluserslist=();
10742:             foreach my $user (sort(keys(%allusers))) {
10743:                 push(@alluserslist,$user.'&user');
10744:             }
10745: 
10746:             if (!%listerror) {
10747:                 # no errors
10748:                 return (\@alluserslist);
10749:             } elsif (scalar(keys(%servers)) == 1) {
10750:                 # one library server, one error 
10751:                 my ($key) = keys(%listerror);
10752:                 return (\@alluserslist, $listerror{$key});
10753:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
10754:                 # con_lost indicates that we might miss data from at least one
10755:                 # library server
10756:                 return (\@alluserslist, 'con_lost');
10757:             } else {
10758:                 # multiple library servers and no con_lost -> data should be
10759:                 # complete. 
10760:                 return (\@alluserslist);
10761:             }
10762: 
10763:         } else {
10764:             return ([],'missing username');
10765:         }
10766:     } elsif(!defined($getpropath)) {
10767:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
10768:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
10769:         return (\@all_domains);
10770:     } else {
10771:         return ([],'missing domain');
10772:     }
10773: }
10774: 
10775: # --------------------------------------------- GetFileTimestamp
10776: # This function utilizes dirlist and returns the date stamp for
10777: # when it was last modified.  It will also return an error of -1
10778: # if an error occurs
10779: 
10780: sub GetFileTimestamp {
10781:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
10782:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
10783:     $studentName   = &LONCAPA::clean_username($studentName);
10784:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
10785:                                     undef,$getuserdir);
10786:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10787:         return -1;
10788:     }
10789:     if (ref($fileref) eq 'ARRAY') {
10790:         my @stats = split('&',$fileref->[0]);
10791:         # @stats contains first the filename, then the stat output
10792:         return $stats[10]; # so this is 10 instead of 9.
10793:     } else {
10794:         return -1;
10795:     }
10796: }
10797: 
10798: sub stat_file {
10799:     my ($uri) = @_;
10800:     $uri = &clutter_with_no_wrapper($uri);
10801: 
10802:     my ($udom,$uname,$file);
10803:     if ($uri =~ m-^/(uploaded|editupload)/-) {
10804: 	($udom,$uname,$file) =
10805: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
10806: 	$file = 'userfiles/'.$file;
10807:     }
10808:     if ($uri =~ m-^/res/-) {
10809: 	($udom,$uname) = 
10810: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
10811: 	$file = $uri;
10812:     }
10813: 
10814:     if (!$udom || !$uname || !$file) {
10815: 	# unable to handle the uri
10816: 	return ();
10817:     }
10818:     my $getpropath;
10819:     if ($file =~ /^userfiles\//) {
10820:         $getpropath = 1;
10821:     }
10822:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
10823:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10824:         return ();
10825:     } else {
10826:         if (ref($listref) eq 'ARRAY') {
10827:             my @stats = split('&',$listref->[0]);
10828: 	    shift(@stats); #filename is first
10829: 	    return @stats;
10830:         }
10831:     }
10832:     return ();
10833: }
10834: 
10835: # --------------------------------------------------------- recursedirs
10836: # Recursive function to traverse either a specific user's Authoring Space
10837: # or corresponding Published Resource Space, and populate the hash ref:
10838: # $dirhashref with URLs of all directories, and if $filehashref hash
10839: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
10840: # or .rights files in resource space, and .meta, .save, .log, and .bak
10841: # files in Authoring Space.
10842: #
10843: # Inputs:
10844: #
10845: # $is_home - true if current server is home server for user's space
10846: # $context - either: priv, or res respectively for Authoring or Resource Space.
10847: # $docroot - Document root (i.e., /home/httpd/html
10848: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
10849: # $relpath - Current path (relative to top level).
10850: # $dirhashref - reference to hash to populate with URLs of directories (Required)
10851: # $filehashref - reference to hash to populate with URLs of files (Optional)
10852: #
10853: # Returns: nothing
10854: #
10855: # Side Effects: populates $dirhashref, and $filehashref (if provided).
10856: #
10857: # Currently used by interface/londocs.pm to create linked select boxes for
10858: # directory and filename to import a Course "Author" resource into a course, and
10859: # also to create linked select boxes for Authoring Space and Directory to choose
10860: # save location for creation of a new "standard" problem from the Course Editor.
10861: #
10862: 
10863: sub recursedirs {
10864:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
10865:     return unless (ref($dirhashref) eq 'HASH');
10866:     my $currpath = $docroot.$toppath;
10867:     if ($relpath) {
10868:         $currpath .= "/$relpath";
10869:     }
10870:     my $savefile;
10871:     if (ref($filehashref)) {
10872:         $savefile = 1;
10873:     }
10874:     if ($is_home) {
10875:         if (opendir(my $dirh,$currpath)) {
10876:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
10877:                 next if ($item eq '');
10878:                 if (-d "$currpath/$item") {
10879:                     my $newpath;
10880:                     if ($relpath) {
10881:                         $newpath = "$relpath/$item";
10882:                     } else {
10883:                         $newpath = $item;
10884:                     }
10885:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
10886:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
10887:                 } elsif ($savefile) {
10888:                     if ($context eq 'priv') {
10889:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
10890:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
10891:                         }
10892:                     } else {
10893:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
10894:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
10895:                         }
10896:                     }
10897:                 }
10898:             }
10899:             closedir($dirh);
10900:         }
10901:     } else {
10902:         my ($dirlistref,$listerror) =
10903:             &dirlist($toppath.$relpath);
10904:         my @dir_lines;
10905:         my $dirptr=16384;
10906:         if (ref($dirlistref) eq 'ARRAY') {
10907:             foreach my $dir_line (sort
10908:                               {
10909:                                   my ($afile)=split('&',$a,2);
10910:                                   my ($bfile)=split('&',$b,2);
10911:                                   return (lc($afile) cmp lc($bfile));
10912:                               } (@{$dirlistref})) {
10913:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
10914:                     split(/\&/,$dir_line,16);
10915:                 $item =~ s/\s+$//;
10916:                 next if (($item =~ /^\.\.?$/) || ($obs));
10917:                 if ($dirptr&$testdir) {
10918:                     my $newpath;
10919:                     if ($relpath) {
10920:                         $newpath = "$relpath/$item";
10921:                     } else {
10922:                         $relpath = '/';
10923:                         $newpath = $item;
10924:                     }
10925:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
10926:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
10927:                 } elsif ($savefile) {
10928:                     if ($context eq 'priv') {
10929:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
10930:                             $filehashref->{$relpath}{$item} = 1;
10931:                         }
10932:                     } else {
10933:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
10934:                             $filehashref->{$relpath}{$item} = 1;
10935:                         }
10936:                     }
10937:                 }
10938:             }
10939:         }
10940:     }
10941:     return;
10942: }
10943: 
10944: # -------------------------------------------------------- Value of a Condition
10945: 
10946: # gets the value of a specific preevaluated condition
10947: #    stored in the string  $env{user.state.<cid>}
10948: # or looks up a condition reference in the bighash and if if hasn't
10949: # already been evaluated recurses into docondval to get the value of
10950: # the condition, then memoizing it to 
10951: #   $env{user.state.<cid>.<condition>}
10952: sub directcondval {
10953:     my $number=shift;
10954:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
10955: 	&Apache::lonuserstate::evalstate();
10956:     }
10957:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
10958: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
10959:     } elsif ($number =~ /^_/) {
10960: 	my $sub_condition;
10961: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10962: 		&GDBM_READER(),0640)) {
10963: 	    $sub_condition=$bighash{'conditions'.$number};
10964: 	    untie(%bighash);
10965: 	}
10966: 	my $value = &docondval($sub_condition);
10967: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
10968: 	return $value;
10969:     }
10970:     if ($env{'user.state.'.$env{'request.course.id'}}) {
10971:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
10972:     } else {
10973:        return 2;
10974:     }
10975: }
10976: 
10977: # get the collection of conditions for this resource
10978: sub condval {
10979:     my $condidx=shift;
10980:     my $allpathcond='';
10981:     foreach my $cond (split(/\|/,$condidx)) {
10982: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
10983: 	    $allpathcond.=
10984: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
10985: 	}
10986:     }
10987:     $allpathcond=~s/\|$//;
10988:     return &docondval($allpathcond);
10989: }
10990: 
10991: #evaluates an expression of conditions
10992: sub docondval {
10993:     my ($allpathcond) = @_;
10994:     my $result=0;
10995:     if ($env{'request.course.id'}
10996: 	&& defined($allpathcond)) {
10997: 	my $operand='|';
10998: 	my @stack;
10999: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
11000: 	    if ($chunk eq '(') {
11001: 		push @stack,($operand,$result);
11002: 	    } elsif ($chunk eq ')') {
11003: 		my $before=pop @stack;
11004: 		if (pop @stack eq '&') {
11005: 		    $result=$result>$before?$before:$result;
11006: 		} else {
11007: 		    $result=$result>$before?$result:$before;
11008: 		}
11009: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
11010: 		$operand=$chunk;
11011: 	    } else {
11012: 		my $new=directcondval($chunk);
11013: 		if ($operand eq '&') {
11014: 		    $result=$result>$new?$new:$result;
11015: 		} else {
11016: 		    $result=$result>$new?$result:$new;
11017: 		}
11018: 	    }
11019: 	}
11020:     }
11021:     return $result;
11022: }
11023: 
11024: # ---------------------------------------------------- Devalidate courseresdata
11025: 
11026: sub devalidatecourseresdata {
11027:     my ($coursenum,$coursedomain)=@_;
11028:     my $hashid=$coursenum.':'.$coursedomain;
11029:     &devalidate_cache_new('courseres',$hashid);
11030: }
11031: 
11032: 
11033: # --------------------------------------------------- Course Resourcedata Query
11034: #
11035: #  Parameters:
11036: #      $coursenum    - Number of the course.
11037: #      $coursedomain - Domain at which the course was created.
11038: #  Returns:
11039: #     A hash of the course parameters along (I think) with timestamps
11040: #     and version info.
11041: 
11042: sub get_courseresdata {
11043:     my ($coursenum,$coursedomain)=@_;
11044:     my $coursehom=&homeserver($coursenum,$coursedomain);
11045:     my $hashid=$coursenum.':'.$coursedomain;
11046:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
11047:     my %dumpreply;
11048:     unless (defined($cached)) {
11049: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
11050: 	$result=\%dumpreply;
11051: 	my ($tmp) = keys(%dumpreply);
11052: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
11053: 	    &do_cache_new('courseres',$hashid,$result,600);
11054: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
11055: 	    return $tmp;
11056: 	} elsif ($tmp =~ /^(error)/) {
11057: 	    $result=undef;
11058: 	    &do_cache_new('courseres',$hashid,$result,600);
11059: 	}
11060:     }
11061:     return $result;
11062: }
11063: 
11064: sub devalidateuserresdata {
11065:     my ($uname,$udom)=@_;
11066:     my $hashid="$udom:$uname";
11067:     &devalidate_cache_new('userres',$hashid);
11068: }
11069: 
11070: sub get_userresdata {
11071:     my ($uname,$udom)=@_;
11072:     #most student don\'t have any data set, check if there is some data
11073:     if (&EXT_cache_status($udom,$uname)) { return undef; }
11074: 
11075:     my $hashid="$udom:$uname";
11076:     my ($result,$cached)=&is_cached_new('userres',$hashid);
11077:     if (!defined($cached)) {
11078: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
11079: 	$result=\%resourcedata;
11080: 	&do_cache_new('userres',$hashid,$result,600);
11081:     }
11082:     my ($tmp)=keys(%$result);
11083:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
11084: 	return $result;
11085:     }
11086:     #error 2 occurs when the .db doesn't exist
11087:     if ($tmp!~/error: 2 /) {
11088:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
11089: 	    &logthis("<font color=\"blue\">WARNING:".
11090: 		     " Trying to get resource data for ".
11091: 		     $uname." at ".$udom.": ".
11092: 		     $tmp."</font>");
11093:         }
11094:     } elsif ($tmp=~/error: 2 /) {
11095: 	#&EXT_cache_set($udom,$uname);
11096: 	&do_cache_new('userres',$hashid,undef,600);
11097: 	undef($tmp); # not really an error so don't send it back
11098:     }
11099:     return $tmp;
11100: }
11101: #----------------------------------------------- resdata - return resource data
11102: #  Purpose:
11103: #    Return resource data for either users or for a course.
11104: #  Parameters:
11105: #     $name      - Course/user name.
11106: #     $domain    - Name of the domain the user/course is registered on.
11107: #     $type      - Type of thing $name is (must be 'course' or 'user')
11108: #     $mapp      - decluttered URL of enclosing map  
11109: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
11110: #     $recurseup - Ref to array of map URLs, starting with map containing
11111: #                  $mapp up through hierarchy of nested maps to top level map.  
11112: #     $courseid  - CourseID (first part of param identifier).
11113: #     $modifier  - Middle part of param identifier.
11114: #     $what      - Last part of param identifier.
11115: #     @which     - Array of names of resources desired.
11116: #  Returns:
11117: #     The value of the first reasource in @which that is found in the
11118: #     resource hash.
11119: #  Exceptional Conditions:
11120: #     If the $type passed in is not valid (not the string 'course' or 
11121: #     'user', an undefined  reference is returned.
11122: #     If none of the resources are found, an undef is returned
11123: sub resdata {
11124:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
11125:         $modifier,$what,@which)=@_;
11126:     my $result;
11127:     if ($type eq 'course') {
11128: 	$result=&get_courseresdata($name,$domain);
11129:     } elsif ($type eq 'user') {
11130: 	$result=&get_userresdata($name,$domain);
11131:     }
11132:     if (!ref($result)) { return $result; }    
11133:     foreach my $item (@which) {
11134:         if ($item->[1] eq 'course') {
11135:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
11136:                 unless ($$recursed) {
11137:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
11138:                     $$recursed = 1;
11139:                 }
11140:                 foreach my $item (@${recurseup}) {
11141:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
11142:                     last if (defined($result->{$norecursechk}));
11143:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
11144:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
11145:                 }
11146:             }
11147:         }
11148:         if (defined($result->{$item->[0]})) {
11149: 	    return [$result->{$item->[0]},$item->[1]];
11150: 	}
11151:     }
11152:     return undef;
11153: }
11154: 
11155: sub get_domain_lti {
11156:     my ($cdom,$context) = @_;
11157:     my ($name,%lti);
11158:     if ($context eq 'consumer') {
11159:         $name = 'ltitools';
11160:     } elsif ($context eq 'provider') {
11161:         $name = 'lti';
11162:     } else {
11163:         return %lti;
11164:     }
11165:     my ($result,$cached)=&is_cached_new($name,$cdom);
11166:     if (defined($cached)) {
11167:         if (ref($result) eq 'HASH') {
11168:             %lti = %{$result};
11169:         }
11170:     } else {
11171:         my %domconfig = &get_dom('configuration',[$name],$cdom);
11172:         if (ref($domconfig{$name}) eq 'HASH') {
11173:             %lti = %{$domconfig{$name}};
11174:             my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
11175:             if (ref($encdomconfig{$name}) eq 'HASH') {
11176:                 foreach my $id (keys(%lti)) {
11177:                     if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
11178:                         foreach my $item ('key','secret') {
11179:                             $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
11180:                         }
11181:                     }
11182:                 }
11183:             }
11184:         }
11185:         my $cachetime = 24*60*60;
11186:         &do_cache_new($name,$cdom,\%lti,$cachetime);
11187:     }
11188:     return %lti;
11189: }
11190: 
11191: sub get_numsuppfiles {
11192:     my ($cnum,$cdom,$ignorecache)=@_;
11193:     my $hashid=$cnum.':'.$cdom;
11194:     my ($suppcount,$cached);
11195:     unless ($ignorecache) {
11196:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
11197:     }
11198:     unless (defined($cached)) {
11199:         my $chome=&homeserver($cnum,$cdom);
11200:         unless ($chome eq 'no_host') {
11201:             ($suppcount,my $errors) = (0,0);
11202:             my $suppmap = 'supplemental.sequence';
11203:             ($suppcount,$errors) = 
11204:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
11205:         }
11206:         &do_cache_new('suppcount',$hashid,$suppcount,600);
11207:     }
11208:     return $suppcount;
11209: }
11210: 
11211: #
11212: # EXT resource caching routines
11213: #
11214: 
11215: {
11216: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
11217: #
11218: # The course for which we cache
11219: my $cachedmapkey='';
11220: # The cached recursive maps for this course
11221: my %cachedmaps=();
11222: # When this was last done
11223: my $cachedmaptime='';
11224: 
11225: sub clear_EXT_cache_status {
11226:     &delenv('cache.EXT.');
11227: }
11228: 
11229: sub EXT_cache_status {
11230:     my ($target_domain,$target_user) = @_;
11231:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11232:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
11233:         # We know already the user has no data
11234:         return 1;
11235:     } else {
11236:         return 0;
11237:     }
11238: }
11239: 
11240: sub EXT_cache_set {
11241:     my ($target_domain,$target_user) = @_;
11242:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11243:     #&appenv({$cachename => time});
11244: }
11245: 
11246: # --------------------------------------------------------- Value of a Variable
11247: sub EXT {
11248: 
11249:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
11250:     unless ($varname) { return ''; }
11251:     #get real user name/domain, courseid and symb
11252:     my $courseid;
11253:     my $publicuser;
11254:     if ($symbparm) {
11255: 	$symbparm=&get_symb_from_alias($symbparm);
11256:     }
11257:     if (!($uname && $udom)) {
11258:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
11259:       if (!$symbparm) {	$symbparm=$cursymb; }
11260:     } else {
11261: 	$courseid=$env{'request.course.id'};
11262:     }
11263:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
11264:     my $rest;
11265:     if (defined($therest[0])) {
11266:        $rest=join('.',@therest);
11267:     } else {
11268:        $rest='';
11269:     }
11270: 
11271:     my $qualifierrest=$qualifier;
11272:     if ($rest) { $qualifierrest.='.'.$rest; }
11273:     my $spacequalifierrest=$space;
11274:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
11275:     if ($realm eq 'user') {
11276: # --------------------------------------------------------------- user.resource
11277: 	if ($space eq 'resource') {
11278: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
11279: 		  || defined($Apache::lonhomework::parsing_a_task))
11280: 		 &&
11281: 		 ($symbparm eq &symbread()) ) {	
11282: 		# if we are in the middle of processing the resource the
11283: 		# get the value we are planning on committing
11284:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
11285:                     return $Apache::lonhomework::results{$qualifierrest};
11286:                 } else {
11287:                     return $Apache::lonhomework::history{$qualifierrest};
11288:                 }
11289: 	    } else {
11290: 		my %restored;
11291: 		if ($publicuser || $env{'request.state'} eq 'construct') {
11292: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
11293: 		} else {
11294: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
11295: 		}
11296: 		return $restored{$qualifierrest};
11297: 	    }
11298: # ----------------------------------------------------------------- user.access
11299:         } elsif ($space eq 'access') {
11300: 	    # FIXME - not supporting calls for a specific user
11301:             return &allowed($qualifier,$rest);
11302: # ------------------------------------------ user.preferences, user.environment
11303:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
11304: 	    if (($uname eq $env{'user.name'}) &&
11305: 		($udom eq $env{'user.domain'})) {
11306: 		return $env{join('.',('environment',$qualifierrest))};
11307: 	    } else {
11308: 		my %returnhash;
11309: 		if (!$publicuser) {
11310: 		    %returnhash=&userenvironment($udom,$uname,
11311: 						 $qualifierrest);
11312: 		}
11313: 		return $returnhash{$qualifierrest};
11314: 	    }
11315: # ----------------------------------------------------------------- user.course
11316:         } elsif ($space eq 'course') {
11317: 	    # FIXME - not supporting calls for a specific user
11318:             return $env{join('.',('request.course',$qualifier))};
11319: # ------------------------------------------------------------------- user.role
11320:         } elsif ($space eq 'role') {
11321: 	    # FIXME - not supporting calls for a specific user
11322:             my ($role,$where)=split(/\./,$env{'request.role'});
11323:             if ($qualifier eq 'value') {
11324: 		return $role;
11325:             } elsif ($qualifier eq 'extent') {
11326:                 return $where;
11327:             }
11328: # ----------------------------------------------------------------- user.domain
11329:         } elsif ($space eq 'domain') {
11330:             return $udom;
11331: # ------------------------------------------------------------------- user.name
11332:         } elsif ($space eq 'name') {
11333:             return $uname;
11334: # ---------------------------------------------------- Any other user namespace
11335:         } else {
11336: 	    my %reply;
11337: 	    if (!$publicuser) {
11338: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
11339: 	    }
11340: 	    return $reply{$qualifierrest};
11341:         }
11342:     } elsif ($realm eq 'query') {
11343: # ---------------------------------------------- pull stuff out of query string
11344:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
11345: 						[$spacequalifierrest]);
11346: 	return $env{'form.'.$spacequalifierrest}; 
11347:    } elsif ($realm eq 'request') {
11348: # ------------------------------------------------------------- request.browser
11349:         if ($space eq 'browser') {
11350:             return $env{'browser.'.$qualifier};
11351: # ------------------------------------------------------------ request.filename
11352:         } else {
11353:             return $env{'request.'.$spacequalifierrest};
11354:         }
11355:     } elsif ($realm eq 'course') {
11356: # ---------------------------------------------------------- course.description
11357:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
11358:     } elsif ($realm eq 'resource') {
11359: 
11360: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
11361: 	    if (!$symbparm) { $symbparm=&symbread(); }
11362: 	}
11363: 
11364:         if ($qualifier eq '') {
11365: 	    if ($space eq 'title') {
11366: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
11367: 	        return &gettitle($symbparm);
11368: 	    }
11369: 	
11370: 	    if ($space eq 'map') {
11371: 	        my ($map) = &decode_symb($symbparm);
11372: 	        return &symbread($map);
11373: 	    }
11374:             if ($space eq 'maptitle') {
11375:                 my ($map) = &decode_symb($symbparm);
11376:                 return &gettitle($map);
11377:             }
11378: 	    if ($space eq 'filename') {
11379: 	        if ($symbparm) {
11380: 		    return &clutter((&decode_symb($symbparm))[2]);
11381: 	        }
11382: 	        return &hreflocation('',$env{'request.filename'});
11383: 	    }
11384: 
11385:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
11386:                 if ($space eq 'visibleparts') {
11387:                     my $navmap = Apache::lonnavmaps::navmap->new();
11388:                     my $item;
11389:                     if (ref($navmap)) {
11390:                         my $res = $navmap->getBySymb($symbparm);
11391:                         my $parts = $res->parts();
11392:                         if (ref($parts) eq 'ARRAY') {
11393:                             $item = join(',',@{$parts});
11394:                         }
11395:                         undef($navmap);
11396:                     }
11397:                     return $item;
11398:                 }
11399:             }
11400:         }
11401: 
11402: 	my ($section, $group, @groups, @recurseup, $recursed);
11403: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
11404:         if (($courseid eq '') && ($cid)) {
11405:             $courseid = $cid;
11406:         }
11407: 	if (($symbparm && $courseid) && 
11408: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
11409: 
11410: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
11411: 
11412: # ----------------------------------------------------- Cascading lookup scheme
11413: 	    my $symbp=$symbparm;
11414: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
11415: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
11416:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
11417: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
11418: 	    if (($env{'user.name'} eq $uname) &&
11419: 		($env{'user.domain'} eq $udom)) {
11420: 		$section=$env{'request.course.sec'};
11421:                 @groups = split(/:/,$env{'request.course.groups'});  
11422:                 @groups=&sort_course_groups($courseid,@groups); 
11423: 	    } else {
11424: 		if (! defined($usection)) {
11425: 		    $section=&getsection($udom,$uname,$courseid);
11426: 		} else {
11427: 		    $section = $usection;
11428: 		}
11429:                 @groups = &get_users_groups($udom,$uname,$courseid);
11430: 	    }
11431: 
11432: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
11433: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
11434:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
11435: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
11436: 
11437: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
11438: 	    my $courselevelr=$courseid.'.'.$symbparm;
11439:             $courseleveli=$courseid.'.'.$recurseparm;
11440: 	    $courselevelm=$courseid.'.'.$mapparm;
11441: 
11442: # ----------------------------------------------------------- first, check user
11443: 
11444: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
11445:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
11446: 				       ([$courselevelr,'resource'],
11447: 					[$courselevelm,'map'     ],
11448:                                         [$courseleveli,'map'     ],
11449: 					[$courselevel, 'course'  ]));
11450: 	    if (defined($userreply)) { return &get_reply($userreply); }
11451: 
11452: # ------------------------------------------------ second, check some of course
11453:             my $coursereply;
11454:             if (@groups > 0) {
11455:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
11456:                                        $recurseparm,$mapparm,$spacequalifierrest,
11457:                                        $mapp,\$recursed,\@recurseup);
11458:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
11459:             }
11460: 
11461: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11462: 				  $env{'course.'.$courseid.'.domain'},
11463: 				  'course',$mapp,\$recursed,\@recurseup,
11464:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
11465: 				  ([$seclevelr,   'resource'],
11466: 				   [$seclevelm,   'map'     ],
11467:                                    [$secleveli,   'map'     ],
11468: 				   [$seclevel,    'course'  ],
11469: 				   [$courselevelr,'resource']));
11470: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
11471: 
11472: # ------------------------------------------------------ third, check map parms
11473: 	    my %parmhash=();
11474: 	    my $thisparm='';
11475: 	    if (tie(%parmhash,'GDBM_File',
11476: 		    $env{'request.course.fn'}.'_parms.db',
11477: 		    &GDBM_READER(),0640)) {
11478: 		$thisparm=$parmhash{$symbparm};
11479: 		untie(%parmhash);
11480: 	    }
11481: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
11482: 	}
11483: # ------------------------------------------ fourth, look in resource metadata
11484:  
11485:         my $what = $spacequalifierrest;
11486: 	$what=~s/\./\_/;
11487: 	my $filename;
11488: 	if (!$symbparm) { $symbparm=&symbread(); }
11489: 	if ($symbparm) {
11490: 	    $filename=(&decode_symb($symbparm))[2];
11491: 	} else {
11492: 	    $filename=$env{'request.filename'};
11493: 	}
11494: 	my $metadata=&metadata($filename,$what);
11495: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
11496: 	$metadata=&metadata($filename,'parameter_'.$what);
11497: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
11498: 
11499: # ----------------------------------------------- fifth, look in rest of course
11500: 	if ($symbparm && defined($courseid) && 
11501: 	    $courseid eq $env{'request.course.id'}) {
11502: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11503: 				     $env{'course.'.$courseid.'.domain'},
11504: 				     'course',$mapp,\$recursed,\@recurseup,
11505:                                      $courseid,'.',$spacequalifierrest,
11506: 				     ([$courselevelm,'map'   ],
11507:                                       [$courseleveli,'map'   ],
11508: 				      [$courselevel, 'course']));
11509: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
11510: 	}
11511: # ------------------------------------------------------------------ Cascade up
11512: 	unless ($space eq '0') {
11513: 	    my @parts=split(/_/,$space);
11514: 	    my $id=pop(@parts);
11515: 	    my $part=join('_',@parts);
11516: 	    if ($part eq '') { $part='0'; }
11517: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
11518: 				 $symbparm,$udom,$uname,$section,1);
11519: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
11520: 	}
11521: 	if ($recurse) { return undef; }
11522: 	my $pack_def=&packages_tab_default($filename,$varname);
11523: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
11524: # ---------------------------------------------------- Any other user namespace
11525:     } elsif ($realm eq 'environment') {
11526: # ----------------------------------------------------------------- environment
11527: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
11528: 	    return $env{'environment.'.$spacequalifierrest};
11529: 	} else {
11530: 	    if ($uname eq 'anonymous' && $udom eq '') {
11531: 		return '';
11532: 	    }
11533: 	    my %returnhash=&userenvironment($udom,$uname,
11534: 					    $spacequalifierrest);
11535: 	    return $returnhash{$spacequalifierrest};
11536: 	}
11537:     } elsif ($realm eq 'system') {
11538: # ----------------------------------------------------------------- system.time
11539: 	if ($space eq 'time') {
11540: 	    return time;
11541:         }
11542:     } elsif ($realm eq 'server') {
11543: # ----------------------------------------------------------------- system.time
11544: 	if ($space eq 'name') {
11545: 	    return $ENV{'SERVER_NAME'};
11546:         }
11547:     }
11548:     return '';
11549: }
11550: 
11551: sub get_reply {
11552:     my ($reply_value) = @_;
11553:     if (ref($reply_value) eq 'ARRAY') {
11554:         if (wantarray) {
11555: 	    return @$reply_value;
11556:         }
11557:         return $reply_value->[0];
11558:     } else {
11559:         return $reply_value;
11560:     }
11561: }
11562: 
11563: sub check_group_parms {
11564:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
11565:         $recursed,$recurseupref) = @_;
11566:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
11567:                   [$what,'course']);
11568:     my $coursereply;
11569:     foreach my $group (@{$groups}) {
11570:         my @groupitems = ();
11571:         foreach my $level (@levels) {
11572:              my $item = $courseid.'.['.$group.'].'.$level->[0];
11573:              push(@groupitems,[$item,$level->[1]]);
11574:         }
11575:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
11576:                                    $env{'course.'.$courseid.'.domain'},
11577:                                    'course',$mapp,$recursed,$recurseupref,
11578:                                    $courseid,'.['.$group.'].',$what,
11579:                                    @groupitems);
11580:         last if (defined($coursereply));
11581:     }
11582:     return $coursereply;
11583: }
11584: 
11585: sub get_map_hierarchy {
11586:     my ($mapname,$courseid) = @_;
11587:     my @recurseup = ();
11588:     if ($mapname) {
11589:         if (($cachedmapkey eq $courseid) &&
11590:             (abs($cachedmaptime-time)<5)) {
11591:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
11592:                 return @{$cachedmaps{$mapname}};
11593:             }
11594:         }
11595:         my $navmap = Apache::lonnavmaps::navmap->new();
11596:         if (ref($navmap)) {
11597:             @recurseup = $navmap->recurseup_maps($mapname);
11598:             undef($navmap);
11599:             $cachedmaps{$mapname} = \@recurseup;
11600:             $cachedmaptime=time;
11601:             $cachedmapkey=$courseid;
11602:         }
11603:     }
11604:     return @recurseup;
11605: }
11606: 
11607: }
11608: 
11609: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
11610:     my ($courseid,@groups) = @_;
11611:     @groups = sort(@groups);
11612:     return @groups;
11613: }
11614: 
11615: sub packages_tab_default {
11616:     my ($uri,$varname)=@_;
11617:     my (undef,$part,$name)=split(/\./,$varname);
11618: 
11619:     my (@extension,@specifics,$do_default);
11620:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
11621: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
11622: 	if ($pack_type eq 'default') {
11623: 	    $do_default=1;
11624: 	} elsif ($pack_type eq 'extension') {
11625: 	    push(@extension,[$package,$pack_type,$pack_part]);
11626: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
11627: 	    # only look at packages defaults for packages that this id is
11628: 	    push(@specifics,[$package,$pack_type,$pack_part]);
11629: 	}
11630:     }
11631:     # first look for a package that matches the requested part id
11632:     foreach my $package (@specifics) {
11633: 	my (undef,$pack_type,$pack_part)=@{$package};
11634: 	next if ($pack_part ne $part);
11635: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11636: 	    return $packagetab{"$pack_type&$name&default"};
11637: 	}
11638:     }
11639:     # look for any possible matching non extension_ package
11640:     foreach my $package (@specifics) {
11641: 	my (undef,$pack_type,$pack_part)=@{$package};
11642: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11643: 	    return $packagetab{"$pack_type&$name&default"};
11644: 	}
11645: 	if ($pack_type eq 'part') { $pack_part='0'; }
11646: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
11647: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
11648: 	}
11649:     }
11650:     # look for any posible extension_ match
11651:     foreach my $package (@extension) {
11652: 	my ($package,$pack_type)=@{$package};
11653: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11654: 	    return $packagetab{"$pack_type&$name&default"};
11655: 	}
11656: 	if (defined($packagetab{$package."&$name&default"})) {
11657: 	    return $packagetab{$package."&$name&default"};
11658: 	}
11659:     }
11660:     # look for a global default setting
11661:     if ($do_default && defined($packagetab{"default&$name&default"})) {
11662: 	return $packagetab{"default&$name&default"};
11663:     }
11664:     return undef;
11665: }
11666: 
11667: sub add_prefix_and_part {
11668:     my ($prefix,$part)=@_;
11669:     my $keyroot;
11670:     if (defined($prefix) && $prefix !~ /^__/) {
11671: 	# prefix that has a part already
11672: 	$keyroot=$prefix;
11673:     } elsif (defined($prefix)) {
11674: 	# prefix that is missing a part
11675: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
11676:     } else {
11677: 	# no prefix at all
11678: 	if (defined($part)) { $keyroot='_'.$part; }
11679:     }
11680:     return $keyroot;
11681: }
11682: 
11683: # ---------------------------------------------------------------- Get metadata
11684: 
11685: my %metaentry;
11686: my %importedpartids;
11687: sub metadata {
11688:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
11689:     $uri=&declutter($uri);
11690:     # if it is a non metadata possible uri return quickly
11691:     if (($uri eq '') || 
11692: 	(($uri =~ m|^/*adm/|) && 
11693: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
11694:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
11695: 	return undef;
11696:     }
11697:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
11698: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
11699: 	return undef;
11700:     }
11701:     my $filename=$uri;
11702:     $uri=~s/\.meta$//;
11703: #
11704: # Is the metadata already cached?
11705: # Look at timestamp of caching
11706: # Everything is cached by the main uri, libraries are never directly cached
11707: #
11708:     if (!defined($liburi)) {
11709: 	my ($result,$cached)=&is_cached_new('meta',$uri);
11710: 	if (defined($cached)) { return $result->{':'.$what}; }
11711:     }
11712:     {
11713: # Imported parts would go here
11714:         my %importedids=();
11715:         my @origfileimportpartids=();
11716:         my $importedparts=0;
11717: #
11718: # Is this a recursive call for a library?
11719: #
11720: #	if (! exists($metacache{$uri})) {
11721: #	    $metacache{$uri}={};
11722: #	}
11723: 	my $cachetime = 60*60;
11724:         if ($liburi) {
11725: 	    $liburi=&declutter($liburi);
11726:             $filename=$liburi;
11727:         } else {
11728: 	    &devalidate_cache_new('meta',$uri);
11729: 	    undef(%metaentry);
11730: 	}
11731:         my %metathesekeys=();
11732:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
11733: 	my $metastring;
11734: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
11735: 	    my $which = &hreflocation('','/'.($liburi || $uri));
11736: 	    $metastring = 
11737: 		&Apache::lonnet::ssi_body($which,
11738: 					  ('grade_target' => 'meta'));
11739: 	    $cachetime = 1; # only want this cached in the child not long term
11740: 	} elsif (($uri !~ m -^(editupload)/-) && 
11741:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
11742: 	    my $file=&filelocation('',&clutter($filename));
11743: 	    #push(@{$metaentry{$uri.'.file'}},$file);
11744: 	    $metastring=&getfile($file);
11745: 	}
11746:         my $parser=HTML::LCParser->new(\$metastring);
11747:         my $token;
11748:         undef %metathesekeys;
11749:         while ($token=$parser->get_token) {
11750: 	    if ($token->[0] eq 'S') {
11751: 		if (defined($token->[2]->{'package'})) {
11752: #
11753: # This is a package - get package info
11754: #
11755: 		    my $package=$token->[2]->{'package'};
11756: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11757: 		    if (defined($token->[2]->{'id'})) { 
11758: 			$keyroot.='_'.$token->[2]->{'id'}; 
11759: 		    }
11760: 		    if ($metaentry{':packages'}) {
11761: 			$metaentry{':packages'}.=','.$package.$keyroot;
11762: 		    } else {
11763: 			$metaentry{':packages'}=$package.$keyroot;
11764: 		    }
11765: 		    foreach my $pack_entry (keys(%packagetab)) {
11766: 			my $part=$keyroot;
11767: 			$part=~s/^\_//;
11768: 			if ($pack_entry=~/^\Q$package\E\&/ || 
11769: 			    $pack_entry=~/^\Q$package\E_0\&/) {
11770: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
11771: 			    # ignore package.tab specified default values
11772:                             # here &package_tab_default() will fetch those
11773: 			    if ($subp eq 'default') { next; }
11774: 			    my $value=$packagetab{$pack_entry};
11775: 			    my $unikey;
11776: 			    if ($pack =~ /_0$/) {
11777: 				$unikey='parameter_0_'.$name;
11778: 				$part=0;
11779: 			    } else {
11780: 				$unikey='parameter'.$keyroot.'_'.$name;
11781: 			    }
11782: 			    if ($subp eq 'display') {
11783: 				$value.=' [Part: '.$part.']';
11784: 			    }
11785: 			    $metaentry{':'.$unikey.'.part'}=$part;
11786: 			    $metathesekeys{$unikey}=1;
11787: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11788: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
11789: 			    }
11790: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
11791: 				$metaentry{':'.$unikey}=
11792: 				    $metaentry{':'.$unikey.'.default'};
11793: 			    }
11794: 			}
11795: 		    }
11796: 		} else {
11797: #
11798: # This is not a package - some other kind of start tag
11799: #
11800: 		    my $entry=$token->[1];
11801: 		    my $unikey='';
11802: 
11803: 		    if ($entry eq 'import') {
11804: #
11805: # Importing a library here
11806: #
11807:                         my $location=$parser->get_text('/import');
11808:                         my $dir=$filename;
11809:                         $dir=~s|[^/]*$||;
11810:                         $location=&filelocation($dir,$location);
11811:                        
11812:                         my $importmode=$token->[2]->{'importmode'};
11813:                         if ($importmode eq 'problem') {
11814: # Import as problem/response
11815:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11816:                         } elsif ($importmode eq 'part') {
11817: # Import as part(s)
11818:                            $importedparts=1;
11819: # We need to get the original file and the imported file to get the part order correct
11820: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
11821: # Load and inspect original file
11822:                            if ($#origfileimportpartids<0) {
11823:                               undef(%importedpartids);
11824:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
11825:                               my $origfile=&getfile($origfilelocation);
11826:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11827:                            }
11828: 
11829: # Load and inspect imported file
11830:                            my $impfile=&getfile($location);
11831:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11832:                            if ($#impfilepartids>=0) {
11833: # This problem had parts
11834:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
11835:                            } else {
11836: # Importing by turning a single problem into a problem part
11837: # It gets the import-tags ID as part-ID
11838:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
11839:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
11840:                            }
11841:                         } else {
11842: # Normal import
11843:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11844:                            if (defined($token->[2]->{'id'})) {
11845:                               $unikey.='_'.$token->[2]->{'id'};
11846:                            }
11847:                         }
11848: 
11849: 			if ($depthcount<20) {
11850: 			    my $metadata = 
11851: 				&metadata($uri,'keys', $location,$unikey,
11852: 					  $depthcount+1);
11853: 			    foreach my $meta (split(',',$metadata)) {
11854: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
11855: 				$metathesekeys{$meta}=1;
11856: 			    }
11857: 			
11858:                         }
11859: 		    } else {
11860: #
11861: # Not importing, some other kind of non-package, non-library start tag
11862: # 
11863:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
11864:                         if (defined($token->[2]->{'id'})) {
11865:                             $unikey.='_'.$token->[2]->{'id'};
11866:                         }
11867: 			if (defined($token->[2]->{'name'})) { 
11868: 			    $unikey.='_'.$token->[2]->{'name'}; 
11869: 			}
11870: 			$metathesekeys{$unikey}=1;
11871: 			foreach my $param (@{$token->[3]}) {
11872: 			    $metaentry{':'.$unikey.'.'.$param} =
11873: 				$token->[2]->{$param};
11874: 			}
11875: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
11876: 			my $default=$metaentry{':'.$unikey.'.default'};
11877: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
11878: 		 # only ws inside the tag, and not in default, so use default
11879: 		 # as value
11880: 			    $metaentry{':'.$unikey}=$default;
11881: 			} elsif ( $internaltext =~ /\S/ ) {
11882: 		  # something interesting inside the tag
11883: 			    $metaentry{':'.$unikey}=$internaltext;
11884: 			} else {
11885: 		  # no interesting values, don't set a default
11886: 			}
11887: # end of not-a-package not-a-library import
11888: 		    }
11889: # end of not-a-package start tag
11890: 		}
11891: # the next is the end of "start tag"
11892: 	    }
11893: 	}
11894: 	my ($extension) = ($uri =~ /\.(\w+)$/);
11895: 	$extension = lc($extension);
11896: 	if ($extension eq 'htm') { $extension='html'; }
11897: 
11898: 	foreach my $key (keys(%packagetab)) {
11899: 	    #no specific packages #how's our extension
11900: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
11901: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
11902: 					 \%metathesekeys);
11903: 	}
11904: 
11905: 	if (!exists($metaentry{':packages'})
11906: 	    || $packagetab{"import_defaults&extension_$extension"}) {
11907: 	    foreach my $key (keys(%packagetab)) {
11908: 		#no specific packages well let's get default then
11909: 		if ($key!~/^default&/) { next; }
11910: 		&metadata_create_package_def($uri,$key,'default',
11911: 					     \%metathesekeys);
11912: 	    }
11913: 	}
11914: # are there custom rights to evaluate
11915: 	if ($metaentry{':copyright'} eq 'custom') {
11916: 
11917:     #
11918:     # Importing a rights file here
11919:     #
11920: 	    unless ($depthcount) {
11921: 		my $location=$metaentry{':customdistributionfile'};
11922: 		my $dir=$filename;
11923: 		$dir=~s|[^/]*$||;
11924: 		$location=&filelocation($dir,$location);
11925: 		my $rights_metadata =
11926: 		    &metadata($uri,'keys',$location,'_rights',
11927: 			      $depthcount+1);
11928: 		foreach my $rights (split(',',$rights_metadata)) {
11929: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
11930: 		    $metathesekeys{$rights}=1;
11931: 		}
11932: 	    }
11933: 	}
11934: 	# uniqifiy package listing
11935: 	my %seen;
11936: 	my @uniq_packages =
11937: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
11938: 	$metaentry{':packages'} = join(',',@uniq_packages);
11939: 
11940:         if ($importedparts) {
11941: # We had imported parts and need to rebuild partorder
11942:            $metaentry{':partorder'}='';
11943:            $metathesekeys{'partorder'}=1;
11944:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
11945:                if ($origfileimportpartids[$index] eq 'part') {
11946: # original part, part of the problem
11947:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
11948:                } else {
11949: # we have imported parts at this position
11950:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
11951:                }
11952:            }
11953:            $metaentry{':partorder'}=~s/^\,//;
11954:         }
11955: 
11956: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
11957: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
11958: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
11959: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
11960: # this is the end of "was not already recently cached
11961:     }
11962:     return $metaentry{':'.$what};
11963: }
11964: 
11965: sub metadata_create_package_def {
11966:     my ($uri,$key,$package,$metathesekeys)=@_;
11967:     my ($pack,$name,$subp)=split(/\&/,$key);
11968:     if ($subp eq 'default') { next; }
11969:     
11970:     if (defined($metaentry{':packages'})) {
11971: 	$metaentry{':packages'}.=','.$package;
11972:     } else {
11973: 	$metaentry{':packages'}=$package;
11974:     }
11975:     my $value=$packagetab{$key};
11976:     my $unikey;
11977:     $unikey='parameter_0_'.$name;
11978:     $metaentry{':'.$unikey.'.part'}=0;
11979:     $$metathesekeys{$unikey}=1;
11980:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11981: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
11982:     }
11983:     if (defined($metaentry{':'.$unikey.'.default'})) {
11984: 	$metaentry{':'.$unikey}=
11985: 	    $metaentry{':'.$unikey.'.default'};
11986:     }
11987: }
11988: 
11989: sub metadata_generate_part0 {
11990:     my ($metadata,$metacache,$uri) = @_;
11991:     my %allnames;
11992:     foreach my $metakey (keys(%$metadata)) {
11993: 	if ($metakey=~/^parameter\_(.*)/) {
11994: 	  my $part=$$metacache{':'.$metakey.'.part'};
11995: 	  my $name=$$metacache{':'.$metakey.'.name'};
11996: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
11997: 	    $allnames{$name}=$part;
11998: 	  }
11999: 	}
12000:     }
12001:     foreach my $name (keys(%allnames)) {
12002:       $$metadata{"parameter_0_$name"}=1;
12003:       my $key=":parameter_0_$name";
12004:       $$metacache{"$key.part"}='0';
12005:       $$metacache{"$key.name"}=$name;
12006:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
12007: 					   $allnames{$name}.'_'.$name.
12008: 					   '.type'};
12009:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
12010: 			     '.display'};
12011:       my $expr='[Part: '.$allnames{$name}.']';
12012:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
12013:       $$metacache{"$key.display"}=$olddis;
12014:     }
12015: }
12016: 
12017: # ------------------------------------------------------ Devalidate title cache
12018: 
12019: sub devalidate_title_cache {
12020:     my ($url)=@_;
12021:     if (!$env{'request.course.id'}) { return; }
12022:     my $symb=&symbread($url);
12023:     if (!$symb) { return; }
12024:     my $key=$env{'request.course.id'}."\0".$symb;
12025:     &devalidate_cache_new('title',$key);
12026: }
12027: 
12028: # ------------------------------------------------- Get the title of a course
12029: 
12030: sub current_course_title {
12031:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
12032: }
12033: # ------------------------------------------------- Get the title of a resource
12034: 
12035: sub gettitle {
12036:     my $urlsymb=shift;
12037:     my $symb=&symbread($urlsymb);
12038:     if ($symb) {
12039: 	my $key=$env{'request.course.id'}."\0".$symb;
12040: 	my ($result,$cached)=&is_cached_new('title',$key);
12041: 	if (defined($cached)) { 
12042: 	    return $result;
12043: 	}
12044: 	my ($map,$resid,$url)=&decode_symb($symb);
12045: 	my $title='';
12046: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
12047: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
12048: 	} else {
12049: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12050: 		    &GDBM_READER(),0640)) {
12051: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
12052: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
12053: 		untie(%bighash);
12054: 	    }
12055: 	}
12056: 	$title=~s/\&colon\;/\:/gs;
12057: 	if ($title) {
12058: # Remember both $symb and $title for dynamic metadata
12059:             $accesshash{$symb.'___crstitle'}=$title;
12060:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
12061: # Cache this title and then return it
12062: 	    return &do_cache_new('title',$key,$title,600);
12063: 	}
12064: 	$urlsymb=$url;
12065:     }
12066:     my $title=&metadata($urlsymb,'title');
12067:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
12068:     return $title;
12069: }
12070: 
12071: sub get_slot {
12072:     my ($which,$cnum,$cdom)=@_;
12073:     if (!$cnum || !$cdom) {
12074: 	(undef,my $courseid)=&whichuser();
12075: 	$cdom=$env{'course.'.$courseid.'.domain'};
12076: 	$cnum=$env{'course.'.$courseid.'.num'};
12077:     }
12078:     my $key=join("\0",'slots',$cdom,$cnum,$which);
12079:     my %slotinfo;
12080:     if (exists($remembered{$key})) {
12081: 	$slotinfo{$which} = $remembered{$key};
12082:     } else {
12083: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
12084: 	&Apache::lonhomework::showhash(%slotinfo);
12085: 	my ($tmp)=keys(%slotinfo);
12086: 	if ($tmp=~/^error:/) { return (); }
12087: 	$remembered{$key} = $slotinfo{$which};
12088:     }
12089:     if (ref($slotinfo{$which}) eq 'HASH') {
12090: 	return %{$slotinfo{$which}};
12091:     }
12092:     return $slotinfo{$which};
12093: }
12094: 
12095: sub get_reservable_slots {
12096:     my ($cnum,$cdom,$uname,$udom) = @_;
12097:     my $now = time;
12098:     my $reservable_info;
12099:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
12100:     if (exists($remembered{$key})) {
12101:         $reservable_info = $remembered{$key};
12102:     } else {
12103:         my %resv;
12104:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
12105:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
12106:         $reservable_info = \%resv;
12107:         $remembered{$key} = $reservable_info;
12108:     }
12109:     return $reservable_info;
12110: }
12111: 
12112: sub get_course_slots {
12113:     my ($cnum,$cdom) = @_;
12114:     my $hashid=$cnum.':'.$cdom;
12115:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
12116:     if (defined($cached)) {
12117:         if (ref($result) eq 'HASH') {
12118:             return %{$result};
12119:         }
12120:     } else {
12121:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
12122:         my ($tmp) = keys(%slots);
12123:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
12124:             &do_cache_new('allslots',$hashid,\%slots,600);
12125:             return %slots;
12126:         }
12127:     }
12128:     return;
12129: }
12130: 
12131: sub devalidate_slots_cache {
12132:     my ($cnum,$cdom)=@_;
12133:     my $hashid=$cnum.':'.$cdom;
12134:     &devalidate_cache_new('allslots',$hashid);
12135: }
12136: 
12137: sub get_coursechange {
12138:     my ($cdom,$cnum) = @_;
12139:     if ($cdom eq '' || $cnum eq '') {
12140:         return unless ($env{'request.course.id'});
12141:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
12142:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
12143:     }
12144:     my $hashid=$cdom.'_'.$cnum;
12145:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
12146:     if ((defined($cached)) && ($change ne '')) {
12147:         return $change;
12148:     } else {
12149:         my %crshash;
12150:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
12151:         if ($crshash{'internal.contentchange'} eq '') {
12152:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
12153:             if ($change eq '') {
12154:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
12155:                 $change = $crshash{'internal.created'};
12156:             }
12157:         } else {
12158:             $change = $crshash{'internal.contentchange'};
12159:         }
12160:         my $cachetime = 600;
12161:         &do_cache_new('crschange',$hashid,$change,$cachetime);
12162:     }
12163:     return $change;
12164: }
12165: 
12166: sub devalidate_coursechange_cache {
12167:     my ($cnum,$cdom)=@_;
12168:     my $hashid=$cnum.':'.$cdom;
12169:     &devalidate_cache_new('crschange',$hashid);
12170: }
12171: 
12172: # ------------------------------------------------- Update symbolic store links
12173: 
12174: sub symblist {
12175:     my ($mapname,%newhash)=@_;
12176:     $mapname=&deversion(&declutter($mapname));
12177:     my %hash;
12178:     if (($env{'request.course.fn'}) && (%newhash)) {
12179:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12180:                       &GDBM_WRCREAT(),0640)) {
12181: 	    foreach my $url (keys(%newhash)) {
12182: 		next if ($url eq 'last_known'
12183: 			 && $env{'form.no_update_last_known'});
12184: 		$hash{declutter($url)}=&encode_symb($mapname,
12185: 						    $newhash{$url}->[1],
12186: 						    $newhash{$url}->[0]);
12187:             }
12188:             if (untie(%hash)) {
12189: 		return 'ok';
12190:             }
12191:         }
12192:     }
12193:     return 'error';
12194: }
12195: 
12196: # --------------------------------------------------------------- Verify a symb
12197: 
12198: sub symbverify {
12199:     my ($symb,$thisurl,$encstate)=@_;
12200:     my $thisfn=$thisurl;
12201:     $thisfn=&declutter($thisfn);
12202: # direct jump to resource in page or to a sequence - will construct own symbs
12203:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
12204: # check URL part
12205:     my ($map,$resid,$url)=&decode_symb($symb);
12206: 
12207:     unless ($url eq $thisfn) { return 0; }
12208: 
12209:     $symb=&symbclean($symb);
12210:     $thisurl=&deversion($thisurl);
12211:     $thisfn=&deversion($thisfn);
12212: 
12213:     my %bighash;
12214:     my $okay=0;
12215: 
12216:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12217:                             &GDBM_READER(),0640)) {
12218:         my $noclutter;
12219:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
12220:             $thisurl =~ s/\?.+$//;
12221:             if ($map =~ m{^uploaded/.+\.page$}) {
12222:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
12223:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
12224:                 $noclutter = 1;
12225:             }
12226:         }
12227:         my $ids;
12228:         if ($noclutter) {
12229:             $ids=$bighash{'ids_'.$thisurl};
12230:         } else {
12231:             $ids=$bighash{'ids_'.&clutter($thisurl)};
12232:         }
12233:         unless ($ids) {
12234:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
12235:             $ids=$bighash{$idkey};
12236:         }
12237:         if ($ids) {
12238: # ------------------------------------------------------------------- Has ID(s)
12239:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
12240:                 $symb =~ s/\?.+$//;
12241:             }
12242: 	    foreach my $id (split(/\,/,$ids)) {
12243: 	       my ($mapid,$resid)=split(/\./,$id);
12244:                if (
12245:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
12246:    eq $symb) {
12247:                    if (ref($encstate)) {
12248:                        $$encstate = $bighash{'encrypted_'.$id};
12249:                    }
12250: 		   if (($env{'request.role.adv'}) ||
12251: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
12252:                        ($thisurl eq '/adm/navmaps')) {
12253: 		       $okay=1;
12254:                        last;
12255: 		   }
12256: 	       }
12257: 	   }
12258:         }
12259: 	untie(%bighash);
12260:     }
12261:     return $okay;
12262: }
12263: 
12264: # --------------------------------------------------------------- Clean-up symb
12265: 
12266: sub symbclean {
12267:     my $symb=shift;
12268:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12269: # remove version from map
12270:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
12271: 
12272: # remove version from URL
12273:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
12274: 
12275: # remove wrapper
12276: 
12277:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
12278:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
12279:     return $symb;
12280: }
12281: 
12282: # ---------------------------------------------- Split symb to find map and url
12283: 
12284: sub encode_symb {
12285:     my ($map,$resid,$url)=@_;
12286:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
12287: }
12288: 
12289: sub decode_symb {
12290:     my $symb=shift;
12291:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12292:     my ($map,$resid,$url)=split(/___/,$symb);
12293:     return (&fixversion($map),$resid,&fixversion($url));
12294: }
12295: 
12296: sub fixversion {
12297:     my $fn=shift;
12298:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
12299:     my %bighash;
12300:     my $uri=&clutter($fn);
12301:     my $key=$env{'request.course.id'}.'_'.$uri;
12302: # is this cached?
12303:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
12304:     if (defined($cached)) { return $result; }
12305: # unfortunately not cached, or expired
12306:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12307: 	    &GDBM_READER(),0640)) {
12308:  	if ($bighash{'version_'.$uri}) {
12309:  	    my $version=$bighash{'version_'.$uri};
12310:  	    unless (($version eq 'mostrecent') || 
12311: 		    ($version==&getversion($uri))) {
12312:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
12313:  	    }
12314:  	}
12315:  	untie %bighash;
12316:     }
12317:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
12318: }
12319: 
12320: sub deversion {
12321:     my $url=shift;
12322:     $url=~s/\.\d+\.(\w+)$/\.$1/;
12323:     return $url;
12324: }
12325: 
12326: # ------------------------------------------------------ Return symb list entry
12327: 
12328: sub symbread {
12329:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
12330:     my $cache_str='request.symbread.cached.'.$thisfn;
12331:     if (defined($env{$cache_str})) {
12332:         if ($ignorecachednull) {
12333:             return $env{$cache_str} unless ($env{$cache_str} eq '');
12334:         } else {
12335:             return $env{$cache_str};
12336:         }
12337:     }
12338: # no filename provided? try from environment
12339:     unless ($thisfn) {
12340:         if ($env{'request.symb'}) {
12341: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
12342: 	}
12343: 	$thisfn=$env{'request.filename'};
12344:     }
12345:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
12346: # is that filename actually a symb? Verify, clean, and return
12347:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
12348: 	if (&symbverify($thisfn,$1)) {
12349: 	    return $env{$cache_str}=&symbclean($thisfn);
12350: 	}
12351:     }
12352:     $thisfn=declutter($thisfn);
12353:     my %hash;
12354:     my %bighash;
12355:     my $syval='';
12356:     if (($env{'request.course.fn'}) && ($thisfn)) {
12357:         my $targetfn = $thisfn;
12358:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
12359:             $targetfn = 'adm/wrapper/'.$thisfn;
12360:         }
12361: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
12362: 	    $targetfn=$1;
12363: 	}
12364:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12365:                       &GDBM_READER(),0640)) {
12366: 	    $syval=$hash{$targetfn};
12367:             untie(%hash);
12368:         }
12369: # ---------------------------------------------------------- There was an entry
12370:         if ($syval) {
12371: 	    #unless ($syval=~/\_\d+$/) {
12372: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
12373: 		    #&appenv({'request.ambiguous' => $thisfn});
12374: 		    #return $env{$cache_str}='';
12375: 		#}    
12376: 		#$syval.=$1;
12377: 	    #}
12378:         } else {
12379: # ------------------------------------------------------- Was not in symb table
12380:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12381:                             &GDBM_READER(),0640)) {
12382: # ---------------------------------------------- Get ID(s) for current resource
12383:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
12384:               unless ($ids) { 
12385:                  $ids=$bighash{'ids_/'.$thisfn};
12386:               }
12387:               unless ($ids) {
12388: # alias?
12389: 		  $ids=$bighash{'mapalias_'.$thisfn};
12390:               }
12391:               if ($ids) {
12392: # ------------------------------------------------------------------- Has ID(s)
12393:                  my @possibilities=split(/\,/,$ids);
12394:                  if ($#possibilities==0) {
12395: # ----------------------------------------------- There is only one possibility
12396: 		     my ($mapid,$resid)=split(/\./,$ids);
12397: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
12398: 						    $resid,$thisfn);
12399:                      if (ref($possibles) eq 'HASH') {
12400:                          $possibles->{$syval} = 1;    
12401:                      }
12402:                      if ($checkforblock) {
12403:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
12404:                          if (@blockers) {
12405:                              $syval = '';
12406:                              return;
12407:                          }
12408:                      }
12409:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
12410: # ------------------------------------------ There is more than one possibility
12411:                      my $realpossible=0;
12412:                      foreach my $id (@possibilities) {
12413: 			 my $file=$bighash{'src_'.$id};
12414:                          my $canaccess;
12415:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
12416:                              $canaccess = 1;
12417:                          } else { 
12418:                              $canaccess = &allowed('bre',$file);
12419:                          }
12420:                          if ($canaccess) {
12421:          		     my ($mapid,$resid)=split(/\./,$id);
12422:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
12423:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
12424: 						             $resid,$thisfn);
12425:                                  if (ref($possibles) eq 'HASH') {
12426:                                      $possibles->{$syval} = 1;
12427:                                  }
12428:                                  if ($checkforblock) {
12429:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
12430:                                      unless (@blockers > 0) {
12431:                                          $syval = $poss_syval;
12432:                                          $realpossible++;
12433:                                      }
12434:                                  } else {
12435:                                      $syval = $poss_syval;
12436:                                      $realpossible++;
12437:                                  }
12438:                              }
12439: 			 }
12440:                      }
12441: 		     if ($realpossible!=1) { $syval=''; }
12442:                  } else {
12443:                      $syval='';
12444:                  }
12445: 	      }
12446:               untie(%bighash);
12447:            }
12448:         }
12449:         if ($syval) {
12450: 	    return $env{$cache_str}=$syval;
12451:         }
12452:     }
12453:     &appenv({'request.ambiguous' => $thisfn});
12454:     return $env{$cache_str}='';
12455: }
12456: 
12457: # ---------------------------------------------------------- Return random seed
12458: 
12459: sub numval {
12460:     my $txt=shift;
12461:     $txt=~tr/A-J/0-9/;
12462:     $txt=~tr/a-j/0-9/;
12463:     $txt=~tr/K-T/0-9/;
12464:     $txt=~tr/k-t/0-9/;
12465:     $txt=~tr/U-Z/0-5/;
12466:     $txt=~tr/u-z/0-5/;
12467:     $txt=~s/\D//g;
12468:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
12469:     return int($txt);
12470: }
12471: 
12472: sub numval2 {
12473:     my $txt=shift;
12474:     $txt=~tr/A-J/0-9/;
12475:     $txt=~tr/a-j/0-9/;
12476:     $txt=~tr/K-T/0-9/;
12477:     $txt=~tr/k-t/0-9/;
12478:     $txt=~tr/U-Z/0-5/;
12479:     $txt=~tr/u-z/0-5/;
12480:     $txt=~s/\D//g;
12481:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12482:     my $total;
12483:     foreach my $val (@txts) { $total+=$val; }
12484:     if ($_64bit) { if ($total > 2**32) { return -1; } }
12485:     return int($total);
12486: }
12487: 
12488: sub numval3 {
12489:     use integer;
12490:     my $txt=shift;
12491:     $txt=~tr/A-J/0-9/;
12492:     $txt=~tr/a-j/0-9/;
12493:     $txt=~tr/K-T/0-9/;
12494:     $txt=~tr/k-t/0-9/;
12495:     $txt=~tr/U-Z/0-5/;
12496:     $txt=~tr/u-z/0-5/;
12497:     $txt=~s/\D//g;
12498:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12499:     my $total;
12500:     foreach my $val (@txts) { $total+=$val; }
12501:     if ($_64bit) { $total=(($total<<32)>>32); }
12502:     return $total;
12503: }
12504: 
12505: sub digest {
12506:     my ($data)=@_;
12507:     my $digest=&Digest::MD5::md5($data);
12508:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
12509:     my ($e,$f);
12510:     {
12511:         use integer;
12512:         $e=($a+$b);
12513:         $f=($c+$d);
12514:         if ($_64bit) {
12515:             $e=(($e<<32)>>32);
12516:             $f=(($f<<32)>>32);
12517:         }
12518:     }
12519:     if (wantarray) {
12520: 	return ($e,$f);
12521:     } else {
12522: 	my $g;
12523: 	{
12524: 	    use integer;
12525: 	    $g=($e+$f);
12526: 	    if ($_64bit) {
12527: 		$g=(($g<<32)>>32);
12528: 	    }
12529: 	}
12530: 	return $g;
12531:     }
12532: }
12533: 
12534: sub latest_rnd_algorithm_id {
12535:     return '64bit5';
12536: }
12537: 
12538: sub get_rand_alg {
12539:     my ($courseid)=@_;
12540:     if (!$courseid) { $courseid=(&whichuser())[1]; }
12541:     if ($courseid) {
12542: 	return $env{"course.$courseid.rndseed"};
12543:     }
12544:     return &latest_rnd_algorithm_id();
12545: }
12546: 
12547: sub validCODE {
12548:     my ($CODE)=@_;
12549:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
12550:     return 0;
12551: }
12552: 
12553: sub getCODE {
12554:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
12555:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
12556: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
12557: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
12558: 	return $Apache::lonhomework::history{'resource.CODE'};
12559:     }
12560:     return undef;
12561: }
12562: #
12563: #  Determines the random seed for a specific context:
12564: #
12565: # parameters:
12566: #   symb      - in course context the symb for the seed.
12567: #   course_id - The course id of the form domain_coursenum.
12568: #   domain    - Domain for the user.
12569: #   course    - Course for the user.
12570: #   cenv      - environment of the course.
12571: #
12572: # NOTE:
12573: #   All parameters are picked out of the environment if missing
12574: #   or not defined.
12575: #   If a symb cannot be determined the current time is used instead.
12576: #
12577: #  For a given well defined symb, courside, domain, username,
12578: #  and course environment, the seed is reproducible.
12579: #
12580: sub rndseed {
12581:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
12582:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
12583:     if (!defined($symb)) {
12584: 	unless ($symb=$wsymb) { return time; }
12585:     }
12586:     if (!defined $courseid) { 
12587: 	$courseid=$wcourseid; 
12588:     }
12589:     if (!defined $domain) { $domain=$wdomain; }
12590:     if (!defined $username) { $username=$wusername }
12591: 
12592:     my $which;
12593:     if (defined($cenv->{'rndseed'})) {
12594: 	$which = $cenv->{'rndseed'};
12595:     } else {
12596: 	$which =&get_rand_alg($courseid);
12597:     }
12598:     if (defined(&getCODE())) {
12599: 
12600: 	if ($which eq '64bit5') {
12601: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
12602: 	} elsif ($which eq '64bit4') {
12603: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
12604: 	} else {
12605: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
12606: 	}
12607:     } elsif ($which eq '64bit5') {
12608: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
12609:     } elsif ($which eq '64bit4') {
12610: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
12611:     } elsif ($which eq '64bit3') {
12612: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
12613:     } elsif ($which eq '64bit2') {
12614: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
12615:     } elsif ($which eq '64bit') {
12616: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
12617:     }
12618:     return &rndseed_32bit($symb,$courseid,$domain,$username);
12619: }
12620: 
12621: sub rndseed_32bit {
12622:     my ($symb,$courseid,$domain,$username)=@_;
12623:     {
12624: 	use integer;
12625: 	my $symbchck=unpack("%32C*",$symb) << 27;
12626: 	my $symbseed=numval($symb) << 22;
12627: 	my $namechck=unpack("%32C*",$username) << 17;
12628: 	my $nameseed=numval($username) << 12;
12629: 	my $domainseed=unpack("%32C*",$domain) << 7;
12630: 	my $courseseed=unpack("%32C*",$courseid);
12631: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
12632: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12633: 	#&logthis("rndseed :$num:$symb");
12634: 	if ($_64bit) { $num=(($num<<32)>>32); }
12635: 	return $num;
12636:     }
12637: }
12638: 
12639: sub rndseed_64bit {
12640:     my ($symb,$courseid,$domain,$username)=@_;
12641:     {
12642: 	use integer;
12643: 	my $symbchck=unpack("%32S*",$symb) << 21;
12644: 	my $symbseed=numval($symb) << 10;
12645: 	my $namechck=unpack("%32S*",$username);
12646: 	
12647: 	my $nameseed=numval($username) << 21;
12648: 	my $domainseed=unpack("%32S*",$domain) << 10;
12649: 	my $courseseed=unpack("%32S*",$courseid);
12650: 	
12651: 	my $num1=$symbchck+$symbseed+$namechck;
12652: 	my $num2=$nameseed+$domainseed+$courseseed;
12653: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12654: 	#&logthis("rndseed :$num:$symb");
12655: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12656: 	return "$num1,$num2";
12657:     }
12658: }
12659: 
12660: sub rndseed_64bit2 {
12661:     my ($symb,$courseid,$domain,$username)=@_;
12662:     {
12663: 	use integer;
12664: 	# strings need to be an even # of cahracters long, it it is odd the
12665:         # last characters gets thrown away
12666: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
12667: 	my $symbseed=numval($symb) << 10;
12668: 	my $namechck=unpack("%32S*",$username.' ');
12669: 	
12670: 	my $nameseed=numval($username) << 21;
12671: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
12672: 	my $courseseed=unpack("%32S*",$courseid.' ');
12673: 	
12674: 	my $num1=$symbchck+$symbseed+$namechck;
12675: 	my $num2=$nameseed+$domainseed+$courseseed;
12676: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12677: 	#&logthis("rndseed :$num:$symb");
12678: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12679: 	return "$num1,$num2";
12680:     }
12681: }
12682: 
12683: sub rndseed_64bit3 {
12684:     my ($symb,$courseid,$domain,$username)=@_;
12685:     {
12686: 	use integer;
12687: 	# strings need to be an even # of cahracters long, it it is odd the
12688:         # last characters gets thrown away
12689: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
12690: 	my $symbseed=numval2($symb) << 10;
12691: 	my $namechck=unpack("%32S*",$username.' ');
12692: 	
12693: 	my $nameseed=numval2($username) << 21;
12694: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
12695: 	my $courseseed=unpack("%32S*",$courseid.' ');
12696: 	
12697: 	my $num1=$symbchck+$symbseed+$namechck;
12698: 	my $num2=$nameseed+$domainseed+$courseseed;
12699: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12700: 	#&logthis("rndseed :$num1:$num2:$_64bit");
12701: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12702: 	
12703: 	return "$num1:$num2";
12704:     }
12705: }
12706: 
12707: sub rndseed_64bit4 {
12708:     my ($symb,$courseid,$domain,$username)=@_;
12709:     {
12710: 	use integer;
12711: 	# strings need to be an even # of cahracters long, it it is odd the
12712:         # last characters gets thrown away
12713: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
12714: 	my $symbseed=numval3($symb) << 10;
12715: 	my $namechck=unpack("%32S*",$username.' ');
12716: 	
12717: 	my $nameseed=numval3($username) << 21;
12718: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
12719: 	my $courseseed=unpack("%32S*",$courseid.' ');
12720: 	
12721: 	my $num1=$symbchck+$symbseed+$namechck;
12722: 	my $num2=$nameseed+$domainseed+$courseseed;
12723: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12724: 	#&logthis("rndseed :$num1:$num2:$_64bit");
12725: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12726: 	
12727: 	return "$num1:$num2";
12728:     }
12729: }
12730: 
12731: sub rndseed_64bit5 {
12732:     my ($symb,$courseid,$domain,$username)=@_;
12733:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
12734:     return "$num1:$num2";
12735: }
12736: 
12737: sub rndseed_CODE_64bit {
12738:     my ($symb,$courseid,$domain,$username)=@_;
12739:     {
12740: 	use integer;
12741: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
12742: 	my $symbseed=numval2($symb);
12743: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12744: 	my $CODEseed=numval(&getCODE());
12745: 	my $courseseed=unpack("%32S*",$courseid.' ');
12746: 	my $num1=$symbseed+$CODEchck;
12747: 	my $num2=$CODEseed+$courseseed+$symbchck;
12748: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12749: 	#&logthis("rndseed :$num1:$num2:$symb");
12750: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
12751: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
12752: 	return "$num1:$num2";
12753:     }
12754: }
12755: 
12756: sub rndseed_CODE_64bit4 {
12757:     my ($symb,$courseid,$domain,$username)=@_;
12758:     {
12759: 	use integer;
12760: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
12761: 	my $symbseed=numval3($symb);
12762: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12763: 	my $CODEseed=numval3(&getCODE());
12764: 	my $courseseed=unpack("%32S*",$courseid.' ');
12765: 	my $num1=$symbseed+$CODEchck;
12766: 	my $num2=$CODEseed+$courseseed+$symbchck;
12767: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12768: 	#&logthis("rndseed :$num1:$num2:$symb");
12769: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
12770: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
12771: 	return "$num1:$num2";
12772:     }
12773: }
12774: 
12775: sub rndseed_CODE_64bit5 {
12776:     my ($symb,$courseid,$domain,$username)=@_;
12777:     my $code = &getCODE();
12778:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
12779:     return "$num1:$num2";
12780: }
12781: 
12782: sub setup_random_from_rndseed {
12783:     my ($rndseed)=@_;
12784:     if ($rndseed =~/([,:])/) {
12785:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
12786:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
12787:             &Math::Random::random_set_seed_from_phrase($rndseed);
12788:         } else {
12789:             &Math::Random::random_set_seed($num1,$num2);
12790:         }
12791:     } else {
12792: 	&Math::Random::random_set_seed_from_phrase($rndseed);
12793:     }
12794: }
12795: 
12796: sub latest_receipt_algorithm_id {
12797:     return 'receipt3';
12798: }
12799: 
12800: sub recunique {
12801:     my $fucourseid=shift;
12802:     my $unique;
12803:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
12804: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
12805: 	$unique=$env{"course.$fucourseid.internal.encseed"};
12806:     } else {
12807: 	$unique=$perlvar{'lonReceipt'};
12808:     }
12809:     return unpack("%32C*",$unique);
12810: }
12811: 
12812: sub recprefix {
12813:     my $fucourseid=shift;
12814:     my $prefix;
12815:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
12816: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
12817: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
12818:     } else {
12819: 	$prefix=$perlvar{'lonHostID'};
12820:     }
12821:     return unpack("%32C*",$prefix);
12822: }
12823: 
12824: sub ireceipt {
12825:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
12826: 
12827:     my $return =&recprefix($fucourseid).'-';
12828: 
12829:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
12830: 	$env{'request.state'} eq 'construct') {
12831: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
12832: 	return $return;
12833:     }
12834: 
12835:     my $cuname=unpack("%32C*",$funame);
12836:     my $cudom=unpack("%32C*",$fudom);
12837:     my $cucourseid=unpack("%32C*",$fucourseid);
12838:     my $cusymb=unpack("%32C*",$fusymb);
12839:     my $cunique=&recunique($fucourseid);
12840:     my $cpart=unpack("%32S*",$part);
12841:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
12842: 
12843: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
12844: 			       
12845: 	$return.= ($cunique%$cuname+
12846: 		   $cunique%$cudom+
12847: 		   $cusymb%$cuname+
12848: 		   $cusymb%$cudom+
12849: 		   $cucourseid%$cuname+
12850: 		   $cucourseid%$cudom+
12851: 		   $cpart%$cuname+
12852: 		   $cpart%$cudom);
12853:     } else {
12854: 	$return.= ($cunique%$cuname+
12855: 		   $cunique%$cudom+
12856: 		   $cusymb%$cuname+
12857: 		   $cusymb%$cudom+
12858: 		   $cucourseid%$cuname+
12859: 		   $cucourseid%$cudom);
12860:     }
12861:     return $return;
12862: }
12863: 
12864: sub receipt {
12865:     my ($part)=@_;
12866:     my ($symb,$courseid,$domain,$name) = &whichuser();
12867:     return &ireceipt($name,$domain,$courseid,$symb,$part);
12868: }
12869: 
12870: sub whichuser {
12871:     my ($passedsymb)=@_;
12872:     my ($symb,$courseid,$domain,$name,$publicuser);
12873:     if (defined($env{'form.grade_symb'})) {
12874: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
12875: 	my $allowed=&allowed('vgr',$tmp_courseid);
12876: 	if (!$allowed &&
12877: 	    exists($env{'request.course.sec'}) &&
12878: 	    $env{'request.course.sec'} !~ /^\s*$/) {
12879: 	    $allowed=&allowed('vgr',$tmp_courseid.
12880: 			      '/'.$env{'request.course.sec'});
12881: 	}
12882: 	if ($allowed) {
12883: 	    ($symb)=&get_env_multiple('form.grade_symb');
12884: 	    $courseid=$tmp_courseid;
12885: 	    ($domain)=&get_env_multiple('form.grade_domain');
12886: 	    ($name)=&get_env_multiple('form.grade_username');
12887: 	    return ($symb,$courseid,$domain,$name,$publicuser);
12888: 	}
12889:     }
12890:     if (!$passedsymb) {
12891: 	$symb=&symbread();
12892:     } else {
12893: 	$symb=$passedsymb;
12894:     }
12895:     $courseid=$env{'request.course.id'};
12896:     $domain=$env{'user.domain'};
12897:     $name=$env{'user.name'};
12898:     if ($name eq 'public' && $domain eq 'public') {
12899: 	if (!defined($env{'form.username'})) {
12900: 	    $env{'form.username'}.=time.rand(10000000);
12901: 	}
12902: 	$name.=$env{'form.username'};
12903:     }
12904:     return ($symb,$courseid,$domain,$name,$publicuser);
12905: 
12906: }
12907: 
12908: # ------------------------------------------------------------ Serves up a file
12909: # returns either the contents of the file or 
12910: # -1 if the file doesn't exist
12911: #
12912: # if the target is a file that was uploaded via DOCS, 
12913: # a check will be made to see if a current copy exists on the local server,
12914: # if it does this will be served, otherwise a copy will be retrieved from
12915: # the home server for the course and stored in /home/httpd/html/userfiles on
12916: # the local server.   
12917: 
12918: sub getfile {
12919:     my ($file) = @_;
12920:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
12921:     &repcopy($file);
12922:     return &readfile($file);
12923: }
12924: 
12925: sub repcopy_userfile {
12926:     my ($file)=@_;
12927:     my $londocroot = $perlvar{'lonDocRoot'};
12928:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
12929:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
12930:     my ($cdom,$cnum,$filename) = 
12931: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
12932:     my $uri="/uploaded/$cdom/$cnum/$filename";
12933:     if (-e "$file") {
12934: # we already have a local copy, check it out
12935: 	my @fileinfo = stat($file);
12936: 	my $rtncode;
12937: 	my $info;
12938: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
12939: 	if ($lwpresp ne 'ok') {
12940: # there is no such file anymore, even though we had a local copy
12941: 	    if ($rtncode eq '404') {
12942: 		unlink($file);
12943: 	    }
12944: 	    return -1;
12945: 	}
12946: 	if ($info < $fileinfo[9]) {
12947: # nice, the file we have is up-to-date, just say okay
12948: 	    return 'ok';
12949: 	} else {
12950: # the file is outdated, get rid of it
12951: 	    unlink($file);
12952: 	}
12953:     }
12954: # one way or the other, at this point, we don't have the file
12955: # construct the correct path for the file
12956:     my @parts = ($cdom,$cnum); 
12957:     if ($filename =~ m|^(.+)/[^/]+$|) {
12958: 	push @parts, split(/\//,$1);
12959:     }
12960:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
12961:     foreach my $part (@parts) {
12962: 	$path .= '/'.$part;
12963: 	if (!-e $path) {
12964: 	    mkdir($path,0770);
12965: 	}
12966:     }
12967: # now the path exists for sure
12968: # get a user agent
12969:     my $transferfile=$file.'.in.transfer';
12970: # FIXME: this should flock
12971:     if (-e $transferfile) { return 'ok'; }
12972:     my $request;
12973:     $uri=~s/^\///;
12974:     my $homeserver = &homeserver($cnum,$cdom);
12975:     my $protocol = $protocol{$homeserver};
12976:     $protocol = 'http' if ($protocol ne 'https');
12977:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
12978:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
12979: # did it work?
12980:     if ($response->is_error()) {
12981: 	unlink($transferfile);
12982: 	&logthis("Userfile repcopy failed for $uri");
12983: 	return -1;
12984:     }
12985: # worked, rename the transfer file
12986:     rename($transferfile,$file);
12987:     return 'ok';
12988: }
12989: 
12990: sub tokenwrapper {
12991:     my $uri=shift;
12992:     $uri=~s|^https?\://([^/]+)||;
12993:     $uri=~s|^/||;
12994:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
12995:     my $token=$1;
12996:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
12997:     if ($udom && $uname && $file) {
12998: 	$file=~s|(\?\.*)*$||;
12999:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
13000:         my $homeserver = &homeserver($uname,$udom);
13001:         my $protocol = $protocol{$homeserver};
13002:         $protocol = 'http' if ($protocol ne 'https');
13003:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
13004:                (($uri=~/\?/)?'&':'?').'token='.$token.
13005:                                '&tokenissued='.$perlvar{'lonHostID'};
13006:     } else {
13007:         return '/adm/notfound.html';
13008:     }
13009: }
13010: 
13011: # call with reqtype HEAD: get last modification time
13012: # call with reqtype GET: get the file contents
13013: # Do not call this with reqtype GET for large files! It loads everything into memory
13014: #
13015: sub getuploaded {
13016:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
13017:     $uri=~s/^\///;
13018:     my $homeserver = &homeserver($cnum,$cdom);
13019:     my $protocol = $protocol{$homeserver};
13020:     $protocol = 'http' if ($protocol ne 'https');
13021:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
13022:     my $request=new HTTP::Request($reqtype,$uri);
13023:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
13024:     $$rtncode = $response->code;
13025:     if (! $response->is_success()) {
13026: 	return 'failed';
13027:     }      
13028:     if ($reqtype eq 'HEAD') {
13029: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
13030:     } elsif ($reqtype eq 'GET') {
13031: 	$$info = $response->content;
13032:     }
13033:     return 'ok';
13034: }
13035: 
13036: sub readfile {
13037:     my $file = shift;
13038:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
13039:     my $fh;
13040:     open($fh,"<",$file);
13041:     my $a='';
13042:     while (my $line = <$fh>) { $a .= $line; }
13043:     return $a;
13044: }
13045: 
13046: sub filelocation {
13047:     my ($dir,$file) = @_;
13048:     my $location;
13049:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
13050: 
13051:     if ($file =~ m-^/adm/-) {
13052: 	$file=~s-^/adm/wrapper/-/-;
13053: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
13054:     }
13055: 
13056:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
13057:         $location = $file;
13058:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
13059:         my ($udom,$uname,$filename)=
13060:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
13061:         my $home=&homeserver($uname,$udom);
13062:         my $is_me=0;
13063:         my @ids=&current_machine_ids();
13064:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
13065:         if ($is_me) {
13066:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
13067:         } else {
13068:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
13069:   	      $udom.'/'.$uname.'/'.$filename;
13070:         }
13071:     } elsif ($file =~ m-^/adm/-) {
13072: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
13073:     } else {
13074:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
13075:         $file=~s:^/(res|priv)/:/:;
13076:         my $space=$1;
13077:         if ( !( $file =~ m:^/:) ) {
13078:             $location = $dir. '/'.$file;
13079:         } else {
13080:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
13081:         }
13082:     }
13083:     $location=~s://+:/:g; # remove duplicate /
13084:     while ($location=~m{/\.\./}) {
13085: 	if ($location =~ m{/[^/]+/\.\./}) {
13086: 	    $location=~ s{/[^/]+/\.\./}{/}g;
13087: 	} else {
13088: 	    $location=~ s{/\.\./}{/}g;
13089: 	}
13090:     } #remove dir/..
13091:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
13092:     return $location;
13093: }
13094: 
13095: sub hreflocation {
13096:     my ($dir,$file)=@_;
13097:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
13098: 	$file=filelocation($dir,$file);
13099:     } elsif ($file=~m-^/adm/-) {
13100: 	$file=~s-^/adm/wrapper/-/-;
13101: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
13102:     }
13103:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
13104: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
13105:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
13106: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
13107: 	        {/uploaded/$1/$2/}x;
13108:     }
13109:     if ($file=~ m{^/userfiles/}) {
13110: 	$file =~ s{^/userfiles/}{/uploaded/};
13111:     }
13112:     return $file;
13113: }
13114: 
13115: 
13116: 
13117: 
13118: 
13119: sub current_machine_domains {
13120:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
13121: }
13122: 
13123: sub machine_domains {
13124:     my ($hostname) = @_;
13125:     my @domains;
13126:     my %hostname = &all_hostnames();
13127:     while( my($id, $name) = each(%hostname)) {
13128: #	&logthis("-$id-$name-$hostname-");
13129: 	if ($hostname eq $name) {
13130: 	    push(@domains,&host_domain($id));
13131: 	}
13132:     }
13133:     return @domains;
13134: }
13135: 
13136: sub current_machine_ids {
13137:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
13138: }
13139: 
13140: sub machine_ids {
13141:     my ($hostname) = @_;
13142:     $hostname ||= &hostname($perlvar{'lonHostID'});
13143:     my @ids;
13144:     my %name_to_host = &all_names();
13145:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
13146: 	return @{ $name_to_host{$hostname} };
13147:     }
13148:     return;
13149: }
13150: 
13151: sub additional_machine_domains {
13152:     my @domains;
13153:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
13154:     while( my $line = <$fh>) {
13155:         $line =~ s/\s//g;
13156:         push(@domains,$line);
13157:     }
13158:     return @domains;
13159: }
13160: 
13161: sub default_login_domain {
13162:     my $domain = $perlvar{'lonDefDomain'};
13163:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
13164:     foreach my $posdom (&current_machine_domains(),
13165:                         &additional_machine_domains()) {
13166:         if (lc($posdom) eq lc($testdomain)) {
13167:             $domain=$posdom;
13168:             last;
13169:         }
13170:     }
13171:     return $domain;
13172: }
13173: 
13174: # ------------------------------------------------------------- Declutters URLs
13175: 
13176: sub declutter {
13177:     my $thisfn=shift;
13178:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
13179:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
13180:         $thisfn=~s{^/home/httpd/html}{};
13181:     }
13182:     $thisfn=~s/^\///;
13183:     $thisfn=~s|^adm/wrapper/||;
13184:     $thisfn=~s|^adm/coursedocs/showdoc/||;
13185:     $thisfn=~s/^res\///;
13186:     $thisfn=~s/^priv\///;
13187:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
13188:         $thisfn=~s/\?.+$//;
13189:     }
13190:     return $thisfn;
13191: }
13192: 
13193: # ------------------------------------------------------------- Clutter up URLs
13194: 
13195: sub clutter {
13196:     my $thisfn='/'.&declutter(shift);
13197:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
13198: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
13199:        $thisfn='/res'.$thisfn; 
13200:     }
13201:     if ($thisfn !~m|^/adm|) {
13202: 	if ($thisfn =~ m|^/ext/|) {
13203: 	    $thisfn='/adm/wrapper'.$thisfn;
13204: 	} else {
13205: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
13206: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
13207: 	    if ($embstyle eq 'ssi'
13208: 		|| ($embstyle eq 'hdn')
13209: 		|| ($embstyle eq 'rat')
13210: 		|| ($embstyle eq 'prv')
13211: 		|| ($embstyle eq 'ign')) {
13212: 		#do nothing with these
13213: 	    } elsif (($embstyle eq 'img') 
13214: 		|| ($embstyle eq 'emb')
13215: 		|| ($embstyle eq 'wrp')) {
13216: 		$thisfn='/adm/wrapper'.$thisfn;
13217: 	    } elsif ($embstyle eq 'unk'
13218: 		     && $thisfn!~/\.(sequence|page)$/) {
13219: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
13220: 	    } else {
13221: #		&logthis("Got a blank emb style");
13222: 	    }
13223: 	}
13224:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
13225:         $thisfn='/adm/wrapper'.$thisfn;
13226:     }
13227:     return $thisfn;
13228: }
13229: 
13230: sub clutter_with_no_wrapper {
13231:     my $uri = &clutter(shift);
13232:     if ($uri =~ m-^/adm/-) {
13233: 	$uri =~ s-^/adm/wrapper/-/-;
13234: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
13235:     }
13236:     return $uri;
13237: }
13238: 
13239: sub freeze_escape {
13240:     my ($value)=@_;
13241:     if (ref($value)) {
13242: 	$value=&nfreeze($value);
13243: 	return '__FROZEN__'.&escape($value);
13244:     }
13245:     return &escape($value);
13246: }
13247: 
13248: 
13249: sub thaw_unescape {
13250:     my ($value)=@_;
13251:     if ($value =~ /^__FROZEN__/) {
13252: 	substr($value,0,10,undef);
13253: 	$value=&unescape($value);
13254: 	return &thaw($value);
13255:     }
13256:     return &unescape($value);
13257: }
13258: 
13259: sub correct_line_ends {
13260:     my ($result)=@_;
13261:     $$result =~s/\r\n/\n/mg;
13262:     $$result =~s/\r/\n/mg;
13263: }
13264: # ================================================================ Main Program
13265: 
13266: sub goodbye {
13267:    &logthis("Starting Shut down");
13268: #not converted to using infrastruture and probably shouldn't be
13269:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
13270: #converted
13271: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
13272:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
13273: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
13274: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
13275: #1.1 only
13276: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
13277: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
13278: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
13279: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
13280:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
13281:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
13282:    &logthis(sprintf("%-20s is %s",'hits',$hits));
13283:    &flushcourselogs();
13284:    &logthis("Shutting down");
13285: }
13286: 
13287: sub get_dns {
13288:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
13289:     if (!$ignore_cache) {
13290: 	my ($content,$cached)=
13291: 	    &Apache::lonnet::is_cached_new('dns',$url);
13292: 	if ($cached) {
13293: 	    &$func($content,$hashref);
13294: 	    return;
13295: 	}
13296:     }
13297: 
13298:     my %alldns;
13299:     open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
13300:     foreach my $dns (<$config>) {
13301: 	next if ($dns !~ /^\^(\S*)/x);
13302:         my $line = $1;
13303:         my ($host,$protocol) = split(/:/,$line);
13304:         if ($protocol ne 'https') {
13305:             $protocol = 'http';
13306:         }
13307: 	$alldns{$host} = $protocol;
13308:     }
13309:     while (%alldns) {
13310: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
13311: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
13312:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
13313:         delete($alldns{$dns});
13314: 	next if ($response->is_error());
13315: 	my @content = split("\n",$response->content);
13316: 	unless ($nocache) {
13317: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
13318: 	}
13319: 	&$func(\@content,$hashref);
13320: 	return;
13321:     }
13322:     close($config);
13323:     my $which = (split('/',$url))[3];
13324:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
13325:     open($config,"<","$perlvar{'lonTabDir'}/dns_$which.tab");
13326:     my @content = <$config>;
13327:     &$func(\@content,$hashref);
13328:     return;
13329: }
13330: 
13331: # ------------------------------------------------------Get DNS checksums file
13332: sub parse_dns_checksums_tab {
13333:     my ($lines,$hashref) = @_;
13334:     my $lonhost = $perlvar{'lonHostID'};
13335:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
13336:     my $loncaparev = &get_server_loncaparev($machine_dom);
13337:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
13338:     my $webconfdir = '/etc/httpd/conf';
13339:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
13340:         $webconfdir = '/etc/apache2';
13341:     } elsif ($distro =~ /^sles(\d+)$/) {
13342:         if ($1 >= 10) {
13343:             $webconfdir = '/etc/apache2';
13344:         }
13345:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
13346:         if ($1 >= 10.0) {
13347:             $webconfdir = '/etc/apache2';
13348:         }
13349:     }
13350:     my ($release,$timestamp) = split(/\-/,$loncaparev);
13351:     my (%chksum,%revnum);
13352:     if (ref($lines) eq 'ARRAY') {
13353:         chomp(@{$lines});
13354:         my $version = shift(@{$lines});
13355:         if ($version eq $release) {  
13356:             foreach my $line (@{$lines}) {
13357:                 my ($file,$version,$shasum) = split(/,/,$line);
13358:                 if ($file =~ m{^/etc/httpd/conf}) {
13359:                     if ($webconfdir eq '/etc/apache2') {
13360:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
13361:                     }
13362:                 }
13363:                 $chksum{$file} = $shasum;
13364:                 $revnum{$file} = $version;
13365:             }
13366:             if (ref($hashref) eq 'HASH') {
13367:                 %{$hashref} = (
13368:                                 sums     => \%chksum,
13369:                                 versions => \%revnum,
13370:                               );
13371:             }
13372:         }
13373:     }
13374:     return;
13375: }
13376: 
13377: sub fetch_dns_checksums {
13378:     my %checksums;
13379:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
13380:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
13381:     my ($release,$timestamp) = split(/\-/,$loncaparev);
13382:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
13383:              \%checksums);
13384:     return \%checksums;
13385: }
13386: 
13387: # ------------------------------------------------------------ Read domain file
13388: {
13389:     my $loaded;
13390:     my %domain;
13391: 
13392:     sub parse_domain_tab {
13393: 	my ($lines) = @_;
13394: 	foreach my $line (@$lines) {
13395: 	    next if ($line =~ /^(\#|\s*$ )/x);
13396: 
13397: 	    chomp($line);
13398: 	    my ($name,@elements) = split(/:/,$line,9);
13399: 	    my %this_domain;
13400: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
13401: 			       'lang_def', 'city', 'longi', 'lati',
13402: 			       'primary') {
13403: 		$this_domain{$field} = shift(@elements);
13404: 	    }
13405: 	    $domain{$name} = \%this_domain;
13406: 	}
13407:     }
13408: 
13409:     sub reset_domain_info {
13410: 	undef($loaded);
13411: 	undef(%domain);
13412:     }
13413: 
13414:     sub load_domain_tab {
13415: 	my ($ignore_cache,$nocache) = @_;
13416: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
13417: 	my $fh;
13418: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
13419: 	    my @lines = <$fh>;
13420: 	    &parse_domain_tab(\@lines);
13421: 	}
13422: 	close($fh);
13423: 	$loaded = 1;
13424:     }
13425: 
13426:     sub domain {
13427: 	&load_domain_tab() if (!$loaded);
13428: 
13429: 	my ($name,$what) = @_;
13430: 	return if ( !exists($domain{$name}) );
13431: 
13432: 	if (!$what) {
13433: 	    return $domain{$name}{'description'};
13434: 	}
13435: 	return $domain{$name}{$what};
13436:     }
13437: 
13438:     sub domain_info {
13439:         &load_domain_tab() if (!$loaded);
13440:         return %domain;
13441:     }
13442: 
13443: }
13444: 
13445: 
13446: # ------------------------------------------------------------- Read hosts file
13447: {
13448:     my %hostname;
13449:     my %hostdom;
13450:     my %libserv;
13451:     my $loaded;
13452:     my %name_to_host;
13453:     my %internetdom;
13454:     my %LC_dns_serv;
13455: 
13456:     sub parse_hosts_tab {
13457: 	my ($file) = @_;
13458: 	foreach my $configline (@$file) {
13459: 	    next if ($configline =~ /^(\#|\s*$ )/x);
13460:             chomp($configline);
13461: 	    if ($configline =~ /^\^/) {
13462:                 if ($configline =~ /^\^([\w.\-]+)/) {
13463:                     $LC_dns_serv{$1} = 1;
13464:                 }
13465:                 next;
13466:             }
13467: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
13468: 	    $name=~s/\s//g;
13469: 	    if ($id && $domain && $role && $name) {
13470:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
13471:                     my $curr = $hostname{$id};
13472:                     my $skip;
13473:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
13474:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
13475:                             $skip = 1;
13476:                         } else {
13477:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
13478:                         }
13479:                     }
13480:                     unless ($skip) {
13481:                         push(@{$name_to_host{$name}},$id);
13482:                     }
13483:                 } else {
13484:                     push(@{$name_to_host{$name}},$id);
13485:                 }
13486: 		$hostname{$id}=$name;
13487: 		$hostdom{$id}=$domain;
13488: 		if ($role eq 'library') { $libserv{$id}=$name; }
13489:                 if (defined($protocol)) {
13490:                     if ($protocol eq 'https') {
13491:                         $protocol{$id} = $protocol;
13492:                     } else {
13493:                         $protocol{$id} = 'http'; 
13494:                     }
13495:                 } else {
13496:                     $protocol{$id} = 'http';
13497:                 }
13498:                 if (defined($intdom)) {
13499:                     $internetdom{$id} = $intdom;
13500:                 }
13501: 	    }
13502: 	}
13503:     }
13504:     
13505:     sub reset_hosts_info {
13506: 	&purge_remembered();
13507: 	&reset_domain_info();
13508: 	&reset_hosts_ip_info();
13509:         undef(%internetdom);
13510: 	undef(%name_to_host);
13511: 	undef(%hostname);
13512: 	undef(%hostdom);
13513: 	undef(%libserv);
13514: 	undef($loaded);
13515:     }
13516: 
13517:     sub load_hosts_tab {
13518: 	my ($ignore_cache,$nocache) = @_;
13519: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
13520: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
13521: 	my @config = <$config>;
13522: 	&parse_hosts_tab(\@config);
13523: 	close($config);
13524: 	$loaded=1;
13525:     }
13526: 
13527:     sub hostname {
13528: 	&load_hosts_tab() if (!$loaded);
13529: 
13530: 	my ($lonid) = @_;
13531: 	return $hostname{$lonid};
13532:     }
13533: 
13534:     sub all_hostnames {
13535: 	&load_hosts_tab() if (!$loaded);
13536: 
13537: 	return %hostname;
13538:     }
13539: 
13540:     sub all_names {
13541:         my ($ignore_cache,$nocache) = @_;
13542: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
13543: 
13544: 	return %name_to_host;
13545:     }
13546: 
13547:     sub all_host_domain {
13548:         &load_hosts_tab() if (!$loaded);
13549:         return %hostdom;
13550:     }
13551: 
13552:     sub all_host_intdom {
13553:         &load_hosts_tab() if (!$loaded);
13554:         return %internetdom;
13555:     }
13556: 
13557:     sub is_library {
13558: 	&load_hosts_tab() if (!$loaded);
13559: 
13560: 	return exists($libserv{$_[0]});
13561:     }
13562: 
13563:     sub all_library {
13564: 	&load_hosts_tab() if (!$loaded);
13565: 
13566: 	return %libserv;
13567:     }
13568: 
13569:     sub unique_library {
13570: 	#2x reverse removes all hostnames that appear more than once
13571:         my %unique = reverse &all_library();
13572:         return reverse %unique;
13573:     }
13574: 
13575:     sub get_servers {
13576: 	&load_hosts_tab() if (!$loaded);
13577: 
13578: 	my ($domain,$type) = @_;
13579: 	my %possible_hosts = ($type eq 'library') ? %libserv
13580: 	                                          : %hostname;
13581: 	my %result;
13582: 	if (ref($domain) eq 'ARRAY') {
13583: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
13584: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
13585: 		    $result{$host} = $hostname;
13586: 		}
13587: 	    }
13588: 	} else {
13589: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
13590: 		if ($hostdom{$host} eq $domain) {
13591: 		    $result{$host} = $hostname;
13592: 		}
13593: 	    }
13594: 	}
13595: 	return %result;
13596:     }
13597: 
13598:     sub get_unique_servers {
13599:         my %unique = reverse &get_servers(@_);
13600: 	return reverse %unique;
13601:     }
13602: 
13603:     sub host_domain {
13604: 	&load_hosts_tab() if (!$loaded);
13605: 
13606: 	my ($lonid) = @_;
13607: 	return $hostdom{$lonid};
13608:     }
13609: 
13610:     sub all_domains {
13611: 	&load_hosts_tab() if (!$loaded);
13612: 
13613: 	my %seen;
13614: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
13615: 	return @uniq;
13616:     }
13617: 
13618:     sub internet_dom {
13619:         &load_hosts_tab() if (!$loaded);
13620: 
13621:         my ($lonid) = @_;
13622:         return $internetdom{$lonid};
13623:     }
13624: 
13625:     sub is_LC_dns {
13626:         &load_hosts_tab() if (!$loaded);
13627: 
13628:         my ($hostname) = @_;
13629:         return exists($LC_dns_serv{$hostname});
13630:     }
13631: 
13632: }
13633: 
13634: { 
13635:     my %iphost;
13636:     my %name_to_ip;
13637:     my %lonid_to_ip;
13638: 
13639:     sub get_hosts_from_ip {
13640: 	my ($ip) = @_;
13641: 	my %iphosts = &get_iphost();
13642: 	if (ref($iphosts{$ip})) {
13643: 	    return @{$iphosts{$ip}};
13644: 	}
13645: 	return;
13646:     }
13647:     
13648:     sub reset_hosts_ip_info {
13649: 	undef(%iphost);
13650: 	undef(%name_to_ip);
13651: 	undef(%lonid_to_ip);
13652:     }
13653: 
13654:     sub get_host_ip {
13655: 	my ($lonid) = @_;
13656: 	if (exists($lonid_to_ip{$lonid})) {
13657: 	    return $lonid_to_ip{$lonid};
13658: 	}
13659: 	my $name=&hostname($lonid);
13660:    	my $ip = gethostbyname($name);
13661: 	return if (!$ip || length($ip) ne 4);
13662: 	$ip=inet_ntoa($ip);
13663: 	$name_to_ip{$name}   = $ip;
13664: 	$lonid_to_ip{$lonid} = $ip;
13665: 	return $ip;
13666:     }
13667:     
13668:     sub get_iphost {
13669: 	my ($ignore_cache,$nocache) = @_;
13670: 
13671: 	if (!$ignore_cache) {
13672: 	    if (%iphost) {
13673: 		return %iphost;
13674: 	    }
13675: 	    my ($ip_info,$cached)=
13676: 		&Apache::lonnet::is_cached_new('iphost','iphost');
13677: 	    if ($cached) {
13678: 		%iphost      = %{$ip_info->[0]};
13679: 		%name_to_ip  = %{$ip_info->[1]};
13680: 		%lonid_to_ip = %{$ip_info->[2]};
13681: 		return %iphost;
13682: 	    }
13683: 	}
13684: 
13685: 	# get yesterday's info for fallback
13686: 	my %old_name_to_ip;
13687: 	my ($ip_info,$cached)=
13688: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
13689: 	if ($cached) {
13690: 	    %old_name_to_ip = %{$ip_info->[1]};
13691: 	}
13692: 
13693: 	my %name_to_host = &all_names($ignore_cache,$nocache);
13694: 	foreach my $name (keys(%name_to_host)) {
13695: 	    my $ip;
13696: 	    if (!exists($name_to_ip{$name})) {
13697: 		$ip = gethostbyname($name);
13698: 		if (!$ip || length($ip) ne 4) {
13699: 		    if (defined($old_name_to_ip{$name})) {
13700: 			$ip = $old_name_to_ip{$name};
13701: 			&logthis("Can't find $name defaulting to old $ip");
13702: 		    } else {
13703: 			&logthis("Name $name no IP found");
13704: 			next;
13705: 		    }
13706: 		} else {
13707: 		    $ip=inet_ntoa($ip);
13708: 		}
13709: 		$name_to_ip{$name} = $ip;
13710: 	    } else {
13711: 		$ip = $name_to_ip{$name};
13712: 	    }
13713: 	    foreach my $id (@{ $name_to_host{$name} }) {
13714: 		$lonid_to_ip{$id} = $ip;
13715: 	    }
13716: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
13717: 	}
13718:         unless ($nocache) {
13719: 	    &do_cache_new('iphost','iphost',
13720: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
13721: 		          48*60*60);
13722:         }
13723: 
13724: 	return %iphost;
13725:     }
13726: 
13727:     #
13728:     #  Given a DNS returns the loncapa host name for that DNS 
13729:     # 
13730:     sub host_from_dns {
13731:         my ($dns) = @_;
13732:         my @hosts;
13733:         my $ip;
13734: 
13735:         if (exists($name_to_ip{$dns})) {
13736:             $ip = $name_to_ip{$dns};
13737:         }
13738:         if (!$ip) {
13739:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
13740:             if (length($ip) == 4) { 
13741: 	        $ip   = &IO::Socket::inet_ntoa($ip);
13742:             }
13743:         }
13744:         if ($ip) {
13745: 	    @hosts = get_hosts_from_ip($ip);
13746: 	    return $hosts[0];
13747:         }
13748:         return undef;
13749:     }
13750: 
13751:     sub get_internet_names {
13752:         my ($lonid) = @_;
13753:         return if ($lonid eq '');
13754:         my ($idnref,$cached)=
13755:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
13756:         if ($cached) {
13757:             return $idnref;
13758:         }
13759:         my $ip = &get_host_ip($lonid);
13760:         my @hosts = &get_hosts_from_ip($ip);
13761:         my %iphost = &get_iphost();
13762:         my (@idns,%seen);
13763:         foreach my $id (@hosts) {
13764:             my $dom = &host_domain($id);
13765:             my $prim_id = &domain($dom,'primary');
13766:             my $prim_ip = &get_host_ip($prim_id);
13767:             next if ($seen{$prim_ip});
13768:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
13769:                 foreach my $id (@{$iphost{$prim_ip}}) {
13770:                     my $intdom = &internet_dom($id);
13771:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
13772:                         push(@idns,$intdom);
13773:                     }
13774:                 }
13775:             }
13776:             $seen{$prim_ip} = 1;
13777:         }
13778:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
13779:     }
13780: 
13781: }
13782: 
13783: sub all_loncaparevs {
13784:     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);
13785: }
13786: 
13787: # ---------------------------------------------------------- Read loncaparev table
13788: {
13789:     sub load_loncaparevs { 
13790:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
13791:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
13792:                 while (my $configline=<$config>) {
13793:                     chomp($configline);
13794:                     my ($hostid,$loncaparev)=split(/:/,$configline);
13795:                     $loncaparevs{$hostid}=$loncaparev;
13796:                 }
13797:                 close($config);
13798:             }
13799:         }
13800:     }
13801: }
13802: 
13803: # ---------------------------------------------------------- Read serverhostID table
13804: {
13805:     sub load_serverhomeIDs {
13806:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
13807:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
13808:                 while (my $configline=<$config>) {
13809:                     chomp($configline);
13810:                     my ($name,$id)=split(/:/,$configline);
13811:                     $serverhomeIDs{$name}=$id;
13812:                 }
13813:                 close($config);
13814:             }
13815:         }
13816:     }
13817: }
13818: 
13819: 
13820: BEGIN {
13821: 
13822: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
13823:     unless ($readit) {
13824: {
13825:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
13826:     %perlvar = (%perlvar,%{$configvars});
13827: }
13828: 
13829: 
13830: # ------------------------------------------------------ Read spare server file
13831: {
13832:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
13833: 
13834:     while (my $configline=<$config>) {
13835:        chomp($configline);
13836:        if ($configline) {
13837: 	   my ($host,$type) = split(':',$configline,2);
13838: 	   if (!defined($type) || $type eq '') { $type = 'default' };
13839: 	   push(@{ $spareid{$type} }, $host);
13840:        }
13841:     }
13842:     close($config);
13843: }
13844: # ------------------------------------------------------------ Read permissions
13845: {
13846:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
13847: 
13848:     while (my $configline=<$config>) {
13849: 	chomp($configline);
13850: 	if ($configline) {
13851: 	    my ($role,$perm)=split(/ /,$configline);
13852: 	    if ($perm ne '') { $pr{$role}=$perm; }
13853: 	}
13854:     }
13855:     close($config);
13856: }
13857: 
13858: # -------------------------------------------- Read plain texts for permissions
13859: {
13860:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
13861: 
13862:     while (my $configline=<$config>) {
13863: 	chomp($configline);
13864: 	if ($configline) {
13865: 	    my ($short,@plain)=split(/:/,$configline);
13866:             %{$prp{$short}} = ();
13867: 	    if (@plain > 0) {
13868:                 $prp{$short}{'std'} = $plain[0];
13869:                 for (my $i=1; $i<@plain; $i++) {
13870:                     $prp{$short}{'alt'.$i} = $plain[$i];  
13871:                 }
13872:             }
13873: 	}
13874:     }
13875:     close($config);
13876: }
13877: 
13878: # ---------------------------------------------------------- Read package table
13879: {
13880:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
13881: 
13882:     while (my $configline=<$config>) {
13883: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
13884: 	chomp($configline);
13885: 	my ($short,$plain)=split(/:/,$configline);
13886: 	my ($pack,$name)=split(/\&/,$short);
13887: 	if ($plain ne '') {
13888: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
13889: 	    $packagetab{$short}=$plain; 
13890: 	}
13891:     }
13892:     close($config);
13893: }
13894: 
13895: # ---------------------------------------------------------- Read loncaparev table
13896: 
13897: &load_loncaparevs();
13898: 
13899: # ---------------------------------------------------------- Read serverhostID table
13900: 
13901: &load_serverhomeIDs();
13902: 
13903: # ---------------------------------------------------------- Read releaseslist XML
13904: {
13905:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
13906:     if (-e $file) {
13907:         my $parser = HTML::LCParser->new($file);
13908:         while (my $token = $parser->get_token()) {
13909:             if ($token->[0] eq 'S') {
13910:                 my $item = $token->[1];
13911:                 my $name = $token->[2]{'name'};
13912:                 my $value = $token->[2]{'value'};
13913:                 my $valuematch = $token->[2]{'valuematch'};
13914:                 my $namematch = $token->[2]{'namematch'};
13915:                 if ($item eq 'parameter') {
13916:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
13917:                         my $release = $parser->get_text();
13918:                         $release =~ s/(^\s*|\s*$ )//gx;
13919:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
13920:                     }
13921:                 } elsif ($item ne '' && $name ne '') {
13922:                     my $release = $parser->get_text();
13923:                     $release =~ s/(^\s*|\s*$ )//gx;
13924:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
13925:                 }
13926:             }
13927:         }
13928:     }
13929: }
13930: 
13931: # ---------------------------------------------------------- Read managers table
13932: {
13933:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
13934:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
13935:             while (my $configline=<$config>) {
13936:                 chomp($configline);
13937:                 next if ($configline =~ /^\#/);
13938:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
13939:                     $managerstab{$configline} = 1;
13940:                 }
13941:             }
13942:             close($config);
13943:         }
13944:     }
13945: }
13946: 
13947: # ------------- set up temporary directory
13948: {
13949:     $tmpdir = LONCAPA::tempdir();
13950: 
13951: }
13952: 
13953: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
13954: 				'compress_threshold'=> 20_000,
13955:  			        });
13956: 
13957: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
13958: $dumpcount=0;
13959: $locknum=0;
13960: 
13961: &logtouch();
13962: &logthis('<font color="yellow">INFO: Read configuration</font>');
13963: $readit=1;
13964:     {
13965: 	use integer;
13966: 	my $test=(2**32)+1;
13967: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
13968: 	&logthis(" Detected 64bit platform ($_64bit)");
13969:     }
13970: }
13971: }
13972: 
13973: 1;
13974: __END__
13975: 
13976: =pod
13977: 
13978: =head1 NAME
13979: 
13980: Apache::lonnet - Subroutines to ask questions about things in the network.
13981: 
13982: =head1 SYNOPSIS
13983: 
13984: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
13985: 
13986:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
13987: 
13988: Common parameters:
13989: 
13990: =over 4
13991: 
13992: =item *
13993: 
13994: $uname : an internal username (if $cname expecting a course Id specifically)
13995: 
13996: =item *
13997: 
13998: $udom : a domain (if $cdom expecting a course's domain specifically)
13999: 
14000: =item *
14001: 
14002: $symb : a resource instance identifier
14003: 
14004: =item *
14005: 
14006: $namespace : the name of a .db file that contains the data needed or
14007: being set.
14008: 
14009: =back
14010: 
14011: =head1 OVERVIEW
14012: 
14013: lonnet provides subroutines which interact with the
14014: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
14015: about classes, users, and resources.
14016: 
14017: For many of these objects you can also use this to store data about
14018: them or modify them in various ways.
14019: 
14020: =head2 Symbs
14021: 
14022: To identify a specific instance of a resource, LON-CAPA uses symbols
14023: or "symbs"X<symb>. These identifiers are built from the URL of the
14024: map, the resource number of the resource in the map, and the URL of
14025: the resource itself. The latter is somewhat redundant, but might help
14026: if maps change.
14027: 
14028: An example is
14029: 
14030:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
14031: 
14032: The respective map entry is
14033: 
14034:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
14035:   title="Problem 2">
14036:  </resource>
14037: 
14038: Symbs are used by the random number generator, as well as to store and
14039: restore data specific to a certain instance of for example a problem.
14040: 
14041: =head2 Storing And Retrieving Data
14042: 
14043: X<store()>X<cstore()>X<restore()>Three of the most important functions
14044: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
14045: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
14046: is is the non-critical message twin of cstore. These functions are for
14047: handlers to store a perl hash to a user's permanent data space in an
14048: easy manner, and to retrieve it again on another call. It is expected
14049: that a handler would use this once at the beginning to retrieve data,
14050: and then again once at the end to send only the new data back.
14051: 
14052: The data is stored in the user's data directory on the user's
14053: homeserver under the ID of the course.
14054: 
14055: The hash that is returned by restore will have all of the previous
14056: value for all of the elements of the hash.
14057: 
14058: Example:
14059: 
14060:  #creating a hash
14061:  my %hash;
14062:  $hash{'foo'}='bar';
14063: 
14064:  #storing it
14065:  &Apache::lonnet::cstore(\%hash);
14066: 
14067:  #changing a value
14068:  $hash{'foo'}='notbar';
14069: 
14070:  #adding a new value
14071:  $hash{'bar'}='foo';
14072:  &Apache::lonnet::cstore(\%hash);
14073: 
14074:  #retrieving the hash
14075:  my %history=&Apache::lonnet::restore();
14076: 
14077:  #print the hash
14078:  foreach my $key (sort(keys(%history))) {
14079:    print("\%history{$key} = $history{$key}");
14080:  }
14081: 
14082: Will print out:
14083: 
14084:  %history{1:foo} = bar
14085:  %history{1:keys} = foo:timestamp
14086:  %history{1:timestamp} = 990455579
14087:  %history{2:bar} = foo
14088:  %history{2:foo} = notbar
14089:  %history{2:keys} = foo:bar:timestamp
14090:  %history{2:timestamp} = 990455580
14091:  %history{bar} = foo
14092:  %history{foo} = notbar
14093:  %history{timestamp} = 990455580
14094:  %history{version} = 2
14095: 
14096: Note that the special hash entries C<keys>, C<version> and
14097: C<timestamp> were added to the hash. C<version> will be equal to the
14098: total number of versions of the data that have been stored. The
14099: C<timestamp> attribute will be the UNIX time the hash was
14100: stored. C<keys> is available in every historical section to list which
14101: keys were added or changed at a specific historical revision of a
14102: hash.
14103: 
14104: B<Warning>: do not store the hash that restore returns directly. This
14105: will cause a mess since it will restore the historical keys as if the
14106: were new keys. I.E. 1:foo will become 1:1:foo etc.
14107: 
14108: Calling convention:
14109: 
14110:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
14111:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
14112: 
14113: For more detailed information, see lonnet specific documentation.
14114: 
14115: =head1 RETURN MESSAGES
14116: 
14117: =over 4
14118: 
14119: =item * B<con_lost>: unable to contact remote host
14120: 
14121: =item * B<con_delayed>: unable to contact remote host, message will be delivered
14122: when the connection is brought back up
14123: 
14124: =item * B<con_failed>: unable to contact remote host and unable to save message
14125: for later delivery
14126: 
14127: =item * B<error:>: an error a occurred, a description of the error follows the :
14128: 
14129: =item * B<no_such_host>: unable to fund a host associated with the user/domain
14130: that was requested
14131: 
14132: =back
14133: 
14134: =head1 PUBLIC SUBROUTINES
14135: 
14136: =head2 Session Environment Functions
14137: 
14138: =over 4
14139: 
14140: =item * 
14141: X<appenv()>
14142: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
14143: the user envirnoment file, and will be restored for each access this
14144: user makes during this session, also modifies the %env for the current
14145: process. Optional rolesarrayref - if defined contains a reference to an array
14146: of roles which are exempt from the restriction on modifying user.role entries 
14147: in the user's environment.db and in %env.    
14148: 
14149: =item *
14150: X<delenv()>
14151: B<delenv($delthis,$regexp)>: removes all items from the session
14152: environment file that begin with $delthis. If the 
14153: optional second arg - $regexp - is true, $delthis is treated as a 
14154: regular expression, otherwise \Q$delthis\E is used. 
14155: The values are also deleted from the current processes %env.
14156: 
14157: =item * get_env_multiple($name) 
14158: 
14159: gets $name from the %env hash, it seemlessly handles the cases where multiple
14160: values may be defined and end up as an array ref.
14161: 
14162: returns an array of values
14163: 
14164: =back
14165: 
14166: =head2 User Information
14167: 
14168: =over 4
14169: 
14170: =item *
14171: X<queryauthenticate()>
14172: B<queryauthenticate($uname,$udom)>: try to determine user's current 
14173: authentication scheme
14174: 
14175: =item *
14176: X<authenticate()>
14177: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
14178: authenticate user from domain's lib servers (first use the current
14179: one). C<$upass> should be the users password.
14180: $checkdefauth is optional (value is 1 if a check should be made to
14181:    authenticate user using default authentication method, and allow
14182:    account creation if username does not have account in the domain).
14183: $clientcancheckhost is optional (value is 1 if checking whether the
14184:    server can host will occur on the client side in lonauth.pm).   
14185: 
14186: =item *
14187: X<homeserver()>
14188: B<homeserver($uname,$udom)>: find the server which has
14189: the user's directory and files (there must be only one), this caches
14190: the answer, and also caches if there is a borken connection.
14191: 
14192: =item *
14193: X<idget()>
14194: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
14195: a list of student/employee IDs or clicker IDs
14196: (student/employee IDs are a unique resource in a domain, there must be 
14197: only 1 ID per username, and only 1 username per ID in a specific domain).
14198: clickerIDs are not necessarily unique, as students might share clickers.
14199: (returns hash: id=>name,id=>name)
14200: 
14201: =item *
14202: X<idrget()>
14203: B<idrget($udom,@unames)>: find the IDs behind a list of
14204: usernames (returns hash: name=>id,name=>id)
14205: 
14206: =item *
14207: X<idput()>
14208: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
14209: names and associated student/employee IDs or clicker IDs.
14210: 
14211: =item *
14212: X<iddel()>
14213: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
14214: student/employee ID or clicker ID username look-ups from domain.
14215: The homeserver ($uhome) and namespace ($namespace) are optional.
14216: If no $uhome is provided, it will be determined usig &homeserver()
14217: for each user.  If no $namespace is provided, the default is ids.
14218: 
14219: =item *
14220: X<updateclickers()>
14221: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
14222: clicker ID-to-username look-ups in clickers.db on library server.
14223: Permitted actions are add or del (i.e., add or delete). The 
14224: clickers.db contains clickerID as keys (escaped), and each corresponding
14225: value is an escaped comma-separated list of usernames (for whom the
14226: library server is the homeserver), who registered that particular ID.
14227: If $critical is true, the update will be sent via &critical, otherwise
14228: &reply() will be used.
14229: 
14230: =item *
14231: X<rolesinit()>
14232: B<rolesinit($udom,$username)>: get user privileges.
14233: returns user role, first access and timer interval hashes
14234: 
14235: =item *
14236: X<privileged()>
14237: B<privileged($username,$domain)>: returns a true if user has a
14238: privileged and active role (i.e. su or dc), false otherwise.
14239: 
14240: =item *
14241: X<getsection()>
14242: B<getsection($udom,$uname,$cname)>: finds the section of student in the
14243: course $cname, return section name/number or '' for "not in course"
14244: and '-1' for "no section"
14245: 
14246: =item *
14247: X<userenvironment()>
14248: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
14249: passed in @what from the requested user's environment, returns a hash
14250: 
14251: =item * 
14252: X<userlog_query()>
14253: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
14254: activity.log file. %filters defines filters applied when parsing the
14255: log file. These can be start or end timestamps, or the type of action
14256: - log to look for Login or Logout events, check for Checkin or
14257: Checkout, role for role selection. The response is in the form
14258: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
14259: escaped strings of the action recorded in the activity.log file.
14260: 
14261: =back
14262: 
14263: =head2 User Roles
14264: 
14265: =over 4
14266: 
14267: =item *
14268: 
14269: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
14270: returns codes for allowed actions.
14271: 
14272: The first argument is required, all others are optional.
14273: 
14274: $priv is the privilege being checked.
14275: $uri contains additional information about what is being checked for access (e.g.,
14276: URL, course ID etc.). 
14277: $symb is the unique resource instance identifier in a course; if needed,
14278: but not provided, it will be retrieved via a call to &symbread(). 
14279: $role is the role for which a priv is being checked (only used if priv is evb). 
14280: $clientip is the user's IP address (only used when checking for access to portfolio 
14281: files).
14282: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
14283: prevents recursive calls to &allowed.
14284: 
14285:  F: full access
14286:  U,I,K: authentication modes (cxx only)
14287:  '': forbidden
14288:  1: user needs to choose course
14289:  2: browse allowed
14290:  A: passphrase authentication needed
14291:  B: access temporarily blocked because of a blocking event in a course.
14292: 
14293: =item *
14294: 
14295: constructaccess($url,$setpriv) : check for access to construction space URL
14296: 
14297: See if the owner domain and name in the URL match those in the
14298: expected environment.  If so, return three element list
14299: ($ownername,$ownerdomain,$ownerhome).
14300: 
14301: Otherwise return the null string.
14302: 
14303: If second argument 'setpriv' is true, it assigns the privileges,
14304: and returns the same three element list, unless the owner has
14305: blocked "ad hoc" Domain Coordinator access to the Author Space,
14306: in which case the null string is returned.
14307: 
14308: =item *
14309: 
14310: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
14311: define a custom role rolename set privileges in format of lonTabs/roles.tab
14312: for system, domain, and course level. $uname and $udom are optional (current
14313: user's username and domain will be used when either of $uname or $udom are absent.
14314: 
14315: =item *
14316: 
14317: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
14318: (rolesplain.tab); plain text explanation of a user role term.
14319: $type is Course (default) or Community.
14320: If $forcedefault evaluates to true, text returned will be default 
14321: text for $type. Otherwise, if this is a course, the text returned 
14322: will be a custom name for the role (if defined in the course's 
14323: environment).  If no custom name is defined the default is returned.
14324:    
14325: =item *
14326: 
14327: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
14328: All arguments are optional. Returns a hash of a roles, either for
14329: co-author/assistant author roles for a user's Construction Space
14330: (default), or if $context is 'userroles', roles for the user himself,
14331: In the hash, keys are set to colon-separated $uname,$udom,$role, and
14332: (optionally) if $withsec is true, a fourth colon-separated item - $section.
14333: For each key, value is set to colon-separated start and end times for
14334: the role.  If no username and domain are specified, will default to
14335: current user/domain. Types, roles, and roledoms are references to arrays
14336: of role statuses (active, future or previous), roles 
14337: (e.g., cc,in, st etc.) and domains of the roles which can be used
14338: to restrict the list of roles reported. If no array ref is 
14339: provided for types, will default to return only active roles.
14340: 
14341: =item *
14342: 
14343: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
14344: user: $uname:$udom has a role in the course: $cdom_$cnum. 
14345: 
14346: Additional optional arguments are: $type (if role checking is to be restricted 
14347: to certain user status types -- previous (expired roles), active (currently
14348: available roles) or future (roles available in the future), and
14349: $hideprivileged -- if true will not report course roles for users who
14350: have active Domain Coordinator role in course's domain or in additional
14351: domains (specified in 'Domains to check for privileged users' in course
14352: environment -- set via:  Course Settings -> Classlists and staff listing).
14353: 
14354: =item *
14355: 
14356: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
14357: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
14358: $possdomains and $possroles are optional array refs -- to domains to check and
14359: roles to check.  If $possdomains is not specified, a dump will be done of the
14360: users' roles.db to check for a dc or su role in any domain. This can be
14361: time consuming if &privileged is called repeatedly (e.g., when displaying a
14362: classlist), so in such cases, supplying a $possdomains array is preferred, as
14363: this then allows &privileged_by_domain() to be used, which caches the identity
14364: of privileged users, eliminating the need for repeated calls to &dump().
14365: 
14366: =item *
14367: 
14368: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
14369: where the outer hash keys are domains specified in the $possdomains array ref,
14370: next inner hash keys are privileged roles specified in the $roles array ref,
14371: and the innermost hash contains key = value pairs for username:domain = end:start
14372: for active or future "privileged" users with that role in that domain. To avoid
14373: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
14374: innerhash are cached using priv_$role and $dom as the identifiers.
14375: 
14376: =back
14377: 
14378: =head2 User Modification
14379: 
14380: =over 4
14381: 
14382: =item *
14383: 
14384: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
14385: user for the level given by URL.  Optional start and end dates (leave empty
14386: string or zero for "no date")
14387: 
14388: =item *
14389: 
14390: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
14391: change a users, password, possible return values are: ok,
14392: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
14393: refused
14394: 
14395: =item *
14396: 
14397: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
14398: 
14399: =item *
14400: 
14401: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
14402:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
14403: 
14404: will update user information (firstname,middlename,lastname,generation,
14405: permanentemail), and if forceid is true, student/employee ID also.
14406: A user's institutional affiliation(s) can also be updated.
14407: User information fields will not be overwritten with empty entries 
14408: unless the field is included in the $candelete array reference.
14409: This array is included when a single user is modified via "Manage Users",
14410: or when Autoupdate.pl is run by cron in a domain.
14411: 
14412: =item *
14413: 
14414: modifystudent
14415: 
14416: modify a student's enrollment and identification information.
14417: The course id is resolved based on the current user's environment.  
14418: This means the invoking user must be a course coordinator or otherwise
14419: associated with a course.
14420: 
14421: This call is essentially a wrapper for lonnet::modifyuser and
14422: lonnet::modify_student_enrollment
14423: 
14424: Inputs: 
14425: 
14426: =over 4
14427: 
14428: =item B<$udom> Student's loncapa domain
14429: 
14430: =item B<$uname> Student's loncapa login name
14431: 
14432: =item B<$uid> Student/Employee ID
14433: 
14434: =item B<$umode> Student's authentication mode
14435: 
14436: =item B<$upass> Student's password
14437: 
14438: =item B<$first> Student's first name
14439: 
14440: =item B<$middle> Student's middle name
14441: 
14442: =item B<$last> Student's last name
14443: 
14444: =item B<$gene> Student's generation
14445: 
14446: =item B<$usec> Student's section in course
14447: 
14448: =item B<$end> Unix time of the roles expiration
14449: 
14450: =item B<$start> Unix time of the roles start date
14451: 
14452: =item B<$forceid> If defined, allow $uid to be changed
14453: 
14454: =item B<$desiredhome> server to use as home server for student
14455: 
14456: =item B<$email> Student's permanent e-mail address
14457: 
14458: =item B<$type> Type of enrollment (auto or manual)
14459: 
14460: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
14461: 
14462: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
14463: 
14464: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
14465: 
14466: =item B<$context> role change context (shown in User Management Logs display in a course)
14467: 
14468: =item B<$inststatus> institutional status of user - : separated string of escaped status types
14469: 
14470: =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.
14471: 
14472: =back
14473: 
14474: =item *
14475: 
14476: modify_student_enrollment
14477: 
14478: Change a student's enrollment status in a class.  The environment variable
14479: 'role.request.course' must be defined for this function to proceed.
14480: 
14481: Inputs:
14482: 
14483: =over 4
14484: 
14485: =item $udom, student's domain
14486: 
14487: =item $uname, student's name
14488: 
14489: =item $uid, student's user id
14490: 
14491: =item $first, student's first name
14492: 
14493: =item $middle
14494: 
14495: =item $last
14496: 
14497: =item $gene
14498: 
14499: =item $usec
14500: 
14501: =item $end
14502: 
14503: =item $start
14504: 
14505: =item $type
14506: 
14507: =item $locktype
14508: 
14509: =item $cid
14510: 
14511: =item $selfenroll
14512: 
14513: =item $context
14514: 
14515: =item $credits, number of credits student will earn from this class
14516: 
14517: =item $instsec, institutional course section code for student
14518: 
14519: =back
14520: 
14521: 
14522: =item *
14523: 
14524: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
14525: custom role; give a custom role to a user for the level given by URL.  Specify
14526: name and domain of role author, and role name
14527: 
14528: =item *
14529: 
14530: revokerole($udom,$uname,$url,$role) : revoke a role for url
14531: 
14532: =item *
14533: 
14534: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
14535: 
14536: =back
14537: 
14538: =head2 Course Infomation
14539: 
14540: =over 4
14541: 
14542: =item *
14543: 
14544: coursedescription($courseid,$options) : returns a hash of information about the
14545: specified course id, including all environment settings for the
14546: course, the description of the course will be in the hash under the
14547: key 'description'
14548: 
14549: $options is an optional parameter that if supplied is a hash reference that controls
14550: what how this function works.  It has the following key/values:
14551: 
14552: =over 4
14553: 
14554: =item freshen_cache
14555: 
14556: If defined, and the environment cache for the course is valid, it is 
14557: returned in the returned hash.
14558: 
14559: =item one_time
14560: 
14561: If defined, the last cache time is set to _now_
14562: 
14563: =item user
14564: 
14565: If defined, the supplied username is used instead of the current user.
14566: 
14567: 
14568: =back
14569: 
14570: =item *
14571: 
14572: resdata($name,$domain,$type,@which) : request for current parameter
14573: setting for a specific $type, where $type is either 'course' or 'user',
14574: @what should be a list of parameters to ask about. This routine caches
14575: answers for 10 minutes.
14576: 
14577: =item *
14578: 
14579: get_courseresdata($courseid, $domain) : dump the entire course resource
14580: data base, returning a hash that is keyed by the resource name and has
14581: values that are the resource value.  I believe that the timestamps and
14582: versions are also returned.
14583: 
14584: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
14585: supplemental content area. This routine caches the number of files for 
14586: 10 minutes.
14587: 
14588: =back
14589: 
14590: =head2 Course Modification
14591: 
14592: =over 4
14593: 
14594: =item *
14595: 
14596: writecoursepref($courseid,%prefs) : write preferences (environment
14597: database) for a course
14598: 
14599: =item *
14600: 
14601: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
14602: 
14603: =item *
14604: 
14605: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
14606: 
14607: =item *
14608: 
14609: is_course($courseid), is_course($cdom, $cnum)
14610: 
14611: Accepts either a combined $courseid (in the form of domain_courseid) or the
14612: two component version $cdom, $cnum. It checks if the specified course exists.
14613: 
14614: Returns:
14615:     undef if the course doesn't exist, otherwise
14616:     in scalar context the combined courseid.
14617:     in list context the two components of the course identifier, domain and 
14618:     courseid.    
14619: 
14620: =back
14621: 
14622: =head2 Resource Subroutines
14623: 
14624: =over 4
14625: 
14626: =item *
14627: 
14628: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
14629: 
14630: =item *
14631: 
14632: repcopy($filename) : subscribes to the requested file, and attempts to
14633: replicate from the owning library server, Might return
14634: 'unavailable', 'not_found', 'forbidden', 'ok', or
14635: 'bad_request', also attempts to grab the metadata for the
14636: resource. Expects the local filesystem pathname
14637: (/home/httpd/html/res/....)
14638: 
14639: =back
14640: 
14641: =head2 Resource Information
14642: 
14643: =over 4
14644: 
14645: =item *
14646: 
14647: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
14648: and returns the value of a variety of different possible values,
14649: $varname should be a request string, and the other parameters can be
14650: used to specify who and what one is asking about. Ordinarily, $cid 
14651: does not need to be specified, as it is retrived from 
14652: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
14653: within lonuserstate::loadmap() when initializing a course, before
14654: $env{'request.course.id'} has been set, so it needs to be provided
14655: in that one case.
14656: 
14657: Possible values for $varname are environment.lastname (or other item
14658: from the envirnment hash), user.name (or someother aspect about the
14659: user), resource.0.maxtries (or some other part and parameter of a
14660: resource)
14661: 
14662: =item *
14663: 
14664: directcondval($number) : get current value of a condition; reads from a state
14665: string
14666: 
14667: =item *
14668: 
14669: condval($condidx) : value of condition index based on state
14670: 
14671: =item *
14672: 
14673: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
14674: resource's metadata, $what should be either a specific key, or either
14675: 'keys' (to get a list of possible keys) or 'packages' to get a list of
14676: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
14677: 
14678: this function automatically caches all requests
14679: 
14680: =item *
14681: 
14682: metadata_query($query,$custom,$customshow) : make a metadata query against the
14683: network of library servers; returns file handle of where SQL and regex results
14684: will be stored for query
14685: 
14686: =item *
14687: 
14688: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
14689: return symbolic list entry (all arguments optional). 
14690: 
14691: Args: filename is the filename (including path) for the file for which a symb 
14692: is required; donotrecurse, if true will prevent calls to allowed() being made 
14693: to check access status if more than one resource was found in the bighash 
14694: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
14695: a randompick); ignorecachednull, if true will prevent a symb of '' being 
14696: returned if $env{$cache_str} is defined as ''; checkforblock if true will
14697: cause possible symbs to be checked to determine if they are subject to content
14698: blocking, if so they will not be included as possible symbs; possibles is a
14699: ref to a hash, which, as a side effect, will be populated with all possible 
14700: symbs (content blocking not tested).
14701:  
14702: returns the data handle
14703: 
14704: =item *
14705: 
14706: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
14707: and is a possible symb for the URL in $thisfn, and if is an encrypted
14708: resource that the user accessed using /enc/ returns a 1 on success, 0
14709: on failure, user must be in a course, as it assumes the existence of
14710: the course initial hash, and uses $env('request.course.id'}.  The third
14711: arg is an optional reference to a scalar.  If this arg is passed in the 
14712: call to symbverify, it will be set to 1 if the symb has been set to be 
14713: encrypted; otherwise it will be null.  
14714: 
14715: =item *
14716: 
14717: symbclean($symb) : removes versions numbers from a symb, returns the
14718: cleaned symb
14719: 
14720: =item *
14721: 
14722: is_on_map($uri) : checks if the $uri is somewhere on the current
14723: course map, user must be in a course for it to work.
14724: 
14725: =item *
14726: 
14727: numval($salt) : return random seed value (addend for rndseed)
14728: 
14729: =item *
14730: 
14731: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
14732: a random seed, all arguments are optional, if they aren't sent it uses the
14733: environment to derive them. Note: if symb isn't sent and it can't get one
14734: from &symbread it will use the current time as its return value
14735: 
14736: =item *
14737: 
14738: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
14739: unfakeable, receipt
14740: 
14741: =item *
14742: 
14743: receipt() : API to ireceipt working off of env values; given out to users
14744: 
14745: =item *
14746: 
14747: countacc($url) : count the number of accesses to a given URL
14748: 
14749: =item *
14750: 
14751: 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
14752: 
14753: =item *
14754: 
14755: 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)
14756: 
14757: =item *
14758: 
14759: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
14760: 
14761: =item *
14762: 
14763: devalidate($symb) : devalidate temporary spreadsheet calculations,
14764: forcing spreadsheet to reevaluate the resource scores next time.
14765: 
14766: =item * 
14767: 
14768: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
14769: when viewing in course context.
14770: 
14771:  input: six args -- filename (decluttered), course number, course domain,
14772:                     url, symb (if registered) and group (if this is a 
14773:                     group item -- e.g., bulletin board, group page etc.).
14774: 
14775:  output: array of five scalars --
14776:          $cfile -- url for file editing if editable on current server
14777:          $home -- homeserver of resource (i.e., for author if published,
14778:                                           or course if uploaded.).
14779:          $switchserver --  1 if server switch will be needed.
14780:          $forceedit -- 1 if icon/link should be to go to edit mode 
14781:          $forceview -- 1 if icon/link should be to go to view mode
14782: 
14783: =item *
14784: 
14785: is_course_upload($file,$cnum,$cdom)
14786: 
14787: Used in course context to determine if current file was uploaded to 
14788: the course (i.e., would be found in /userfiles/docs on the course's 
14789: homeserver.
14790: 
14791:   input: 3 args -- filename (decluttered), course number and course domain.
14792:   output: boolean -- 1 if file was uploaded.
14793: 
14794: =back
14795: 
14796: =head2 Storing/Retreiving Data
14797: 
14798: =over 4
14799: 
14800: =item *
14801: 
14802: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
14803: permanently for this url; hashref needs to be given and should be a \%hashname;
14804: the remaining args aren't required and if they aren't passed or are '' they will
14805: be derived from the env (with the exception of $laststore, which is an 
14806: optional arg used when a user's submission is stored in grading).
14807: $laststore is $version=$timestamp, where $version is the most recent version
14808: number retrieved for the corresponding $symb in the $namespace db file, and
14809: $timestamp is the timestamp for that transaction (UNIX time).
14810: $laststore is currently only passed when cstore() is called by 
14811: structuretags::finalize_storage().
14812: 
14813: =item *
14814: 
14815: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
14816: but uses critical subroutine
14817: 
14818: =item *
14819: 
14820: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
14821: all args are optional
14822: 
14823: =item *
14824: 
14825: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
14826: dumps the complete (or key matching regexp) namespace into a hash
14827: ($udom, $uname, $regexp, $range are optional) for a namespace that is
14828: normally &store()ed into
14829: 
14830: $range should be either an integer '100' (give me the first 100
14831:                                            matching records)
14832:               or be  two integers sperated by a - with no spaces
14833:                  '30-50' (give me the 30th through the 50th matching
14834:                           records)
14835: 
14836: 
14837: =item *
14838: 
14839: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
14840: replaces a &store() version of data with a replacement set of data
14841: for a particular resource in a namespace passed in the $storehash hash 
14842: reference. If $tolog is true, the transaction is logged in the courselog
14843: with an action=PUTSTORE.
14844: 
14845: =item *
14846: 
14847: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
14848: works very similar to store/cstore, but all data is stored in a
14849: temporary location and can be reset using tmpreset, $storehash should
14850: be a hash reference, returns nothing on success
14851: 
14852: =item *
14853: 
14854: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
14855: similar to restore, but all data is stored in a temporary location and
14856: can be reset using tmpreset. Returns a hash of values on success,
14857: error string otherwise.
14858: 
14859: =item *
14860: 
14861: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
14862: deltes all keys for $symb form the temporary storage hash.
14863: 
14864: =item *
14865: 
14866: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
14867: reference filled in from namesp ($udom and $uname are optional)
14868: 
14869: =item *
14870: 
14871: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
14872: namesp ($udom and $uname are optional)
14873: 
14874: =item *
14875: 
14876: dump($namespace,$udom,$uname,$regexp,$range) : 
14877: dumps the complete (or key matching regexp) namespace into a hash
14878: ($udom, $uname, $regexp, $range are optional)
14879: 
14880: $range should be either an integer '100' (give me the first 100
14881:                                            matching records)
14882:               or be  two integers sperated by a - with no spaces
14883:                  '30-50' (give me the 30th through the 50th matching
14884:                           records)
14885: =item *
14886: 
14887: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
14888: $store can be a scalar, an array reference, or if the amount to be 
14889: incremented is > 1, a hash reference.
14890: 
14891: ($udom and $uname are optional)
14892: 
14893: =item *
14894: 
14895: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
14896: ($udom and $uname are optional)
14897: 
14898: =item *
14899: 
14900: cput($namespace,$storehash,$udom,$uname) : critical put
14901: ($udom and $uname are optional)
14902: 
14903: =item *
14904: 
14905: newput($namespace,$storehash,$udom,$uname) :
14906: 
14907: Attempts to store the items in the $storehash, but only if they don't
14908: currently exist, if this succeeds you can be certain that you have 
14909: successfully created a new key value pair in the $namespace db.
14910: 
14911: 
14912: Args:
14913:  $namespace: name of database to store values to
14914:  $storehash: hashref to store to the db
14915:  $udom: (optional) domain of user containing the db
14916:  $uname: (optional) name of user caontaining the db
14917: 
14918: Returns:
14919:  'ok' -> succeeded in storing all keys of $storehash
14920:  'key_exists: <key>' -> failed to anything out of $storehash, as at
14921:                         least <key> already existed in the db (other
14922:                         requested keys may also already exist)
14923:  'error: <msg>' -> unable to tie the DB or other error occurred
14924:  'con_lost' -> unable to contact request server
14925:  'refused' -> action was not allowed by remote machine
14926: 
14927: 
14928: =item *
14929: 
14930: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
14931: reference filled in from namesp (encrypts the return communication)
14932: ($udom and $uname are optional)
14933: 
14934: =item *
14935: 
14936: log($udom,$name,$home,$message) : write to permanent log for user; use
14937: critical subroutine
14938: 
14939: =item *
14940: 
14941: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
14942: array reference filled in from namespace found in domain level on either
14943: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
14944: 
14945: =item *
14946: 
14947: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
14948: domain level either on specified domain server ($uhome) or primary domain 
14949: server ($udom and $uhome are optional)
14950: 
14951: =item * 
14952: 
14953: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
14954: for: authentication, language, quotas, timezone, date locale, and portal URL in
14955: the target domain.
14956: 
14957: May also include additional key => value pairs for the following groups:
14958: 
14959: =over
14960: 
14961: =item
14962: disk quotas (MB allocated by default to portfolios and authoring spaces).
14963: 
14964: =over
14965: 
14966: =item defaultquota, authorquota
14967: 
14968: =back
14969: 
14970: =item
14971: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
14972: portfolio for users).
14973: 
14974: =over
14975: 
14976: =item
14977: aboutme, blog, webdav, portfolio
14978: 
14979: =back
14980: 
14981: =item
14982: requestcourses: ability to request courses, and how requests are processed.
14983: 
14984: =over
14985: 
14986: =item
14987: official, unofficial, community, textbook, placement
14988: 
14989: =back
14990: 
14991: =item
14992: inststatus: types of institutional affiliation, and order in which they are displayed.
14993: 
14994: =over
14995: 
14996: =item
14997: inststatustypes, inststatusorder, inststatusguest
14998: 
14999: =back
15000: 
15001: =item
15002: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
15003: for course's uploaded content.
15004: 
15005: =over
15006: 
15007: =item
15008: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
15009: communityquota, textbookquota, placementquota
15010: 
15011: =back
15012: 
15013: =item
15014: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
15015: on your servers.
15016: 
15017: =over
15018: 
15019: =item 
15020: remotesessions, hostedsessions
15021: 
15022: =back
15023: 
15024: =back
15025: 
15026: In cases where a domain coordinator has never used the "Set Domain Configuration"
15027: utility to create a configuration.db file on a domain's primary library server 
15028: only the following domain defaults: auth_def, auth_arg_def, lang_def
15029: -- corresponding values are authentication type (internal, krb4, krb5,
15030: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
15031: will be available. Values are retrieved from cache (if current), unless the
15032: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
15033: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
15034: 
15035: Typical usage:
15036: 
15037: %domdefaults = &get_domain_defaults($target_domain);
15038: 
15039: =back
15040: 
15041: =head2 Network Status Functions
15042: 
15043: =over 4
15044: 
15045: =item *
15046: 
15047: dirlist() : return directory list based on URI (first arg).
15048: 
15049: Inputs: 1 required, 5 optional.
15050: 
15051: =over
15052: 
15053: =item 
15054: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
15055: 
15056: =item
15057: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
15058: 
15059: =item
15060: $username -  username of user/course to be listed. Extracted from $uri if absent. 
15061: 
15062: =item
15063: $getpropath - boolean: 1 if prepend path using &propath(). 
15064: 
15065: =item
15066: $getuserdir - boolean: 1 if prepend path for "userfiles".
15067: 
15068: =item 
15069: $alternateRoot - path to prepend in place of path from $uri.
15070: 
15071: =back
15072: 
15073: Returns: Array of up to two items.
15074: 
15075: =over
15076: 
15077: a reference to an array of files/subdirectories
15078: 
15079: =over
15080: 
15081: Each element in the array of files/subdirectories is a & separated list of
15082: item name and the result of running stat on the item.  If dirlist was requested
15083: for a file instead of a directory, the item name will be ''. For a directory 
15084: listing, if the item is a metadata file, the element will end &N&M 
15085: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
15086: default copyright set (1).  
15087: 
15088: =back
15089: 
15090: a scalar containing error condition (if encountered).
15091: 
15092: =over
15093: 
15094: =item 
15095: no_host (no homeserver identified for $username:$domain).
15096: 
15097: =item 
15098: no_such_host (server contacted for listing not identified as valid host).
15099: 
15100: =item 
15101: con_lost (connection to remote server failed).
15102: 
15103: =item 
15104: refused (invalid $username:$domain received on lond side).
15105: 
15106: =item 
15107: no_such_dir (directory at specified path on lond side does not exist). 
15108: 
15109: =item 
15110: empty (directory at specified path on lond side is empty).
15111: 
15112: =over
15113: 
15114: This is currently not encountered because the &ls3, &ls2, 
15115: &ls (_handler) routines on the lond side do not filter out
15116: . and .. from a directory listing. 
15117: 
15118: =back
15119: 
15120: =back
15121: 
15122: =back
15123: 
15124: =item *
15125: 
15126: spareserver() : find server with least workload from spare.tab
15127: 
15128: 
15129: =item *
15130: 
15131: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
15132: if there is no corresponding loncapa host.
15133: 
15134: =back
15135: 
15136: 
15137: =head2 Apache Request
15138: 
15139: =over 4
15140: 
15141: =item *
15142: 
15143: ssi($url,%hash) : server side include, does a complete request cycle on url to
15144: localhost, posts hash
15145: 
15146: =back
15147: 
15148: =head2 Data to String to Data
15149: 
15150: =over 4
15151: 
15152: =item *
15153: 
15154: hash2str(%hash) : convert a hash into a string complete with escaping and '='
15155: and '&' separators, supports elements that are arrayrefs and hashrefs
15156: 
15157: =item *
15158: 
15159: hashref2str($hashref) : convert a hashref into a string complete with
15160: escaping and '=' and '&' separators, supports elements that are
15161: arrayrefs and hashrefs
15162: 
15163: =item *
15164: 
15165: arrayref2str($arrayref) : convert an arrayref into a string complete
15166: with escaping and '&' separators, supports elements that are arrayrefs
15167: and hashrefs
15168: 
15169: =item *
15170: 
15171: str2hash($string) : convert string to hash using unescaping and
15172: splitting on '=' and '&', supports elements that are arrayrefs and
15173: hashrefs
15174: 
15175: =item *
15176: 
15177: str2array($string) : convert string to hash using unescaping and
15178: splitting on '&', supports elements that are arrayrefs and hashrefs
15179: 
15180: =back
15181: 
15182: =head2 Logging Routines
15183: 
15184: 
15185: These routines allow one to make log messages in the lonnet.log and
15186: lonnet.perm logfiles.
15187: 
15188: =over 4
15189: 
15190: =item *
15191: 
15192: logtouch() : make sure the logfile, lonnet.log, exists
15193: 
15194: =item *
15195: 
15196: logthis() : append message to the normal lonnet.log file, it gets
15197: preiodically rolled over and deleted.
15198: 
15199: =item *
15200: 
15201: logperm() : append a permanent message to lonnet.perm.log, this log
15202: file never gets deleted by any automated portion of the system, only
15203: messages of critical importance should go in here.
15204: 
15205: 
15206: =back
15207: 
15208: =head2 General File Helper Routines
15209: 
15210: =over 4
15211: 
15212: =item *
15213: 
15214: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
15215: (a) files in /uploaded
15216:   (i) If a local copy of the file exists - 
15217:       compares modification date of local copy with last-modified date for 
15218:       definitive version stored on home server for course. If local copy is 
15219:       stale, requests a new version from the home server and stores it. 
15220:       If the original has been removed from the home server, then local copy 
15221:       is unlinked.
15222:   (ii) If local copy does not exist -
15223:       requests the file from the home server and stores it. 
15224:   
15225:   If $caller is 'uploadrep':  
15226:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
15227:     for request for files originally uploaded via DOCS. 
15228:      - returns 'ok' if fresh local copy now available, -1 otherwise.
15229:   
15230:   Otherwise:
15231:      This indicates a call from the content generation phase of the request.
15232:      -  returns the entire contents of the file or -1.
15233:      
15234: (b) files in /res
15235:    - returns the entire contents of a file or -1; 
15236:    it properly subscribes to and replicates the file if neccessary.
15237: 
15238: 
15239: =item *
15240: 
15241: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
15242:                   reference
15243: 
15244: returns either a stat() list of data about the file or an empty list
15245: if the file doesn't exist or couldn't find out about it (connection
15246: problems or user unknown)
15247: 
15248: =item *
15249: 
15250: filelocation($dir,$file) : returns file system location of a file
15251: based on URI; meant to be "fairly clean" absolute reference, $dir is a
15252: directory that relative $file lookups are to looked in ($dir of /a/dir
15253: and a file of ../bob will become /a/bob)
15254: 
15255: =item *
15256: 
15257: hreflocation($dir,$file) : returns file system location or a URL; same as
15258: filelocation except for hrefs
15259: 
15260: =item *
15261: 
15262: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
15263: also removes beginning /home/httpd/html unless /priv/ follows it.
15264: 
15265: =back
15266: 
15267: =head2 Usererfile file routines (/uploaded*)
15268: 
15269: =over 4
15270: 
15271: =item *
15272: 
15273: userfileupload(): main rotine for putting a file in a user or course's
15274:                   filespace, arguments are,
15275: 
15276:  formname - required - this is the name of the element in $env where the
15277:            filename, and the contents of the file to create/modifed exist
15278:            the filename is in $env{'form.'.$formname.'.filename'} and the
15279:            contents of the file is located in $env{'form.'.$formname}
15280:  context - if coursedoc, store the file in the course of the active role
15281:              of the current user; 
15282:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
15283:            if 'canceloverwrite': delete file in tmp/overwrites directory
15284:  subdir - required - subdirectory to put the file in under ../userfiles/
15285:          if undefined, it will be placed in "unknown"
15286: 
15287:  (This routine calls clean_filename() to remove any dangerous
15288:  characters from the filename, and then calls finuserfileupload() to
15289:  complete the transaction)
15290: 
15291:  returns either the url of the uploaded file (/uploaded/....) if successful
15292:  and /adm/notfound.html if unsuccessful
15293: 
15294: =item *
15295: 
15296: clean_filename(): routine for cleaing a filename up for storage in
15297:                  userfile space, argument is:
15298: 
15299:  filename - proposed filename
15300: 
15301: returns: the new clean filename
15302: 
15303: =item *
15304: 
15305: finishuserfileupload(): routine that creates and sends the file to
15306: userspace, probably shouldn't be called directly
15307: 
15308:   docuname: username or courseid of destination for the file
15309:   docudom: domain of user/course of destination for the file
15310:   formname: same as for userfileupload()
15311:   fname: filename (including subdirectories) for the file
15312:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
15313:   allfiles: reference to hash used to store objects found by parser
15314:   codebase: reference to hash used for codebases of java objects found by parser
15315:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
15316:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
15317:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
15318:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
15319:   context: if 'overwrite', will move the uploaded file from its temporary location to
15320:             userfiles to facilitate overwriting a previously uploaded file with same name.
15321:   mimetype: reference to scalar to accommodate mime type determined
15322:             from File::MMagic if $parser = parse.
15323: 
15324:  returns either the url of the uploaded file (/uploaded/....) if successful
15325:  and /adm/notfound.html if unsuccessful (or an error message if context 
15326:  was 'overwrite').
15327:  
15328: 
15329: =item *
15330: 
15331: renameuserfile(): renames an existing userfile to a new name
15332: 
15333:   Args:
15334:    docuname: username or courseid of destination for the file
15335:    docudom: domain of user/course of destination for the file
15336:    old: current file name (including any subdirs under userfiles)
15337:    new: desired file name (including any subdirs under userfiles)
15338: 
15339: =item *
15340: 
15341: mkdiruserfile(): creates a directory is a userfiles dir
15342: 
15343:   Args:
15344:    docuname: username or courseid of destination for the file
15345:    docudom: domain of user/course of destination for the file
15346:    dir: dir to create (including any subdirs under userfiles)
15347: 
15348: =item *
15349: 
15350: removeuserfile(): removes a file that exists in userfiles
15351: 
15352:   Args:
15353:    docuname: username or courseid of destination for the file
15354:    docudom: domain of user/course of destination for the file
15355:    fname: filname to delete (including any subdirs under userfiles)
15356: 
15357: =item *
15358: 
15359: removeuploadedurl(): convience function for removeuserfile()
15360: 
15361:   Args:
15362:    url:  a full /uploaded/... url to delete
15363: 
15364: =item * 
15365: 
15366: get_portfile_permissions():
15367:   Args:
15368:     domain: domain of user or course contain the portfolio files
15369:     user: name of user or num of course contain the portfolio files
15370:   Returns:
15371:     hashref of a dump of the proper file_permissions.db
15372:    
15373: 
15374: =item * 
15375: 
15376: get_access_controls():
15377: 
15378: Args:
15379:   current_permissions: the hash ref returned from get_portfile_permissions()
15380:   group: (optional) the group you want the files associated with
15381:   file: (optional) the file you want access info on
15382: 
15383: Returns:
15384:     a hash (keys are file names) of hashes containing
15385:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
15386:         values are XML containing access control settings (see below) 
15387: 
15388: Internal notes:
15389: 
15390:  access controls are stored in file_permissions.db as key=value pairs.
15391:     key -> path to file/file_name\0uniqueID:scope_end_start
15392:         where scope -> public,guest,course,group,domains or users.
15393:               end -> UNIX time for end of access (0 -> no end date)
15394:               start -> UNIX time for start of access
15395: 
15396:     value -> XML description of access control
15397:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
15398:             <start></start>
15399:             <end></end>
15400: 
15401:             <password></password>  for scope type = guest
15402: 
15403:             <domain></domain>     for scope type = course or group
15404:             <number></number>
15405:             <roles id="">
15406:              <role></role>
15407:              <access></access>
15408:              <section></section>
15409:              <group></group>
15410:             </roles>
15411: 
15412:             <dom></dom>         for scope type = domains
15413: 
15414:             <users>             for scope type = users
15415:              <user>
15416:               <uname></uname>
15417:               <udom></udom>
15418:              </user>
15419:             </users>
15420:            </scope> 
15421:               
15422:  Access data is also aggregated for each file in an additional key=value pair:
15423:  key -> path to file/file_name\0accesscontrol 
15424:  value -> reference to hash
15425:           hash contains key = value pairs
15426:           where key = uniqueID:scope_end_start
15427:                 value = UNIX time record was last updated
15428: 
15429:           Used to improve speed of look-ups of access controls for each file.  
15430:  
15431:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
15432: 
15433: =item *
15434: 
15435: modify_access_controls():
15436: 
15437: Modifies access controls for a portfolio file
15438: Args
15439: 1. file name
15440: 2. reference to hash of required changes,
15441: 3. domain
15442: 4. username
15443:   where domain,username are the domain of the portfolio owner 
15444:   (either a user or a course) 
15445: 
15446: Returns:
15447: 1. result of additions or updates ('ok' or 'error', with error message). 
15448: 2. result of deletions ('ok' or 'error', with error message).
15449: 3. reference to hash of any new or updated access controls.
15450: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
15451:    key = integer (inbound ID)
15452:    value = uniqueID
15453: 
15454: =item *
15455: 
15456: get_timebased_id():
15457: 
15458: Attempts to get a unique timestamp-based suffix for use with items added to a 
15459: course via the Course Editor (e.g., folders, composite pages, 
15460: group bulletin boards).
15461: 
15462: Args: (first three required; six others optional)
15463: 
15464: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
15465:    docssequence, or name of group
15466: 
15467: 2. keyid (alphanumeric): name of temporary locking key in hash,
15468:    e.g., num, boardids
15469: 
15470: 3. namespace: name of gdbm file used to store suffixes already assigned;  
15471:    file will be named nohist_namespace.db
15472: 
15473: 4. cdom: domain of course; default is current course domain from %env
15474: 
15475: 5. cnum: course number; default is current course number from %env
15476: 
15477: 6. idtype: set to concat if an additional digit is to be appended to the 
15478:    unix timestamp to form the suffix, if the plain timestamp is already
15479:    in use.  Default is to not do this, but simply increment the unix 
15480:    timestamp by 1 until a unique key is obtained.
15481: 
15482: 7. who: holder of locking key; defaults to user:domain for user.
15483: 
15484: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
15485:    retrying); default is 3.
15486: 
15487: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
15488: 
15489: Returns:
15490: 
15491: 1. suffix obtained (numeric)
15492: 
15493: 2. result of deleting locking key (ok if deleted, or lock never obtained)
15494: 
15495: 3. error: contains (localized) error message if an error occurred.
15496: 
15497: 
15498: =back
15499: 
15500: =head2 HTTP Helper Routines
15501: 
15502: =over 4
15503: 
15504: =item *
15505: 
15506: escape() : unpack non-word characters into CGI-compatible hex codes
15507: 
15508: =item *
15509: 
15510: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
15511: 
15512: =back
15513: 
15514: =head1 PRIVATE SUBROUTINES
15515: 
15516: =head2 Underlying communication routines (Shouldn't call)
15517: 
15518: =over 4
15519: 
15520: =item *
15521: 
15522: subreply() : tries to pass a message to lonc, returns con_lost if incapable
15523: 
15524: =item *
15525: 
15526: reply() : uses subreply to send a message to remote machine, logs all failures
15527: 
15528: =item *
15529: 
15530: critical() : passes a critical message to another server; if cannot
15531: get through then place message in connection buffer directory and
15532: returns con_delayed, if incapable of saving message, returns
15533: con_failed
15534: 
15535: =item *
15536: 
15537: reconlonc() : tries to reconnect lonc client processes.
15538: 
15539: =back
15540: 
15541: =head2 Resource Access Logging
15542: 
15543: =over 4
15544: 
15545: =item *
15546: 
15547: flushcourselogs() : flush (save) buffer logs and access logs
15548: 
15549: =item *
15550: 
15551: courselog($what) : save message for course in hash
15552: 
15553: =item *
15554: 
15555: courseacclog($what) : save message for course using &courselog().  Perform
15556: special processing for specific resource types (problems, exams, quizzes, etc).
15557: 
15558: =item *
15559: 
15560: goodbye() : flush course logs and log shutting down; it is called in srm.conf
15561: as a PerlChildExitHandler
15562: 
15563: =back
15564: 
15565: =head2 Other
15566: 
15567: =over 4
15568: 
15569: =item *
15570: 
15571: symblist($mapname,%newhash) : update symbolic storage links
15572: 
15573: =back
15574: 
15575: =cut
15576: 

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