File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1358: download - view: text, annotated - select for diffs
Mon Nov 13 00:22:03 2017 UTC (6 years, 8 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Fix typo introduced in rev. 1.1117.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1358 2017/11/13 00:22:03 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:     }
  711: 
  712:     return $handle;
  713: }
  714: 
  715: sub timed_flock {
  716:     my ($file,$lock_type) = @_;
  717:     my $failed=0;
  718:     eval {
  719: 	local $SIG{__DIE__}='DEFAULT';
  720: 	local $SIG{ALRM}=sub {
  721: 	    $failed=1;
  722: 	    die("failed lock");
  723: 	};
  724: 	alarm(13);
  725: 	flock($file,$lock_type);
  726: 	alarm(0);
  727:     };
  728:     if ($failed) {
  729: 	return undef;
  730:     } else {
  731: 	return 1;
  732:     }
  733: }
  734: 
  735: # ---------------------------------------------------------- Append Environment
  736: 
  737: sub appenv {
  738:     my ($newenv,$roles) = @_;
  739:     if (ref($newenv) eq 'HASH') {
  740:         foreach my $key (keys(%{$newenv})) {
  741:             my $refused = 0;
  742: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  743:                 $refused = 1;
  744:                 if (ref($roles) eq 'ARRAY') {
  745:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
  746:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  747:                         $refused = 0;
  748:                     }
  749:                 }
  750:             }
  751:             if ($refused) {
  752:                 &logthis("<font color=\"blue\">WARNING: ".
  753:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  754:                          .'</font>');
  755: 	        delete($newenv->{$key});
  756:             } else {
  757:                 $env{$key}=$newenv->{$key};
  758:             }
  759:         }
  760:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  761:         if ($opened
  762: 	    && &timed_flock($env_file,LOCK_EX)
  763: 	    &&
  764: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  765: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  766: 	    while (my ($key,$value) = each(%{$newenv})) {
  767: 	        $disk_env{$key} = $value;
  768: 	    }
  769: 	    untie(%disk_env);
  770:         }
  771:     }
  772:     return 'ok';
  773: }
  774: # ----------------------------------------------------- Delete from Environment
  775: 
  776: sub delenv {
  777:     my ($delthis,$regexp,$roles) = @_;
  778:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  779:         my $refused = 1;
  780:         if (ref($roles) eq 'ARRAY') {
  781:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  782:             if (grep(/^\Q$role\E$/,@{$roles})) {
  783:                 $refused = 0;
  784:             }
  785:         }
  786:         if ($refused) {
  787:             &logthis("<font color=\"blue\">WARNING: ".
  788:                      "Attempt to delete from environment ".$delthis);
  789:             return 'error';
  790:         }
  791:     }
  792:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  793:     if ($opened
  794: 	&& &timed_flock($env_file,LOCK_EX)
  795: 	&&
  796: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  797: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  798: 	foreach my $key (keys(%disk_env)) {
  799: 	    if ($regexp) {
  800:                 if ($key=~/^$delthis/) {
  801:                     delete($env{$key});
  802:                     delete($disk_env{$key});
  803:                 } 
  804:             } else {
  805:                 if ($key=~/^\Q$delthis\E/) {
  806: 		    delete($env{$key});
  807: 		    delete($disk_env{$key});
  808: 	        }
  809:             }
  810: 	}
  811: 	untie(%disk_env);
  812:     }
  813:     return 'ok';
  814: }
  815: 
  816: sub get_env_multiple {
  817:     my ($name) = @_;
  818:     my @values;
  819:     if (defined($env{$name})) {
  820:         # exists is it an array
  821:         if (ref($env{$name})) {
  822:             @values=@{ $env{$name} };
  823:         } else {
  824:             $values[0]=$env{$name};
  825:         }
  826:     }
  827:     return(@values);
  828: }
  829: 
  830: # ------------------------------------------------------------------- Locking
  831: 
  832: sub set_lock {
  833:     my ($text)=@_;
  834:     $locknum++;
  835:     my $id=$$.'-'.$locknum;
  836:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  837:              'session.lock.'.$id => $text});
  838:     return $id;
  839: }
  840: 
  841: sub get_locks {
  842:     my $num=0;
  843:     my %texts=();
  844:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  845:        if ($lock=~/\w/) {
  846:           $num++;
  847:           $texts{$lock}=$env{'session.lock.'.$lock};
  848:        }
  849:    }
  850:    return ($num,%texts);
  851: }
  852: 
  853: sub remove_lock {
  854:     my ($id)=@_;
  855:     my $newlocks='';
  856:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  857:        if (($lock=~/\w/) && ($lock ne $id)) {
  858:           $newlocks.=','.$lock;
  859:        }
  860:     }
  861:     &appenv({'session.locks' => $newlocks});
  862:     &delenv('session.lock.'.$id);
  863: }
  864: 
  865: sub remove_all_locks {
  866:     my $activelocks=$env{'session.locks'};
  867:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  868:        if ($lock=~/\w/) {
  869:           &remove_lock($lock);
  870:        }
  871:     }
  872: }
  873: 
  874: 
  875: # ------------------------------------------ Find out current server userload
  876: sub userload {
  877:     my $numusers=0;
  878:     {
  879: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  880: 	my $filename;
  881: 	my $curtime=time;
  882: 	while ($filename=readdir(LONIDS)) {
  883: 	    next if ($filename eq '.' || $filename eq '..');
  884: 	    next if ($filename =~ /publicuser_\d+\.id/);
  885: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  886: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  887: 	}
  888: 	closedir(LONIDS);
  889:     }
  890:     my $userloadpercent=0;
  891:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  892:     if ($maxuserload) {
  893: 	$userloadpercent=100*$numusers/$maxuserload;
  894:     }
  895:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  896:     return $userloadpercent;
  897: }
  898: 
  899: # ------------------------------ Find server with least workload from spare.tab
  900: 
  901: sub spareserver {
  902:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  903:     my $spare_server;
  904:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  905:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  906:                                                      :  $userloadpercent;
  907:     my ($uint_dom,$remotesessions);
  908:     if (($udom ne '') && (&domain($udom) ne '')) {
  909:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  910:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  911:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  912:         $remotesessions = $udomdefaults{'remotesessions'};
  913:     }
  914:     my $spareshash = &this_host_spares($udom);
  915:     if (ref($spareshash) eq 'HASH') {
  916:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  917:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  918:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  919:                                              $try_server));
  920: 	        ($spare_server, $lowest_load) =
  921: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  922:             }
  923:         }
  924: 
  925:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
  926: 
  927:         if (!$found_server) {
  928:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
  929: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
  930:                     next unless (&spare_can_host($udom,$uint_dom,
  931:                                                  $remotesessions,$try_server));
  932: 	            ($spare_server, $lowest_load) =
  933: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
  934:                 }
  935: 	    }
  936:         }
  937:     }
  938: 
  939:     if (!$want_server_name) {
  940:         my $protocol = 'http';
  941:         if ($protocol{$spare_server} eq 'https') {
  942:             $protocol = $protocol{$spare_server};
  943:         }
  944:         if (defined($spare_server)) {
  945:             my $hostname = &hostname($spare_server);
  946:             if (defined($hostname)) {
  947: 	        $spare_server = $protocol.'://'.$hostname;
  948:             }
  949:         }
  950:     }
  951:     return $spare_server;
  952: }
  953: 
  954: sub compare_server_load {
  955:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
  956: 
  957:     if ($required) {
  958:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
  959:         my $remoterev = &get_server_loncaparev(undef,$try_server);
  960:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
  961:         if (($major eq '' && $minor eq '') ||
  962:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
  963:             return ($spare_server,$lowest_load);
  964:         }
  965:     }
  966: 
  967:     my $loadans     = &reply('load',    $try_server);
  968:     my $userloadans = &reply('userload',$try_server);
  969: 
  970:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  971: 	return ($spare_server, $lowest_load); #didn't get a number from the server
  972:     }
  973: 
  974:     my $load;
  975:     if ($loadans =~ /\d/) {
  976: 	if ($userloadans =~ /\d/) {
  977: 	    #both are numbers, pick the bigger one
  978: 	    $load = ($loadans > $userloadans) ? $loadans 
  979: 		                              : $userloadans;
  980: 	} else {
  981: 	    $load = $loadans;
  982: 	}
  983:     } else {
  984: 	$load = $userloadans;
  985:     }
  986: 
  987:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  988: 	$spare_server = $try_server;
  989: 	$lowest_load  = $load;
  990:     }
  991:     return ($spare_server,$lowest_load);
  992: }
  993: 
  994: # --------------------------- ask offload servers if user already has a session
  995: sub find_existing_session {
  996:     my ($udom,$uname) = @_;
  997:     my $spareshash = &this_host_spares($udom);
  998:     if (ref($spareshash) eq 'HASH') {
  999:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
 1000:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
 1001:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1002:             }
 1003:         }
 1004:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
 1005:             foreach my $try_server (@{ $spareshash->{'default'} }) {
 1006:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
 1007:             }
 1008:         }
 1009:     }
 1010:     return;
 1011: }
 1012: 
 1013: # -------------------------------- ask if server already has a session for user
 1014: sub has_user_session {
 1015:     my ($lonid,$udom,$uname) = @_;
 1016:     my $result = &reply(join(':','userhassession',
 1017: 			     map {&escape($_)} ($udom,$uname)),$lonid);
 1018:     return 1 if ($result eq 'ok');
 1019: 
 1020:     return 0;
 1021: }
 1022: 
 1023: # --------- determine least loaded server in a user's domain which allows login
 1024: 
 1025: sub choose_server {
 1026:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
 1027:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
 1028:     my %servers = &get_servers($udom);
 1029:     my $lowest_load = 30000;
 1030:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
 1031:     if ($skiploadbal) {
 1032:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
 1033:         unless (defined($cached)) {
 1034:             my $cachetime = 60*60*24;
 1035:             my %domconfig =
 1036:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1037:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1038:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
 1039:                                            $cachetime);
 1040:             }
 1041:         }
 1042:     }
 1043:     foreach my $lonhost (keys(%servers)) {
 1044:         if ($skiploadbal) {
 1045:             if (ref($balancers) eq 'HASH') {
 1046:                 next if (exists($balancers->{$lonhost}));
 1047:             }
 1048:         }   
 1049:         my $loginvia;
 1050:         if ($checkloginvia) {
 1051:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
 1052:             if ($loginvia) {
 1053:                 my ($server,$path) = split(/:/,$loginvia);
 1054:                 ($login_host, $lowest_load) =
 1055:                     &compare_server_load($server, $login_host, $lowest_load, $required);
 1056:                 if ($login_host eq $server) {
 1057:                     $portal_path = $path;
 1058:                     $isredirect = 1;
 1059:                 }
 1060:             } else {
 1061:                 ($login_host, $lowest_load) =
 1062:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1063:                 if ($login_host eq $lonhost) {
 1064:                     $portal_path = '';
 1065:                     $isredirect = ''; 
 1066:                 }
 1067:             }
 1068:         } else {
 1069:             ($login_host, $lowest_load) =
 1070:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1071:         }
 1072:     }
 1073:     if ($login_host ne '') {
 1074:         $hostname = &hostname($login_host);
 1075:     }
 1076:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
 1077: }
 1078: 
 1079: # --------------------------------------------- Try to change a user's password
 1080: 
 1081: sub changepass {
 1082:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
 1083:     $currentpass = &escape($currentpass);
 1084:     $newpass     = &escape($newpass);
 1085:     my $lonhost = $perlvar{'lonHostID'};
 1086:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
 1087: 		       $server);
 1088:     if (! $answer) {
 1089: 	&logthis("No reply on password change request to $server ".
 1090: 		 "by $uname in domain $udom.");
 1091:     } elsif ($answer =~ "^ok") {
 1092:         &logthis("$uname in $udom successfully changed their password ".
 1093: 		 "on $server.");
 1094:     } elsif ($answer =~ "^pwchange_failure") {
 1095: 	&logthis("$uname in $udom was unable to change their password ".
 1096: 		 "on $server.  The action was blocked by either lcpasswd ".
 1097: 		 "or pwchange");
 1098:     } elsif ($answer =~ "^non_authorized") {
 1099:         &logthis("$uname in $udom did not get their password correct when ".
 1100: 		 "attempting to change it on $server.");
 1101:     } elsif ($answer =~ "^auth_mode_error") {
 1102:         &logthis("$uname in $udom attempted to change their password despite ".
 1103: 		 "not being locally or internally authenticated on $server.");
 1104:     } elsif ($answer =~ "^unknown_user") {
 1105:         &logthis("$uname in $udom attempted to change their password ".
 1106: 		 "on $server but were unable to because $server is not ".
 1107: 		 "their home server.");
 1108:     } elsif ($answer =~ "^refused") {
 1109: 	&logthis("$server refused to change $uname in $udom password because ".
 1110: 		 "it was sent an unencrypted request to change the password.");
 1111:     } elsif ($answer =~ "invalid_client") {
 1112:         &logthis("$server refused to change $uname in $udom password because ".
 1113:                  "it was a reset by e-mail originating from an invalid server.");
 1114:     }
 1115:     return $answer;
 1116: }
 1117: 
 1118: # ----------------------- Try to determine user's current authentication scheme
 1119: 
 1120: sub queryauthenticate {
 1121:     my ($uname,$udom)=@_;
 1122:     my $uhome=&homeserver($uname,$udom);
 1123:     if (!$uhome) {
 1124: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1125: 	return 'no_host';
 1126:     }
 1127:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1128:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1129: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1130:     }
 1131:     return $answer;
 1132: }
 1133: 
 1134: # --------- Try to authenticate user from domain's lib servers (first this one)
 1135: 
 1136: sub authenticate {
 1137:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1138:     $upass=&escape($upass);
 1139:     $uname= &LONCAPA::clean_username($uname);
 1140:     my $uhome=&homeserver($uname,$udom,1);
 1141:     my $newhome;
 1142:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1143: # Maybe the machine was offline and only re-appeared again recently?
 1144:         &reconlonc();
 1145: # One more
 1146: 	$uhome=&homeserver($uname,$udom,1);
 1147:         if (($uhome eq 'no_host') && $checkdefauth) {
 1148:             if (defined(&domain($udom,'primary'))) {
 1149:                 $newhome=&domain($udom,'primary');
 1150:             }
 1151:             if ($newhome ne '') {
 1152:                 $uhome = $newhome;
 1153:             }
 1154:         }
 1155: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1156: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1157: 	    return 'no_host';
 1158:         }
 1159:     }
 1160:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1161:     if ($answer eq 'authorized') {
 1162:         if ($newhome) {
 1163:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1164:             return 'no_account_on_host'; 
 1165:         } else {
 1166:             &logthis("User $uname at $udom authorized by $uhome");
 1167:             return $uhome;
 1168:         }
 1169:     }
 1170:     if ($answer eq 'non_authorized') {
 1171: 	&logthis("User $uname at $udom rejected by $uhome");
 1172: 	return 'no_host'; 
 1173:     }
 1174:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1175:     return 'no_host';
 1176: }
 1177: 
 1178: sub can_host_session {
 1179:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1180:     my $canhost = 1;
 1181:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1182:     if (ref($remotesessions) eq 'HASH') {
 1183:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1184:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1185:                 $canhost = 0;
 1186:             } else {
 1187:                 $canhost = 1;
 1188:             }
 1189:         }
 1190:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1191:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1192:                 $canhost = 1;
 1193:             } else {
 1194:                 $canhost = 0;
 1195:             }
 1196:         }
 1197:         if ($canhost) {
 1198:             if ($remotesessions->{'version'} ne '') {
 1199:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1200:                 if ($reqmajor ne '' && $reqminor ne '') {
 1201:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1202:                         my $major = $1;
 1203:                         my $minor = $2;
 1204:                         if (($major < $reqmajor ) ||
 1205:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1206:                             $canhost = 0;
 1207:                         }
 1208:                     } else {
 1209:                         $canhost = 0;
 1210:                     }
 1211:                 }
 1212:             }
 1213:         }
 1214:     }
 1215:     if ($canhost) {
 1216:         if (ref($hostedsessions) eq 'HASH') {
 1217:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1218:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1219:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1220:                 if (($uint_dom ne '') && 
 1221:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1222:                     $canhost = 0;
 1223:                 } else {
 1224:                     $canhost = 1;
 1225:                 }
 1226:             }
 1227:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1228:                 if (($uint_dom ne '') && 
 1229:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1230:                     $canhost = 1;
 1231:                 } else {
 1232:                     $canhost = 0;
 1233:                 }
 1234:             }
 1235:         }
 1236:     }
 1237:     return $canhost;
 1238: }
 1239: 
 1240: sub spare_can_host {
 1241:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1242:     my $canhost=1;
 1243:     my $try_server_hostname = &hostname($try_server);
 1244:     my $serverhomeID = &get_server_homeID($try_server_hostname);
 1245:     my $serverhomedom = &host_domain($serverhomeID);
 1246:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
 1247:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
 1248:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
 1249:             $canhost = 0;
 1250:         }
 1251:     }
 1252:     if (($canhost) && ($uint_dom)) {
 1253:         my @intdoms;
 1254:         my $internet_names = &get_internet_names($try_server);
 1255:         if (ref($internet_names) eq 'ARRAY') {
 1256:             @intdoms = @{$internet_names};
 1257:         }
 1258:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1259:             my $remoterev = &get_server_loncaparev(undef,$try_server);
 1260:             $canhost = &can_host_session($udom,$try_server,$remoterev,
 1261:                                          $remotesessions,
 1262:                                          $defdomdefaults{'hostedsessions'});
 1263:         }
 1264:     }
 1265:     return $canhost;
 1266: }
 1267: 
 1268: sub this_host_spares {
 1269:     my ($dom) = @_;
 1270:     my ($dom_in_use,$lonhost_in_use,$result);
 1271:     my @hosts = &current_machine_ids();
 1272:     foreach my $lonhost (@hosts) {
 1273:         if (&host_domain($lonhost) eq $dom) {
 1274:             $dom_in_use = $dom;
 1275:             $lonhost_in_use = $lonhost;
 1276:             last;
 1277:         }
 1278:     }
 1279:     if ($dom_in_use ne '') {
 1280:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1281:     }
 1282:     if (ref($result) ne 'HASH') {
 1283:         $lonhost_in_use = $perlvar{'lonHostID'};
 1284:         $dom_in_use = &host_domain($lonhost_in_use);
 1285:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1286:         if (ref($result) ne 'HASH') {
 1287:             $result = \%spareid;
 1288:         }
 1289:     }
 1290:     return $result;
 1291: }
 1292: 
 1293: sub spares_for_offload  {
 1294:     my ($dom_in_use,$lonhost_in_use) = @_;
 1295:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1296:     if (defined($cached)) {
 1297:         return $result;
 1298:     } else {
 1299:         my $cachetime = 60*60*24;
 1300:         my %domconfig =
 1301:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1302:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1303:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1304:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1305:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1306:                 }
 1307:             }
 1308:         }
 1309:     }
 1310:     return;
 1311: }
 1312: 
 1313: sub get_lonbalancer_config {
 1314:     my ($servers) = @_;
 1315:     my ($currbalancer,$currtargets);
 1316:     if (ref($servers) eq 'HASH') {
 1317:         foreach my $server (keys(%{$servers})) {
 1318:             my %what = (
 1319:                          spareid => 1,
 1320:                          perlvar => 1,
 1321:                        );
 1322:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1323:             if ($result eq 'ok') {
 1324:                 if (ref($returnhash) eq 'HASH') {
 1325:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1326:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1327:                             $currbalancer = $server;
 1328:                             $currtargets = {};
 1329:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1330:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1331:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1332:                                 }
 1333:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1334:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1335:                                 }
 1336:                             }
 1337:                             last;
 1338:                         }
 1339:                     }
 1340:                 }
 1341:             }
 1342:         }
 1343:     }
 1344:     return ($currbalancer,$currtargets);
 1345: }
 1346: 
 1347: sub check_loadbalancing {
 1348:     my ($uname,$udom,$caller) = @_;
 1349:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1350:         $rule_in_effect,$offloadto,$otherserver);
 1351:     my $lonhost = $perlvar{'lonHostID'};
 1352:     my @hosts = &current_machine_ids();
 1353:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1354:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1355:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1356:     my $serverhomedom = &host_domain($lonhost);
 1357:     my $domneedscache;
 1358:     my $cachetime = 60*60*24;
 1359: 
 1360:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1361:         $dom_in_use = $udom;
 1362:         $homeintdom = 1;
 1363:     } else {
 1364:         $dom_in_use = $serverhomedom;
 1365:     }
 1366:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1367:     unless (defined($cached)) {
 1368:         my %domconfig =
 1369:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1370:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1371:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1372:         } else {
 1373:             $domneedscache = $dom_in_use;
 1374:         }
 1375:     }
 1376:     if (ref($result) eq 'HASH') {
 1377:         ($is_balancer,$currtargets,$currrules) = 
 1378:             &check_balancer_result($result,@hosts);
 1379:         if ($is_balancer) {
 1380:             if (ref($currrules) eq 'HASH') {
 1381:                 if ($homeintdom) {
 1382:                     if ($uname ne '') {
 1383:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1384:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1385:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1386:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1387:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1388:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1389:                             }
 1390:                         }
 1391:                         if ($rule_in_effect eq '') {
 1392:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1393:                             if ($userenv{'inststatus'} ne '') {
 1394:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1395:                                 my ($othertitle,$usertypes,$types) =
 1396:                                     &Apache::loncommon::sorted_inst_types($udom);
 1397:                                 if (ref($types) eq 'ARRAY') {
 1398:                                     foreach my $type (@{$types}) {
 1399:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1400:                                             if (exists($currrules->{$type})) {
 1401:                                                 $rule_in_effect = $currrules->{$type};
 1402:                                             }
 1403:                                         }
 1404:                                     }
 1405:                                 }
 1406:                             } else {
 1407:                                 if (exists($currrules->{'default'})) {
 1408:                                     $rule_in_effect = $currrules->{'default'};
 1409:                                 }
 1410:                             }
 1411:                         }
 1412:                     } else {
 1413:                         if (exists($currrules->{'default'})) {
 1414:                             $rule_in_effect = $currrules->{'default'};
 1415:                         }
 1416:                     }
 1417:                 } else {
 1418:                     if ($currrules->{'_LC_external'} ne '') {
 1419:                         $rule_in_effect = $currrules->{'_LC_external'};
 1420:                     }
 1421:                 }
 1422:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1423:                                                        $uname,$udom);
 1424:             }
 1425:         }
 1426:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1427:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1428:         unless (defined($cached)) {
 1429:             my %domconfig =
 1430:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1431:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1432:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
 1433:             } else {
 1434:                 $domneedscache = $serverhomedom;
 1435:             }
 1436:         }
 1437:         if (ref($result) eq 'HASH') {
 1438:             ($is_balancer,$currtargets,$currrules) = 
 1439:                 &check_balancer_result($result,@hosts);
 1440:             if ($is_balancer) {
 1441:                 if (ref($currrules) eq 'HASH') {
 1442:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1443:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1444:                     }
 1445:                 }
 1446:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1447:                                                        $uname,$udom);
 1448:             }
 1449:         } else {
 1450:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1451:                 $is_balancer = 1;
 1452:                 $offloadto = &this_host_spares($dom_in_use);
 1453:             }
 1454:             unless (defined($cached)) {
 1455:                 $domneedscache = $serverhomedom;
 1456:             }
 1457:         }
 1458:     } else {
 1459:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1460:             $is_balancer = 1;
 1461:             $offloadto = &this_host_spares($dom_in_use);
 1462:         }
 1463:         unless (defined($cached)) {
 1464:             $domneedscache = $serverhomedom;
 1465:         }
 1466:     }
 1467:     if ($domneedscache) {
 1468:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
 1469:     }
 1470:     if ($is_balancer) {
 1471:         my $lowest_load = 30000;
 1472:         if (ref($offloadto) eq 'HASH') {
 1473:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1474:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1475:                     ($otherserver,$lowest_load) =
 1476:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1477:                 }
 1478:             }
 1479:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1480: 
 1481:             if (!$found_server) {
 1482:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1483:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1484:                         ($otherserver,$lowest_load) =
 1485:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1486:                     }
 1487:                 }
 1488:             }
 1489:         } elsif (ref($offloadto) eq 'ARRAY') {
 1490:             if (@{$offloadto} == 1) {
 1491:                 $otherserver = $offloadto->[0];
 1492:             } elsif (@{$offloadto} > 1) {
 1493:                 foreach my $try_server (@{$offloadto}) {
 1494:                     ($otherserver,$lowest_load) =
 1495:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1496:                 }
 1497:             }
 1498:         }
 1499:         unless ($caller eq 'login') {
 1500:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1501:                 $is_balancer = 0;
 1502:                 if ($uname ne '' && $udom ne '') {
 1503:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1504:                     
 1505:                         &appenv({'user.loadbalexempt'     => $lonhost,  
 1506:                                  'user.loadbalcheck.time' => time});
 1507:                     }
 1508:                 }
 1509:             }
 1510:         }
 1511:     }
 1512:     return ($is_balancer,$otherserver);
 1513: }
 1514: 
 1515: sub check_balancer_result {
 1516:     my ($result,@hosts) = @_;
 1517:     my ($is_balancer,$currtargets,$currrules);
 1518:     if (ref($result) eq 'HASH') {
 1519:         if ($result->{'lonhost'} ne '') {
 1520:             my $currbalancer = $result->{'lonhost'};
 1521:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1522:                 $is_balancer = 1;
 1523:                 $currtargets = $result->{'targets'};
 1524:                 $currrules = $result->{'rules'};
 1525:             }
 1526:         } else {
 1527:             foreach my $key (keys(%{$result})) {
 1528:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1529:                     (ref($result->{$key}) eq 'HASH')) {
 1530:                     $is_balancer = 1;
 1531:                     $currrules = $result->{$key}{'rules'};
 1532:                     $currtargets = $result->{$key}{'targets'};
 1533:                     last;
 1534:                 }
 1535:             }
 1536:         }
 1537:     }
 1538:     return ($is_balancer,$currtargets,$currrules);
 1539: }
 1540: 
 1541: sub get_loadbalancer_targets {
 1542:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1543:     my $offloadto;
 1544:     if ($rule_in_effect eq 'none') {
 1545:         return [$perlvar{'lonHostID'}];
 1546:     } elsif ($rule_in_effect eq '') {
 1547:         $offloadto = $currtargets;
 1548:     } else {
 1549:         if ($rule_in_effect eq 'homeserver') {
 1550:             my $homeserver = &homeserver($uname,$udom);
 1551:             if ($homeserver ne 'no_host') {
 1552:                 $offloadto = [$homeserver];
 1553:             }
 1554:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1555:             my %domconfig =
 1556:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1557:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1558:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1559:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1560:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1561:                     }
 1562:                 }
 1563:             } else {
 1564:                 my %servers = &internet_dom_servers($udom);
 1565:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1566:                 if (&hostname($remotebalancer) ne '') {
 1567:                     $offloadto = [$remotebalancer];
 1568:                 }
 1569:             }
 1570:         } elsif (&hostname($rule_in_effect) ne '') {
 1571:             $offloadto = [$rule_in_effect];
 1572:         }
 1573:     }
 1574:     return $offloadto;
 1575: }
 1576: 
 1577: sub internet_dom_servers {
 1578:     my ($dom) = @_;
 1579:     my (%uniqservers,%servers);
 1580:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1581:     my @machinedoms = &machine_domains($primaryserver);
 1582:     foreach my $mdom (@machinedoms) {
 1583:         my %currservers = %servers;
 1584:         my %server = &get_servers($mdom);
 1585:         %servers = (%currservers,%server);
 1586:     }
 1587:     my %by_hostname;
 1588:     foreach my $id (keys(%servers)) {
 1589:         push(@{$by_hostname{$servers{$id}}},$id);
 1590:     }
 1591:     foreach my $hostname (sort(keys(%by_hostname))) {
 1592:         if (@{$by_hostname{$hostname}} > 1) {
 1593:             my $match = 0;
 1594:             foreach my $id (@{$by_hostname{$hostname}}) {
 1595:                 if (&host_domain($id) eq $dom) {
 1596:                     $uniqservers{$id} = $hostname;
 1597:                     $match = 1;
 1598:                 }
 1599:             }
 1600:             unless ($match) {
 1601:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1602:             }
 1603:         } else {
 1604:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1605:         }
 1606:     }
 1607:     return %uniqservers;
 1608: }
 1609: 
 1610: sub trusted_domains {
 1611:     my ($cmdtype,$calldom) = @_;
 1612:     my ($trusted,$untrusted);
 1613:     if (&domain($calldom) eq '') {
 1614:         return ($trusted,$untrusted);
 1615:     }
 1616:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|domroles|catalog|reqcrs|msg)$/) {
 1617:         return ($trusted,$untrusted);
 1618:     }
 1619:     my $callprimary = &domain($calldom,'primary');
 1620:     my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
 1621:     if ($intcalldom eq '') {
 1622:         return ($trusted,$untrusted);
 1623:     }
 1624: 
 1625:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
 1626:     unless (defined($cached)) {
 1627:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
 1628:         &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
 1629:         $trustconfig = $domconfig{'trust'};
 1630:     }
 1631:     if (ref($trustconfig)) {
 1632:         my (%possexc,%possinc,@allexc,@allinc); 
 1633:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
 1634:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
 1635:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
 1636:             }
 1637:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
 1638:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
 1639:             }
 1640:         }
 1641:         if (keys(%possexc)) {
 1642:             if (keys(%possinc)) {
 1643:                 foreach my $key (sort(keys(%possexc))) {
 1644:                     next if ($key eq $intcalldom);
 1645:                     unless ($possinc{$key}) {
 1646:                         push(@allexc,$key);
 1647:                     }
 1648:                 }
 1649:             } else {
 1650:                 @allexc = sort(keys(%possexc));
 1651:             }
 1652:         }
 1653:         if (keys(%possinc)) {
 1654:             $possinc{$intcalldom} = 1;
 1655:             @allinc = sort(keys(%possinc));
 1656:         }
 1657:         if ((@allexc > 0) || (@allinc > 0)) {
 1658:             my %doms_by_intdom;
 1659:             my %allintdoms = &all_host_intdom();
 1660:             my %alldoms = &all_host_domain();
 1661:             foreach my $key (%allintdoms) {
 1662:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
 1663:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
 1664:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
 1665:                     }
 1666:                 } else {
 1667:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
 1668:                 }
 1669:             }
 1670:             foreach my $exc (@allexc) {
 1671:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
 1672:                     $untrusted = $doms_by_intdom{$exc};
 1673:                 }
 1674:             }
 1675:             foreach my $inc (@allinc) {
 1676:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
 1677:                     $trusted = $doms_by_intdom{$inc};
 1678:                 }
 1679:             }
 1680:         }
 1681:     }
 1682:     return ($trusted,$untrusted);
 1683: }
 1684: 
 1685: sub will_trust {
 1686:     my ($cmdtype,$domain,$possdom) = @_;
 1687:     return 1 if ($domain eq $possdom);
 1688:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
 1689:     my $willtrust; 
 1690:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
 1691:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
 1692:             $willtrust = 1;
 1693:         }
 1694:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
 1695:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
 1696:             $willtrust = 1;
 1697:         }
 1698:     } else {
 1699:         $willtrust = 1;
 1700:     }
 1701:     return $willtrust;
 1702: }
 1703: 
 1704: # ---------------------- Find the homebase for a user from domain's lib servers
 1705: 
 1706: my %homecache;
 1707: sub homeserver {
 1708:     my ($uname,$udom,$ignoreBadCache)=@_;
 1709:     my $index="$uname:$udom";
 1710: 
 1711:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1712: 
 1713:     my %servers = &get_servers($udom,'library');
 1714:     foreach my $tryserver (keys(%servers)) {
 1715:         next if ($ignoreBadCache ne 'true' && 
 1716: 		 exists($badServerCache{$tryserver}));
 1717: 
 1718: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1719: 	if ($answer eq 'found') {
 1720: 	    delete($badServerCache{$tryserver}); 
 1721: 	    return $homecache{$index}=$tryserver;
 1722: 	} elsif ($answer eq 'no_host') {
 1723: 	    $badServerCache{$tryserver}=1;
 1724: 	}
 1725:     }    
 1726:     return 'no_host';
 1727: }
 1728: 
 1729: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
 1730: 
 1731: sub idget {
 1732:     my ($udom,$idsref,$namespace)=@_;
 1733:     my %returnhash=();
 1734:     my @ids=(); 
 1735:     if (ref($idsref) eq 'ARRAY') {
 1736:         @ids = @{$idsref};
 1737:     } else {
 1738:         return %returnhash; 
 1739:     }
 1740:     if ($namespace eq '') {
 1741:         $namespace = 'ids';
 1742:     }
 1743:     
 1744:     my %servers = &get_servers($udom,'library');
 1745:     foreach my $tryserver (keys(%servers)) {
 1746: 	my $idlist=join('&', map { &escape($_); } @ids);
 1747: 	if ($namespace eq 'ids') {
 1748: 	    $idlist=~tr/A-Z/a-z/;
 1749: 	}
 1750: 	my $reply;
 1751: 	if ($namespace eq 'ids') {
 1752: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1753: 	} else {
 1754: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
 1755: 	}
 1756: 	my @answer=();
 1757: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1758: 	    @answer=split(/\&/,$reply);
 1759: 	}                    ;
 1760: 	my $i;
 1761: 	for ($i=0;$i<=$#ids;$i++) {
 1762: 	    if ($answer[$i]) {
 1763: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
 1764: 	    }
 1765: 	}
 1766:     }
 1767:     return %returnhash;
 1768: }
 1769: 
 1770: # ------------------------------------- Find the IDs behind a list of usernames
 1771: 
 1772: sub idrget {
 1773:     my ($udom,@unames)=@_;
 1774:     my %returnhash=();
 1775:     foreach my $uname (@unames) {
 1776:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1777:     }
 1778:     return %returnhash;
 1779: }
 1780: 
 1781: # Store away a list of names and associated student/employee IDs or clicker IDs
 1782: 
 1783: sub idput {
 1784:     my ($udom,$idsref,$uhom,$namespace)=@_;
 1785:     my %servers=();
 1786:     my %ids=();
 1787:     my %byid = ();
 1788:     if (ref($idsref) eq 'HASH') {
 1789:         %ids=%{$idsref};
 1790:     }
 1791:     if ($namespace eq '') {
 1792:         $namespace = 'ids'; 
 1793:     }
 1794:     foreach my $uname (keys(%ids)) {
 1795: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1796:         if ($uhom eq '') {
 1797:             $uhom=&homeserver($uname,$udom);
 1798:         }
 1799:         if ($uhom ne 'no_host') {
 1800:             my $esc_unam=&escape($uname);
 1801:             if ($namespace eq 'ids') {
 1802:                 my $id=&escape($ids{$uname});
 1803:                 $id=~tr/A-Z/a-z/;
 1804:                 my $esc_unam=&escape($uname);
 1805:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
 1806:             } else {
 1807:                 my @currids = split(/,/,$ids{$uname});
 1808:                 foreach my $id (@currids) {
 1809:                     $byid{$uhom}{$id} .= $uname.',';
 1810:                 }
 1811:             }
 1812:         }
 1813:     }
 1814:     if ($namespace eq 'clickers') {
 1815:         foreach my $server (keys(%byid)) {
 1816:             if (ref($byid{$server}) eq 'HASH') {
 1817:                 foreach my $id (keys(%{$byid{$server}})) {
 1818:                     $byid{$server} =~ s/,$//;
 1819:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
 1820:                 }
 1821:             }
 1822:         }
 1823:     }
 1824:     foreach my $server (keys(%servers)) {
 1825:         $servers{$server} =~ s/\&$//;
 1826:         if ($namespace eq 'ids') {     
 1827:             &critical('idput:'.$udom.':'.$servers{$server},$server);
 1828:         } else {
 1829:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
 1830:         }
 1831:     }
 1832: }
 1833: 
 1834: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
 1835: 
 1836: sub iddel {
 1837:     my ($udom,$idshashref,$uhome,$namespace)=@_;
 1838:     my %result=();
 1839:     my %ids=();
 1840:     my %byid = ();
 1841:     if (ref($idshashref) eq 'HASH') {
 1842:         %ids=%{$idshashref};
 1843:     } else {
 1844:         return %result;
 1845:     }
 1846:     if ($namespace eq '') {
 1847:         $namespace = 'ids';
 1848:     }
 1849:     my %servers=();
 1850:     while (my ($id,$unamestr) = each(%ids)) {
 1851:         if ($namespace eq 'ids') {
 1852:             my $uhom = $uhome;
 1853:             if ($uhom eq '') { 
 1854:                 $uhom=&homeserver($unamestr,$udom);
 1855:             }
 1856:             if ($uhom ne 'no_host') {
 1857:                 $servers{$uhom}.='&'.&escape($id);
 1858:             }
 1859:          } else {
 1860:             my @curritems = split(/,/,$ids{$id});
 1861:             foreach my $uname (@curritems) {
 1862:                 my $uhom = $uhome;
 1863:                 if ($uhom eq '') {
 1864:                     $uhom=&homeserver($uname,$udom);
 1865:                 }
 1866:                 if ($uhom ne 'no_host') { 
 1867:                     $byid{$uhom}{$id} .= $uname.',';
 1868:                 }
 1869:             }
 1870:         }
 1871:     }
 1872:     if ($namespace eq 'clickers') {
 1873:         foreach my $server (keys(%byid)) {
 1874:             if (ref($byid{$server}) eq 'HASH') {
 1875:                 foreach my $id (keys(%{$byid{$server}})) {
 1876:                     $byid{$server}{$id} =~ s/,$//;
 1877:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
 1878:                 }
 1879:             }
 1880:         }
 1881:     }
 1882:     foreach my $server (keys(%servers)) {
 1883:         $servers{$server} =~ s/\&$//;
 1884:         if ($namespace eq 'ids') {
 1885:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
 1886:         } elsif ($namespace eq 'clickers') {
 1887:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
 1888:         }
 1889:     }
 1890:     return %result;
 1891: }
 1892: 
 1893: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
 1894: 
 1895: sub updateclickers {
 1896:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
 1897:     my %clickers;
 1898:     if (ref($idshashref) eq 'HASH') {
 1899:         %clickers=%{$idshashref};
 1900:     } else {
 1901:         return;
 1902:     }
 1903:     my $items='';
 1904:     foreach my $item (keys(%clickers)) {
 1905:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
 1906:     }
 1907:     $items=~s/\&$//;
 1908:     my $request = "updateclickers:$udom:$action:$items";
 1909:     if ($critical) {
 1910:         return &critical($request,$uhome);
 1911:     } else {
 1912:         return &reply($request,$uhome);
 1913:     }
 1914: }
 1915: 
 1916: # ------------------------------dump from db file owned by domainconfig user
 1917: sub dump_dom {
 1918:     my ($namespace, $udom, $regexp) = @_;
 1919: 
 1920:     $udom ||= $env{'user.domain'};
 1921: 
 1922:     return () unless $udom;
 1923: 
 1924:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 1925: }
 1926: 
 1927: # ------------------------------------------ get items from domain db files   
 1928: 
 1929: sub get_dom {
 1930:     my ($namespace,$storearr,$udom,$uhome)=@_;
 1931:     return if ($udom eq 'public');
 1932:     my $items='';
 1933:     foreach my $item (@$storearr) {
 1934:         $items.=&escape($item).'&';
 1935:     }
 1936:     $items=~s/\&$//;
 1937:     if (!$udom) {
 1938:         $udom=$env{'user.domain'};
 1939:         return if ($udom eq 'public');
 1940:         if (defined(&domain($udom,'primary'))) {
 1941:             $uhome=&domain($udom,'primary');
 1942:         } else {
 1943:             undef($uhome);
 1944:         }
 1945:     } else {
 1946:         if (!$uhome) {
 1947:             if (defined(&domain($udom,'primary'))) {
 1948:                 $uhome=&domain($udom,'primary');
 1949:             }
 1950:         }
 1951:     }
 1952:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1953:         my $rep;
 1954:         if ($namespace =~ /^enc/) {
 1955:             $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
 1956:         } else {
 1957:             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 1958:         }
 1959:         my %returnhash;
 1960:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 1961:             return %returnhash;
 1962:         }
 1963:         my @pairs=split(/\&/,$rep);
 1964:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1965:             return @pairs;
 1966:         }
 1967:         my $i=0;
 1968:         foreach my $item (@$storearr) {
 1969:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 1970:             $i++;
 1971:         }
 1972:         return %returnhash;
 1973:     } else {
 1974:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1975:     }
 1976: }
 1977: 
 1978: # -------------------------------------------- put items in domain db files 
 1979: 
 1980: sub put_dom {
 1981:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1982:     if (!$udom) {
 1983:         $udom=$env{'user.domain'};
 1984:         if (defined(&domain($udom,'primary'))) {
 1985:             $uhome=&domain($udom,'primary');
 1986:         } else {
 1987:             undef($uhome);
 1988:         }
 1989:     } else {
 1990:         if (!$uhome) {
 1991:             if (defined(&domain($udom,'primary'))) {
 1992:                 $uhome=&domain($udom,'primary');
 1993:             }
 1994:         }
 1995:     } 
 1996:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1997:         my $items='';
 1998:         foreach my $item (keys(%$storehash)) {
 1999:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 2000:         }
 2001:         $items=~s/\&$//;
 2002:         if ($namespace =~ /^enc/) {
 2003:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
 2004:         } else {
 2005:             return &reply("putdom:$udom:$namespace:$items",$uhome);
 2006:         }
 2007:     } else {
 2008:         &logthis("put_dom failed - no homeserver and/or domain");
 2009:     }
 2010: }
 2011: 
 2012: # --------------------- newput for items in db file owned by domainconfig user
 2013: sub newput_dom {
 2014:     my ($namespace,$storehash,$udom) = @_;
 2015:     my $result;
 2016:     if (!$udom) {
 2017:         $udom=$env{'user.domain'};
 2018:     }
 2019:     if ($udom) {
 2020:         my $uname = &get_domainconfiguser($udom);
 2021:         $result = &newput($namespace,$storehash,$udom,$uname);
 2022:     }
 2023:     return $result;
 2024: }
 2025: 
 2026: # --------------------- delete for items in db file owned by domainconfig user
 2027: sub del_dom {
 2028:     my ($namespace,$storearr,$udom)=@_;
 2029:     if (ref($storearr) eq 'ARRAY') {
 2030:         if (!$udom) {
 2031:             $udom=$env{'user.domain'};
 2032:         }
 2033:         if ($udom) {
 2034:             my $uname = &get_domainconfiguser($udom); 
 2035:             return &del($namespace,$storearr,$udom,$uname);
 2036:         }
 2037:     }
 2038: }
 2039: 
 2040: # ----------------------------------construct domainconfig user for a domain 
 2041: sub get_domainconfiguser {
 2042:     my ($udom) = @_;
 2043:     return $udom.'-domainconfig';
 2044: }
 2045: 
 2046: sub retrieve_inst_usertypes {
 2047:     my ($udom) = @_;
 2048:     my (%returnhash,@order);
 2049:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 2050:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 2051:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 2052:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
 2053:     } else {
 2054:         if (defined(&domain($udom,'primary'))) {
 2055:             my $uhome=&domain($udom,'primary');
 2056:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 2057:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 2058:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
 2059:                 return (\%returnhash,\@order);
 2060:             }
 2061:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 2062:             my @pairs=split(/\&/,$hashitems);
 2063:             foreach my $item (@pairs) {
 2064:                 my ($key,$value)=split(/=/,$item,2);
 2065:                 $key = &unescape($key);
 2066:                 next if ($key =~ /^error: 2 /);
 2067:                 $returnhash{$key}=&thaw_unescape($value);
 2068:             }
 2069:             my @esc_order = split(/\&/,$orderitems);
 2070:             foreach my $item (@esc_order) {
 2071:                 push(@order,&unescape($item));
 2072:             }
 2073:         } else {
 2074:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
 2075:         }
 2076:         return (\%returnhash,\@order);
 2077:     }
 2078: }
 2079: 
 2080: sub is_domainimage {
 2081:     my ($url) = @_;
 2082:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
 2083:         if (&domain($1) ne '') {
 2084:             return '1';
 2085:         }
 2086:     }
 2087:     return;
 2088: }
 2089: 
 2090: sub inst_directory_query {
 2091:     my ($srch) = @_;
 2092:     my $udom = $srch->{'srchdomain'};
 2093:     my %results;
 2094:     my $homeserver = &domain($udom,'primary');
 2095:     my $outcome;
 2096:     if ($homeserver ne '') {
 2097:         unless ($homeserver eq $perlvar{'lonHostID'}) {
 2098:             if ($srch->{'srchby'} eq 'email') {
 2099:                 my $lcrev = &get_server_loncaparev(undef,$homeserver);
 2100:                 my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2101:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
 2102:                     (($major == 2) && ($minor < 12))) {
 2103:                     return;
 2104:                 }
 2105:             }
 2106:         }
 2107: 	my $queryid=&reply("querysend:instdirsearch:".
 2108: 			   &escape($srch->{'srchby'}).':'.
 2109: 			   &escape($srch->{'srchterm'}).':'.
 2110: 			   &escape($srch->{'srchtype'}),$homeserver);
 2111: 	my $host=&hostname($homeserver);
 2112: 	if ($queryid !~/^\Q$host\E\_/) {
 2113: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
 2114: 	    return;
 2115: 	}
 2116: 	my $response = &get_query_reply($queryid);
 2117: 	my $maxtries = 5;
 2118: 	my $tries = 1;
 2119: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2120: 	    $response = &get_query_reply($queryid);
 2121: 	    $tries ++;
 2122: 	}
 2123: 
 2124:         if (!&error($response) && $response ne 'refused') {
 2125:             if ($response eq 'unavailable') {
 2126:                 $outcome = $response;
 2127:             } else {
 2128:                 $outcome = 'ok';
 2129:                 my @matches = split(/\n/,$response);
 2130:                 foreach my $match (@matches) {
 2131:                     my ($key,$value) = split(/=/,$match);
 2132:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 2133:                 }
 2134:             }
 2135:         }
 2136:     }
 2137:     return ($outcome,%results);
 2138: }
 2139: 
 2140: sub usersearch {
 2141:     my ($srch) = @_;
 2142:     my $dom = $srch->{'srchdomain'};
 2143:     my %results;
 2144:     my %libserv = &all_library();
 2145:     my $query = 'usersearch';
 2146:     foreach my $tryserver (keys(%libserv)) {
 2147:         if (&host_domain($tryserver) eq $dom) {
 2148:             unless ($tryserver eq $perlvar{'lonHostID'}) {
 2149:                 if ($srch->{'srchby'} eq 'email') {
 2150:                     my $lcrev = &get_server_loncaparev(undef,$tryserver);
 2151:                     my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
 2152:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
 2153:                              (($major == 2) && ($minor < 12)));
 2154:                 }
 2155:             }
 2156:             my $host=&hostname($tryserver);
 2157:             my $queryid=
 2158:                 &reply("querysend:".&escape($query).':'.
 2159:                        &escape($srch->{'srchby'}).':'.
 2160:                        &escape($srch->{'srchtype'}).':'.
 2161:                        &escape($srch->{'srchterm'}),$tryserver);
 2162:             if ($queryid !~/^\Q$host\E\_/) {
 2163:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 2164:                 next;
 2165:             }
 2166:             my $reply = &get_query_reply($queryid);
 2167:             my $maxtries = 1;
 2168:             my $tries = 1;
 2169:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 2170:                 $reply = &get_query_reply($queryid);
 2171:                 $tries ++;
 2172:             }
 2173:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 2174:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 2175:             } else {
 2176:                 my @matches;
 2177:                 if ($reply =~ /\n/) {
 2178:                     @matches = split(/\n/,$reply);
 2179:                 } else {
 2180:                     @matches = split(/\&/,$reply);
 2181:                 }
 2182:                 foreach my $match (@matches) {
 2183:                     my ($uname,$udom,%userhash);
 2184:                     foreach my $entry (split(/:/,$match)) {
 2185:                         my ($key,$value) =
 2186:                             map {&unescape($_);} split(/=/,$entry);
 2187:                         $userhash{$key} = $value;
 2188:                         if ($key eq 'username') {
 2189:                             $uname = $value;
 2190:                         } elsif ($key eq 'domain') {
 2191:                             $udom = $value;
 2192:                         }
 2193:                     }
 2194:                     $results{$uname.':'.$udom} = \%userhash;
 2195:                 }
 2196:             }
 2197:         }
 2198:     }
 2199:     return %results;
 2200: }
 2201: 
 2202: sub get_instuser {
 2203:     my ($udom,$uname,$id) = @_;
 2204:     my $homeserver = &domain($udom,'primary');
 2205:     my ($outcome,%results);
 2206:     if ($homeserver ne '') {
 2207:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 2208:                            &escape($id).':'.&escape($udom),$homeserver);
 2209:         my $host=&hostname($homeserver);
 2210:         if ($queryid !~/^\Q$host\E\_/) {
 2211:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 2212:             return;
 2213:         }
 2214:         my $response = &get_query_reply($queryid);
 2215:         my $maxtries = 5;
 2216:         my $tries = 1;
 2217:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 2218:             $response = &get_query_reply($queryid);
 2219:             $tries ++;
 2220:         }
 2221:         if (!&error($response) && $response ne 'refused') {
 2222:             if ($response eq 'unavailable') {
 2223:                 $outcome = $response;
 2224:             } else {
 2225:                 $outcome = 'ok';
 2226:                 my @matches = split(/\n/,$response);
 2227:                 foreach my $match (@matches) {
 2228:                     my ($key,$value) = split(/=/,$match);
 2229:                     $results{&unescape($key)} = &thaw_unescape($value);
 2230:                 }
 2231:             }
 2232:         }
 2233:     }
 2234:     my %userinfo;
 2235:     if (ref($results{$uname}) eq 'HASH') {
 2236:         %userinfo = %{$results{$uname}};
 2237:     } 
 2238:     return ($outcome,%userinfo);
 2239: }
 2240: 
 2241: sub get_multiple_instusers {
 2242:     my ($udom,$users,$caller) = @_;
 2243:     my ($outcome,$results);
 2244:     if (ref($users) eq 'HASH') {
 2245:         my $count = keys(%{$users}); 
 2246:         my $requested = &freeze_escape($users);
 2247:         my $homeserver = &domain($udom,'primary');
 2248:         if ($homeserver ne '') {
 2249:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
 2250:             my $host=&hostname($homeserver);
 2251:             if ($queryid !~/^\Q$host\E\_/) {
 2252:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
 2253:                          ' for host: '.$homeserver.'in domain '.$udom);
 2254:                 return ($outcome,$results);
 2255:             }
 2256:             my $response = &get_query_reply($queryid);
 2257:             my $maxtries = 5;
 2258:             if ($count > 100) {
 2259:                 $maxtries = 1+int($count/20);
 2260:             }
 2261:             my $tries = 1;
 2262:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
 2263:                 $response = &get_query_reply($queryid);
 2264:                 $tries ++;
 2265:             }
 2266:             if ($response eq '') {
 2267:                 $results = {};
 2268:                 foreach my $key (keys(%{$users})) {
 2269:                     my ($uname,$id);
 2270:                     if ($caller eq 'id') {
 2271:                         $id = $key;
 2272:                     } else {
 2273:                         $uname = $key;
 2274:                     }
 2275:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
 2276:                     $outcome = $resp;
 2277:                     if ($resp eq 'ok') {
 2278:                         %{$results} = (%{$results}, %info);
 2279:                     } else {
 2280:                         last;
 2281:                     }
 2282:                 }
 2283:             } elsif(!&error($response) && ($response ne 'refused')) {
 2284:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
 2285:                     $outcome = $response;
 2286:                 } else {
 2287:                     ($outcome,my $userdata) = split(/=/,$response,2);
 2288:                     if ($outcome eq 'ok') {
 2289:                         $results = &thaw_unescape($userdata); 
 2290:                     }
 2291:                 }
 2292:             }
 2293:         }
 2294:     }
 2295:     return ($outcome,$results);
 2296: }
 2297: 
 2298: sub inst_rulecheck {
 2299:     my ($udom,$uname,$id,$item,$rules) = @_;
 2300:     my %returnhash;
 2301:     if ($udom ne '') {
 2302:         if (ref($rules) eq 'ARRAY') {
 2303:             @{$rules} = map {&escape($_);} (@{$rules});
 2304:             my $rulestr = join(':',@{$rules});
 2305:             my $homeserver=&domain($udom,'primary');
 2306:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2307:                 my $response;
 2308:                 if ($item eq 'username') {                
 2309:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 2310:                                               ':'.&escape($uname).':'.$rulestr,
 2311:                                               $homeserver));
 2312:                 } elsif ($item eq 'id') {
 2313:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 2314:                                               ':'.&escape($id).':'.$rulestr,
 2315:                                               $homeserver));
 2316:                 } elsif ($item eq 'selfcreate') {
 2317:                     $response=&unescape(&reply('instselfcreatecheck:'.
 2318:                                                &escape($udom).':'.&escape($uname).
 2319:                                               ':'.$rulestr,$homeserver));
 2320:                 }
 2321:                 if ($response ne 'refused') {
 2322:                     my @pairs=split(/\&/,$response);
 2323:                     foreach my $item (@pairs) {
 2324:                         my ($key,$value)=split(/=/,$item,2);
 2325:                         $key = &unescape($key);
 2326:                         next if ($key =~ /^error: 2 /);
 2327:                         $returnhash{$key}=&thaw_unescape($value);
 2328:                     }
 2329:                 }
 2330:             }
 2331:         }
 2332:     }
 2333:     return %returnhash;
 2334: }
 2335: 
 2336: sub inst_userrules {
 2337:     my ($udom,$check) = @_;
 2338:     my (%ruleshash,@ruleorder);
 2339:     if ($udom ne '') {
 2340:         my $homeserver=&domain($udom,'primary');
 2341:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2342:             my $response;
 2343:             if ($check eq 'id') {
 2344:                 $response=&reply('instidrules:'.&escape($udom),
 2345:                                  $homeserver);
 2346:             } elsif ($check eq 'email') {
 2347:                 $response=&reply('instemailrules:'.&escape($udom),
 2348:                                  $homeserver);
 2349:             } else {
 2350:                 $response=&reply('instuserrules:'.&escape($udom),
 2351:                                  $homeserver);
 2352:             }
 2353:             if (($response ne 'refused') && ($response ne 'error') && 
 2354:                 ($response ne 'unknown_cmd') && 
 2355:                 ($response ne 'no_such_host')) {
 2356:                 my ($hashitems,$orderitems) = split(/:/,$response);
 2357:                 my @pairs=split(/\&/,$hashitems);
 2358:                 foreach my $item (@pairs) {
 2359:                     my ($key,$value)=split(/=/,$item,2);
 2360:                     $key = &unescape($key);
 2361:                     next if ($key =~ /^error: 2 /);
 2362:                     $ruleshash{$key}=&thaw_unescape($value);
 2363:                 }
 2364:                 my @esc_order = split(/\&/,$orderitems);
 2365:                 foreach my $item (@esc_order) {
 2366:                     push(@ruleorder,&unescape($item));
 2367:                 }
 2368:             }
 2369:         }
 2370:     }
 2371:     return (\%ruleshash,\@ruleorder);
 2372: }
 2373: 
 2374: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 2375: 
 2376: sub get_domain_defaults {
 2377:     my ($domain,$ignore_cache) = @_;
 2378:     return if (($domain eq '') || ($domain eq 'public'));
 2379:     my $cachetime = 60*60*24;
 2380:     unless ($ignore_cache) {
 2381:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 2382:         if (defined($cached)) {
 2383:             if (ref($result) eq 'HASH') {
 2384:                 return %{$result};
 2385:             }
 2386:         }
 2387:     }
 2388:     my %domdefaults;
 2389:     my %domconfig =
 2390:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 2391:                                   'requestcourses','inststatus',
 2392:                                   'coursedefaults','usersessions',
 2393:                                   'requestauthor','selfenrollment',
 2394:                                   'coursecategories','ssl','autoenroll',
 2395:                                   'trust','helpsettings'],$domain);
 2396:     my @coursetypes = ('official','unofficial','community','textbook','placement');
 2397:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2398:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2399:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2400:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2401:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2402:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2403:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2404:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
 2405:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
 2406:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
 2407:     } else {
 2408:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2409:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2410:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2411:     }
 2412:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2413:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2414:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2415:         } else {
 2416:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2417:         }
 2418:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2419:         foreach my $item (@usertools) {
 2420:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2421:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2422:             }
 2423:         }
 2424:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2425:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2426:         }
 2427:     }
 2428:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2429:         foreach my $item ('official','unofficial','community','textbook','placement') {
 2430:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2431:         }
 2432:     }
 2433:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2434:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2435:     }
 2436:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2437:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
 2438:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2439:         }
 2440:     }
 2441:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2442:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
 2443:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
 2444:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
 2445:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
 2446:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
 2447:         }
 2448:         foreach my $type (@coursetypes) {
 2449:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2450:                 unless ($type eq 'community') {
 2451:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
 2452:                 }
 2453:             }
 2454:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2455:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
 2456:             }
 2457:             if ($domdefaults{'postsubmit'} eq 'on') {
 2458:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
 2459:                     $domdefaults{$type.'postsubtimeout'} = 
 2460:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
 2461:                 }
 2462:             }
 2463:         }
 2464:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
 2465:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
 2466:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
 2467:                 if (@clonecodes) {
 2468:                     $domdefaults{'canclone'} = join('+',@clonecodes);
 2469:                 }
 2470:             }
 2471:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
 2472:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
 2473:         }
 2474:         if ($domconfig{'coursedefaults'}{'texengine'}) {
 2475:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
 2476:         } 
 2477:     }
 2478:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2479:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2480:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2481:         }
 2482:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2483:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2484:         }
 2485:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
 2486:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
 2487:         }
 2488:     }
 2489:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
 2490:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
 2491:             my @settings = ('types','registered','enroll_dates','access_dates','section',
 2492:                             'approval','limit');
 2493:             foreach my $type (@coursetypes) {
 2494:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
 2495:                     my @mgrdc = ();
 2496:                     foreach my $item (@settings) {
 2497:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
 2498:                             push(@mgrdc,$item);
 2499:                         }
 2500:                     }
 2501:                     if (@mgrdc) {
 2502:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
 2503:                     }
 2504:                 }
 2505:             }
 2506:         }
 2507:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
 2508:             foreach my $type (@coursetypes) {
 2509:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
 2510:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
 2511:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
 2512:                     }
 2513:                 }
 2514:             }
 2515:         }
 2516:     }
 2517:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2518:         $domdefaults{'catauth'} = 'std';
 2519:         $domdefaults{'catunauth'} = 'std';
 2520:         if ($domconfig{'coursecategories'}{'auth'}) { 
 2521:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
 2522:         }
 2523:         if ($domconfig{'coursecategories'}{'unauth'}) {
 2524:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
 2525:         }
 2526:     }
 2527:     if (ref($domconfig{'ssl'}) eq 'HASH') {
 2528:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
 2529:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
 2530:         }
 2531:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
 2532:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
 2533:         }
 2534:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
 2535:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
 2536:         }
 2537:     }
 2538:     if (ref($domconfig{'trust'}) eq 'HASH') {
 2539:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
 2540:         foreach my $prefix (@prefixes) {
 2541:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
 2542:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
 2543:             }
 2544:         }
 2545:     }
 2546:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 2547:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
 2548:     }
 2549:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
 2550:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
 2551:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
 2552:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
 2553:         }
 2554:     }
 2555:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2556:     return %domdefaults;
 2557: }
 2558: 
 2559: sub course_portal_url {
 2560:     my ($cnum,$cdom) = @_;
 2561:     my $chome = &homeserver($cnum,$cdom);
 2562:     my $hostname = &hostname($chome);
 2563:     my $protocol = $protocol{$chome};
 2564:     $protocol = 'http' if ($protocol ne 'https');
 2565:     my %domdefaults = &get_domain_defaults($cdom);
 2566:     my $firsturl;
 2567:     if ($domdefaults{'portal_def'}) {
 2568:         $firsturl = $domdefaults{'portal_def'};
 2569:     } else {
 2570:         $firsturl = $protocol.'://'.$hostname;
 2571:     }
 2572:     return $firsturl;
 2573: }
 2574: 
 2575: # --------------------------------------------------- Assign a key to a student
 2576: 
 2577: sub assign_access_key {
 2578: #
 2579: # a valid key looks like uname:udom#comments
 2580: # comments are being appended
 2581: #
 2582:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2583:     $kdom=
 2584:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2585:     $knum=
 2586:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2587:     $cdom=
 2588:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2589:     $cnum=
 2590:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2591:     $udom=$env{'user.name'} unless (defined($udom));
 2592:     $uname=$env{'user.domain'} unless (defined($uname));
 2593:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2594:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2595:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2596:                                                   # assigned to this person
 2597:                                                   # - this should not happen,
 2598:                                                   # unless something went wrong
 2599:                                                   # the first time around
 2600: # ready to assign
 2601:         $logentry=$1.'; '.$logentry;
 2602:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2603:                                                  $kdom,$knum) eq 'ok') {
 2604: # key now belongs to user
 2605: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2606:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2607:                 &appenv({'environment.'.$envkey => $ckey});
 2608:                 return 'ok';
 2609:             } else {
 2610:                 return 
 2611:   'error: Count not permanently assign key, will need to be re-entered later.';
 2612: 	    }
 2613:         } else {
 2614:             return 'error: Could not assign key, try again later.';
 2615:         }
 2616:     } elsif (!$existing{$ckey}) {
 2617: # the key does not exist
 2618: 	return 'error: The key does not exist';
 2619:     } else {
 2620: # the key is somebody else's
 2621: 	return 'error: The key is already in use';
 2622:     }
 2623: }
 2624: 
 2625: # ------------------------------------------ put an additional comment on a key
 2626: 
 2627: sub comment_access_key {
 2628: #
 2629: # a valid key looks like uname:udom#comments
 2630: # comments are being appended
 2631: #
 2632:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2633:     $cdom=
 2634:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2635:     $cnum=
 2636:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2637:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2638:     if ($existing{$ckey}) {
 2639:         $existing{$ckey}.='; '.$logentry;
 2640: # ready to assign
 2641:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2642:                                                  $cdom,$cnum) eq 'ok') {
 2643: 	    return 'ok';
 2644:         } else {
 2645: 	    return 'error: Count not store comment.';
 2646:         }
 2647:     } else {
 2648: # the key does not exist
 2649: 	return 'error: The key does not exist';
 2650:     }
 2651: }
 2652: 
 2653: # ------------------------------------------------------ Generate a set of keys
 2654: 
 2655: sub generate_access_keys {
 2656:     my ($number,$cdom,$cnum,$logentry)=@_;
 2657:     $cdom=
 2658:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2659:     $cnum=
 2660:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2661:     unless (&allowed('mky',$cdom)) { return 0; }
 2662:     unless (($cdom) && ($cnum)) { return 0; }
 2663:     if ($number>10000) { return 0; }
 2664:     sleep(2); # make sure don't get same seed twice
 2665:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2666:     my $total=0;
 2667:     for (my $i=1;$i<=$number;$i++) {
 2668:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2669:                   sprintf("%lx",int(100000*rand)).'-'.
 2670:                   sprintf("%lx",int(100000*rand));
 2671:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2672:        $newkey=~s/0/h/g; # and also 0 and O
 2673:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2674:        if ($existing{$newkey}) {
 2675:            $i--;
 2676:        } else {
 2677: 	  if (&put('accesskeys',
 2678:               { $newkey => '# generated '.localtime().
 2679:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2680:                            '; '.$logentry },
 2681: 		   $cdom,$cnum) eq 'ok') {
 2682:               $total++;
 2683: 	  }
 2684:        }
 2685:     }
 2686:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2687:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2688:     return $total;
 2689: }
 2690: 
 2691: # ------------------------------------------------------- Validate an accesskey
 2692: 
 2693: sub validate_access_key {
 2694:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2695:     $cdom=
 2696:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2697:     $cnum=
 2698:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2699:     $udom=$env{'user.domain'} unless (defined($udom));
 2700:     $uname=$env{'user.name'} unless (defined($uname));
 2701:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2702:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2703: }
 2704: 
 2705: # ------------------------------------- Find the section of student in a course
 2706: sub devalidate_getsection_cache {
 2707:     my ($udom,$unam,$courseid)=@_;
 2708:     my $hashid="$udom:$unam:$courseid";
 2709:     &devalidate_cache_new('getsection',$hashid);
 2710: }
 2711: 
 2712: sub courseid_to_courseurl {
 2713:     my ($courseid) = @_;
 2714:     #already url style courseid
 2715:     return $courseid if ($courseid =~ m{^/});
 2716: 
 2717:     if (exists($env{'course.'.$courseid.'.num'})) {
 2718: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2719: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2720: 	return "/$cdom/$cnum";
 2721:     }
 2722: 
 2723:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2724:     if (exists($courseinfo{'num'})) {
 2725: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2726:     }
 2727: 
 2728:     return undef;
 2729: }
 2730: 
 2731: sub getsection {
 2732:     my ($udom,$unam,$courseid)=@_;
 2733:     my $cachetime=1800;
 2734: 
 2735:     my $hashid="$udom:$unam:$courseid";
 2736:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2737:     if (defined($cached)) { return $result; }
 2738: 
 2739:     my %Pending; 
 2740:     my %Expired;
 2741:     #
 2742:     # Each role can either have not started yet (pending), be active, 
 2743:     #    or have expired.
 2744:     #
 2745:     # If there is an active role, we are done.
 2746:     #
 2747:     # If there is more than one role which has not started yet, 
 2748:     #     choose the one which will start sooner
 2749:     # If there is one role which has not started yet, return it.
 2750:     #
 2751:     # If there is more than one expired role, choose the one which ended last.
 2752:     # If there is a role which has expired, return it.
 2753:     #
 2754:     $courseid = &courseid_to_courseurl($courseid);
 2755:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 2756:     foreach my $key (keys(%roleshash)) {
 2757:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2758:         my $section=$1;
 2759:         if ($key eq $courseid.'_st') { $section=''; }
 2760:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2761:         my $now=time;
 2762:         if (defined($end) && $end && ($now > $end)) {
 2763:             $Expired{$end}=$section;
 2764:             next;
 2765:         }
 2766:         if (defined($start) && $start && ($now < $start)) {
 2767:             $Pending{$start}=$section;
 2768:             next;
 2769:         }
 2770:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2771:     }
 2772:     #
 2773:     # Presumedly there will be few matching roles from the above
 2774:     # loop and the sorting time will be negligible.
 2775:     if (scalar(keys(%Pending))) {
 2776:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2777:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2778:     } 
 2779:     if (scalar(keys(%Expired))) {
 2780:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2781:         my $time = pop(@sorted);
 2782:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2783:     }
 2784:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2785: }
 2786: 
 2787: sub save_cache {
 2788:     &purge_remembered();
 2789:     #&Apache::loncommon::validate_page();
 2790:     undef(%env);
 2791:     undef($env_loaded);
 2792: }
 2793: 
 2794: my $to_remember=-1;
 2795: my %remembered;
 2796: my %accessed;
 2797: my $kicks=0;
 2798: my $hits=0;
 2799: sub make_key {
 2800:     my ($name,$id) = @_;
 2801:     if (length($id) > 65 
 2802: 	&& length(&escape($id)) > 200) {
 2803: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2804:     }
 2805:     return &escape($name.':'.$id);
 2806: }
 2807: 
 2808: sub devalidate_cache_new {
 2809:     my ($name,$id,$debug) = @_;
 2810:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2811:     my $remembered_id=$name.':'.$id;
 2812:     $id=&make_key($name,$id);
 2813:     $memcache->delete($id);
 2814:     delete($remembered{$remembered_id});
 2815:     delete($accessed{$remembered_id});
 2816: }
 2817: 
 2818: sub is_cached_new {
 2819:     my ($name,$id,$debug) = @_;
 2820:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
 2821:     if (exists($remembered{$remembered_id})) {
 2822: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
 2823: 	$accessed{$remembered_id}=[&gettimeofday()];
 2824: 	$hits++;
 2825: 	return ($remembered{$remembered_id},1);
 2826:     }
 2827:     $id=&make_key($name,$id);
 2828:     my $value = $memcache->get($id);
 2829:     if (!(defined($value))) {
 2830: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2831: 	return (undef,undef);
 2832:     }
 2833:     if ($value eq '__undef__') {
 2834: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2835: 	$value=undef;
 2836:     }
 2837:     &make_room($remembered_id,$value,$debug);
 2838:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2839:     return ($value,1);
 2840: }
 2841: 
 2842: sub do_cache_new {
 2843:     my ($name,$id,$value,$time,$debug) = @_;
 2844:     my $remembered_id=$name.':'.$id;
 2845:     $id=&make_key($name,$id);
 2846:     my $setvalue=$value;
 2847:     if (!defined($setvalue)) {
 2848: 	$setvalue='__undef__';
 2849:     }
 2850:     if (!defined($time) ) {
 2851: 	$time=600;
 2852:     }
 2853:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 2854:     my $result = $memcache->set($id,$setvalue,$time);
 2855:     if (! $result) {
 2856: 	&logthis("caching of id -> $id  failed");
 2857: 	$memcache->disconnect_all();
 2858:     }
 2859:     # need to make a copy of $value
 2860:     &make_room($remembered_id,$value,$debug);
 2861:     return $value;
 2862: }
 2863: 
 2864: sub make_room {
 2865:     my ($remembered_id,$value,$debug)=@_;
 2866: 
 2867:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
 2868:                                     : $value;
 2869:     if ($to_remember<0) { return; }
 2870:     $accessed{$remembered_id}=[&gettimeofday()];
 2871:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 2872:     my $to_kick;
 2873:     my $max_time=0;
 2874:     foreach my $other (keys(%accessed)) {
 2875: 	if (&tv_interval($accessed{$other}) > $max_time) {
 2876: 	    $to_kick=$other;
 2877: 	    $max_time=&tv_interval($accessed{$other});
 2878: 	}
 2879:     }
 2880:     delete($remembered{$to_kick});
 2881:     delete($accessed{$to_kick});
 2882:     $kicks++;
 2883:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 2884:     return;
 2885: }
 2886: 
 2887: sub purge_remembered {
 2888:     #&logthis("Tossing ".scalar(keys(%remembered)));
 2889:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 2890:     undef(%remembered);
 2891:     undef(%accessed);
 2892: }
 2893: # ------------------------------------- Read an entry from a user's environment
 2894: 
 2895: sub userenvironment {
 2896:     my ($udom,$unam,@what)=@_;
 2897:     my $items;
 2898:     foreach my $item (@what) {
 2899:         $items.=&escape($item).'&';
 2900:     }
 2901:     $items=~s/\&$//;
 2902:     my %returnhash=();
 2903:     my $uhome = &homeserver($unam,$udom);
 2904:     unless ($uhome eq 'no_host') {
 2905:         my @answer=split(/\&/, 
 2906:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 2907:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 2908:             return %returnhash;
 2909:         }
 2910:         my $i;
 2911:         for ($i=0;$i<=$#what;$i++) {
 2912: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 2913:         }
 2914:     }
 2915:     return %returnhash;
 2916: }
 2917: 
 2918: # ---------------------------------------------------------- Get a studentphoto
 2919: sub studentphoto {
 2920:     my ($udom,$unam,$ext) = @_;
 2921:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2922:     if (defined($env{'request.course.id'})) {
 2923:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 2924:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 2925:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 2926:             } else {
 2927:                 my ($result,$perm_reqd)=
 2928: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2929:                 if ($result eq 'ok') {
 2930:                     if (!($perm_reqd eq 'yes')) {
 2931:                         return(&retrievestudentphoto($udom,$unam,$ext));
 2932:                     }
 2933:                 }
 2934:             }
 2935:         }
 2936:     } else {
 2937:         my ($result,$perm_reqd) = 
 2938: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2939:         if ($result eq 'ok') {
 2940:             if (!($perm_reqd eq 'yes')) {
 2941:                 return(&retrievestudentphoto($udom,$unam,$ext));
 2942:             }
 2943:         }
 2944:     }
 2945:     return '/adm/lonKaputt/lonlogo_broken.gif';
 2946: }
 2947: 
 2948: sub retrievestudentphoto {
 2949:     my ($udom,$unam,$ext,$type) = @_;
 2950:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2951:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 2952:     if ($ret eq 'ok') {
 2953:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 2954:         if ($type eq 'thumbnail') {
 2955:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 2956:         }
 2957:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 2958:         return $tokenurl;
 2959:     } else {
 2960:         if ($type eq 'thumbnail') {
 2961:             return '/adm/lonKaputt/genericstudent_tn.gif';
 2962:         } else { 
 2963:             return '/adm/lonKaputt/lonlogo_broken.gif';
 2964:         }
 2965:     }
 2966: }
 2967: 
 2968: # -------------------------------------------------------------------- New chat
 2969: 
 2970: sub chatsend {
 2971:     my ($newentry,$anon,$group)=@_;
 2972:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 2973:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2974:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 2975:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 2976: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 2977: 		   &escape($newentry)).':'.$group,$chome);
 2978: }
 2979: 
 2980: # ------------------------------------------ Find current version of a resource
 2981: 
 2982: sub getversion {
 2983:     my $fname=&clutter(shift);
 2984:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 2985:     return &currentversion(&filelocation('',$fname));
 2986: }
 2987: 
 2988: sub currentversion {
 2989:     my $fname=shift;
 2990:     my $author=$fname;
 2991:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2992:     my ($udom,$uname)=split(/\//,$author);
 2993:     my $home=&homeserver($uname,$udom);
 2994:     if ($home eq 'no_host') { 
 2995:         return -1; 
 2996:     }
 2997:     my $answer=&reply("currentversion:$fname",$home);
 2998:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2999: 	return -1;
 3000:     }
 3001:     return $answer;
 3002: }
 3003: 
 3004: #
 3005: # Return special version number of resource if set by override, empty otherwise
 3006: #
 3007: sub usedversion {
 3008:     my $fname=shift;
 3009:     unless ($fname) { $fname=$env{'request.uri'}; }
 3010:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 3011:     if ($urlversion) { return $urlversion; }
 3012:     return '';
 3013: }
 3014: 
 3015: # ----------------------------- Subscribe to a resource, return URL if possible
 3016: 
 3017: sub subscribe {
 3018:     my $fname=shift;
 3019:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 3020:     $fname=~s/[\n\r]//g;
 3021:     my $author=$fname;
 3022:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3023:     my ($udom,$uname)=split(/\//,$author);
 3024:     my $home=homeserver($uname,$udom);
 3025:     if ($home eq 'no_host') {
 3026:         return 'not_found';
 3027:     }
 3028:     my $answer=reply("sub:$fname",$home);
 3029:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 3030: 	$answer.=' by '.$home;
 3031:     }
 3032:     return $answer;
 3033: }
 3034:     
 3035: # -------------------------------------------------------------- Replicate file
 3036: 
 3037: sub repcopy {
 3038:     my $filename=shift;
 3039:     $filename=~s/\/+/\//g;
 3040:     my $londocroot = $perlvar{'lonDocRoot'};
 3041:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 3042:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 3043:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 3044: 	$filename=~m{^/*(uploaded|editupload)/}) {
 3045: 	return &repcopy_userfile($filename);
 3046:     }
 3047:     $filename=~s/[\n\r]//g;
 3048:     my $transname="$filename.in.transfer";
 3049: # FIXME: this should flock
 3050:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 3051:     my $remoteurl=subscribe($filename);
 3052:     if ($remoteurl =~ /^con_lost by/) {
 3053: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3054:            return 'unavailable';
 3055:     } elsif ($remoteurl eq 'not_found') {
 3056: 	   #&logthis("Subscribe returned not_found: $filename");
 3057: 	   return 'not_found';
 3058:     } elsif ($remoteurl =~ /^rejected by/) {
 3059: 	   &logthis("Subscribe returned $remoteurl: $filename");
 3060:            return 'forbidden';
 3061:     } elsif ($remoteurl eq 'directory') {
 3062:            return 'ok';
 3063:     } else {
 3064:         my $author=$filename;
 3065:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 3066:         my ($udom,$uname)=split(/\//,$author);
 3067:         my $home=homeserver($uname,$udom);
 3068:         unless ($home eq $perlvar{'lonHostID'}) {
 3069:            my @parts=split(/\//,$filename);
 3070:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 3071:            if ($path ne "$londocroot/res") {
 3072:                &logthis("Malconfiguration for replication: $filename");
 3073: 	       return 'bad_request';
 3074:            }
 3075:            my $count;
 3076:            for ($count=5;$count<$#parts;$count++) {
 3077:                $path.="/$parts[$count]";
 3078:                if ((-e $path)!=1) {
 3079: 		   mkdir($path,0777);
 3080:                }
 3081:            }
 3082:            my $request=new HTTP::Request('GET',"$remoteurl");
 3083:            my $response;
 3084:            if ($remoteurl =~ m{/raw/}) {
 3085:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
 3086:            } else {
 3087:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
 3088:            }
 3089:            if ($response->is_error()) {
 3090: 	       unlink($transname);
 3091:                my $message=$response->status_line;
 3092:                &logthis("<font color=\"blue\">WARNING:"
 3093:                        ." LWP get: $message: $filename</font>");
 3094:                return 'unavailable';
 3095:            } else {
 3096: 	       if ($remoteurl!~/\.meta$/) {
 3097:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 3098:                   my $mresponse;
 3099:                   if ($remoteurl =~ m{/raw/}) {
 3100:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
 3101:                   } else {
 3102:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
 3103:                   }
 3104:                   if ($mresponse->is_error()) {
 3105: 		      unlink($filename.'.meta');
 3106:                       &logthis(
 3107:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 3108:                   }
 3109: 	       }
 3110:                rename($transname,$filename);
 3111:                return 'ok';
 3112:            }
 3113:        }
 3114:     }
 3115: }
 3116: 
 3117: # ------------------------------------------------ Get server side include body
 3118: sub ssi_body {
 3119:     my ($filelink,%form)=@_;
 3120:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 3121:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 3122:     }
 3123:     my $output='';
 3124:     my $response;
 3125:     if ($filelink=~/^https?\:/) {
 3126:        ($output,$response)=&externalssi($filelink);
 3127:     } else {
 3128:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 3129:        $filelink .= 'inhibitmenu=yes';
 3130:        ($output,$response)=&ssi($filelink,%form);
 3131:     }
 3132:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 3133:     $output=~s/^.*?\<body[^\>]*\>//si;
 3134:     $output=~s/\<\/body\s*\>.*?$//si;
 3135:     if (wantarray) {
 3136:         return ($output, $response);
 3137:     } else {
 3138:         return $output;
 3139:     }
 3140: }
 3141: 
 3142: # --------------------------------------------------------- Server Side Include
 3143: 
 3144: sub absolute_url {
 3145:     my ($host_name) = @_;
 3146:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 3147:     if ($host_name eq '') {
 3148: 	$host_name = $ENV{'SERVER_NAME'};
 3149:     }
 3150:     return $protocol.$host_name;
 3151: }
 3152: 
 3153: #
 3154: #   Server side include.
 3155: # Parameters:
 3156: #  fn     Possibly encrypted resource name/id.
 3157: #  form   Hash that describes how the rendering should be done
 3158: #         and other things.
 3159: # Returns:
 3160: #   Scalar context: The content of the response.
 3161: #   Array context:  2 element list of the content and the full response object.
 3162: #     
 3163: sub ssi {
 3164: 
 3165:     my ($fn,%form)=@_;
 3166:     my $request;
 3167: 
 3168:     $form{'no_update_last_known'}=1;
 3169:     &Apache::lonenc::check_encrypt(\$fn);
 3170:     if (%form) {
 3171:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 3172:       $request->content(join('&',map { 
 3173:             my $name = escape($_);
 3174:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
 3175:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
 3176:             : &escape($form{$_}) );    
 3177:         } keys(%form)));
 3178:     } else {
 3179:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 3180:     }
 3181: 
 3182:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 3183:     my $lonhost = $perlvar{'lonHostID'};
 3184:     my $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar);
 3185: 
 3186:     if (wantarray) {
 3187: 	return ($response->content, $response);
 3188:     } else {
 3189: 	return $response->content;
 3190:     }
 3191: }
 3192: 
 3193: sub externalssi {
 3194:     my ($url)=@_;
 3195:     my $request=new HTTP::Request('GET',$url);
 3196:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
 3197:     if (wantarray) {
 3198:         return ($response->content, $response);
 3199:     } else {
 3200:         return $response->content;
 3201:     }
 3202: }
 3203: 
 3204: 
 3205: # If the local copy of a replicated resource is outdated, trigger a  
 3206: # connection from the homeserver to flush the delayed queue. If no update 
 3207: # happens, remove local copies of outdated resource (and corresponding
 3208: # metadata file).
 3209: 
 3210: sub remove_stale_resfile {
 3211:     my ($url) = @_;
 3212:     my $removed;
 3213:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
 3214:         my $audom = $1;
 3215:         my $auname = $2;
 3216:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
 3217:             my $homeserver = &homeserver($auname,$audom);
 3218:             unless (($homeserver eq 'no_host') ||
 3219:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
 3220:                 my $fname = &filelocation('',$url);
 3221:                 if (-e $fname) {
 3222:                     my $protocol = $protocol{$homeserver};
 3223:                     $protocol = 'http' if ($protocol ne 'https');
 3224:                     my $hostname = &hostname($homeserver);
 3225:                     if ($hostname) {
 3226:                         my $uri = &declutter($url);
 3227:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
 3228:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
 3229:                         if ($response->is_success()) {
 3230:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
 3231:                             my $locmodtime = (stat($fname))[9];
 3232:                             if ($locmodtime < $remmodtime) {
 3233:                                 my $stale;
 3234:                                 my $answer = &reply('pong',$homeserver);
 3235:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
 3236:                                     sleep(0.2);
 3237:                                     $locmodtime = (stat($fname))[9];
 3238:                                     if ($locmodtime < $remmodtime) {
 3239:                                         my $posstransfer = $fname.'.in.transfer';
 3240:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
 3241:                                             $removed = 1;
 3242:                                         } else {
 3243:                                             $stale = 1;
 3244:                                         }
 3245:                                     } else {
 3246:                                         $removed = 1;
 3247:                                     }
 3248:                                 } else {
 3249:                                     $stale = 1;
 3250:                                 }
 3251:                                 if ($stale) {
 3252:                                     unlink($fname);
 3253:                                     if ($uri!~/\.meta$/) {
 3254:                                         unlink($fname.'.meta');
 3255:                                     }
 3256:                                     &reply("unsub:$fname",$homeserver);
 3257:                                     $removed = 1;
 3258:                                 }
 3259:                             }
 3260:                         }
 3261:                     }
 3262:                 }
 3263:             }
 3264:         }
 3265:     }
 3266:     return $removed;
 3267: }
 3268: 
 3269: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 3270: 
 3271: sub allowuploaded {
 3272:     my ($srcurl,$url)=@_;
 3273:     $url=&clutter(&declutter($url));
 3274:     my $dir=$url;
 3275:     $dir=~s/\/[^\/]+$//;
 3276:     my %httpref=();
 3277:     my $httpurl=&hreflocation('',$url);
 3278:     $httpref{'httpref.'.$httpurl}=$srcurl;
 3279:     &Apache::lonnet::appenv(\%httpref);
 3280: }
 3281: 
 3282: #
 3283: # Determine if the current user should be able to edit a particular resource,
 3284: # when viewing in course context.
 3285: # (a) When viewing resource used to determine if "Edit" item is included in 
 3286: #     Functions.
 3287: # (b) When displaying folder contents in course editor, used to determine if
 3288: #     "Edit" link will be displayed alongside resource.
 3289: #
 3290: #  input: six args -- filename (decluttered), course number, course domain,
 3291: #                   url, symb (if registered) and group (if this is a group
 3292: #                   item -- e.g., bulletin board, group page etc.).
 3293: #  output: array of five scalars -- 
 3294: #          $cfile -- url for file editing if editable on current server
 3295: #          $home -- homeserver of resource (i.e., for author if published,
 3296: #                                           or course if uploaded.).
 3297: #          $switchserver --  1 if server switch will be needed.
 3298: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 3299: #          $forceview -- 1 if icon/link should be to go to view mode
 3300: #
 3301: 
 3302: sub can_edit_resource {
 3303:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 3304:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 3305: #
 3306: # For aboutme pages user can only edit his/her own.
 3307: #
 3308:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 3309:         my ($sdom,$sname) = ($1,$2);
 3310:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 3311:             $home = $env{'user.home'};
 3312:             $cfile = $resurl;
 3313:             if ($env{'form.forceedit'}) {
 3314:                 $forceview = 1;
 3315:             } else {
 3316:                 $forceedit = 1;
 3317:             }
 3318:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3319:         } else {
 3320:             return;
 3321:         }
 3322:     }
 3323: 
 3324:     if ($env{'request.course.id'}) {
 3325:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 3326:         if ($group ne '') {
 3327: # if this is a group homepage or group bulletin board, check group privs
 3328:             my $allowed = 0;
 3329:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 3330:                 if ((&allowed('mdg',$env{'request.course.id'}.
 3331:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3332:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3333:                     $allowed = 1;
 3334:                 }
 3335:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 3336:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 3337:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 3338:                     $allowed = 1;
 3339:                 }
 3340:             }
 3341:             if ($allowed) {
 3342:                 $home=&homeserver($cnum,$cdom);
 3343:                 if ($env{'form.forceedit'}) {
 3344:                     $forceview = 1;
 3345:                 } else {
 3346:                     $forceedit = 1;
 3347:                 }
 3348:                 $cfile = $resurl;
 3349:             } else {
 3350:                 return;
 3351:             }
 3352:         } else {
 3353:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 3354:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 3355:                     return;
 3356:                 }
 3357:             } elsif (!$crsedit) {
 3358: #
 3359: # No edit allowed where CC has switched to student role.
 3360: #
 3361:                 return;
 3362:             }
 3363:         }
 3364:     }
 3365: 
 3366:     if ($file ne '') {
 3367:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 3368:             if (&is_course_upload($file,$cnum,$cdom)) {
 3369:                 $uploaded = 1;
 3370:                 $incourse = 1;
 3371:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 3372:                     $cfile = &hreflocation('',$file);
 3373:                     if ($env{'form.forceedit'}) {
 3374:                         $forceview = 1;
 3375:                     } else {
 3376:                         $forceedit = 1;
 3377:                     }
 3378:                 }
 3379:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 3380:                 $incourse = 1;
 3381:                 if ($env{'form.forceedit'}) {
 3382:                     $forceview = 1;
 3383:                 } else {
 3384:                     $forceedit = 1;
 3385:                 }
 3386:                 $cfile = $resurl;
 3387:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 3388:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 3389:                     $incourse = 1;
 3390:                     if ($env{'form.forceedit'}) {
 3391:                         $forceview = 1;
 3392:                     } else {
 3393:                         $forceedit = 1;
 3394:                     }
 3395:                     $cfile = $resurl;
 3396:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 3397:                     $incourse = 1;
 3398:                     $cfile = $resurl.'/smpedit';
 3399:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 3400:                     $incourse = 1;
 3401:                     if ($env{'form.forceedit'}) {
 3402:                         $forceview = 1;
 3403:                     } else {
 3404:                         $forceedit = 1;
 3405:                     }
 3406:                     $cfile = $resurl;
 3407:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3408:                     $incourse = 1;
 3409:                     if ($env{'form.forceedit'}) {
 3410:                         $forceview = 1;
 3411:                     } else {
 3412:                         $forceedit = 1;
 3413:                     }
 3414:                     $cfile = $resurl;
 3415:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3416:                     $incourse = 1;
 3417:                     if ($env{'form.forceedit'}) {
 3418:                         $forceview = 1;
 3419:                     } else {
 3420:                         $forceedit = 1;
 3421:                     }
 3422:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3423:                 }
 3424:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 3425:                 my $template = '/res/lib/templates/simpleproblem.problem';
 3426:                 if (&is_on_map($template)) { 
 3427:                     $incourse = 1;
 3428:                     $forceview = 1;
 3429:                     $cfile = $template;
 3430:                 }
 3431:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3432:                     $incourse = 1;
 3433:                     if ($env{'form.forceedit'}) {
 3434:                         $forceview = 1;
 3435:                     } else {
 3436:                         $forceedit = 1;
 3437:                     }
 3438:                     $cfile = $resurl;
 3439:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3440:                 $incourse = 1;
 3441:                 if ($env{'form.forceedit'}) {
 3442:                     $forceview = 1;
 3443:                 } else {
 3444:                     $forceedit = 1;
 3445:                 }
 3446:                 $cfile = $resurl;
 3447:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 3448:                 $incourse = 1;
 3449:                 $forceview = 1;
 3450:                 if ($symb) {
 3451:                     my ($map,$id,$res)=&decode_symb($symb);
 3452:                     $env{'request.symb'} = $symb;
 3453:                     $cfile = &clutter($res);
 3454:                 } else {
 3455:                     $cfile = $env{'form.suppurl'};
 3456:                     my $escfile = &unescape($cfile);
 3457:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
 3458:                         $cfile = '/adm/wrapper'.$escfile;
 3459:                     } else {
 3460:                         $escfile =~ s{^http://}{};
 3461:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
 3462:                     }
 3463:                 }
 3464:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3465:                 if ($env{'form.forceedit'}) {
 3466:                     $forceview = 1;
 3467:                 } else {
 3468:                     $forceedit = 1;
 3469:                 }
 3470:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3471:             }
 3472:         }
 3473:         if ($uploaded || $incourse) {
 3474:             $home=&homeserver($cnum,$cdom);
 3475:         } elsif ($file !~ m{/$}) {
 3476:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 3477:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 3478:             # Check that the user has permission to edit this resource
 3479:             my $setpriv = 1;
 3480:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 3481:             if (defined($cfudom)) {
 3482:                 $home=&homeserver($cfuname,$cfudom);
 3483:                 $cfile=$file;
 3484:             }
 3485:         }
 3486:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 3487:             (($home ne '') && ($home ne 'no_host'))) {
 3488:             my @ids=&current_machine_ids();
 3489:             unless (grep(/^\Q$home\E$/,@ids)) {
 3490:                 $switchserver=1;
 3491:             }
 3492:         }
 3493:     }
 3494:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3495: }
 3496: 
 3497: sub is_course_upload {
 3498:     my ($file,$cnum,$cdom) = @_;
 3499:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 3500:     $uploadpath =~ s{^\/}{};
 3501:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 3502:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 3503:         return 1;
 3504:     }
 3505:     return;
 3506: }
 3507: 
 3508: sub in_course {
 3509:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 3510:     if ($hideprivileged) {
 3511:         my $skipuser;
 3512:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 3513:         my @possdoms = ($cdom);  
 3514:         if ($coursehash{'checkforpriv'}) { 
 3515:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 3516:         }
 3517:         if (&privileged($uname,$udom,\@possdoms)) {
 3518:             $skipuser = 1;
 3519:             if ($coursehash{'nothideprivileged'}) {
 3520:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3521:                     my $user;
 3522:                     if ($item =~ /:/) {
 3523:                         $user = $item;
 3524:                     } else {
 3525:                         $user = join(':',split(/[\@]/,$item));
 3526:                     }
 3527:                     if ($user eq $uname.':'.$udom) {
 3528:                         undef($skipuser);
 3529:                         last;
 3530:                     }
 3531:                 }
 3532:             }
 3533:             if ($skipuser) {
 3534:                 return 0;
 3535:             }
 3536:         }
 3537:     }
 3538:     $type ||= 'any';
 3539:     if (!defined($cdom) || !defined($cnum)) {
 3540:         my $cid  = $env{'request.course.id'};
 3541:         $cdom = $env{'course.'.$cid.'.domain'};
 3542:         $cnum = $env{'course.'.$cid.'.num'};
 3543:     }
 3544:     my $typesref;
 3545:     if (($type eq 'any') || ($type eq 'all')) {
 3546:         $typesref = ['active','previous','future'];
 3547:     } elsif ($type eq 'previous' || $type eq 'future') {
 3548:         $typesref = [$type];
 3549:     }
 3550:     my %roles = &get_my_roles($uname,$udom,'userroles',
 3551:                               $typesref,undef,[$cdom]);
 3552:     my ($tmp) = keys(%roles);
 3553:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 3554:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 3555:     if (@course_roles > 0) {
 3556:         return 1;
 3557:     }
 3558:     return 0;
 3559: }
 3560: 
 3561: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 3562: # input: action, courseID, current domain, intended
 3563: #        path to file, source of file, instruction to parse file for objects,
 3564: #        ref to hash for embedded objects,
 3565: #        ref to hash for codebase of java objects.
 3566: #        reference to scalar to accommodate mime type determined
 3567: #          from File::MMagic if $parser = parse.
 3568: #
 3569: # output: url to file (if action was uploaddoc), 
 3570: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 3571: #
 3572: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 3573: # course.
 3574: #
 3575: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3576: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 3577: #          course's home server.
 3578: #
 3579: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 3580: #          be copied from $source (current location) to 
 3581: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3582: #         and will then be copied to
 3583: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 3584: #         course's home server.
 3585: #
 3586: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3587: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 3588: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3589: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 3590: #         in course's home server.
 3591: #
 3592: 
 3593: sub process_coursefile {
 3594:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 3595:         $mimetype)=@_;
 3596:     my $fetchresult;
 3597:     my $home=&homeserver($docuname,$docudom);
 3598:     if ($action eq 'propagate') {
 3599:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3600: 			     $home);
 3601:     } else {
 3602:         my $fpath = '';
 3603:         my $fname = $file;
 3604:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3605:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3606:         my $filepath = &build_filepath($fpath);
 3607:         if ($action eq 'copy') {
 3608:             if ($source eq '') {
 3609:                 $fetchresult = 'no source file';
 3610:                 return $fetchresult;
 3611:             } else {
 3612:                 my $destination = $filepath.'/'.$fname;
 3613:                 rename($source,$destination);
 3614:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3615:                                  $home);
 3616:             }
 3617:         } elsif ($action eq 'uploaddoc') {
 3618:             open(my $fh,'>'.$filepath.'/'.$fname);
 3619:             print $fh $env{'form.'.$source};
 3620:             close($fh);
 3621:             if ($parser eq 'parse') {
 3622:                 my $mm = new File::MMagic;
 3623:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 3624:                 if ($type eq 'text/html') {
 3625:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 3626:                     unless ($parse_result eq 'ok') {
 3627:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 3628:                     }
 3629:                 }
 3630:                 if (ref($mimetype)) {
 3631:                     $$mimetype = $type;
 3632:                 } 
 3633:             }
 3634:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3635:                                  $home);
 3636:             if ($fetchresult eq 'ok') {
 3637:                 return '/uploaded/'.$fpath.'/'.$fname;
 3638:             } else {
 3639:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3640:                         ' to host '.$home.': '.$fetchresult);
 3641:                 return '/adm/notfound.html';
 3642:             }
 3643:         }
 3644:     }
 3645:     unless ( $fetchresult eq 'ok') {
 3646:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3647:              ' to host '.$home.': '.$fetchresult);
 3648:     }
 3649:     return $fetchresult;
 3650: }
 3651: 
 3652: sub build_filepath {
 3653:     my ($fpath) = @_;
 3654:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 3655:     unless ($fpath eq '') {
 3656:         my @parts=split('/',$fpath);
 3657:         foreach my $part (@parts) {
 3658:             $filepath.= '/'.$part;
 3659:             if ((-e $filepath)!=1) {
 3660:                 mkdir($filepath,0777);
 3661:             }
 3662:         }
 3663:     }
 3664:     return $filepath;
 3665: }
 3666: 
 3667: sub store_edited_file {
 3668:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 3669:     my $file = $primary_url;
 3670:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 3671:     my $fpath = '';
 3672:     my $fname = $file;
 3673:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3674:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3675:     my $filepath = &build_filepath($fpath);
 3676:     open(my $fh,'>'.$filepath.'/'.$fname);
 3677:     print $fh $content;
 3678:     close($fh);
 3679:     my $home=&homeserver($docuname,$docudom);
 3680:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3681: 			  $home);
 3682:     if ($$fetchresult eq 'ok') {
 3683:         return '/uploaded/'.$fpath.'/'.$fname;
 3684:     } else {
 3685:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3686: 		 ' to host '.$home.': '.$$fetchresult);
 3687:         return '/adm/notfound.html';
 3688:     }
 3689: }
 3690: 
 3691: sub clean_filename {
 3692:     my ($fname,$args)=@_;
 3693: # Replace Windows backslashes by forward slashes
 3694:     $fname=~s/\\/\//g;
 3695:     if (!$args->{'keep_path'}) {
 3696:         # Get rid of everything but the actual filename
 3697: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 3698:     }
 3699: # Replace spaces by underscores
 3700:     $fname=~s/\s+/\_/g;
 3701: # Replace all other weird characters by nothing
 3702:     $fname=~s{[^/\w\.\-]}{}g;
 3703: # Replace all .\d. sequences with _\d. so they no longer look like version
 3704: # numbers
 3705:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 3706:     return $fname;
 3707: }
 3708: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 3709: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 3710: # image with the same aspect ratio as the original, but with dimensions which do 
 3711: # not exceed $resizewidth and $resizeheight.
 3712:  
 3713: sub resizeImage {
 3714:     my ($img_path,$resizewidth,$resizeheight) = @_;
 3715:     my $ima = Image::Magick->new;
 3716:     my $resized;
 3717:     if (-e $img_path) {
 3718:         $ima->Read($img_path);
 3719:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 3720:             my $width = $ima->Get('width');
 3721:             my $height = $ima->Get('height');
 3722:             if ($width > $resizewidth) {
 3723: 	        my $factor = $width/$resizewidth;
 3724:                 my $newheight = $height/$factor;
 3725:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 3726:                 $resized = 1;
 3727:             }
 3728:         }
 3729:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 3730:             my $width = $ima->Get('width');
 3731:             my $height = $ima->Get('height');
 3732:             if ($height > $resizeheight) {
 3733:                 my $factor = $height/$resizeheight;
 3734:                 my $newwidth = $width/$factor;
 3735:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 3736:                 $resized = 1;
 3737:             }
 3738:         }
 3739:         if ($resized) {
 3740:             $ima->Write($img_path);
 3741:         }
 3742:     }
 3743:     return;
 3744: }
 3745: 
 3746: # --------------- Take an uploaded file and put it into the userfiles directory
 3747: # input: $formname - the contents of the file are in $env{"form.$formname"}
 3748: #                    the desired filename is in $env{"form.$formname.filename"}
 3749: #        $context - possible values: coursedoc, existingfile, overwrite, 
 3750: #                                    canceloverwrite, or ''. 
 3751: #                   if 'coursedoc': upload to the current course
 3752: #                   if 'existingfile': write file to tmp/overwrites directory 
 3753: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 3754: #                   $context is passed as argument to &finishuserfileupload
 3755: #        $subdir - directory in userfile to store the file into
 3756: #        $parser - instruction to parse file for objects ($parser = parse)    
 3757: #        $allfiles - reference to hash for embedded objects
 3758: #        $codebase - reference to hash for codebase of java objects
 3759: #        $desuname - username for permanent storage of uploaded file
 3760: #        $dsetudom - domain for permanaent storage of uploaded file
 3761: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 3762: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 3763: #        $resizewidth - width (pixels) to which to resize uploaded image
 3764: #        $resizeheight - height (pixels) to which to resize uploaded image
 3765: #        $mimetype - reference to scalar to accommodate mime type determined
 3766: #                    from File::MMagic.
 3767: # 
 3768: # output: url of file in userspace, or error: <message> 
 3769: #             or /adm/notfound.html if failure to upload occurse
 3770: 
 3771: sub userfileupload {
 3772:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 3773:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 3774:     if (!defined($subdir)) { $subdir='unknown'; }
 3775:     my $fname=$env{'form.'.$formname.'.filename'};
 3776:     $fname=&clean_filename($fname);
 3777:     # See if there is anything left
 3778:     unless ($fname) { return 'error: no uploaded file'; }
 3779:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 3780:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 3781:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 3782:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3783:         my $now = time;
 3784:         my $filepath;
 3785:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 3786:              $filepath = 'tmp/helprequests/'.$now;
 3787:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 3788:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 3789:                          '_'.$env{'user.domain'}.'/pending';
 3790:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3791:             my ($docuname,$docudom);
 3792:             if ($destudom =~ /^$match_domain$/) {
 3793:                 $docudom = $destudom;
 3794:             } else {
 3795:                 $docudom = $env{'user.domain'};
 3796:             }
 3797:             if ($destuname =~ /^$match_username$/) {
 3798:                 $docuname = $destuname;
 3799:             } else {
 3800:                 $docuname = $env{'user.name'};
 3801:             }
 3802:             if (exists($env{'form.group'})) {
 3803:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3804:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3805:             }
 3806:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 3807:             if ($context eq 'canceloverwrite') {
 3808:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 3809:                 if (-e  $tempfile) {
 3810:                     my @info = stat($tempfile);
 3811:                     if ($info[9] eq $env{'form.timestamp'}) {
 3812:                         unlink($tempfile);
 3813:                     }
 3814:                 }
 3815:                 return;
 3816:             }
 3817:         }
 3818:         # Create the directory if not present
 3819:         my @parts=split(/\//,$filepath);
 3820:         my $fullpath = $perlvar{'lonDaemons'};
 3821:         for (my $i=0;$i<@parts;$i++) {
 3822:             $fullpath .= '/'.$parts[$i];
 3823:             if ((-e $fullpath)!=1) {
 3824:                 mkdir($fullpath,0777);
 3825:             }
 3826:         }
 3827:         open(my $fh,'>'.$fullpath.'/'.$fname);
 3828:         print $fh $env{'form.'.$formname};
 3829:         close($fh);
 3830:         if ($context eq 'existingfile') {
 3831:             my @info = stat($fullpath.'/'.$fname);
 3832:             return ($fullpath.'/'.$fname,$info[9]);
 3833:         } else {
 3834:             return $fullpath.'/'.$fname;
 3835:         }
 3836:     }
 3837:     if ($subdir eq 'scantron') {
 3838:         $fname = 'scantron_orig_'.$fname;
 3839:     } else {
 3840:         $fname="$subdir/$fname";
 3841:     }
 3842:     if ($context eq 'coursedoc') {
 3843: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3844: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3845:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 3846:             return &finishuserfileupload($docuname,$docudom,
 3847: 					 $formname,$fname,$parser,$allfiles,
 3848: 					 $codebase,$thumbwidth,$thumbheight,
 3849:                                          $resizewidth,$resizeheight,$context,$mimetype);
 3850:         } else {
 3851:             if ($env{'form.folder'}) {
 3852:                 $fname=$env{'form.folder'}.'/'.$fname;
 3853:             }
 3854:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 3855: 				       $fname,$formname,$parser,
 3856: 				       $allfiles,$codebase,$mimetype);
 3857:         }
 3858:     } elsif (defined($destuname)) {
 3859:         my $docuname=$destuname;
 3860:         my $docudom=$destudom;
 3861: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3862: 				     $parser,$allfiles,$codebase,
 3863:                                      $thumbwidth,$thumbheight,
 3864:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3865:     } else {
 3866:         my $docuname=$env{'user.name'};
 3867:         my $docudom=$env{'user.domain'};
 3868:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 3869:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3870:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3871:         }
 3872: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3873: 				     $parser,$allfiles,$codebase,
 3874:                                      $thumbwidth,$thumbheight,
 3875:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3876:     }
 3877: }
 3878: 
 3879: sub finishuserfileupload {
 3880:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 3881:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 3882:     my $path=$docudom.'/'.$docuname.'/';
 3883:     my $filepath=$perlvar{'lonDocRoot'};
 3884:   
 3885:     my ($fnamepath,$file,$fetchthumb);
 3886:     $file=$fname;
 3887:     if ($fname=~m|/|) {
 3888:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 3889: 	$path.=$fnamepath.'/';
 3890:     }
 3891:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 3892:     my $count;
 3893:     for ($count=4;$count<=$#parts;$count++) {
 3894:         $filepath.="/$parts[$count]";
 3895:         if ((-e $filepath)!=1) {
 3896: 	    mkdir($filepath,0777);
 3897:         }
 3898:     }
 3899: 
 3900: # Save the file
 3901:     {
 3902: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 3903: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 3904: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 3905: 	    return '/adm/notfound.html';
 3906: 	}
 3907:         if ($context eq 'overwrite') {
 3908:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 3909:             my $target = $filepath.'/'.$file;
 3910:             if (-e $source) {
 3911:                 my @info = stat($source);
 3912:                 if ($info[9] eq $env{'form.timestamp'}) {   
 3913:                     unless (&File::Copy::move($source,$target)) {
 3914:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 3915:                         return "Moving from $source failed";
 3916:                     }
 3917:                 } else {
 3918:                     return "Temporary file: $source had unexpected date/time for last modification";
 3919:                 }
 3920:             } else {
 3921:                 return "Temporary file: $source missing";
 3922:             }
 3923:         } elsif (!print FH ($env{'form.'.$formname})) {
 3924: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 3925: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 3926: 	    return '/adm/notfound.html';
 3927: 	}
 3928: 	close(FH);
 3929:         if ($resizewidth && $resizeheight) {
 3930:             my $mm = new File::MMagic;
 3931:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 3932:             if ($mime_type =~ m{^image/}) {
 3933: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 3934:             }  
 3935: 	}
 3936:     }
 3937:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 3938:         if (ref($mimetype)) {
 3939:             if ($$mimetype eq '') {
 3940:                 my $mm = new File::MMagic;
 3941:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 3942:                 $$mimetype = $type;
 3943:             }
 3944:         }
 3945:     }
 3946:     if ($parser eq 'parse') {
 3947:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 3948:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 3949:                                                        $allfiles,$codebase);
 3950:             unless ($parse_result eq 'ok') {
 3951:                 &logthis('Failed to parse '.$filepath.$file.
 3952: 	   	         ' for embedded media: '.$parse_result); 
 3953:             }
 3954:         }
 3955:     }
 3956:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 3957:         my $input = $filepath.'/'.$file;
 3958:         my $output = $filepath.'/'.'tn-'.$file;
 3959:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 3960:         system("convert -sample $thumbsize $input $output");
 3961:         if (-e $filepath.'/'.'tn-'.$file) {
 3962:             $fetchthumb  = 1; 
 3963:         }
 3964:     }
 3965:  
 3966: # Notify homeserver to grep it
 3967: #
 3968:     my $docuhome=&homeserver($docuname,$docudom);	
 3969:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 3970:     if ($fetchresult eq 'ok') {
 3971:         if ($fetchthumb) {
 3972:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 3973:             if ($thumbresult ne 'ok') {
 3974:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 3975:                          $docuhome.': '.$thumbresult);
 3976:             }
 3977:         }
 3978: #
 3979: # Return the URL to it
 3980:         return '/uploaded/'.$path.$file;
 3981:     } else {
 3982:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 3983: 		 ': '.$fetchresult);
 3984:         return '/adm/notfound.html';
 3985:     }
 3986: }
 3987: 
 3988: sub extract_embedded_items {
 3989:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 3990:     my @state = ();
 3991:     my (%lastids,%related,%shockwave,%flashvars);
 3992:     my %javafiles = (
 3993:                       codebase => '',
 3994:                       code => '',
 3995:                       archive => ''
 3996:                     );
 3997:     my %mediafiles = (
 3998:                       src => '',
 3999:                       movie => '',
 4000:                      );
 4001:     my $p;
 4002:     if ($content) {
 4003:         $p = HTML::LCParser->new($content);
 4004:     } else {
 4005:         $p = HTML::LCParser->new($fullpath);
 4006:     }
 4007:     while (my $t=$p->get_token()) {
 4008: 	if ($t->[0] eq 'S') {
 4009: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 4010: 	    push(@state, $tagname);
 4011:             if (lc($tagname) eq 'allow') {
 4012:                 &add_filetype($allfiles,$attr->{'src'},'src');
 4013:             }
 4014: 	    if (lc($tagname) eq 'img') {
 4015: 		&add_filetype($allfiles,$attr->{'src'},'src');
 4016: 	    }
 4017: 	    if (lc($tagname) eq 'a') {
 4018:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 4019:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4020:                 }
 4021: 	    }
 4022:             if (lc($tagname) eq 'script') {
 4023:                 my $src;
 4024:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 4025:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 4026:                 } else {
 4027:                     if ($attr->{'src'} ne '') {
 4028:                         $src = $attr->{'src'};
 4029:                         &add_filetype($allfiles,$src,'src');
 4030:                     }
 4031:                 }
 4032:                 my $text = $p->get_trimmed_text();
 4033:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 4034:                     my @swfargs = split(/,/,$1);
 4035:                     foreach my $item (@swfargs) {
 4036:                         $item =~ s/["']//g;
 4037:                         $item =~ s/^\s+//;
 4038:                         $item =~ s/\s+$//;
 4039:                     }
 4040:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 4041:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 4042:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 4043:                         } else {
 4044:                             $related{$swfargs[0]} = [$swfargs[2]];
 4045:                         }
 4046:                     }
 4047:                 }
 4048:             }
 4049:             if (lc($tagname) eq 'link') {
 4050:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 4051:                     &add_filetype($allfiles,$attr->{'href'},'href');
 4052:                 }
 4053:             }
 4054: 	    if (lc($tagname) eq 'object' ||
 4055: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 4056: 		foreach my $item (keys(%javafiles)) {
 4057: 		    $javafiles{$item} = '';
 4058: 		}
 4059:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 4060:                     $lastids{lc($tagname)} = $attr->{'id'};
 4061:                 }
 4062: 	    }
 4063: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 4064: 		my $name = lc($attr->{'name'});
 4065: 		foreach my $item (keys(%javafiles)) {
 4066: 		    if ($name eq $item) {
 4067: 			$javafiles{$item} = $attr->{'value'};
 4068: 			last;
 4069: 		    }
 4070: 		}
 4071:                 my $pathfrom;
 4072: 		foreach my $item (keys(%mediafiles)) {
 4073: 		    if ($name eq $item) {
 4074:                         $pathfrom = $attr->{'value'};
 4075:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 4076: 			&add_filetype($allfiles,$pathfrom,$name);
 4077: 			last;
 4078: 		    }
 4079: 		}
 4080:                 if ($name eq 'flashvars') {
 4081:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 4082:                 }
 4083:                 if ($pathfrom ne '') {
 4084:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 4085:                                          $pathfrom);
 4086:                 }
 4087: 	    }
 4088: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 4089: 		foreach my $item (keys(%javafiles)) {
 4090: 		    if ($attr->{$item}) {
 4091: 			$javafiles{$item} = $attr->{$item};
 4092: 			last;
 4093: 		    }
 4094: 		}
 4095: 		foreach my $item (keys(%mediafiles)) {
 4096: 		    if ($attr->{$item}) {
 4097: 			&add_filetype($allfiles,$attr->{$item},$item);
 4098: 			last;
 4099: 		    }
 4100: 		}
 4101:                 if (lc($tagname) eq 'embed') {
 4102:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 4103:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 4104:                                              $attr->{'src'});
 4105:                     }
 4106:                 }
 4107: 	    }
 4108:             if (lc($tagname) eq 'iframe') {
 4109:                 my $src = $attr->{'src'} ;
 4110:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 4111:                     &add_filetype($allfiles,$src,'src');
 4112:                 } elsif ($src =~ m{^/}) {
 4113:                     if ($env{'request.course.id'}) {
 4114:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4115:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4116:                         my $url = &hreflocation('',$fullpath);
 4117:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 4118:                             my $relpath = $1;
 4119:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 4120:                                 &add_filetype($allfiles,$1,'src');
 4121:                             }
 4122:                         }
 4123:                     }
 4124:                 }
 4125:             }
 4126:             if ($t->[4] =~ m{/>$}) {
 4127:                 pop(@state);
 4128:             }
 4129: 	} elsif ($t->[0] eq 'E') {
 4130: 	    my ($tagname) = ($t->[1]);
 4131: 	    if ($javafiles{'codebase'} ne '') {
 4132: 		$javafiles{'codebase'} .= '/';
 4133: 	    }  
 4134: 	    if (lc($tagname) eq 'applet' ||
 4135: 		lc($tagname) eq 'object' ||
 4136: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 4137: 		) {
 4138: 		foreach my $item (keys(%javafiles)) {
 4139: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 4140: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 4141: 			&add_filetype($allfiles,$file,$item);
 4142: 		    }
 4143: 		}
 4144: 	    } 
 4145: 	    pop @state;
 4146: 	}
 4147:     }
 4148:     foreach my $id (sort(keys(%flashvars))) {
 4149:         if ($shockwave{$id} ne '') {
 4150:             my @pairs = split(/\&/,$flashvars{$id});
 4151:             foreach my $pair (@pairs) {
 4152:                 my ($key,$value) = split(/\=/,$pair);
 4153:                 if ($key eq 'thumb') {
 4154:                     &add_filetype($allfiles,$value,$key);
 4155:                 } elsif ($key eq 'content') {
 4156:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 4157:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 4158:                     if ($ext ne '') {
 4159:                         &add_filetype($allfiles,$path.$value,$ext);
 4160:                     }
 4161:                 }
 4162:             }
 4163:         }
 4164:     }
 4165:     return 'ok';
 4166: }
 4167: 
 4168: sub add_filetype {
 4169:     my ($allfiles,$file,$type)=@_;
 4170:     if (exists($allfiles->{$file})) {
 4171: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 4172: 	    push(@{$allfiles->{$file}}, &escape($type));
 4173: 	}
 4174:     } else {
 4175: 	@{$allfiles->{$file}} = (&escape($type));
 4176:     }
 4177: }
 4178: 
 4179: sub embedded_dependency {
 4180:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 4181:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 4182:         if (($identifier ne '') &&
 4183:             (ref($related->{$identifier}) eq 'ARRAY') &&
 4184:             ($pathfrom ne '')) {
 4185:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 4186:             foreach my $dep (@{$related->{$identifier}}) {
 4187:                 &add_filetype($allfiles,$path.$dep,'object');
 4188:             }
 4189:         }
 4190:     }
 4191:     return;
 4192: }
 4193: 
 4194: sub removeuploadedurl {
 4195:     my ($url)=@_;	
 4196:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 4197:     return &removeuserfile($uname,$udom,$fname);
 4198: }
 4199: 
 4200: sub removeuserfile {
 4201:     my ($docuname,$docudom,$fname)=@_;
 4202:     my $home=&homeserver($docuname,$docudom);    
 4203:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 4204:     if ($result eq 'ok') {	
 4205:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 4206:             my $metafile = $fname.'.meta';
 4207:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 4208: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 4209:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 4210:             my $sqlresult = 
 4211:                 &update_portfolio_table($docuname,$docudom,$file,
 4212:                                         'portfolio_metadata',$group,
 4213:                                         'delete');
 4214:         }
 4215:     }
 4216:     return $result;
 4217: }
 4218: 
 4219: sub mkdiruserfile {
 4220:     my ($docuname,$docudom,$dir)=@_;
 4221:     my $home=&homeserver($docuname,$docudom);
 4222:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 4223: }
 4224: 
 4225: sub renameuserfile {
 4226:     my ($docuname,$docudom,$old,$new)=@_;
 4227:     my $home=&homeserver($docuname,$docudom);
 4228:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 4229:                         &escape("$old").':'.&escape("$new"),$home);
 4230:     if ($result eq 'ok') {
 4231:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 4232:             my $oldmeta = $old.'.meta';
 4233:             my $newmeta = $new.'.meta';
 4234:             my $metaresult = 
 4235:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 4236: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 4237:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 4238:             my $sqlresult = 
 4239:                 &update_portfolio_table($docuname,$docudom,$file,
 4240:                                         'portfolio_metadata',$group,
 4241:                                         'delete');
 4242:         }
 4243:     }
 4244:     return $result;
 4245: }
 4246: 
 4247: # ------------------------------------------------------------------------- Log
 4248: 
 4249: sub log {
 4250:     my ($dom,$nam,$hom,$what)=@_;
 4251:     return critical("log:$dom:$nam:$what",$hom);
 4252: }
 4253: 
 4254: # ------------------------------------------------------------------ Course Log
 4255: #
 4256: # This routine flushes several buffers of non-mission-critical nature
 4257: #
 4258: 
 4259: sub flushcourselogs {
 4260:     &logthis('Flushing log buffers');
 4261: #
 4262: # course logs
 4263: # This is a log of all transactions in a course, which can be used
 4264: # for data mining purposes
 4265: #
 4266: # It also collects the courseid database, which lists last transaction
 4267: # times and course titles for all courseids
 4268: #
 4269:     my %courseidbuffer=();
 4270:     foreach my $crsid (keys(%courselogs)) {
 4271:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 4272: 		          &escape($courselogs{$crsid}),
 4273: 		          $coursehombuf{$crsid}) eq 'ok') {
 4274: 	    delete $courselogs{$crsid};
 4275:         } else {
 4276:             &logthis('Failed to flush log buffer for '.$crsid);
 4277:             if (length($courselogs{$crsid})>40000) {
 4278:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 4279:                         " exceeded maximum size, deleting.</font>");
 4280:                delete $courselogs{$crsid};
 4281:             }
 4282:         }
 4283:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 4284:             'description' => $coursedescrbuf{$crsid},
 4285:             'inst_code'    => $courseinstcodebuf{$crsid},
 4286:             'type'        => $coursetypebuf{$crsid},
 4287:             'owner'       => $courseownerbuf{$crsid},
 4288:         };
 4289:     }
 4290: #
 4291: # Write course id database (reverse lookup) to homeserver of courses 
 4292: # Is used in pickcourse
 4293: #
 4294:     foreach my $crs_home (keys(%courseidbuffer)) {
 4295:         my $response = &courseidput(&host_domain($crs_home),
 4296:                                     $courseidbuffer{$crs_home},
 4297:                                     $crs_home,'timeonly');
 4298:     }
 4299: #
 4300: # File accesses
 4301: # Writes to the dynamic metadata of resources to get hit counts, etc.
 4302: #
 4303:     foreach my $entry (keys(%accesshash)) {
 4304:         if ($entry =~ /___count$/) {
 4305:             my ($dom,$name);
 4306:             ($dom,$name,undef)=
 4307: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 4308:             if (! defined($dom) || $dom eq '' || 
 4309:                 ! defined($name) || $name eq '') {
 4310:                 my $cid = $env{'request.course.id'};
 4311:                 $dom  = $env{'request.'.$cid.'.domain'};
 4312:                 $name = $env{'request.'.$cid.'.num'};
 4313:             }
 4314:             my $value = $accesshash{$entry};
 4315:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 4316:             my %temphash=($url => $value);
 4317:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 4318:             if ($result eq 'ok') {
 4319:                 delete $accesshash{$entry};
 4320:             }
 4321:         } else {
 4322:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 4323:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 4324:             my %temphash=($entry => $accesshash{$entry});
 4325:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 4326:                 delete $accesshash{$entry};
 4327:             }
 4328:         }
 4329:     }
 4330: #
 4331: # Roles
 4332: # Reverse lookup of user roles for course faculty/staff and co-authorship
 4333: #
 4334:     foreach my $entry (keys(%userrolehash)) {
 4335:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 4336: 	    split(/\:/,$entry);
 4337:         if (&Apache::lonnet::put('nohist_userroles',
 4338:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 4339:                 $rudom,$runame) eq 'ok') {
 4340: 	    delete $userrolehash{$entry};
 4341:         }
 4342:     }
 4343: #
 4344: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
 4345: #
 4346:     my %domrolebuffer = ();
 4347:     foreach my $entry (keys(%domainrolehash)) {
 4348:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 4349:         if ($domrolebuffer{$rudom}) {
 4350:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 4351:                       '='.&escape($domainrolehash{$entry});
 4352:         } else {
 4353:             $domrolebuffer{$rudom}.=&escape($entry).
 4354:                       '='.&escape($domainrolehash{$entry});
 4355:         }
 4356:         delete $domainrolehash{$entry};
 4357:     }
 4358:     foreach my $dom (keys(%domrolebuffer)) {
 4359: 	my %servers;
 4360: 	if (defined(&domain($dom,'primary'))) {
 4361: 	    my $primary=&domain($dom,'primary');
 4362: 	    my $hostname=&hostname($primary);
 4363: 	    $servers{$primary} = $hostname;
 4364: 	} else { 
 4365: 	    %servers = &get_servers($dom,'library');
 4366: 	}
 4367: 	foreach my $tryserver (keys(%servers)) {
 4368: 	    if (&reply('domroleput:'.$dom.':'.
 4369: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
 4370: 		last;
 4371: 	    } else {  
 4372: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 4373: 	    }
 4374:         }
 4375:     }
 4376:     $dumpcount++;
 4377: }
 4378: 
 4379: sub courselog {
 4380:     my $what=shift;
 4381:     $what=time.':'.$what;
 4382:     unless ($env{'request.course.id'}) { return ''; }
 4383:     $coursedombuf{$env{'request.course.id'}}=
 4384:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 4385:     $coursenumbuf{$env{'request.course.id'}}=
 4386:        $env{'course.'.$env{'request.course.id'}.'.num'};
 4387:     $coursehombuf{$env{'request.course.id'}}=
 4388:        $env{'course.'.$env{'request.course.id'}.'.home'};
 4389:     $coursedescrbuf{$env{'request.course.id'}}=
 4390:        $env{'course.'.$env{'request.course.id'}.'.description'};
 4391:     $courseinstcodebuf{$env{'request.course.id'}}=
 4392:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 4393:     $courseownerbuf{$env{'request.course.id'}}=
 4394:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 4395:     $coursetypebuf{$env{'request.course.id'}}=
 4396:        $env{'course.'.$env{'request.course.id'}.'.type'};
 4397:     if (defined $courselogs{$env{'request.course.id'}}) {
 4398: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 4399:     } else {
 4400: 	$courselogs{$env{'request.course.id'}}.=$what;
 4401:     }
 4402:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 4403: 	&flushcourselogs();
 4404:     }
 4405: }
 4406: 
 4407: sub courseacclog {
 4408:     my $fnsymb=shift;
 4409:     unless ($env{'request.course.id'}) { return ''; }
 4410:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 4411:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 4412:         $what.=':POST';
 4413:         # FIXME: Probably ought to escape things....
 4414: 	foreach my $key (keys(%env)) {
 4415:             if ($key=~/^form\.(.*)/) {
 4416:                 my $formitem = $1;
 4417:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 4418:                     $what.=':'.$formitem.'='.$env{$key};
 4419:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 4420:                     $what.=':'.$formitem.'='.$env{$key};
 4421:                 }
 4422:             }
 4423:         }
 4424:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 4425:         # FIXME: We should not be depending on a form parameter that someone
 4426:         # editing lonsearchcat.pm might change in the future.
 4427:         if ($env{'form.phase'} eq 'course_search') {
 4428:             $what.= ':POST';
 4429:             # FIXME: Probably ought to escape things....
 4430:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 4431:                                  'crsdiscuss') {
 4432:                 $what.=':'.$element.'='.$env{'form.'.$element};
 4433:             }
 4434:         }
 4435:     }
 4436:     &courselog($what);
 4437: }
 4438: 
 4439: sub countacc {
 4440:     my $url=&declutter(shift);
 4441:     return if (! defined($url) || $url eq '');
 4442:     unless ($env{'request.course.id'}) { return ''; }
 4443: #
 4444: # Mark that this url was used in this course
 4445: #
 4446:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 4447: #
 4448: # Increase the access count for this resource in this child process
 4449: #
 4450:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 4451:     $accesshash{$key}++;
 4452: }
 4453: 
 4454: sub linklog {
 4455:     my ($from,$to)=@_;
 4456:     $from=&declutter($from);
 4457:     $to=&declutter($to);
 4458:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 4459:     $accesshash{$to.'___'.$from.'___goto'}=1;
 4460: }
 4461: 
 4462: sub statslog {
 4463:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 4464:     if ($users<2) { return; }
 4465:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 4466:             'course'       => $env{'request.course.id'},
 4467:             'sections'     => '"all"',
 4468:             'num_students' => $users,
 4469:             'part'         => $part,
 4470:             'symb'         => $symb,
 4471:             'mean_tries'   => $av_attempts,
 4472:             'deg_of_diff'  => $degdiff});
 4473:     foreach my $key (keys(%dynstore)) {
 4474:         $accesshash{$key}=$dynstore{$key};
 4475:     }
 4476: }
 4477:   
 4478: sub userrolelog {
 4479:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 4480:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 4481:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4482:        $userrolehash
 4483:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4484:                     =$tend.':'.$tstart;
 4485:     }
 4486:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 4487:        $userrolehash
 4488:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 4489:                     =$tend.':'.$tstart;
 4490:     }
 4491:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
 4492:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4493:        $domainrolehash
 4494:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4495:                     = $tend.':'.$tstart;
 4496:     }
 4497: }
 4498: 
 4499: sub courserolelog {
 4500:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 4501:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 4502:         my $cdom = $1;
 4503:         my $cnum = $2;
 4504:         my $sec = $3;
 4505:         my $namespace = 'rolelog';
 4506:         my %storehash = (
 4507:                            role    => $trole,
 4508:                            start   => $tstart,
 4509:                            end     => $tend,
 4510:                            selfenroll => $selfenroll,
 4511:                            context    => $context,
 4512:                         );
 4513:         if ($trole eq 'gr') {
 4514:             $namespace = 'groupslog';
 4515:             $storehash{'group'} = $sec;
 4516:         } else {
 4517:             $storehash{'section'} = $sec;
 4518:         }
 4519:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 4520:                    $domain,$cnum,$cdom);
 4521:         if (($trole ne 'st') || ($sec ne '')) {
 4522:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 4523:         }
 4524:     }
 4525:     return;
 4526: }
 4527: 
 4528: sub domainrolelog {
 4529:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4530:     if ($area =~ m{^/($match_domain)/$}) {
 4531:         my $cdom = $1;
 4532:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 4533:         my $namespace = 'rolelog';
 4534:         my %storehash = (
 4535:                            role    => $trole,
 4536:                            start   => $tstart,
 4537:                            end     => $tend,
 4538:                            context => $context,
 4539:                         );
 4540:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 4541:                    $domain,$domconfiguser,$cdom);
 4542:     }
 4543:     return;
 4544: 
 4545: }
 4546: 
 4547: sub coauthorrolelog {
 4548:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4549:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 4550:         my $audom = $1;
 4551:         my $auname = $2;
 4552:         my $namespace = 'rolelog';
 4553:         my %storehash = (
 4554:                            role    => $trole,
 4555:                            start   => $tstart,
 4556:                            end     => $tend,
 4557:                            context => $context,
 4558:                         );
 4559:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 4560:                    $domain,$auname,$audom);
 4561:     }
 4562:     return;
 4563: }
 4564: 
 4565: sub get_course_adv_roles {
 4566:     my ($cid,$codes) = @_;
 4567:     $cid=$env{'request.course.id'} unless (defined($cid));
 4568:     my %coursehash=&coursedescription($cid);
 4569:     my $crstype = &Apache::loncommon::course_type($cid);
 4570:     my %nothide=();
 4571:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4572:         if ($user !~ /:/) {
 4573: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 4574:         } else {
 4575:             $nothide{$user}=1;
 4576:         }
 4577:     }
 4578:     my @possdoms = ($coursehash{'domain'});
 4579:     if ($coursehash{'checkforpriv'}) {
 4580:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 4581:     }
 4582:     my %returnhash=();
 4583:     my %dumphash=
 4584:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 4585:     my $now=time;
 4586:     my %privileged;
 4587:     foreach my $entry (keys(%dumphash)) {
 4588: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4589:         if (($tstart) && ($tstart<0)) { next; }
 4590:         if (($tend) && ($tend<$now)) { next; }
 4591:         if (($tstart) && ($now<$tstart)) { next; }
 4592:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 4593: 	if ($username eq '' || $domain eq '') { next; }
 4594:         if ((&privileged($username,$domain,\@possdoms)) &&
 4595:             (!$nothide{$username.':'.$domain})) { next; }
 4596: 	if ($role eq 'cr') { next; }
 4597:         if ($codes) {
 4598:             if ($section) { $role .= ':'.$section; }
 4599:             if ($returnhash{$role}) {
 4600:                 $returnhash{$role}.=','.$username.':'.$domain;
 4601:             } else {
 4602:                 $returnhash{$role}=$username.':'.$domain;
 4603:             }
 4604:         } else {
 4605:             my $key=&plaintext($role,$crstype);
 4606:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 4607:             if ($returnhash{$key}) {
 4608: 	        $returnhash{$key}.=','.$username.':'.$domain;
 4609:             } else {
 4610:                 $returnhash{$key}=$username.':'.$domain;
 4611:             }
 4612:         }
 4613:     }
 4614:     return %returnhash;
 4615: }
 4616: 
 4617: sub get_my_roles {
 4618:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 4619:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 4620:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 4621:     my (%dumphash,%nothide);
 4622:     if ($context eq 'userroles') {
 4623:         %dumphash = &dump('roles',$udom,$uname);
 4624:     } else {
 4625:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 4626:         if ($hidepriv) {
 4627:             my %coursehash=&coursedescription($udom.'_'.$uname);
 4628:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4629:                 if ($user !~ /:/) {
 4630:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 4631:                 } else {
 4632:                     $nothide{$user} = 1;
 4633:                 }
 4634:             }
 4635:         }
 4636:     }
 4637:     my %returnhash=();
 4638:     my $now=time;
 4639:     my %privileged;
 4640:     foreach my $entry (keys(%dumphash)) {
 4641:         my ($role,$tend,$tstart);
 4642:         if ($context eq 'userroles') {
 4643:             next if ($entry =~ /^rolesdef/);
 4644: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 4645:         } else {
 4646:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4647:         }
 4648:         if (($tstart) && ($tstart<0)) { next; }
 4649:         my $status = 'active';
 4650:         if (($tend) && ($tend<=$now)) {
 4651:             $status = 'previous';
 4652:         } 
 4653:         if (($tstart) && ($now<$tstart)) {
 4654:             $status = 'future';
 4655:         }
 4656:         if (ref($types) eq 'ARRAY') {
 4657:             if (!grep(/^\Q$status\E$/,@{$types})) {
 4658:                 next;
 4659:             } 
 4660:         } else {
 4661:             if ($status ne 'active') {
 4662:                 next;
 4663:             }
 4664:         }
 4665:         my ($rolecode,$username,$domain,$section,$area);
 4666:         if ($context eq 'userroles') {
 4667:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 4668:             (undef,$domain,$username,$section) = split(/\//,$area);
 4669:         } else {
 4670:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 4671:         }
 4672:         if (ref($roledoms) eq 'ARRAY') {
 4673:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 4674:                 next;
 4675:             }
 4676:         }
 4677:         if (ref($roles) eq 'ARRAY') {
 4678:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 4679:                 if ($role =~ /^cr\//) {
 4680:                     if (!grep(/^cr$/,@{$roles})) {
 4681:                         next;
 4682:                     }
 4683:                 } elsif ($role =~ /^gr\//) {
 4684:                     if (!grep(/^gr$/,@{$roles})) {
 4685:                         next;
 4686:                     }
 4687:                 } else {
 4688:                     next;
 4689:                 }
 4690:             }
 4691:         }
 4692:         if ($hidepriv) {
 4693:             my @privroles = ('dc','su');
 4694:             if ($context eq 'userroles') {
 4695:                 next if (grep(/^\Q$role\E$/,@privroles));
 4696:             } else {
 4697:                 my $possdoms = [$domain];
 4698:                 if (ref($roledoms) eq 'ARRAY') {
 4699:                    push(@{$possdoms},@{$roledoms}); 
 4700:                 }
 4701:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 4702:                     if (!$nothide{$username.':'.$domain}) {
 4703:                         next;
 4704:                     }
 4705:                 }
 4706:             }
 4707:         }
 4708:         if ($withsec) {
 4709:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 4710:                 $tstart.':'.$tend;
 4711:         } else {
 4712:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 4713:         }
 4714:     }
 4715:     return %returnhash;
 4716: }
 4717: 
 4718: sub get_all_adhocroles {
 4719:     my ($dom) = @_;
 4720:     my @roles_by_num = ();
 4721:     my %domdefaults = &get_domain_defaults($dom);
 4722:     my (%description,%access_in_dom,%access_info);
 4723:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
 4724:         my $count = 0;
 4725:         my %domcurrent = %{$domdefaults{'adhocroles'}};
 4726:         my %ordered;
 4727:         foreach my $role (sort(keys(%domcurrent))) {
 4728:             my ($order,$desc,$access_in_dom);
 4729:             if (ref($domcurrent{$role}) eq 'HASH') {
 4730:                 $order = $domcurrent{$role}{'order'};
 4731:                 $desc = $domcurrent{$role}{'desc'};
 4732:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
 4733:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
 4734:             }
 4735:             if ($order eq '') {
 4736:                 $order = $count;
 4737:             }
 4738:             $ordered{$order} = $role;
 4739:             if ($desc ne '') {
 4740:                 $description{$role} = $desc;
 4741:             } else {
 4742:                 $description{$role}= $role;
 4743:             }
 4744:             $count++;
 4745:         }
 4746:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
 4747:             push(@roles_by_num,$ordered{$item});
 4748:         }
 4749:     }
 4750:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
 4751: }
 4752: 
 4753: sub get_my_adhocroles {
 4754:     my ($cid,$checkreg) = @_;
 4755:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
 4756:     if ($env{'request.course.id'} eq $cid) {
 4757:         $cdom = $env{'course.'.$cid.'.domain'};
 4758:         $cnum = $env{'course.'.$cid.'.num'};
 4759:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
 4760:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
 4761:         $cdom = $1;
 4762:         $cnum = $2;
 4763:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
 4764:                                      $cdom,$cnum);
 4765:     }
 4766:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
 4767:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
 4768:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
 4769:         if ($rosterhash{$user} ne '') {
 4770:             my $type = (split(/:/,$rosterhash{$user}))[5];
 4771:             return ([],{}) if ($type eq 'auto');
 4772:         }
 4773:     }
 4774:     if (($cdom ne '') && ($cnum ne ''))  {
 4775:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
 4776:             my $then=$env{'user.login.time'};
 4777:             my $update=$env{'user.update.time'};
 4778:             if (!$update) {
 4779:                 $update = $then;
 4780:             }
 4781:             my @liveroles;
 4782:             foreach my $role ('dh','da') {
 4783:                 if ($env{"user.role.$role./$cdom/"}) {
 4784:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
 4785:                     my $limit = $update;
 4786:                     if ($env{'request.role'} eq "$role./$cdom/") {
 4787:                         $limit = $then;
 4788:                     }
 4789:                     my $activerole = 1;
 4790:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
 4791:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
 4792:                     if ($activerole) {
 4793:                         push(@liveroles,$role);
 4794:                     }
 4795:                 }
 4796:             }
 4797:             if (@liveroles) {
 4798:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
 4799:                     my ($accessref,$accessinfo,%access_in_dom);
 4800:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
 4801:                     if (ref($roles_by_num) eq 'ARRAY') {
 4802:                         if (@{$roles_by_num}) {
 4803:                             my %settings;
 4804:                             if ($env{'request.course.id'} eq $cid) {
 4805:                                 foreach my $envkey (keys(%env)) {
 4806:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
 4807:                                         $settings{$1} = $env{$envkey};
 4808:                                     }
 4809:                                 }
 4810:                             } else {
 4811:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
 4812:                             }
 4813:                             my %setincrs;
 4814:                             if ($settings{'internal.adhocaccess'}) {
 4815:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
 4816:                             }
 4817:                             my @statuses;
 4818:                             if ($env{'environment.inststatus'}) {
 4819:                                 @statuses = split(/,/,$env{'environment.inststatus'});
 4820:                             }
 4821:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
 4822:                             if (ref($accessref) eq 'HASH') {
 4823:                                 %access_in_dom = %{$accessref};
 4824:                             }
 4825:                             foreach my $role (@{$roles_by_num}) {
 4826:                                 my ($curraccess,@okstatus,@personnel);
 4827:                                 if ($setincrs{$role}) {
 4828:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
 4829:                                     if ($curraccess eq 'status') {
 4830:                                         @okstatus = split(/\&/,$rest);
 4831:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 4832:                                         @personnel = split(/\&/,$rest);
 4833:                                     }
 4834:                                 } else {
 4835:                                     $curraccess = $access_in_dom{$role};
 4836:                                     if (ref($accessinfo) eq 'HASH') {
 4837:                                         if ($curraccess eq 'status') {
 4838:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 4839:                                                 @okstatus = @{$accessinfo->{$role}};
 4840:                                             }
 4841:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 4842:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
 4843:                                                 @personnel = @{$accessinfo->{$role}};
 4844:                                             }
 4845:                                         }
 4846:                                     }
 4847:                                 }
 4848:                                 if ($curraccess eq 'none') {
 4849:                                     next;
 4850:                                 } elsif ($curraccess eq 'all') {
 4851:                                     push(@possroles,$role);
 4852:                                 } elsif ($curraccess eq 'dh') {
 4853:                                     if (grep(/^dh$/,@liveroles)) {
 4854:                                         push(@possroles,$role);
 4855:                                     } else {
 4856:                                         next;
 4857:                                     }
 4858:                                 } elsif ($curraccess eq 'da') {
 4859:                                     if (grep(/^da$/,@liveroles)) {
 4860:                                         push(@possroles,$role);
 4861:                                     } else {
 4862:                                         next;
 4863:                                     }
 4864:                                 } elsif ($curraccess eq 'status') {
 4865:                                     if (@okstatus) {
 4866:                                         if (!@statuses) {
 4867:                                             if (grep(/^default$/,@okstatus)) {
 4868:                                                 push(@possroles,$role);
 4869:                                             }
 4870:                                         } else {
 4871:                                             foreach my $status (@okstatus) {
 4872:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
 4873:                                                     push(@possroles,$role);
 4874:                                                     last;
 4875:                                                 }
 4876:                                             }
 4877:                                         }
 4878:                                     }
 4879:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
 4880:                                     if (grep(/^\Q$user\E$/,@personnel)) {
 4881:                                         if ($curraccess eq 'exc') {
 4882:                                             push(@possroles,$role);
 4883:                                         }
 4884:                                     } elsif ($curraccess eq 'inc') {
 4885:                                         push(@possroles,$role);
 4886:                                     }
 4887:                                 }
 4888:                             }
 4889:                         }
 4890:                     }
 4891:                 }
 4892:             }
 4893:         }
 4894:     }
 4895:     unless (ref($description) eq 'HASH') {
 4896:         if (ref($roles_by_num) eq 'ARRAY') {
 4897:             my %desc;
 4898:             map { $desc{$_} = $_; } (@{$roles_by_num});
 4899:             $description = \%desc;
 4900:         } else {
 4901:             $description = {};
 4902:         }
 4903:     }
 4904:     return (\@possroles,$description);
 4905: }
 4906: 
 4907: # ----------------------------------------------------- Frontpage Announcements
 4908: #
 4909: #
 4910: 
 4911: sub postannounce {
 4912:     my ($server,$text)=@_;
 4913:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 4914:     unless ($text=~/\w/) { $text=''; }
 4915:     return &reply('setannounce:'.&escape($text),$server);
 4916: }
 4917: 
 4918: sub getannounce {
 4919: 
 4920:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 4921: 	my $announcement='';
 4922: 	while (my $line = <$fh>) { $announcement .= $line; }
 4923: 	close($fh);
 4924: 	if ($announcement=~/\w/) { 
 4925: 	    return 
 4926:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 4927:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 4928: 	} else {
 4929: 	    return '';
 4930: 	}
 4931:     } else {
 4932: 	return '';
 4933:     }
 4934: }
 4935: 
 4936: # ---------------------------------------------------------- Course ID routines
 4937: # Deal with domain's nohist_courseid.db files
 4938: #
 4939: 
 4940: sub courseidput {
 4941:     my ($domain,$storehash,$coursehome,$caller) = @_;
 4942:     return unless (ref($storehash) eq 'HASH');
 4943:     my $outcome;
 4944:     if ($caller eq 'timeonly') {
 4945:         my $cids = '';
 4946:         foreach my $item (keys(%$storehash)) {
 4947:             $cids.=&escape($item).'&';
 4948:         }
 4949:         $cids=~s/\&$//;
 4950:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 4951:                           $coursehome);       
 4952:     } else {
 4953:         my $items = '';
 4954:         foreach my $item (keys(%$storehash)) {
 4955:             $items.= &escape($item).'='.
 4956:                      &freeze_escape($$storehash{$item}).'&';
 4957:         }
 4958:         $items=~s/\&$//;
 4959:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 4960:                           $coursehome);
 4961:     }
 4962:     if ($outcome eq 'unknown_cmd') {
 4963:         my $what;
 4964:         foreach my $cid (keys(%$storehash)) {
 4965:             $what .= &escape($cid).'=';
 4966:             foreach my $item ('description','inst_code','owner','type') {
 4967:                 $what .= &escape($storehash->{$cid}{$item}).':';
 4968:             }
 4969:             $what =~ s/\:$/&/;
 4970:         }
 4971:         $what =~ s/\&$//;  
 4972:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 4973:     } else {
 4974:         return $outcome;
 4975:     }
 4976: }
 4977: 
 4978: sub courseiddump {
 4979:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 4980:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 4981:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 4982:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 4983:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
 4984:     my $as_hash = 1;
 4985:     my %returnhash;
 4986:     if (!$domfilter) { $domfilter=''; }
 4987:     my %libserv = &all_library();
 4988:     foreach my $tryserver (keys(%libserv)) {
 4989:         if ( (  $hostidflag == 1 
 4990: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 4991: 	     || (!defined($hostidflag)) ) {
 4992: 
 4993: 	    if (($domfilter eq '') ||
 4994: 		(&host_domain($tryserver) eq $domfilter)) {
 4995:                 my $rep;
 4996:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 4997:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 4998:                         join(":", (&host_domain($tryserver), $sincefilter, 
 4999:                                 &escape($descfilter), &escape($instcodefilter), 
 5000:                                 &escape($ownerfilter), &escape($coursefilter),
 5001:                                 &escape($typefilter), &escape($regexp_ok), 
 5002:                                 $as_hash, &escape($selfenrollonly), 
 5003:                                 &escape($catfilter), $showhidden, $caller, 
 5004:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 5005:                                 &escape($createdbefore), &escape($createdafter), 
 5006:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
 5007:                                 $reqcrsdom,&escape($reqinstcode))));
 5008:                 } else {
 5009:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 5010:                              $sincefilter.':'.&escape($descfilter).':'.
 5011:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 5012:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 5013:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 5014:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 5015:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 5016:                              &escape($cc_clone).':'.$cloneonly.':'.
 5017:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 5018:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
 5019:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
 5020:                 }
 5021:                      
 5022:                 my @pairs=split(/\&/,$rep);
 5023:                 foreach my $item (@pairs) {
 5024:                     my ($key,$value)=split(/\=/,$item,2);
 5025:                     $key = &unescape($key);
 5026:                     next if ($key =~ /^error: 2 /);
 5027:                     my $result = &thaw_unescape($value);
 5028:                     if (ref($result) eq 'HASH') {
 5029:                         $returnhash{$key}=$result;
 5030:                     } else {
 5031:                         my @responses = split(/:/,$value);
 5032:                         my @items = ('description','inst_code','owner','type');
 5033:                         for (my $i=0; $i<@responses; $i++) {
 5034:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 5035:                         }
 5036:                     }
 5037:                 }
 5038:             }
 5039:         }
 5040:     }
 5041:     return %returnhash;
 5042: }
 5043: 
 5044: sub courselastaccess {
 5045:     my ($cdom,$cnum,$hostidref) = @_;
 5046:     my %returnhash;
 5047:     if ($cdom && $cnum) {
 5048:         my $chome = &homeserver($cnum,$cdom);
 5049:         if ($chome ne 'no_host') {
 5050:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 5051:             &extract_lastaccess(\%returnhash,$rep);
 5052:         }
 5053:     } else {
 5054:         if (!$cdom) { $cdom=''; }
 5055:         my %libserv = &all_library();
 5056:         foreach my $tryserver (keys(%libserv)) {
 5057:             if (ref($hostidref) eq 'ARRAY') {
 5058:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 5059:             } 
 5060:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 5061:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 5062:                 &extract_lastaccess(\%returnhash,$rep);
 5063:             }
 5064:         }
 5065:     }
 5066:     return %returnhash;
 5067: }
 5068: 
 5069: sub extract_lastaccess {
 5070:     my ($returnhash,$rep) = @_;
 5071:     if (ref($returnhash) eq 'HASH') {
 5072:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 5073:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 5074:                  $rep eq '') {
 5075:             my @pairs=split(/\&/,$rep);
 5076:             foreach my $item (@pairs) {
 5077:                 my ($key,$value)=split(/\=/,$item,2);
 5078:                 $key = &unescape($key);
 5079:                 next if ($key =~ /^error: 2 /);
 5080:                 $returnhash->{$key} = &thaw_unescape($value);
 5081:             }
 5082:         }
 5083:     }
 5084:     return;
 5085: }
 5086: 
 5087: # ---------------------------------------------------------- DC e-mail
 5088: 
 5089: sub dcmailput {
 5090:     my ($domain,$msgid,$message,$server)=@_;
 5091:     my $status = &Apache::lonnet::critical(
 5092:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 5093:        &escape($message),$server);
 5094:     return $status;
 5095: }
 5096: 
 5097: sub dcmaildump {
 5098:     my ($dom,$startdate,$enddate,$senders) = @_;
 5099:     my %returnhash=();
 5100: 
 5101:     if (defined(&domain($dom,'primary'))) {
 5102:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 5103:                                                          &escape($enddate).':';
 5104: 	my @esc_senders=map { &escape($_)} @$senders;
 5105: 	$cmd.=&escape(join('&',@esc_senders));
 5106: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 5107:             my ($key,$value) = split(/\=/,$line,2);
 5108:             if (($key) && ($value)) {
 5109:                 $returnhash{&unescape($key)} = &unescape($value);
 5110:             }
 5111:         }
 5112:     }
 5113:     return %returnhash;
 5114: }
 5115: # ---------------------------------------------------------- Domain roles
 5116: 
 5117: sub get_domain_roles {
 5118:     my ($dom,$roles,$startdate,$enddate)=@_;
 5119:     if ((!defined($startdate)) || ($startdate eq '')) {
 5120:         $startdate = '.';
 5121:     }
 5122:     if ((!defined($enddate)) || ($enddate eq '')) {
 5123:         $enddate = '.';
 5124:     }
 5125:     my $rolelist;
 5126:     if (ref($roles) eq 'ARRAY') {
 5127:         $rolelist = join('&',@{$roles});
 5128:     }
 5129:     my %personnel = ();
 5130: 
 5131:     my %servers = &get_servers($dom,'library');
 5132:     foreach my $tryserver (keys(%servers)) {
 5133: 	%{$personnel{$tryserver}}=();
 5134: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 5135: 					    &escape($startdate).':'.
 5136: 					    &escape($enddate).':'.
 5137: 					    &escape($rolelist), $tryserver))) {
 5138: 	    my ($key,$value) = split(/\=/,$line,2);
 5139: 	    if (($key) && ($value)) {
 5140: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 5141: 	    }
 5142: 	}
 5143:     }
 5144:     return %personnel;
 5145: }
 5146: 
 5147: sub get_active_domroles {
 5148:     my ($dom,$roles) = @_;
 5149:     return () unless (ref($roles) eq 'ARRAY');
 5150:     my $now = time;
 5151:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
 5152:     my %domroles;
 5153:     foreach my $server (keys(%dompersonnel)) {
 5154:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
 5155:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
 5156:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
 5157:         }
 5158:     }
 5159:     return %domroles;
 5160: }
 5161: 
 5162: # ----------------------------------------------------------- Interval timing 
 5163: 
 5164: {
 5165: # Caches needed for speedup of navmaps
 5166: # We don't want to cache this for very long at all (5 seconds at most)
 5167: # 
 5168: # The user for whom we cache
 5169: my $cachedkey='';
 5170: # The cached times for this user
 5171: my %cachedtimes=();
 5172: # When this was last done
 5173: my $cachedtime='';
 5174: 
 5175: sub load_all_first_access {
 5176:     my ($uname,$udom,$ignorecache)=@_;
 5177:     if (($cachedkey eq $uname.':'.$udom) &&
 5178:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
 5179:         (!$ignorecache)) {
 5180:         return;
 5181:     }
 5182:     $cachedtime=time;
 5183:     $cachedkey=$uname.':'.$udom;
 5184:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 5185: }
 5186: 
 5187: sub get_first_access {
 5188:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
 5189:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5190:     if ($argsymb) { $symb=$argsymb; }
 5191:     my ($map,$id,$res)=&decode_symb($symb);
 5192:     if ($argmap) { $map = $argmap; }
 5193:     if ($type eq 'course') {
 5194: 	$res='course';
 5195:     } elsif ($type eq 'map') {
 5196: 	$res=&symbread($map);
 5197:     } else {
 5198: 	$res=$symb;
 5199:     }
 5200:     &load_all_first_access($uname,$udom,$ignorecache);
 5201:     return $cachedtimes{"$courseid\0$res"};
 5202: }
 5203: 
 5204: sub set_first_access {
 5205:     my ($type,$interval)=@_;
 5206:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 5207:     my ($map,$id,$res)=&decode_symb($symb);
 5208:     if ($type eq 'course') {
 5209: 	$res='course';
 5210:     } elsif ($type eq 'map') {
 5211: 	$res=&symbread($map);
 5212:     } else {
 5213: 	$res=$symb;
 5214:     }
 5215:     $cachedkey='';
 5216:     my $firstaccess=&get_first_access($type,$symb,$map);
 5217:     if (!$firstaccess) {
 5218:         my $start = time;
 5219: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 5220:                           $udom,$uname);
 5221:         if ($putres eq 'ok') {
 5222:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 5223:                  $udom,$uname); 
 5224:             &appenv(
 5225:                      {
 5226:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 5227:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 5228:                      }
 5229:                   );
 5230:         }
 5231:         return $putres;
 5232:     }
 5233:     return 'already_set';
 5234: }
 5235: }
 5236: 
 5237: # --------------------------------------------- Set Expire Date for Spreadsheet
 5238: 
 5239: sub expirespread {
 5240:     my ($uname,$udom,$stype,$usymb)=@_;
 5241:     my $cid=$env{'request.course.id'}; 
 5242:     if ($cid) {
 5243:        my $now=time;
 5244:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 5245:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 5246:                             $env{'course.'.$cid.'.num'}.
 5247: 	        	    ':nohist_expirationdates:'.
 5248:                             &escape($key).'='.$now,
 5249:                             $env{'course.'.$cid.'.home'})
 5250:     }
 5251:     return 'ok';
 5252: }
 5253: 
 5254: # ----------------------------------------------------- Devalidate Spreadsheets
 5255: 
 5256: sub devalidate {
 5257:     my ($symb,$uname,$udom)=@_;
 5258:     my $cid=$env{'request.course.id'}; 
 5259:     if ($cid) {
 5260:         # delete the stored spreadsheets for
 5261:         # - the student level sheet of this user in course's homespace
 5262:         # - the assessment level sheet for this resource 
 5263:         #   for this user in user's homespace
 5264: 	# - current conditional state info
 5265: 	my $key=$uname.':'.$udom.':';
 5266:         my $status=
 5267: 	    &del('nohist_calculatedsheets',
 5268: 		 [$key.'studentcalc:'],
 5269: 		 $env{'course.'.$cid.'.domain'},
 5270: 		 $env{'course.'.$cid.'.num'})
 5271: 		.' '.
 5272: 	    &del('nohist_calculatedsheets_'.$cid,
 5273: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 5274:         unless ($status eq 'ok ok') {
 5275:            &logthis('Could not devalidate spreadsheet '.
 5276:                     $uname.' at '.$udom.' for '.
 5277: 		    $symb.': '.$status);
 5278:         }
 5279: 	&delenv('user.state.'.$cid);
 5280:     }
 5281: }
 5282: 
 5283: sub get_scalar {
 5284:     my ($string,$end) = @_;
 5285:     my $value;
 5286:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 5287: 	$value = $1;
 5288:     } elsif ($$string =~ s/^([^&]*?)&//) {
 5289: 	$value = $1;
 5290:     }
 5291:     return &unescape($value);
 5292: }
 5293: 
 5294: sub array2str {
 5295:   my (@array) = @_;
 5296:   my $result=&arrayref2str(\@array);
 5297:   $result=~s/^__ARRAY_REF__//;
 5298:   $result=~s/__END_ARRAY_REF__$//;
 5299:   return $result;
 5300: }
 5301: 
 5302: sub arrayref2str {
 5303:   my ($arrayref) = @_;
 5304:   my $result='__ARRAY_REF__';
 5305:   foreach my $elem (@$arrayref) {
 5306:     if(ref($elem) eq 'ARRAY') {
 5307:       $result.=&arrayref2str($elem).'&';
 5308:     } elsif(ref($elem) eq 'HASH') {
 5309:       $result.=&hashref2str($elem).'&';
 5310:     } elsif(ref($elem)) {
 5311:       #print("Got a ref of ".(ref($elem))." skipping.");
 5312:     } else {
 5313:       $result.=&escape($elem).'&';
 5314:     }
 5315:   }
 5316:   $result=~s/\&$//;
 5317:   $result .= '__END_ARRAY_REF__';
 5318:   return $result;
 5319: }
 5320: 
 5321: sub hash2str {
 5322:   my (%hash) = @_;
 5323:   my $result=&hashref2str(\%hash);
 5324:   $result=~s/^__HASH_REF__//;
 5325:   $result=~s/__END_HASH_REF__$//;
 5326:   return $result;
 5327: }
 5328: 
 5329: sub hashref2str {
 5330:   my ($hashref)=@_;
 5331:   my $result='__HASH_REF__';
 5332:   foreach my $key (sort(keys(%$hashref))) {
 5333:     if (ref($key) eq 'ARRAY') {
 5334:       $result.=&arrayref2str($key).'=';
 5335:     } elsif (ref($key) eq 'HASH') {
 5336:       $result.=&hashref2str($key).'=';
 5337:     } elsif (ref($key)) {
 5338:       $result.='=';
 5339:       #print("Got a ref of ".(ref($key))." skipping.");
 5340:     } else {
 5341: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 5342:     }
 5343: 
 5344:     if(ref($hashref->{$key}) eq 'ARRAY') {
 5345:       $result.=&arrayref2str($hashref->{$key}).'&';
 5346:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 5347:       $result.=&hashref2str($hashref->{$key}).'&';
 5348:     } elsif(ref($hashref->{$key})) {
 5349:        $result.='&';
 5350:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 5351:     } else {
 5352:       $result.=&escape($hashref->{$key}).'&';
 5353:     }
 5354:   }
 5355:   $result=~s/\&$//;
 5356:   $result .= '__END_HASH_REF__';
 5357:   return $result;
 5358: }
 5359: 
 5360: sub str2hash {
 5361:     my ($string)=@_;
 5362:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 5363:     return %$hash;
 5364: }
 5365: 
 5366: sub str2hashref {
 5367:   my ($string) = @_;
 5368: 
 5369:   my %hash;
 5370: 
 5371:   if($string !~ /^__HASH_REF__/) {
 5372:       if (! ($string eq '' || !defined($string))) {
 5373: 	  $hash{'error'}='Not hash reference';
 5374:       }
 5375:       return (\%hash, $string);
 5376:   }
 5377: 
 5378:   $string =~ s/^__HASH_REF__//;
 5379: 
 5380:   while($string !~ /^__END_HASH_REF__/) {
 5381:       #key
 5382:       my $key='';
 5383:       if($string =~ /^__HASH_REF__/) {
 5384:           ($key, $string)=&str2hashref($string);
 5385:           if(defined($key->{'error'})) {
 5386:               $hash{'error'}='Bad data';
 5387:               return (\%hash, $string);
 5388:           }
 5389:       } elsif($string =~ /^__ARRAY_REF__/) {
 5390:           ($key, $string)=&str2arrayref($string);
 5391:           if($key->[0] eq 'Array reference error') {
 5392:               $hash{'error'}='Bad data';
 5393:               return (\%hash, $string);
 5394:           }
 5395:       } else {
 5396:           $string =~ s/^(.*?)=//;
 5397: 	  $key=&unescape($1);
 5398:       }
 5399:       $string =~ s/^=//;
 5400: 
 5401:       #value
 5402:       my $value='';
 5403:       if($string =~ /^__HASH_REF__/) {
 5404:           ($value, $string)=&str2hashref($string);
 5405:           if(defined($value->{'error'})) {
 5406:               $hash{'error'}='Bad data';
 5407:               return (\%hash, $string);
 5408:           }
 5409:       } elsif($string =~ /^__ARRAY_REF__/) {
 5410:           ($value, $string)=&str2arrayref($string);
 5411:           if($value->[0] eq 'Array reference error') {
 5412:               $hash{'error'}='Bad data';
 5413:               return (\%hash, $string);
 5414:           }
 5415:       } else {
 5416: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 5417:       }
 5418:       $string =~ s/^&//;
 5419: 
 5420:       $hash{$key}=$value;
 5421:   }
 5422: 
 5423:   $string =~ s/^__END_HASH_REF__//;
 5424: 
 5425:   return (\%hash, $string);
 5426: }
 5427: 
 5428: sub str2array {
 5429:     my ($string)=@_;
 5430:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 5431:     return @$array;
 5432: }
 5433: 
 5434: sub str2arrayref {
 5435:   my ($string) = @_;
 5436:   my @array;
 5437: 
 5438:   if($string !~ /^__ARRAY_REF__/) {
 5439:       if (! ($string eq '' || !defined($string))) {
 5440: 	  $array[0]='Array reference error';
 5441:       }
 5442:       return (\@array, $string);
 5443:   }
 5444: 
 5445:   $string =~ s/^__ARRAY_REF__//;
 5446: 
 5447:   while($string !~ /^__END_ARRAY_REF__/) {
 5448:       my $value='';
 5449:       if($string =~ /^__HASH_REF__/) {
 5450:           ($value, $string)=&str2hashref($string);
 5451:           if(defined($value->{'error'})) {
 5452:               $array[0] ='Array reference error';
 5453:               return (\@array, $string);
 5454:           }
 5455:       } elsif($string =~ /^__ARRAY_REF__/) {
 5456:           ($value, $string)=&str2arrayref($string);
 5457:           if($value->[0] eq 'Array reference error') {
 5458:               $array[0] ='Array reference error';
 5459:               return (\@array, $string);
 5460:           }
 5461:       } else {
 5462: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 5463:       }
 5464:       $string =~ s/^&//;
 5465: 
 5466:       push(@array, $value);
 5467:   }
 5468: 
 5469:   $string =~ s/^__END_ARRAY_REF__//;
 5470: 
 5471:   return (\@array, $string);
 5472: }
 5473: 
 5474: # -------------------------------------------------------------------Temp Store
 5475: 
 5476: sub tmpreset {
 5477:   my ($symb,$namespace,$domain,$stuname) = @_;
 5478:   if (!$symb) {
 5479:     $symb=&symbread();
 5480:     if (!$symb) { $symb= $env{'request.url'}; }
 5481:   }
 5482:   $symb=escape($symb);
 5483: 
 5484:   if (!$namespace) { $namespace=$env{'request.state'}; }
 5485:   $namespace=~s/\//\_/g;
 5486:   $namespace=~s/\W//g;
 5487: 
 5488:   if (!$domain) { $domain=$env{'user.domain'}; }
 5489:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5490:   if ($domain eq 'public' && $stuname eq 'public') {
 5491:       $stuname=$ENV{'REMOTE_ADDR'};
 5492:   }
 5493:   my $path=LONCAPA::tempdir();
 5494:   my %hash;
 5495:   if (tie(%hash,'GDBM_File',
 5496: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5497: 	  &GDBM_WRCREAT(),0640)) {
 5498:     foreach my $key (keys(%hash)) {
 5499:       if ($key=~ /:$symb/) {
 5500: 	delete($hash{$key});
 5501:       }
 5502:     }
 5503:   }
 5504: }
 5505: 
 5506: sub tmpstore {
 5507:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 5508: 
 5509:   if (!$symb) {
 5510:     $symb=&symbread();
 5511:     if (!$symb) { $symb= $env{'request.url'}; }
 5512:   }
 5513:   $symb=escape($symb);
 5514: 
 5515:   if (!$namespace) {
 5516:     # I don't think we would ever want to store this for a course.
 5517:     # it seems this will only be used if we don't have a course.
 5518:     #$namespace=$env{'request.course.id'};
 5519:     #if (!$namespace) {
 5520:       $namespace=$env{'request.state'};
 5521:     #}
 5522:   }
 5523:   $namespace=~s/\//\_/g;
 5524:   $namespace=~s/\W//g;
 5525:   if (!$domain) { $domain=$env{'user.domain'}; }
 5526:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5527:   if ($domain eq 'public' && $stuname eq 'public') {
 5528:       $stuname=$ENV{'REMOTE_ADDR'};
 5529:   }
 5530:   my $now=time;
 5531:   my %hash;
 5532:   my $path=LONCAPA::tempdir();
 5533:   if (tie(%hash,'GDBM_File',
 5534: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5535: 	  &GDBM_WRCREAT(),0640)) {
 5536:     $hash{"version:$symb"}++;
 5537:     my $version=$hash{"version:$symb"};
 5538:     my $allkeys=''; 
 5539:     foreach my $key (keys(%$storehash)) {
 5540:       $allkeys.=$key.':';
 5541:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 5542:     }
 5543:     $hash{"$version:$symb:timestamp"}=$now;
 5544:     $allkeys.='timestamp';
 5545:     $hash{"$version:keys:$symb"}=$allkeys;
 5546:     if (untie(%hash)) {
 5547:       return 'ok';
 5548:     } else {
 5549:       return "error:$!";
 5550:     }
 5551:   } else {
 5552:     return "error:$!";
 5553:   }
 5554: }
 5555: 
 5556: # -----------------------------------------------------------------Temp Restore
 5557: 
 5558: sub tmprestore {
 5559:   my ($symb,$namespace,$domain,$stuname) = @_;
 5560: 
 5561:   if (!$symb) {
 5562:     $symb=&symbread();
 5563:     if (!$symb) { $symb= $env{'request.url'}; }
 5564:   }
 5565:   $symb=escape($symb);
 5566: 
 5567:   if (!$namespace) { $namespace=$env{'request.state'}; }
 5568: 
 5569:   if (!$domain) { $domain=$env{'user.domain'}; }
 5570:   if (!$stuname) { $stuname=$env{'user.name'}; }
 5571:   if ($domain eq 'public' && $stuname eq 'public') {
 5572:       $stuname=$ENV{'REMOTE_ADDR'};
 5573:   }
 5574:   my %returnhash;
 5575:   $namespace=~s/\//\_/g;
 5576:   $namespace=~s/\W//g;
 5577:   my %hash;
 5578:   my $path=LONCAPA::tempdir();
 5579:   if (tie(%hash,'GDBM_File',
 5580: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 5581: 	  &GDBM_READER(),0640)) {
 5582:     my $version=$hash{"version:$symb"};
 5583:     $returnhash{'version'}=$version;
 5584:     my $scope;
 5585:     for ($scope=1;$scope<=$version;$scope++) {
 5586:       my $vkeys=$hash{"$scope:keys:$symb"};
 5587:       my @keys=split(/:/,$vkeys);
 5588:       my $key;
 5589:       $returnhash{"$scope:keys"}=$vkeys;
 5590:       foreach $key (@keys) {
 5591: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 5592: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 5593:       }
 5594:     }
 5595:     if (!(untie(%hash))) {
 5596:       return "error:$!";
 5597:     }
 5598:   } else {
 5599:     return "error:$!";
 5600:   }
 5601:   return %returnhash;
 5602: }
 5603: 
 5604: # ----------------------------------------------------------------------- Store
 5605: 
 5606: sub store {
 5607:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 5608:     my $home='';
 5609: 
 5610:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 5611: 
 5612:     $symb=&symbclean($symb);
 5613:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 5614: 
 5615:     if (!$domain) { $domain=$env{'user.domain'}; }
 5616:     if (!$stuname) { $stuname=$env{'user.name'}; }
 5617: 
 5618:     &devalidate($symb,$stuname,$domain);
 5619: 
 5620:     $symb=escape($symb);
 5621:     if (!$namespace) { 
 5622:        unless ($namespace=$env{'request.course.id'}) { 
 5623:           return ''; 
 5624:        } 
 5625:     }
 5626:     if (!$home) { $home=$env{'user.home'}; }
 5627: 
 5628:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 5629:     $$storehash{'host'}=$perlvar{'lonHostID'};
 5630: 
 5631:     my $namevalue='';
 5632:     foreach my $key (keys(%$storehash)) {
 5633:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5634:     }
 5635:     $namevalue=~s/\&$//;
 5636:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 5637:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 5638: }
 5639: 
 5640: # -------------------------------------------------------------- Critical Store
 5641: 
 5642: sub cstore {
 5643:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 5644:     my $home='';
 5645: 
 5646:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 5647: 
 5648:     $symb=&symbclean($symb);
 5649:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 5650: 
 5651:     if (!$domain) { $domain=$env{'user.domain'}; }
 5652:     if (!$stuname) { $stuname=$env{'user.name'}; }
 5653: 
 5654:     &devalidate($symb,$stuname,$domain);
 5655: 
 5656:     $symb=escape($symb);
 5657:     if (!$namespace) { 
 5658:        unless ($namespace=$env{'request.course.id'}) { 
 5659:           return ''; 
 5660:        } 
 5661:     }
 5662:     if (!$home) { $home=$env{'user.home'}; }
 5663: 
 5664:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 5665:     $$storehash{'host'}=$perlvar{'lonHostID'};
 5666: 
 5667:     my $namevalue='';
 5668:     foreach my $key (keys(%$storehash)) {
 5669:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5670:     }
 5671:     $namevalue=~s/\&$//;
 5672:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 5673:     return critical
 5674:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 5675: }
 5676: 
 5677: # --------------------------------------------------------------------- Restore
 5678: 
 5679: sub restore {
 5680:     my ($symb,$namespace,$domain,$stuname) = @_;
 5681:     my $home='';
 5682: 
 5683:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 5684: 
 5685:     if (!$symb) {
 5686:         return if ($namespace eq 'courserequests');
 5687:         unless ($symb=escape(&symbread())) { return ''; }
 5688:     } else {
 5689:         unless ($namespace eq 'courserequests') {
 5690:             $symb=&escape(&symbclean($symb));
 5691:         }
 5692:     }
 5693:     if (!$namespace) { 
 5694:        unless ($namespace=$env{'request.course.id'}) { 
 5695:           return ''; 
 5696:        } 
 5697:     }
 5698:     if (!$domain) { $domain=$env{'user.domain'}; }
 5699:     if (!$stuname) { $stuname=$env{'user.name'}; }
 5700:     if (!$home) { $home=$env{'user.home'}; }
 5701:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 5702: 
 5703:     my %returnhash=();
 5704:     foreach my $line (split(/\&/,$answer)) {
 5705: 	my ($name,$value)=split(/\=/,$line);
 5706:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 5707:     }
 5708:     my $version;
 5709:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 5710:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 5711:           $returnhash{$item}=$returnhash{$version.':'.$item};
 5712:        }
 5713:     }
 5714:     return %returnhash;
 5715: }
 5716: 
 5717: # ---------------------------------------------------------- Course Description
 5718: #
 5719: #  
 5720: 
 5721: sub coursedescription {
 5722:     my ($courseid,$args)=@_;
 5723:     $courseid=~s/^\///;
 5724:     $courseid=~s/\_/\//g;
 5725:     my ($cdomain,$cnum)=split(/\//,$courseid);
 5726:     my $chome=&homeserver($cnum,$cdomain);
 5727:     my $normalid=$cdomain.'_'.$cnum;
 5728:     # need to always cache even if we get errors otherwise we keep 
 5729:     # trying and trying and trying to get the course description.
 5730:     my %envhash=();
 5731:     my %returnhash=();
 5732:     
 5733:     my $expiretime=600;
 5734:     if ($env{'request.course.id'} eq $normalid) {
 5735: 	$expiretime=120;
 5736:     }
 5737: 
 5738:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 5739:     if (!$args->{'freshen_cache'}
 5740: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 5741: 	foreach my $key (keys(%env)) {
 5742: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 5743: 	    my ($setting) = $1;
 5744: 	    $returnhash{$setting} = $env{$key};
 5745: 	}
 5746: 	return %returnhash;
 5747:     }
 5748: 
 5749:     # get the data again
 5750: 
 5751:     if (!$args->{'one_time'}) {
 5752: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 5753:     }
 5754: 
 5755:     if ($chome ne 'no_host') {
 5756:        %returnhash=&dump('environment',$cdomain,$cnum);
 5757:        if (!exists($returnhash{'con_lost'})) {
 5758: 	   my $username = $env{'user.name'}; # Defult username
 5759: 	   if(defined $args->{'user'}) {
 5760: 	       $username = $args->{'user'};
 5761: 	   }
 5762:            $returnhash{'home'}= $chome;
 5763: 	   $returnhash{'domain'} = $cdomain;
 5764: 	   $returnhash{'num'} = $cnum;
 5765:            if (!defined($returnhash{'type'})) {
 5766:                $returnhash{'type'} = 'Course';
 5767:            }
 5768:            while (my ($name,$value) = each %returnhash) {
 5769:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 5770:            }
 5771:            $returnhash{'url'}=&clutter($returnhash{'url'});
 5772:            $returnhash{'fn'}=LONCAPA::tempdir() .
 5773: 	       $username.'_'.$cdomain.'_'.$cnum;
 5774:            $envhash{'course.'.$normalid.'.home'}=$chome;
 5775:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 5776:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 5777:        }
 5778:     }
 5779:     if (!$args->{'one_time'}) {
 5780: 	&appenv(\%envhash);
 5781:     }
 5782:     return %returnhash;
 5783: }
 5784: 
 5785: sub update_released_required {
 5786:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 5787:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 5788:         $cid = $env{'request.course.id'};
 5789:         $cdom = $env{'course.'.$cid.'.domain'};
 5790:         $cnum = $env{'course.'.$cid.'.num'};
 5791:         $chome = $env{'course.'.$cid.'.home'};
 5792:     }
 5793:     if ($needsrelease) {
 5794:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 5795:         my $needsupdate;
 5796:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 5797:             $needsupdate = 1;
 5798:         } else {
 5799:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 5800:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 5801:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 5802:                 $needsupdate = 1;
 5803:             }
 5804:         }
 5805:         if ($needsupdate) {
 5806:             my %needshash = (
 5807:                              'internal.releaserequired' => $needsrelease,
 5808:                             );
 5809:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 5810:             if ($putresult eq 'ok') {
 5811:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 5812:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 5813:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 5814:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 5815:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 5816:                 }
 5817:             }
 5818:         }
 5819:     }
 5820:     return;
 5821: }
 5822: 
 5823: # -------------------------------------------------See if a user is privileged
 5824: 
 5825: sub privileged {
 5826:     my ($username,$domain,$possdomains,$possroles)=@_;
 5827:     my $now = time;
 5828:     my $roles;
 5829:     if (ref($possroles) eq 'ARRAY') {
 5830:         $roles = $possroles; 
 5831:     } else {
 5832:         $roles = ['dc','su'];
 5833:     }
 5834:     if (ref($possdomains) eq 'ARRAY') {
 5835:         my %privileged = &privileged_by_domain($possdomains,$roles);
 5836:         foreach my $dom (@{$possdomains}) {
 5837:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 5838:                 (ref($privileged{$dom}) eq 'HASH')) {
 5839:                 foreach my $role (@{$roles}) {
 5840:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5841:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 5842:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 5843:                             return 1 unless (($end && $end < $now) ||
 5844:                                              ($start && $start > $now));
 5845:                         }
 5846:                     }
 5847:                 }
 5848:             }
 5849:         }
 5850:     } else {
 5851:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 5852:         my $now = time;
 5853: 
 5854:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
 5855:             my ($trole, $tend, $tstart) = split(/_/, $role);
 5856:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 5857:                 return 1 unless ($tend && $tend < $now) 
 5858:                         or ($tstart && $tstart > $now);
 5859:             }
 5860:         }
 5861:     }
 5862:     return 0;
 5863: }
 5864: 
 5865: sub privileged_by_domain {
 5866:     my ($domains,$roles) = @_;
 5867:     my %privileged = ();
 5868:     my $cachetime = 60*60*24;
 5869:     my $now = time;
 5870:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 5871:         return %privileged;
 5872:     }
 5873:     foreach my $dom (@{$domains}) {
 5874:         next if (ref($privileged{$dom}) eq 'HASH');
 5875:         my $needroles;
 5876:         foreach my $role (@{$roles}) {
 5877:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 5878:             if (defined($cached)) {
 5879:                 if (ref($result) eq 'HASH') {
 5880:                     $privileged{$dom}{$role} = $result;
 5881:                 }
 5882:             } else {
 5883:                 $needroles = 1;
 5884:             }
 5885:         }
 5886:         if ($needroles) {
 5887:             my %dompersonnel = &get_domain_roles($dom,$roles);
 5888:             $privileged{$dom} = {};
 5889:             foreach my $server (keys(%dompersonnel)) {
 5890:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 5891:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 5892:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 5893:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 5894:                         next if ($end && $end < $now);
 5895:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 5896:                             $dompersonnel{$server}{$item};
 5897:                     }
 5898:                 }
 5899:             }
 5900:             if (ref($privileged{$dom}) eq 'HASH') {
 5901:                 foreach my $role (@{$roles}) {
 5902:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5903:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 5904:                     } else {
 5905:                         my %hash = ();
 5906:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 5907:                     }
 5908:                 }
 5909:             }
 5910:         }
 5911:     }
 5912:     return %privileged;
 5913: }
 5914: 
 5915: # -------------------------------------------------------- Get user privileges
 5916: 
 5917: sub rolesinit {
 5918:     my ($domain, $username) = @_;
 5919:     my %userroles = ('user.login.time' => time);
 5920:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 5921: 
 5922:     # firstaccess and timerinterval are related to timed maps/resources. 
 5923:     # also, blocking can be triggered by an activating timer
 5924:     # it's saved in the user's %env.
 5925:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 5926:     my %timerinterval = &dump('timerinterval', $domain, $username);
 5927:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 5928:         %timerintchk, %timerintenv);
 5929: 
 5930:     foreach my $key (keys(%firstaccess)) {
 5931:         my ($cid, $rest) = split(/\0/, $key);
 5932:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 5933:     }
 5934: 
 5935:     foreach my $key (keys(%timerinterval)) {
 5936:         my ($cid,$rest) = split(/\0/,$key);
 5937:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 5938:     }
 5939: 
 5940:     my %allroles=();
 5941:     my %allgroups=();
 5942: 
 5943:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
 5944:         my $role = $rolesdump{$area};
 5945:         $area =~ s/\_\w\w$//;
 5946: 
 5947:         my ($trole, $tend, $tstart, $group_privs);
 5948: 
 5949:         if ($role =~ /^cr/) {
 5950:         # Custom role, defined by a user 
 5951:         # e.g., user.role.cr/msu/smith/mynewrole
 5952:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 5953:                 $trole = $1;
 5954:                 ($tend, $tstart) = split('_', $2);
 5955:             } else {
 5956:                 $trole = $role;
 5957:             }
 5958:         } elsif ($role =~ m|^gr/|) {
 5959:         # Role of member in a group, defined within a course/community
 5960:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 5961:             ($trole, $tend, $tstart) = split(/_/, $role);
 5962:             next if $tstart eq '-1';
 5963:             ($trole, $group_privs) = split(/\//, $trole);
 5964:             $group_privs = &unescape($group_privs);
 5965:         } else {
 5966:         # Just a normal role, defined in roles.tab
 5967:             ($trole, $tend, $tstart) = split(/_/,$role);
 5968:         }
 5969: 
 5970:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 5971:                  $username);
 5972:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 5973: 
 5974:         # role expired or not available yet?
 5975:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 5976:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 5977: 
 5978:         next if $area eq '' or $trole eq '';
 5979: 
 5980:         my $spec = "$trole.$area";
 5981:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 5982: 
 5983:         if ($trole =~ /^cr\//) {
 5984:         # Custom role, defined by a user
 5985:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 5986:         } elsif ($trole eq 'gr') {
 5987:         # Role of a member in a group, defined within a course/community
 5988:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 5989:             next;
 5990:         } else {
 5991:         # Normal role, defined in roles.tab
 5992:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 5993:         }
 5994: 
 5995:         my $cid = $tdomain.'_'.$trest;
 5996:         unless ($firstaccchk{$cid}) {
 5997:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 5998:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 5999:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 6000:                         $coursetimerstarts{$cid}{$item}; 
 6001:                 }
 6002:             }
 6003:             $firstaccchk{$cid} = 1;
 6004:         }
 6005:         unless ($timerintchk{$cid}) {
 6006:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 6007:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 6008:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 6009:                        $coursetimerintervals{$cid}{$item};
 6010:                 }
 6011:             }
 6012:             $timerintchk{$cid} = 1;
 6013:         }
 6014:     }
 6015: 
 6016:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
 6017:                                                           \%allroles, \%allgroups);
 6018:     $env{'user.adv'} = $userroles{'user.adv'};
 6019:     $env{'user.rar'} = $userroles{'user.rar'};
 6020: 
 6021:     return (\%userroles,\%firstaccenv,\%timerintenv);
 6022: }
 6023: 
 6024: sub set_arearole {
 6025:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 6026:     unless ($nolog) {
 6027: # log the associated role with the area
 6028:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 6029:     }
 6030:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 6031: }
 6032: 
 6033: sub custom_roleprivs {
 6034:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 6035:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 6036:     my $homsvr = &homeserver($rauthor,$rdomain);
 6037:     if (&hostname($homsvr) ne '') {
 6038:         my ($rdummy,$roledef)=
 6039:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 6040:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 6041:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 6042:             if (defined($syspriv)) {
 6043:                 if ($trest =~ /^$match_community$/) {
 6044:                     $syspriv =~ s/bre\&S//; 
 6045:                 }
 6046:                 $$allroles{'cm./'}.=':'.$syspriv;
 6047:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 6048:             }
 6049:             if ($tdomain ne '') {
 6050:                 if (defined($dompriv)) {
 6051:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 6052:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 6053:                 }
 6054:                 if (($trest ne '') && (defined($coursepriv))) {
 6055:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
 6056:                         my $rolename = $1;
 6057:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
 6058:                     }
 6059:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 6060:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 6061:                 }
 6062:             }
 6063:         }
 6064:     }
 6065: }
 6066: 
 6067: sub course_adhocrole_privs {
 6068:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
 6069:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
 6070:     if ($overrides{"internal.adhocpriv.$rolename"}) {
 6071:         my (%currprivs,%storeprivs);
 6072:         foreach my $item (split(/:/,$coursepriv)) {
 6073:             my ($priv,$restrict) = split(/\&/,$item);
 6074:             $currprivs{$priv} = $restrict;
 6075:         }
 6076:         my (%possadd,%possremove,%full);
 6077:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
 6078:             my ($priv,$restrict)=split(/\&/,$item);
 6079:             $full{$priv} = $restrict;
 6080:         }
 6081:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
 6082:              next if ($item eq '');
 6083:              my ($rule,$rest) = split(/=/,$item);
 6084:              next unless (($rule eq 'off') || ($rule eq 'on'));
 6085:              foreach my $priv (split(/:/,$rest)) {
 6086:                  if ($priv ne '') {
 6087:                      if ($rule eq 'off') {
 6088:                          $possremove{$priv} = 1;
 6089:                      } else {
 6090:                          $possadd{$priv} = 1;
 6091:                      }
 6092:                  }
 6093:              }
 6094:          }
 6095:          foreach my $priv (sort(keys(%full))) {
 6096:              if (exists($currprivs{$priv})) {
 6097:                  unless (exists($possremove{$priv})) {
 6098:                      $storeprivs{$priv} = $currprivs{$priv};
 6099:                  }
 6100:              } elsif (exists($possadd{$priv})) {
 6101:                  $storeprivs{$priv} = $full{$priv};
 6102:              }
 6103:          }
 6104:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
 6105:      }
 6106:      return $coursepriv;
 6107: }
 6108: 
 6109: sub group_roleprivs {
 6110:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 6111:     my $access = 1;
 6112:     my $now = time;
 6113:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 6114:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 6115:     if ($access) {
 6116:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 6117:         $$allgroups{$course}{$group} .=':'.$group_privs;
 6118:     }
 6119: }
 6120: 
 6121: sub standard_roleprivs {
 6122:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 6123:     if (defined($pr{$trole.':s'})) {
 6124:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 6125:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 6126:     }
 6127:     if ($tdomain ne '') {
 6128:         if (defined($pr{$trole.':d'})) {
 6129:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6130:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 6131:         }
 6132:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 6133:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 6134:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 6135:         }
 6136:     }
 6137: }
 6138: 
 6139: sub set_userprivs {
 6140:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 6141:     my $author=0;
 6142:     my $adv=0;
 6143:     my $rar=0;
 6144:     my %grouproles = ();
 6145:     if (keys(%{$allgroups}) > 0) {
 6146:         my @groupkeys; 
 6147:         foreach my $role (keys(%{$allroles})) {
 6148:             push(@groupkeys,$role);
 6149:         }
 6150:         if (ref($groups_roles) eq 'HASH') {
 6151:             foreach my $key (keys(%{$groups_roles})) {
 6152:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 6153:                     push(@groupkeys,$key);
 6154:                 }
 6155:             }
 6156:         }
 6157:         if (@groupkeys > 0) {
 6158:             foreach my $role (@groupkeys) {
 6159:                 my ($trole,$area,$sec,$extendedarea);
 6160:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 6161:                     $trole = $1;
 6162:                     $area = $2;
 6163:                     $sec = $3;
 6164:                     $extendedarea = $area.$sec;
 6165:                     if (exists($$allgroups{$area})) {
 6166:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 6167:                             my $spec = $trole.'.'.$extendedarea;
 6168:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 6169:                                                 $$allgroups{$area}{$group};
 6170:                         }
 6171:                     }
 6172:                 }
 6173:             }
 6174:         }
 6175:     }
 6176:     foreach my $group (keys(%grouproles)) {
 6177:         $$allroles{$group} = $grouproles{$group};
 6178:     }
 6179:     foreach my $role (keys(%{$allroles})) {
 6180:         my %thesepriv;
 6181:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 6182:         foreach my $item (split(/:/,$$allroles{$role})) {
 6183:             if ($item ne '') {
 6184:                 my ($privilege,$restrictions)=split(/&/,$item);
 6185:                 if ($restrictions eq '') {
 6186:                     $thesepriv{$privilege}='F';
 6187:                 } elsif ($thesepriv{$privilege} ne 'F') {
 6188:                     $thesepriv{$privilege}.=$restrictions;
 6189:                 }
 6190:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 6191:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
 6192:             }
 6193:         }
 6194:         my $thesestr='';
 6195:         foreach my $priv (sort(keys(%thesepriv))) {
 6196: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 6197: 	}
 6198:         $userroles->{'user.priv.'.$role} = $thesestr;
 6199:     }
 6200:     return ($author,$adv,$rar);
 6201: }
 6202: 
 6203: sub role_status {
 6204:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 6205:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 6206:         my ($one,$two) = split(m{\./},$rolekey,2);
 6207:         (undef,undef,$$role) = split(/\./,$one,3);
 6208:         unless (!defined($$role) || $$role eq '') {
 6209:             $$where = '/'.$two;
 6210:             $$trolecode=$$role.'.'.$$where;
 6211:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 6212:             $$tstatus='is';
 6213:             if ($$tstart && $$tstart>$update) {
 6214:                 $$tstatus='future';
 6215:                 if ($$tstart<$now) {
 6216:                     if ($$tstart && $$tstart>$refresh) {
 6217:                         if (($$where ne '') && ($$role ne '')) {
 6218:                             my (%allroles,%allgroups,$group_privs,
 6219:                                 %groups_roles,@rolecodes);
 6220:                             my %userroles = (
 6221:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 6222:                             );
 6223:                             @rolecodes = ('cm'); 
 6224:                             my $spec=$$role.'.'.$$where;
 6225:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 6226:                             if ($$role =~ /^cr\//) {
 6227:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 6228:                                 push(@rolecodes,'cr');
 6229:                             } elsif ($$role eq 'gr') {
 6230:                                 push(@rolecodes,$$role);
 6231:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 6232:                                                     $env{'user.name'});
 6233:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 6234:                                 (undef,my $group_privs) = split(/\//,$trole);
 6235:                                 $group_privs = &unescape($group_privs);
 6236:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 6237:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 6238:                                 &get_groups_roles($tdomain,$trest,
 6239:                                                   \%course_roles,\@rolecodes,
 6240:                                                   \%groups_roles);
 6241:                             } else {
 6242:                                 push(@rolecodes,$$role);
 6243:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 6244:                             }
 6245:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
 6246:                                                                    \%groups_roles);
 6247:                             &appenv(\%userroles,\@rolecodes);
 6248:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6249:                         }
 6250:                     }
 6251:                     $$tstatus = 'is';
 6252:                 }
 6253:             }
 6254:             if ($$tend) {
 6255:                 if ($$tend<$update) {
 6256:                     $$tstatus='expired';
 6257:                 } elsif ($$tend<$now) {
 6258:                     $$tstatus='will_not';
 6259:                 }
 6260:             }
 6261:         }
 6262:     }
 6263: }
 6264: 
 6265: sub get_groups_roles {
 6266:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 6267:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 6268:                   (ref($rolecodes) eq 'ARRAY') && 
 6269:                   (ref($groups_roles) eq 'HASH')); 
 6270:     if (keys(%{$cdom_courseroles}) > 0) {
 6271:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 6272:         if ($cdom ne '' && $cnum ne '') {
 6273:             foreach my $key (keys(%{$cdom_courseroles})) {
 6274:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 6275:                     my $crsrole = $1;
 6276:                     my $crssec = $2;
 6277:                     if ($crsrole =~ /^cr/) {
 6278:                         unless (grep(/^cr$/,@{$rolecodes})) {
 6279:                             push(@{$rolecodes},'cr');
 6280:                         }
 6281:                     } else {
 6282:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 6283:                             push(@{$rolecodes},$crsrole);
 6284:                         }
 6285:                     }
 6286:                     my $rolekey = "$crsrole./$cdom/$cnum";
 6287:                     if ($crssec ne '') {
 6288:                         $rolekey .= "/$crssec";
 6289:                     }
 6290:                     $rolekey .= './';
 6291:                     $groups_roles->{$rolekey} = $rolecodes;
 6292:                 }
 6293:             }
 6294:         }
 6295:     }
 6296:     return;
 6297: }
 6298: 
 6299: sub delete_env_groupprivs {
 6300:     my ($where,$courseroles,$possroles) = @_;
 6301:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 6302:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 6303:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 6304:         %{$courseroles->{$udom}} =
 6305:             &get_my_roles('','','userroles',['active'],
 6306:                           $possroles,[$udom],1);
 6307:     }
 6308:     if (ref($courseroles->{$udom}) eq 'HASH') {
 6309:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 6310:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 6311:             my $area = '/'.$cdom.'/'.$cnum;
 6312:             my $privkey = "user.priv.$crsrole.$area";
 6313:             if ($crssec ne '') {
 6314:                 $privkey .= '/'.$crssec;
 6315:             }
 6316:             $privkey .= ".$area/$group";
 6317:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 6318:         }
 6319:     }
 6320:     return;
 6321: }
 6322: 
 6323: sub check_adhoc_privs {
 6324:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
 6325:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 6326:     if ($sec) {
 6327:         $cckey .= '/'.$sec;
 6328:     } 
 6329:     my $setprivs;
 6330:     if ($env{$cckey}) {
 6331:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 6332:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 6333:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 6334:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6335:             $setprivs = 1;
 6336:         }
 6337:     } else {
 6338:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
 6339:         $setprivs = 1;
 6340:     }
 6341:     return $setprivs;
 6342: }
 6343: 
 6344: sub set_adhoc_privileges {
 6345: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
 6346:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
 6347:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 6348:     if ($sec ne '') {
 6349:         $area .= '/'.$sec;
 6350:     }
 6351:     my $spec = $role.'.'.$area;
 6352:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 6353:                                   $env{'user.name'},1);
 6354:     my %rolehash = ();
 6355:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
 6356:         my $rolename = $1;
 6357:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
 6358:         my %domdef = &get_domain_defaults($dcdom);
 6359:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
 6360:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
 6361:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
 6362:             }
 6363:         }
 6364:     } else {
 6365:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
 6366:     }
 6367:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
 6368:     &appenv(\%userroles,[$role,'cm']);
 6369:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
 6370:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 6371:         &appenv( {'request.role'        => $spec,
 6372:                   'request.role.domain' => $dcdom,
 6373:                   'request.course.sec'  => $sec,
 6374:                  }
 6375:                );
 6376:         my $tadv=0;
 6377:         if (&allowed('adv') eq 'F') { $tadv=1; }
 6378:         &appenv({'request.role.adv'    => $tadv});
 6379:     }
 6380: }
 6381: 
 6382: # --------------------------------------------------------------- get interface
 6383: 
 6384: sub get {
 6385:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6386:    my $items='';
 6387:    foreach my $item (@$storearr) {
 6388:        $items.=&escape($item).'&';
 6389:    }
 6390:    $items=~s/\&$//;
 6391:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6392:    if (!$uname) { $uname=$env{'user.name'}; }
 6393:    my $uhome=&homeserver($uname,$udomain);
 6394: 
 6395:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 6396:    my @pairs=split(/\&/,$rep);
 6397:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 6398:      return @pairs;
 6399:    }
 6400:    my %returnhash=();
 6401:    my $i=0;
 6402:    foreach my $item (@$storearr) {
 6403:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 6404:       $i++;
 6405:    }
 6406:    return %returnhash;
 6407: }
 6408: 
 6409: # --------------------------------------------------------------- del interface
 6410: 
 6411: sub del {
 6412:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6413:    my $items='';
 6414:    foreach my $item (@$storearr) {
 6415:        $items.=&escape($item).'&';
 6416:    }
 6417: 
 6418:    $items=~s/\&$//;
 6419:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6420:    if (!$uname) { $uname=$env{'user.name'}; }
 6421:    my $uhome=&homeserver($uname,$udomain);
 6422:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 6423: }
 6424: 
 6425: # -------------------------------------------------------------- dump interface
 6426: 
 6427: sub unserialize {
 6428:     my ($rep, $escapedkeys) = @_;
 6429: 
 6430:     return {} if $rep =~ /^error/;
 6431: 
 6432:     my %returnhash=();
 6433: 	foreach my $item (split(/\&/,$rep)) {
 6434: 	    my ($key, $value) = split(/=/, $item, 2);
 6435: 	    $key = unescape($key) unless $escapedkeys;
 6436: 	    next if $key =~ /^error: 2 /;
 6437: 	    $returnhash{$key} = &thaw_unescape($value);
 6438: 	}
 6439:     #return %returnhash;
 6440:     return \%returnhash;
 6441: }        
 6442: 
 6443: # see Lond::dump_with_regexp
 6444: # if $escapedkeys hash keys won't get unescaped.
 6445: sub dump {
 6446:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 6447:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6448:     if (!$uname) { $uname=$env{'user.name'}; }
 6449:     my $uhome=&homeserver($uname,$udomain);
 6450: 
 6451:     if ($regexp) {
 6452:         $regexp=&escape($regexp);
 6453:     } else {
 6454:         $regexp='.';
 6455:     }
 6456:     if (grep { $_ eq $uhome } current_machine_ids()) {
 6457:         # user is hosted on this machine
 6458:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 6459:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 6460:         return %{unserialize($reply, $escapedkeys)};
 6461:     }
 6462:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 6463:     my @pairs=split(/\&/,$rep);
 6464:     my %returnhash=();
 6465:     if (!($rep =~ /^error/ )) {
 6466: 	foreach my $item (@pairs) {
 6467: 	    my ($key,$value)=split(/=/,$item,2);
 6468:         $key = unescape($key) unless $escapedkeys;
 6469:         #$key = &unescape($key);
 6470: 	    next if ($key =~ /^error: 2 /);
 6471: 	    $returnhash{$key}=&thaw_unescape($value);
 6472: 	}
 6473:     }
 6474:     return %returnhash;
 6475: }
 6476: 
 6477: 
 6478: # --------------------------------------------------------- dumpstore interface
 6479: 
 6480: sub dumpstore {
 6481:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 6482:    # same as dump but keys must be escaped. They may contain colon separated
 6483:    # lists of values that may themself contain colons (e.g. symbs).
 6484:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 6485: }
 6486: 
 6487: # -------------------------------------------------------------- keys interface
 6488: 
 6489: sub getkeys {
 6490:    my ($namespace,$udomain,$uname)=@_;
 6491:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6492:    if (!$uname) { $uname=$env{'user.name'}; }
 6493:    my $uhome=&homeserver($uname,$udomain);
 6494:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 6495:    my @keyarray=();
 6496:    foreach my $key (split(/\&/,$rep)) {
 6497:       next if ($key =~ /^error: 2 /);
 6498:       push(@keyarray,&unescape($key));
 6499:    }
 6500:    return @keyarray;
 6501: }
 6502: 
 6503: # --------------------------------------------------------------- currentdump
 6504: sub currentdump {
 6505:    my ($courseid,$sdom,$sname)=@_;
 6506:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 6507:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 6508:    $sname    = $env{'user.name'}         if (! defined($sname));
 6509:    my $uhome = &homeserver($sname,$sdom);
 6510:    my $rep;
 6511: 
 6512:    if (grep { $_ eq $uhome } current_machine_ids()) {
 6513:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 6514:                    $courseid)));
 6515:    } else {
 6516:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 6517:    }
 6518: 
 6519:    return if ($rep =~ /^(error:|no_such_host)/);
 6520:    #
 6521:    my %returnhash=();
 6522:    #
 6523:    if ($rep eq 'unknown_cmd') {
 6524:        # an old lond will not know currentdump
 6525:        # Do a dump and make it look like a currentdump
 6526:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 6527:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 6528:        my %hash = @tmp;
 6529:        @tmp=();
 6530:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 6531:    } else {
 6532:        my @pairs=split(/\&/,$rep);
 6533:        foreach my $pair (@pairs) {
 6534:            my ($key,$value)=split(/=/,$pair,2);
 6535:            my ($symb,$param) = split(/:/,$key);
 6536:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 6537:                                                         &thaw_unescape($value);
 6538:        }
 6539:    }
 6540:    return %returnhash;
 6541: }
 6542: 
 6543: sub convert_dump_to_currentdump{
 6544:     my %hash = %{shift()};
 6545:     my %returnhash;
 6546:     # Code ripped from lond, essentially.  The only difference
 6547:     # here is the unescaping done by lonnet::dump().  Conceivably
 6548:     # we might run in to problems with parameter names =~ /^v\./
 6549:     while (my ($key,$value) = each(%hash)) {
 6550:         my ($v,$symb,$param) = split(/:/,$key);
 6551: 	$symb  = &unescape($symb);
 6552: 	$param = &unescape($param);
 6553:         next if ($v eq 'version' || $symb eq 'keys');
 6554:         next if (exists($returnhash{$symb}) &&
 6555:                  exists($returnhash{$symb}->{$param}) &&
 6556:                  $returnhash{$symb}->{'v.'.$param} > $v);
 6557:         $returnhash{$symb}->{$param}=$value;
 6558:         $returnhash{$symb}->{'v.'.$param}=$v;
 6559:     }
 6560:     #
 6561:     # Remove all of the keys in the hashes which keep track of
 6562:     # the version of the parameter.
 6563:     while (my ($symb,$param_hash) = each(%returnhash)) {
 6564:         # use a foreach because we are going to delete from the hash.
 6565:         foreach my $key (keys(%$param_hash)) {
 6566:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 6567:         }
 6568:     }
 6569:     return \%returnhash;
 6570: }
 6571: 
 6572: # ------------------------------------------------------ critical inc interface
 6573: 
 6574: sub cinc {
 6575:     return &inc(@_,'critical');
 6576: }
 6577: 
 6578: # --------------------------------------------------------------- inc interface
 6579: 
 6580: sub inc {
 6581:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 6582:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6583:     if (!$uname) { $uname=$env{'user.name'}; }
 6584:     my $uhome=&homeserver($uname,$udomain);
 6585:     my $items='';
 6586:     if (! ref($store)) {
 6587:         # got a single value, so use that instead
 6588:         $items = &escape($store).'=&';
 6589:     } elsif (ref($store) eq 'SCALAR') {
 6590:         $items = &escape($$store).'=&';        
 6591:     } elsif (ref($store) eq 'ARRAY') {
 6592:         $items = join('=&',map {&escape($_);} @{$store});
 6593:     } elsif (ref($store) eq 'HASH') {
 6594:         while (my($key,$value) = each(%{$store})) {
 6595:             $items.= &escape($key).'='.&escape($value).'&';
 6596:         }
 6597:     }
 6598:     $items=~s/\&$//;
 6599:     if ($critical) {
 6600: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 6601:     } else {
 6602: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 6603:     }
 6604: }
 6605: 
 6606: # --------------------------------------------------------------- put interface
 6607: 
 6608: sub put {
 6609:    my ($namespace,$storehash,$udomain,$uname)=@_;
 6610:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6611:    if (!$uname) { $uname=$env{'user.name'}; }
 6612:    my $uhome=&homeserver($uname,$udomain);
 6613:    my $items='';
 6614:    foreach my $item (keys(%$storehash)) {
 6615:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 6616:    }
 6617:    $items=~s/\&$//;
 6618:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 6619: }
 6620: 
 6621: # ------------------------------------------------------------ newput interface
 6622: 
 6623: sub newput {
 6624:    my ($namespace,$storehash,$udomain,$uname)=@_;
 6625:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6626:    if (!$uname) { $uname=$env{'user.name'}; }
 6627:    my $uhome=&homeserver($uname,$udomain);
 6628:    my $items='';
 6629:    foreach my $key (keys(%$storehash)) {
 6630:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 6631:    }
 6632:    $items=~s/\&$//;
 6633:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 6634: }
 6635: 
 6636: # ---------------------------------------------------------  putstore interface
 6637: 
 6638: sub putstore {
 6639:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
 6640:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6641:    if (!$uname) { $uname=$env{'user.name'}; }
 6642:    my $uhome=&homeserver($uname,$udomain);
 6643:    my $items='';
 6644:    foreach my $key (keys(%$storehash)) {
 6645:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 6646:    }
 6647:    $items=~s/\&$//;
 6648:    my $esc_symb=&escape($symb);
 6649:    my $esc_v=&escape($version);
 6650:    my $reply =
 6651:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 6652: 	      $uhome);
 6653:    if (($tolog) && ($reply eq 'ok')) {
 6654:        my $namevalue='';
 6655:        foreach my $key (keys(%{$storehash})) {
 6656:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 6657:        }
 6658:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
 6659:                      '&host='.&escape($perlvar{'lonHostID'}).
 6660:                      '&version='.$esc_v.
 6661:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
 6662:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
 6663:    }
 6664:    if ($reply eq 'unknown_cmd') {
 6665:        # gfall back to way things use to be done
 6666:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 6667: 			    $uname);
 6668:    }
 6669:    return $reply;
 6670: }
 6671: 
 6672: sub old_putstore {
 6673:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 6674:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 6675:     if (!$uname) { $uname=$env{'user.name'}; }
 6676:     my $uhome=&homeserver($uname,$udomain);
 6677:     my %newstorehash;
 6678:     foreach my $item (keys(%$storehash)) {
 6679: 	my $key = $version.':'.&escape($symb).':'.$item;
 6680: 	$newstorehash{$key} = $storehash->{$item};
 6681:     }
 6682:     my $items='';
 6683:     my %allitems = ();
 6684:     foreach my $item (keys(%newstorehash)) {
 6685: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 6686: 	    my $key = $1.':keys:'.$2;
 6687: 	    $allitems{$key} .= $3.':';
 6688: 	}
 6689: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 6690:     }
 6691:     foreach my $item (keys(%allitems)) {
 6692: 	$allitems{$item} =~ s/\:$//;
 6693: 	$items.= $item.'='.$allitems{$item}.'&';
 6694:     }
 6695:     $items=~s/\&$//;
 6696:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 6697: }
 6698: 
 6699: # ------------------------------------------------------ critical put interface
 6700: 
 6701: sub cput {
 6702:    my ($namespace,$storehash,$udomain,$uname)=@_;
 6703:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6704:    if (!$uname) { $uname=$env{'user.name'}; }
 6705:    my $uhome=&homeserver($uname,$udomain);
 6706:    my $items='';
 6707:    foreach my $item (keys(%$storehash)) {
 6708:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 6709:    }
 6710:    $items=~s/\&$//;
 6711:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 6712: }
 6713: 
 6714: # -------------------------------------------------------------- eget interface
 6715: 
 6716: sub eget {
 6717:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6718:    my $items='';
 6719:    foreach my $item (@$storearr) {
 6720:        $items.=&escape($item).'&';
 6721:    }
 6722:    $items=~s/\&$//;
 6723:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6724:    if (!$uname) { $uname=$env{'user.name'}; }
 6725:    my $uhome=&homeserver($uname,$udomain);
 6726:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 6727:    my @pairs=split(/\&/,$rep);
 6728:    my %returnhash=();
 6729:    my $i=0;
 6730:    foreach my $item (@$storearr) {
 6731:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 6732:       $i++;
 6733:    }
 6734:    return %returnhash;
 6735: }
 6736: 
 6737: # ------------------------------------------------------------ tmpput interface
 6738: sub tmpput {
 6739:     my ($storehash,$server,$context)=@_;
 6740:     my $items='';
 6741:     foreach my $item (keys(%$storehash)) {
 6742: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 6743:     }
 6744:     $items=~s/\&$//;
 6745:     if (defined($context)) {
 6746:         $items .= ':'.&escape($context);
 6747:     }
 6748:     return &reply("tmpput:$items",$server);
 6749: }
 6750: 
 6751: # ------------------------------------------------------------ tmpget interface
 6752: sub tmpget {
 6753:     my ($token,$server)=@_;
 6754:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 6755:     my $rep=&reply("tmpget:$token",$server);
 6756:     my %returnhash;
 6757:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
 6758:         return %returnhash;
 6759:     }
 6760:     foreach my $item (split(/\&/,$rep)) {
 6761: 	my ($key,$value)=split(/=/,$item);
 6762: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 6763:     }
 6764:     return %returnhash;
 6765: }
 6766: 
 6767: # ------------------------------------------------------------ tmpdel interface
 6768: sub tmpdel {
 6769:     my ($token,$server)=@_;
 6770:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 6771:     return &reply("tmpdel:$token",$server);
 6772: }
 6773: 
 6774: # ------------------------------------------------------------ get_timebased_id 
 6775: 
 6776: sub get_timebased_id {
 6777:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 6778:         $maxtries) = @_;
 6779:     my ($newid,$error,$dellock);
 6780:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 6781:         return ('','ok','invalid call to get suffix');
 6782:     }
 6783: 
 6784: # set defaults for any optional args for which values were not supplied
 6785:     if ($who eq '') {
 6786:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 6787:     }
 6788:     if (!$locktries) {
 6789:         $locktries = 3;
 6790:     }
 6791:     if (!$maxtries) {
 6792:         $maxtries = 10;
 6793:     }
 6794:     
 6795:     if (($cdom eq '') || ($cnum eq '')) {
 6796:         if ($env{'request.course.id'}) {
 6797:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6798:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6799:         }
 6800:         if (($cdom eq '') || ($cnum eq '')) {
 6801:             return ('','ok','call to get suffix not in course context');
 6802:         }
 6803:     }
 6804: 
 6805: # construct locking item
 6806:     my $lockhash = {
 6807:                       $prefix."\0".'locked_'.$keyid => $who,
 6808:                    };
 6809:     my $tries = 0;
 6810: 
 6811: # attempt to get lock on nohist_$namespace file
 6812:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 6813:     while (($gotlock ne 'ok') && $tries <$locktries) {
 6814:         $tries ++;
 6815:         sleep 1;
 6816:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 6817:     }
 6818: 
 6819: # attempt to get unique identifier, based on current timestamp
 6820:     if ($gotlock eq 'ok') {
 6821:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 6822:         my $id = time;
 6823:         $newid = $id;
 6824:         if ($idtype eq 'addcode') {
 6825:             $newid .= &sixnum_code();
 6826:         }
 6827:         my $idtries = 0;
 6828:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 6829:             if ($idtype eq 'concat') {
 6830:                 $newid = $id.$idtries;
 6831:             } elsif ($idtype eq 'addcode') {
 6832:                 $newid = $newid.&sixnum_code();
 6833:             } else {
 6834:                 $newid ++;
 6835:             }
 6836:             $idtries ++;
 6837:         }
 6838:         if (!exists($inuse{$prefix."\0".$newid})) {
 6839:             my %new_item =  (
 6840:                               $prefix."\0".$newid => $who,
 6841:                             );
 6842:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 6843:                                                  $cdom,$cnum);
 6844:             if ($putresult ne 'ok') {
 6845:                 undef($newid);
 6846:                 $error = 'error saving new item: '.$putresult;
 6847:             }
 6848:         } else {
 6849:              undef($newid);
 6850:              $error = ('error: no unique suffix available for the new item ');
 6851:         }
 6852: #  remove lock
 6853:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 6854:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 6855:     } else {
 6856:         $error = "error: could not obtain lockfile\n";
 6857:         $dellock = 'ok';
 6858:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
 6859:             $dellock = 'nolock';
 6860:         }
 6861:     }
 6862:     return ($newid,$dellock,$error);
 6863: }
 6864: 
 6865: sub sixnum_code {
 6866:     my $code;
 6867:     for (0..6) {
 6868:         $code .= int( rand(9) );
 6869:     }
 6870:     return $code;
 6871: }
 6872: 
 6873: # -------------------------------------------------- portfolio access checking
 6874: 
 6875: sub portfolio_access {
 6876:     my ($requrl,$clientip) = @_;
 6877:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 6878:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
 6879:     if ($result) {
 6880:         my %setters;
 6881:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 6882:             my ($startblock,$endblock) =
 6883:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 6884:             if ($startblock && $endblock) {
 6885:                 return 'B';
 6886:             }
 6887:         } else {
 6888:             my ($startblock,$endblock) =
 6889:                 &Apache::loncommon::blockcheck(\%setters,'port');
 6890:             if ($startblock && $endblock) {
 6891:                 return 'B';
 6892:             }
 6893:         }
 6894:     }
 6895:     if ($result eq 'ok') {
 6896:        return 'F';
 6897:     } elsif ($result =~ /^[^:]+:guest_/) {
 6898:        return 'A';
 6899:     }
 6900:     return '';
 6901: }
 6902: 
 6903: sub get_portfolio_access {
 6904:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
 6905: 
 6906:     if (!ref($access_hash)) {
 6907: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 6908: 	my %access_controls = &get_access_controls($current_perms,$group,
 6909: 						   $file_name);
 6910: 	$access_hash = $access_controls{$file_name};
 6911:     }
 6912: 
 6913:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
 6914:     my $now = time;
 6915:     if (ref($access_hash) eq 'HASH') {
 6916:         foreach my $key (keys(%{$access_hash})) {
 6917:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 6918:             if ($start > $now) {
 6919:                 next;
 6920:             }
 6921:             if ($end && $end<$now) {
 6922:                 next;
 6923:             }
 6924:             if ($scope eq 'public') {
 6925:                 $public = $key;
 6926:                 last;
 6927:             } elsif ($scope eq 'guest') {
 6928:                 $guest = $key;
 6929:             } elsif ($scope eq 'domains') {
 6930:                 push(@domains,$key);
 6931:             } elsif ($scope eq 'users') {
 6932:                 push(@users,$key);
 6933:             } elsif ($scope eq 'course') {
 6934:                 push(@courses,$key);
 6935:             } elsif ($scope eq 'group') {
 6936:                 push(@groups,$key);
 6937:             } elsif ($scope eq 'ip') {
 6938:                 push(@ips,$key);
 6939:             }
 6940:         }
 6941:         if ($public) {
 6942:             return 'ok';
 6943:         } elsif (@ips > 0) {
 6944:             my $allowed;
 6945:             foreach my $ipkey (@ips) {
 6946:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
 6947:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
 6948:                         $allowed = 1;
 6949:                         last; 
 6950:                     }
 6951:                 }
 6952:             }
 6953:             if ($allowed) {
 6954:                 return 'ok';
 6955:             }
 6956:         }
 6957:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 6958:             if ($guest) {
 6959:                 return $guest;
 6960:             }
 6961:         } else {
 6962:             if (@domains > 0) {
 6963:                 foreach my $domkey (@domains) {
 6964:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 6965:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 6966:                             return 'ok';
 6967:                         }
 6968:                     }
 6969:                 }
 6970:             }
 6971:             if (@users > 0) {
 6972:                 foreach my $userkey (@users) {
 6973:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 6974:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 6975:                             if (ref($item) eq 'HASH') {
 6976:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 6977:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 6978:                                     return 'ok';
 6979:                                 }
 6980:                             }
 6981:                         }
 6982:                     } 
 6983:                 }
 6984:             }
 6985:             my %roleshash;
 6986:             my @courses_and_groups = @courses;
 6987:             push(@courses_and_groups,@groups); 
 6988:             if (@courses_and_groups > 0) {
 6989:                 my (%allgroups,%allroles); 
 6990:                 my ($start,$end,$role,$sec,$group);
 6991:                 foreach my $envkey (%env) {
 6992:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 6993:                         my $cid = $2.'_'.$3; 
 6994:                         if ($1 eq 'gr') {
 6995:                             $group = $4;
 6996:                             $allgroups{$cid}{$group} = $env{$envkey};
 6997:                         } else {
 6998:                             if ($4 eq '') {
 6999:                                 $sec = 'none';
 7000:                             } else {
 7001:                                 $sec = $4;
 7002:                             }
 7003:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7004:                         }
 7005:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 7006:                         my $cid = $2.'_'.$3;
 7007:                         if ($4 eq '') {
 7008:                             $sec = 'none';
 7009:                         } else {
 7010:                             $sec = $4;
 7011:                         }
 7012:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 7013:                     }
 7014:                 }
 7015:                 if (keys(%allroles) == 0) {
 7016:                     return;
 7017:                 }
 7018:                 foreach my $key (@courses_and_groups) {
 7019:                     my %content = %{$$access_hash{$key}};
 7020:                     my $cnum = $content{'number'};
 7021:                     my $cdom = $content{'domain'};
 7022:                     my $cid = $cdom.'_'.$cnum;
 7023:                     if (!exists($allroles{$cid})) {
 7024:                         next;
 7025:                     }    
 7026:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 7027:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 7028:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 7029:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 7030:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 7031:                         foreach my $role (keys(%{$allroles{$cid}})) {
 7032:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 7033:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 7034:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 7035:                                         if (grep/^all$/,@sections) {
 7036:                                             return 'ok';
 7037:                                         } else {
 7038:                                             if (grep/^$sec$/,@sections) {
 7039:                                                 return 'ok';
 7040:                                             }
 7041:                                         }
 7042:                                     }
 7043:                                 }
 7044:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 7045:                                     if (grep/^none$/,@groups) {
 7046:                                         return 'ok';
 7047:                                     }
 7048:                                 } else {
 7049:                                     if (grep/^all$/,@groups) {
 7050:                                         return 'ok';
 7051:                                     } 
 7052:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 7053:                                         if (grep/^$group$/,@groups) {
 7054:                                             return 'ok';
 7055:                                         }
 7056:                                     }
 7057:                                 } 
 7058:                             }
 7059:                         }
 7060:                     }
 7061:                 }
 7062:             }
 7063:             if ($guest) {
 7064:                 return $guest;
 7065:             }
 7066:         }
 7067:     }
 7068:     return;
 7069: }
 7070: 
 7071: sub course_group_datechecker {
 7072:     my ($dates,$now,$status) = @_;
 7073:     my ($start,$end) = split(/\./,$dates);
 7074:     if (!$start && !$end) {
 7075:         return 'ok';
 7076:     }
 7077:     if (grep/^active$/,@{$status}) {
 7078:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 7079:             return 'ok';
 7080:         }
 7081:     }
 7082:     if (grep/^previous$/,@{$status}) {
 7083:         if ($end > $now ) {
 7084:             return 'ok';
 7085:         }
 7086:     }
 7087:     if (grep/^future$/,@{$status}) {
 7088:         if ($start > $now) {
 7089:             return 'ok';
 7090:         }
 7091:     }
 7092:     return; 
 7093: }
 7094: 
 7095: sub parse_portfolio_url {
 7096:     my ($url) = @_;
 7097: 
 7098:     my ($type,$udom,$unum,$group,$file_name);
 7099:     
 7100:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 7101: 	$type = 1;
 7102:         $udom = $1;
 7103:         $unum = $2;
 7104:         $file_name = $3;
 7105:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 7106: 	$type = 2;
 7107:         $udom = $1;
 7108:         $unum = $2;
 7109:         $group = $3;
 7110:         $file_name = $3.'/'.$4;
 7111:     }
 7112:     if (wantarray) {
 7113: 	return ($type,$udom,$unum,$file_name,$group);
 7114:     }
 7115:     return $type;
 7116: }
 7117: 
 7118: sub is_portfolio_url {
 7119:     my ($url) = @_;
 7120:     return scalar(&parse_portfolio_url($url));
 7121: }
 7122: 
 7123: sub is_portfolio_file {
 7124:     my ($file) = @_;
 7125:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 7126:         return 1;
 7127:     }
 7128:     return;
 7129: }
 7130: 
 7131: sub usertools_access {
 7132:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 7133:     my ($access,%tools);
 7134:     if ($context eq '') {
 7135:         $context = 'tools';
 7136:     }
 7137:     if ($context eq 'requestcourses') {
 7138:         %tools = (
 7139:                       official   => 1,
 7140:                       unofficial => 1,
 7141:                       community  => 1,
 7142:                       textbook   => 1,
 7143:                       placement  => 1,
 7144:                  );
 7145:     } elsif ($context eq 'requestauthor') {
 7146:         %tools = (
 7147:                       requestauthor => 1,
 7148:                  );
 7149:     } else {
 7150:         %tools = (
 7151:                       aboutme   => 1,
 7152:                       blog      => 1,
 7153:                       webdav    => 1,
 7154:                       portfolio => 1,
 7155:                  );
 7156:     }
 7157:     return if (!defined($tools{$tool}));
 7158: 
 7159:     if (($udom eq '') || ($uname eq '')) {
 7160:         $udom = $env{'user.domain'};
 7161:         $uname = $env{'user.name'};
 7162:     }
 7163: 
 7164:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7165:         if ($action ne 'reload') {
 7166:             if ($context eq 'requestcourses') {
 7167:                 return $env{'environment.canrequest.'.$tool};
 7168:             } elsif ($context eq 'requestauthor') {
 7169:                 return $env{'environment.canrequest.author'};
 7170:             } else {
 7171:                 return $env{'environment.availabletools.'.$tool};
 7172:             }
 7173:         }
 7174:     }
 7175: 
 7176:     my ($toolstatus,$inststatus,$envkey);
 7177:     if ($context eq 'requestauthor') {
 7178:         $envkey = $context; 
 7179:     } else {
 7180:         $envkey = $context.'.'.$tool;
 7181:     }
 7182: 
 7183:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 7184:          ($action ne 'reload')) {
 7185:         $toolstatus = $env{'environment.'.$envkey};
 7186:         $inststatus = $env{'environment.inststatus'};
 7187:     } else {
 7188:         if (ref($userenvref) eq 'HASH') {
 7189:             $toolstatus = $userenvref->{$envkey};
 7190:             $inststatus = $userenvref->{'inststatus'};
 7191:         } else {
 7192:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 7193:             $toolstatus = $userenv{$envkey};
 7194:             $inststatus = $userenv{'inststatus'};
 7195:         }
 7196:     }
 7197: 
 7198:     if ($toolstatus ne '') {
 7199:         if ($toolstatus) {
 7200:             $access = 1;
 7201:         } else {
 7202:             $access = 0;
 7203:         }
 7204:         return $access;
 7205:     }
 7206: 
 7207:     my ($is_adv,%domdef);
 7208:     if (ref($is_advref) eq 'HASH') {
 7209:         $is_adv = $is_advref->{'is_adv'};
 7210:     } else {
 7211:         $is_adv = &is_advanced_user($udom,$uname);
 7212:     }
 7213:     if (ref($domdefref) eq 'HASH') {
 7214:         %domdef = %{$domdefref};
 7215:     } else {
 7216:         %domdef = &get_domain_defaults($udom);
 7217:     }
 7218:     if (ref($domdef{$tool}) eq 'HASH') {
 7219:         if ($is_adv) {
 7220:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 7221:                 if ($domdef{$tool}{'_LC_adv'}) { 
 7222:                     $access = 1;
 7223:                 } else {
 7224:                     $access = 0;
 7225:                 }
 7226:                 return $access;
 7227:             }
 7228:         }
 7229:         if ($inststatus ne '') {
 7230:             my ($hasaccess,$hasnoaccess);
 7231:             foreach my $affiliation (split(/:/,$inststatus)) {
 7232:                 if ($domdef{$tool}{$affiliation} ne '') { 
 7233:                     if ($domdef{$tool}{$affiliation}) {
 7234:                         $hasaccess = 1;
 7235:                     } else {
 7236:                         $hasnoaccess = 1;
 7237:                     }
 7238:                 }
 7239:             }
 7240:             if ($hasaccess || $hasnoaccess) {
 7241:                 if ($hasaccess) {
 7242:                     $access = 1;
 7243:                 } elsif ($hasnoaccess) {
 7244:                     $access = 0; 
 7245:                 }
 7246:                 return $access;
 7247:             }
 7248:         } else {
 7249:             if ($domdef{$tool}{'default'} ne '') {
 7250:                 if ($domdef{$tool}{'default'}) {
 7251:                     $access = 1;
 7252:                 } elsif ($domdef{$tool}{'default'} == 0) {
 7253:                     $access = 0;
 7254:                 }
 7255:                 return $access;
 7256:             }
 7257:         }
 7258:     } else {
 7259:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 7260:             $access = 1;
 7261:         } else {
 7262:             $access = 0;
 7263:         }
 7264:         return $access;
 7265:     }
 7266: }
 7267: 
 7268: sub is_course_owner {
 7269:     my ($cdom,$cnum,$udom,$uname) = @_;
 7270:     if (($udom eq '') || ($uname eq '')) {
 7271:         $udom = $env{'user.domain'};
 7272:         $uname = $env{'user.name'};
 7273:     }
 7274:     unless (($udom eq '') || ($uname eq '')) {
 7275:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 7276:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 7277:                 return 1;
 7278:             } else {
 7279:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 7280:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 7281:                     return 1;
 7282:                 }
 7283:             }
 7284:         }
 7285:     }
 7286:     return;
 7287: }
 7288: 
 7289: sub is_advanced_user {
 7290:     my ($udom,$uname) = @_;
 7291:     if ($udom ne '' && $uname ne '') {
 7292:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7293:             if (wantarray) {
 7294:                 return ($env{'user.adv'},$env{'user.author'});
 7295:             } else {
 7296:                 return $env{'user.adv'};
 7297:             }
 7298:         }
 7299:     }
 7300:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 7301:     my %allroles;
 7302:     my ($is_adv,$is_author);
 7303:     foreach my $role (keys(%roleshash)) {
 7304:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 7305:         my $area = '/'.$tdomain.'/'.$trest;
 7306:         if ($sec ne '') {
 7307:             $area .= '/'.$sec;
 7308:         }
 7309:         if (($area ne '') && ($trole ne '')) {
 7310:             my $spec=$trole.'.'.$area;
 7311:             if ($trole =~ /^cr\//) {
 7312:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 7313:             } elsif ($trole ne 'gr') {
 7314:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 7315:             }
 7316:             if ($trole eq 'au') {
 7317:                 $is_author = 1;
 7318:             }
 7319:         }
 7320:     }
 7321:     foreach my $role (keys(%allroles)) {
 7322:         last if ($is_adv);
 7323:         foreach my $item (split(/:/,$allroles{$role})) {
 7324:             if ($item ne '') {
 7325:                 my ($privilege,$restrictions)=split(/&/,$item);
 7326:                 if ($privilege eq 'adv') {
 7327:                     $is_adv = 1;
 7328:                     last;
 7329:                 }
 7330:             }
 7331:         }
 7332:     }
 7333:     if (wantarray) {
 7334:         return ($is_adv,$is_author);
 7335:     }
 7336:     return $is_adv;
 7337: }
 7338: 
 7339: sub check_can_request {
 7340:     my ($dom,$can_request,$request_domains) = @_;
 7341:     my $canreq = 0;
 7342:     my ($types,$typename) = &Apache::loncommon::course_types();
 7343:     my @options = ('approval','validate','autolimit');
 7344:     my $optregex = join('|',@options);
 7345:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 7346:         foreach my $type (@{$types}) {
 7347:             if (&usertools_access($env{'user.name'},
 7348:                                   $env{'user.domain'},
 7349:                                   $type,undef,'requestcourses')) {
 7350:                 $canreq ++;
 7351:                 if (ref($request_domains) eq 'HASH') {
 7352:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 7353:                 }
 7354:                 if ($dom eq $env{'user.domain'}) {
 7355:                     $can_request->{$type} = 1;
 7356:                 }
 7357:             }
 7358:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 7359:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 7360:                 if (@curr > 0) {
 7361:                     foreach my $item (@curr) {
 7362:                         if (ref($request_domains) eq 'HASH') {
 7363:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 7364:                             if ($otherdom ne '') {
 7365:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 7366:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 7367:                                         push(@{$request_domains->{$type}},$otherdom);
 7368:                                     }
 7369:                                 } else {
 7370:                                     push(@{$request_domains->{$type}},$otherdom);
 7371:                                 }
 7372:                             }
 7373:                         }
 7374:                     }
 7375:                     unless($dom eq $env{'user.domain'}) {
 7376:                         $canreq ++;
 7377:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 7378:                             $can_request->{$type} = 1;
 7379:                         }
 7380:                     }
 7381:                 }
 7382:             }
 7383:         }
 7384:     }
 7385:     return $canreq;
 7386: }
 7387: 
 7388: # ---------------------------------------------- Custom access rule evaluation
 7389: 
 7390: sub customaccess {
 7391:     my ($priv,$uri)=@_;
 7392:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 7393:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 7394:     $udom = &LONCAPA::clean_domain($udom);
 7395:     $ucrs = &LONCAPA::clean_username($ucrs);
 7396:     my $access=0;
 7397:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 7398: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 7399: 	if ($type eq 'user') {
 7400: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 7401: 		my ($tdom,$tuname)=split(m{/},$scope);
 7402: 		if ($tdom) {
 7403: 		    if ($tdom ne $env{'user.domain'}) { next; }
 7404: 		}
 7405: 		if ($tuname) {
 7406: 		    if ($tuname ne $env{'user.name'}) { next; }
 7407: 		}
 7408: 		$access=($effect eq 'allow');
 7409: 		last;
 7410: 	    }
 7411: 	} else {
 7412: 	    if ($role) {
 7413: 		if ($role ne $urole) { next; }
 7414: 	    }
 7415: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 7416: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 7417: 		if ($tdom) {
 7418: 		    if ($tdom ne $udom) { next; }
 7419: 		}
 7420: 		if ($tcrs) {
 7421: 		    if ($tcrs ne $ucrs) { next; }
 7422: 		}
 7423: 		if ($tsec) {
 7424: 		    if ($tsec ne $usec) { next; }
 7425: 		}
 7426: 		$access=($effect eq 'allow');
 7427: 		last;
 7428: 	    }
 7429: 	    if ($realm eq '' && $role eq '') {
 7430: 		$access=($effect eq 'allow');
 7431: 	    }
 7432: 	}
 7433:     }
 7434:     return $access;
 7435: }
 7436: 
 7437: # ------------------------------------------------- Check for a user privilege
 7438: 
 7439: sub allowed {
 7440:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
 7441:     my $ver_orguri=$uri;
 7442:     $uri=&deversion($uri);
 7443:     my $orguri=$uri;
 7444:     $uri=&declutter($uri);
 7445: 
 7446:     if ($priv eq 'evb') {
 7447: # Evade communication block restrictions for specified role in a course
 7448:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 7449:             return $1;
 7450:         } else {
 7451:             return;
 7452:         }
 7453:     }
 7454: 
 7455:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 7456: # Free bre access to adm and meta resources
 7457:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$})) 
 7458: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 7459: 	&& ($priv eq 'bre')) {
 7460: 	return 'F';
 7461:     }
 7462: 
 7463: # Free bre access to user's own portfolio contents
 7464:     my ($space,$domain,$name,@dir)=split('/',$uri);
 7465:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 7466: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 7467:         my %setters;
 7468:         my ($startblock,$endblock) = 
 7469:             &Apache::loncommon::blockcheck(\%setters,'port');
 7470:         if ($startblock && $endblock) {
 7471:             return 'B';
 7472:         } else {
 7473:             return 'F';
 7474:         }
 7475:     }
 7476: 
 7477: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 7478:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 7479:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 7480:         if (exists($env{'request.course.id'})) {
 7481:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7482:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7483:             if (($domain eq $cdom) && ($name eq $cnum)) {
 7484:                 my $courseprivid=$env{'request.course.id'};
 7485:                 $courseprivid=~s/\_/\//;
 7486:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 7487:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 7488:                     return $1; 
 7489:                 } else {
 7490:                     if ($env{'request.course.sec'}) {
 7491:                         $courseprivid.='/'.$env{'request.course.sec'};
 7492:                     }
 7493:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 7494:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 7495:                         return $2;
 7496:                     }
 7497:                 }
 7498:             }
 7499:         }
 7500:     }
 7501: 
 7502: # Free bre to public access
 7503: 
 7504:     if ($priv eq 'bre') {
 7505:         my $copyright=&metadata($uri,'copyright');
 7506: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 7507:            return 'F'; 
 7508:         }
 7509:         if ($copyright eq 'priv') {
 7510:             $uri=~/([^\/]+)\/([^\/]+)\//;
 7511: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 7512: 		return '';
 7513:             }
 7514:         }
 7515:         if ($copyright eq 'domain') {
 7516:             $uri=~/([^\/]+)\/([^\/]+)\//;
 7517: 	    unless (($env{'user.domain'} eq $1) ||
 7518:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 7519: 		return '';
 7520:             }
 7521:         }
 7522:         if ($env{'request.role'}=~ /li\.\//) {
 7523:             # Library role, so allow browsing of resources in this domain.
 7524:             return 'F';
 7525:         }
 7526:         if ($copyright eq 'custom') {
 7527: 	    unless (&customaccess($priv,$uri)) { return ''; }
 7528:         }
 7529:     }
 7530:     # Domain coordinator is trying to create a course
 7531:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 7532:         # uri is the requested domain in this case.
 7533:         # comparison to 'request.role.domain' shows if the user has selected
 7534:         # a role of dc for the domain in question.
 7535:         return 'F' if ($uri eq $env{'request.role.domain'});
 7536:     }
 7537: 
 7538:     my $thisallowed='';
 7539:     my $statecond=0;
 7540:     my $courseprivid='';
 7541: 
 7542:     my $ownaccess;
 7543:     # Community Coordinator or Assistant Co-author browsing resource space.
 7544:     if (($priv eq 'bro') && ($env{'user.author'})) {
 7545:         if ($uri eq '') {
 7546:             $ownaccess = 1;
 7547:         } else {
 7548:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 7549:                 my $udom = $env{'user.domain'};
 7550:                 my $uname = $env{'user.name'};
 7551:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 7552:                     $ownaccess = 1;
 7553:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 7554:                     unless ($uri =~ m{\.\./}) {
 7555:                         $ownaccess = 1;
 7556:                     }
 7557:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 7558:                     my $now = time;
 7559:                     if ($uri =~ m{^([^/]+)/?$}) {
 7560:                         my $adom = $1;
 7561:                         foreach my $key (keys(%env)) {
 7562:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 7563:                                 my ($start,$end) = split('.',$env{$key});
 7564:                                 if (($now >= $start) && (!$end || $end < $now)) {
 7565:                                     $ownaccess = 1;
 7566:                                     last;
 7567:                                 }
 7568:                             }
 7569:                         }
 7570:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 7571:                         my $adom = $1;
 7572:                         my $aname = $2;
 7573:                         foreach my $role ('ca','aa') { 
 7574:                             if ($env{"user.role.$role./$adom/$aname"}) {
 7575:                                 my ($start,$end) =
 7576:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 7577:                                 if (($now >= $start) && (!$end || $end < $now)) {
 7578:                                     $ownaccess = 1;
 7579:                                     last;
 7580:                                 }
 7581:                             }
 7582:                         }
 7583:                     }
 7584:                 }
 7585:             }
 7586:         }
 7587:     }
 7588: 
 7589: # Course
 7590: 
 7591:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 7592:         unless (($priv eq 'bro') && (!$ownaccess)) {
 7593:             $thisallowed.=$1;
 7594:         }
 7595:     }
 7596: 
 7597: # Domain
 7598: 
 7599:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 7600:        =~/\Q$priv\E\&([^\:]*)/) {
 7601:         unless (($priv eq 'bro') && (!$ownaccess)) {
 7602:             $thisallowed.=$1;
 7603:         }
 7604:     }
 7605: 
 7606: # User who is not author or co-author might still be able to edit
 7607: # resource of an author in the domain (e.g., if Domain Coordinator).
 7608:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 7609:         (&allowed('mdc',$env{'request.course.id'}))) {
 7610:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 7611:             $thisallowed.=$1;
 7612:         }
 7613:     }
 7614: 
 7615: # Course: uri itself is a course
 7616:     my $courseuri=$uri;
 7617:     $courseuri=~s/\_(\d)/\/$1/;
 7618:     $courseuri=~s/^([^\/])/\/$1/;
 7619: 
 7620:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 7621:        =~/\Q$priv\E\&([^\:]*)/) {
 7622:         unless (($priv eq 'bro') && (!$ownaccess)) {
 7623:             $thisallowed.=$1;
 7624:         }
 7625:     }
 7626: 
 7627: # URI is an uploaded document for this course, default permissions don't matter
 7628: # not allowing 'edit' access (editupload) to uploaded course docs
 7629:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 7630: 	$thisallowed='';
 7631:         my ($match)=&is_on_map($uri);
 7632:         if ($match) {
 7633:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 7634:                   =~/\Q$priv\E\&([^\:]*)/) {
 7635:                 my $value = $1;
 7636:                 if ($noblockcheck) {
 7637:                     $thisallowed.=$value;
 7638:                 } else {
 7639:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
 7640:                     if (@blockers > 0) {
 7641:                         $thisallowed = 'B';
 7642:                     } else {
 7643:                         $thisallowed.=$value;
 7644:                     }
 7645:                 }
 7646:             }
 7647:         } else {
 7648:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 7649:             if ($refuri) {
 7650:                 if ($refuri =~ m|^/adm/|) {
 7651:                     $thisallowed='F';
 7652:                 } else {
 7653:                     $refuri=&declutter($refuri);
 7654:                     my ($match) = &is_on_map($refuri);
 7655:                     if ($match) {
 7656:                         if ($noblockcheck) {
 7657:                             $thisallowed='F';
 7658:                         } else {
 7659:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 7660:                             if (@blockers > 0) {
 7661:                                 $thisallowed = 'B';
 7662:                             } else {
 7663:                                 $thisallowed='F';
 7664:                             }
 7665:                         }
 7666:                     }
 7667:                 }
 7668:             }
 7669:         }
 7670:     }
 7671: 
 7672:     if ($priv eq 'bre'
 7673: 	&& $thisallowed ne 'F' 
 7674: 	&& $thisallowed ne '2'
 7675: 	&& &is_portfolio_url($uri)) {
 7676: 	$thisallowed = &portfolio_access($uri,$clientip);
 7677:     }
 7678: 
 7679: # Full access at system, domain or course-wide level? Exit.
 7680:     if ($thisallowed=~/F/) {
 7681: 	return 'F';
 7682:     }
 7683: 
 7684: # If this is generating or modifying users, exit with special codes
 7685: 
 7686:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 7687: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 7688: 	    my ($audom,$auname)=split('/',$uri);
 7689: # no author name given, so this just checks on the general right to make a co-author in this domain
 7690: 	    unless ($auname) { return $thisallowed; }
 7691: # an author name is given, so we are about to actually make a co-author for a certain account
 7692: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 7693: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 7694: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 7695: 	}
 7696: 	return $thisallowed;
 7697:     }
 7698: #
 7699: # Gathered so far: system, domain and course wide privileges
 7700: #
 7701: # Course: See if uri or referer is an individual resource that is part of 
 7702: # the course
 7703: 
 7704:     if ($env{'request.course.id'}) {
 7705: 
 7706:        $courseprivid=$env{'request.course.id'};
 7707:        if ($env{'request.course.sec'}) {
 7708:           $courseprivid.='/'.$env{'request.course.sec'};
 7709:        }
 7710:        $courseprivid=~s/\_/\//;
 7711:        my $checkreferer=1;
 7712:        my ($match,$cond)=&is_on_map($uri);
 7713:        if ($match) {
 7714:            $statecond=$cond;
 7715:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 7716:                =~/\Q$priv\E\&([^\:]*)/) {
 7717:                my $value = $1;
 7718:                if ($priv eq 'bre') {
 7719:                    if ($noblockcheck) {
 7720:                        $thisallowed.=$value;
 7721:                    } else {
 7722:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
 7723:                        if (@blockers > 0) {
 7724:                            $thisallowed = 'B';
 7725:                        } else {
 7726:                            $thisallowed.=$value;
 7727:                        }
 7728:                    }
 7729:                } else {
 7730:                    $thisallowed.=$value;
 7731:                }
 7732:                $checkreferer=0;
 7733:            }
 7734:        }
 7735:        
 7736:        if ($checkreferer) {
 7737: 	  my $refuri=$env{'httpref.'.$orguri};
 7738:             unless ($refuri) {
 7739:                 foreach my $key (keys(%env)) {
 7740: 		    if ($key=~/^httpref\..*\*/) {
 7741: 			my $pattern=$key;
 7742:                         $pattern=~s/^httpref\.\/res\///;
 7743:                         $pattern=~s/\*/\[\^\/\]\+/g;
 7744:                         $pattern=~s/\//\\\//g;
 7745:                         if ($orguri=~/$pattern/) {
 7746: 			    $refuri=$env{$key};
 7747:                         }
 7748:                     }
 7749:                 }
 7750:             }
 7751: 
 7752:          if ($refuri) { 
 7753: 	  $refuri=&declutter($refuri);
 7754:           my ($match,$cond)=&is_on_map($refuri);
 7755:             if ($match) {
 7756:               my $refstatecond=$cond;
 7757:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 7758:                   =~/\Q$priv\E\&([^\:]*)/) {
 7759:                   my $value = $1;
 7760:                   if ($priv eq 'bre') {
 7761:                       if ($noblockcheck) {
 7762:                           $thisallowed.=$value;
 7763:                       } else {
 7764:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 7765:                           if (@blockers > 0) {
 7766:                               $thisallowed = 'B';
 7767:                           } else {
 7768:                               $thisallowed.=$value;
 7769:                           }
 7770:                       }
 7771:                   } else {
 7772:                       $thisallowed.=$value;
 7773:                   }
 7774:                   $uri=$refuri;
 7775:                   $statecond=$refstatecond;
 7776:               }
 7777:           }
 7778:         }
 7779:        }
 7780:    }
 7781: 
 7782: #
 7783: # Gathered now: all privileges that could apply, and condition number
 7784: # 
 7785: #
 7786: # Full or no access?
 7787: #
 7788: 
 7789:     if ($thisallowed=~/F/) {
 7790: 	return 'F';
 7791:     }
 7792: 
 7793:     unless ($thisallowed) {
 7794:         return '';
 7795:     }
 7796: 
 7797: # Restrictions exist, deal with them
 7798: #
 7799: #   C:according to course preferences
 7800: #   R:according to resource settings
 7801: #   L:unless locked
 7802: #   X:according to user session state
 7803: #
 7804: 
 7805: # Possibly locked functionality, check all courses
 7806: # Locks might take effect only after 10 minutes cache expiration for other
 7807: # courses, and 2 minutes for current course
 7808: 
 7809:     my $envkey;
 7810:     if ($thisallowed=~/L/) {
 7811:         foreach $envkey (keys(%env)) {
 7812:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 7813:                my $courseid=$2;
 7814:                my $roleid=$1.'.'.$2;
 7815:                $courseid=~s/^\///;
 7816:                my $expiretime=600;
 7817:                if ($env{'request.role'} eq $roleid) {
 7818: 		  $expiretime=120;
 7819:                }
 7820: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 7821:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 7822:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 7823: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 7824:                }
 7825:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 7826:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 7827: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 7828:                        &log($env{'user.domain'},$env{'user.name'},
 7829:                             $env{'user.home'},
 7830:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 7831:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 7832:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 7833: 		       return '';
 7834:                    }
 7835:                }
 7836:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 7837:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 7838: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 7839:                        &log($env{'user.domain'},$env{'user.name'},
 7840:                             $env{'user.home'},
 7841:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 7842:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 7843:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 7844: 		       return '';
 7845:                    }
 7846:                }
 7847: 	   }
 7848:        }
 7849:     }
 7850:    
 7851: #
 7852: # Rest of the restrictions depend on selected course
 7853: #
 7854: 
 7855:     unless ($env{'request.course.id'}) {
 7856: 	if ($thisallowed eq 'A') {
 7857: 	    return 'A';
 7858:         } elsif ($thisallowed eq 'B') {
 7859:             return 'B';
 7860: 	} else {
 7861: 	    return '1';
 7862: 	}
 7863:     }
 7864: 
 7865: #
 7866: # Now user is definitely in a course
 7867: #
 7868: 
 7869: 
 7870: # Course preferences
 7871: 
 7872:    if ($thisallowed=~/C/) {
 7873:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 7874:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 7875:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 7876: 	   =~/\Q$rolecode\E/) {
 7877: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 7878: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 7879: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 7880: 			$env{'request.course.id'});
 7881: 	   }
 7882:            return '';
 7883:        }
 7884: 
 7885:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 7886: 	   =~/\Q$unamedom\E/) {
 7887: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
 7888: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 7889: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 7890: 			$env{'request.course.id'});
 7891: 	   }
 7892:            return '';
 7893:        }
 7894:    }
 7895: 
 7896: # Resource preferences
 7897: 
 7898:    if ($thisallowed=~/R/) {
 7899:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 7900:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 7901: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 7902: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 7903: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 7904: 	   }
 7905: 	   return '';
 7906:        }
 7907:    }
 7908: 
 7909: # Restricted by state or randomout?
 7910: 
 7911:    if ($thisallowed=~/X/) {
 7912:       if ($env{'acc.randomout'}) {
 7913: 	 if (!$symb) { $symb=&symbread($uri,1); }
 7914:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 7915:             return ''; 
 7916:          }
 7917:       }
 7918:       if (&condval($statecond)) {
 7919: 	 return '2';
 7920:       } else {
 7921:          return '';
 7922:       }
 7923:    }
 7924: 
 7925:     if ($thisallowed eq 'A') {
 7926: 	return 'A';
 7927:     } elsif ($thisallowed eq 'B') {
 7928:         return 'B';
 7929:     }
 7930:    return 'F';
 7931: }
 7932: 
 7933: # ------------------------------------------- Check construction space access
 7934: 
 7935: sub constructaccess {
 7936:     my ($url,$setpriv)=@_;
 7937: 
 7938: # We do not allow editing of previous versions of files
 7939:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 7940: 
 7941: # Get username and domain from URL
 7942:     my ($ownername,$ownerdomain,$ownerhome);
 7943: 
 7944:     ($ownerdomain,$ownername) =
 7945:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
 7946: 
 7947: # The URL does not really point to any authorspace, forget it
 7948:     unless (($ownername) && ($ownerdomain)) { return ''; }
 7949: 
 7950: # Now we need to see if the user has access to the authorspace of
 7951: # $ownername at $ownerdomain
 7952: 
 7953:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 7954: # Real author for this?
 7955:        $ownerhome = $env{'user.home'};
 7956:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 7957:           return ($ownername,$ownerdomain,$ownerhome);
 7958:        }
 7959:     } else {
 7960: # Co-author for this?
 7961:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 7962:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 7963:             $ownerhome = &homeserver($ownername,$ownerdomain);
 7964:             return ($ownername,$ownerdomain,$ownerhome);
 7965:         }
 7966:         if ($env{'request.course.id'}) {
 7967:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
 7968:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
 7969:                 if (&allowed('mdc',$env{'request.course.id'})) {
 7970:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
 7971:                     return ($ownername,$ownerdomain,$ownerhome);
 7972:                 }
 7973:             }
 7974:         }
 7975:     }
 7976: 
 7977: # We don't have any access right now. If we are not possibly going to do anything about this,
 7978: # we might as well leave
 7979:    unless ($setpriv) { return ''; }
 7980: 
 7981: # Backdoor access?
 7982:     my $allowed=&allowed('eco',$ownerdomain);
 7983: # Nope
 7984:     unless ($allowed) { return ''; }
 7985: # Looks like we may have access, but could be locked by the owner of the construction space
 7986:     if ($allowed eq 'U') {
 7987:         my %blocked=&get('environment',['domcoord.author'],
 7988:                          $ownerdomain,$ownername);
 7989: # Is blocked by owner
 7990:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 7991:     }
 7992:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 7993: # Grant temporary access
 7994:         my $then=$env{'user.login.time'};
 7995:         my $update=$env{'user.update.time'};
 7996:         if (!$update) { $update = $then; }
 7997:         my $refresh=$env{'user.refresh.time'};
 7998:         if (!$refresh) { $refresh = $update; }
 7999:         my $now = time;
 8000:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 8001:                            $now,'ca','constructaccess');
 8002:         $ownerhome = &homeserver($ownername,$ownerdomain);
 8003:         return($ownername,$ownerdomain,$ownerhome);
 8004:     }
 8005: # No business here
 8006:     return '';
 8007: }
 8008: 
 8009: # ----------------------------------------------------------- Content Blocking
 8010: 
 8011: {
 8012: # Caches for faster Course Contents display where content blocking
 8013: # is in operation (i.e., interval param set) for timed quiz.
 8014: #
 8015: # User for whom data are being temporarily cached.
 8016: my $cacheduser='';
 8017: # Cached blockers for this user (a hash of blocking items). 
 8018: my %cachedblockers=();
 8019: # When the data were last cached.
 8020: my $cachedlast='';
 8021: 
 8022: sub load_all_blockers {
 8023:     my ($uname,$udom,$blocks)=@_;
 8024:     if (($uname ne '') && ($udom ne '')) { 
 8025:         if (($cacheduser eq $uname.':'.$udom) &&
 8026:             (abs($cachedlast-time)<5)) {
 8027:             return;
 8028:         }
 8029:     }
 8030:     $cachedlast=time;
 8031:     $cacheduser=$uname.':'.$udom;
 8032:     %cachedblockers = &get_commblock_resources($blocks);
 8033: }
 8034: 
 8035: sub get_comm_blocks {
 8036:     my ($cdom,$cnum) = @_;
 8037:     if ($cdom eq '' || $cnum eq '') {
 8038:         return unless ($env{'request.course.id'});
 8039:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 8040:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 8041:     }
 8042:     my %commblocks;
 8043:     my $hashid=$cdom.'_'.$cnum;
 8044:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 8045:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 8046:         %commblocks = %{$blocksref};
 8047:     } else {
 8048:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 8049:         my $cachetime = 600;
 8050:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 8051:     }
 8052:     return %commblocks;
 8053: }
 8054: 
 8055: sub get_commblock_resources {
 8056:     my ($blocks) = @_;
 8057:     my %blockers = ();
 8058:     return %blockers unless ($env{'request.course.id'});
 8059:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8060:     my %commblocks;
 8061:     if (ref($blocks) eq 'HASH') {
 8062:         %commblocks = %{$blocks};
 8063:     } else {
 8064:         %commblocks = &get_comm_blocks();
 8065:     }
 8066:     return %blockers unless (keys(%commblocks) > 0); 
 8067:     my $navmap = Apache::lonnavmaps::navmap->new();
 8068:     return %blockers unless (ref($navmap));
 8069:     my $now = time;
 8070:     foreach my $block (keys(%commblocks)) {
 8071:         if ($block =~ /^(\d+)____(\d+)$/) {
 8072:             my ($start,$end) = ($1,$2);
 8073:             if ($start <= $now && $end >= $now) {
 8074:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8075:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8076:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8077:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8078:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
 8079:                             }
 8080:                         }
 8081:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8082:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8083:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8084:                             }
 8085:                         }
 8086:                     }
 8087:                 }
 8088:             }
 8089:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 8090:             my $item = $1;
 8091:             my @to_test;
 8092:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 8093:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 8094:                     my @interval;
 8095:                     my $type = 'map';
 8096:                     if ($item eq 'course') {
 8097:                         $type = 'course';
 8098:                         @interval=&EXT("resource.0.interval");
 8099:                     } else {
 8100:                         if ($item =~ /___\d+___/) {
 8101:                             $type = 'resource';
 8102:                             @interval=&EXT("resource.0.interval",$item);
 8103:                             if (ref($navmap)) {                        
 8104:                                 my $res = $navmap->getBySymb($item); 
 8105:                                 push(@to_test,$res);
 8106:                             }
 8107:                         } else {
 8108:                             my $mapsymb = &symbread($item,1);
 8109:                             if ($mapsymb) {
 8110:                                 if (ref($navmap)) {
 8111:                                     my $mapres = $navmap->getBySymb($mapsymb);
 8112:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
 8113:                                     foreach my $res (@to_test) {
 8114:                                         my $symb = $res->symb();
 8115:                                         next if ($symb eq $mapsymb);
 8116:                                         if ($symb ne '') {
 8117:                                             @interval=&EXT("resource.0.interval",$symb);
 8118:                                             if ($interval[1] eq 'map') {
 8119:                                                 last;
 8120:                                             }
 8121:                                         }
 8122:                                     }
 8123:                                 }
 8124:                             }
 8125:                         }
 8126:                     }
 8127:                     if ($interval[0] =~ /^(\d+)/) {
 8128:                         my $timelimit = $1; 
 8129:                         my $first_access;
 8130:                         if ($type eq 'resource') {
 8131:                             $first_access=&get_first_access($interval[1],$item);
 8132:                         } elsif ($type eq 'map') {
 8133:                             $first_access=&get_first_access($interval[1],undef,$item);
 8134:                         } else {
 8135:                             $first_access=&get_first_access($interval[1]);
 8136:                         }
 8137:                         if ($first_access) {
 8138:                             my $timesup = $first_access+$timelimit;
 8139:                             if ($timesup > $now) {
 8140:                                 my $activeblock;
 8141:                                 foreach my $res (@to_test) {
 8142:                                     if ($res->answerable()) {
 8143:                                         $activeblock = 1;
 8144:                                         last;
 8145:                                     }
 8146:                                 }
 8147:                                 if ($activeblock) {
 8148:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 8149:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 8150:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 8151:                                          }
 8152:                                     }
 8153:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 8154:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 8155:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 8156:                                         }
 8157:                                     }
 8158:                                 }
 8159:                             }
 8160:                         }
 8161:                     }
 8162:                 }
 8163:             }
 8164:         }
 8165:     }
 8166:     return %blockers;
 8167: }
 8168: 
 8169: sub has_comm_blocking {
 8170:     my ($priv,$symb,$uri,$blocks) = @_;
 8171:     my @blockers;
 8172:     return unless ($env{'request.course.id'});
 8173:     return unless ($priv eq 'bre');
 8174:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 8175:     return if ($env{'request.state'} eq 'construct');
 8176:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
 8177:     return unless (keys(%cachedblockers) > 0);
 8178:     my (%possibles,@symbs);
 8179:     if (!$symb) {
 8180:         $symb = &symbread($uri,1,1,1,\%possibles);
 8181:     }
 8182:     if ($symb) {
 8183:         @symbs = ($symb);
 8184:     } elsif (keys(%possibles)) { 
 8185:         @symbs = keys(%possibles);
 8186:     }
 8187:     my $noblock;
 8188:     foreach my $symb (@symbs) {
 8189:         last if ($noblock);
 8190:         my ($map,$resid,$resurl)=&decode_symb($symb);
 8191:         foreach my $block (keys(%cachedblockers)) {
 8192:             if ($block =~ /^firstaccess____(.+)$/) {
 8193:                 my $item = $1;
 8194:                 if (($item eq $map) || ($item eq $symb)) {
 8195:                     $noblock = 1;
 8196:                     last;
 8197:                 }
 8198:             }
 8199:             if (ref($cachedblockers{$block}) eq 'HASH') {
 8200:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
 8201:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
 8202:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 8203:                             push(@blockers,$block);
 8204:                         }
 8205:                     }
 8206:                 }
 8207:             }
 8208:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
 8209:                 if ($cachedblockers{$block}{'maps'}{$map}) {
 8210:                     unless (grep(/^\Q$block\E$/,@blockers)) {
 8211:                         push(@blockers,$block);
 8212:                     }
 8213:                 }
 8214:             }
 8215:         }
 8216:     }
 8217:     return if ($noblock);
 8218:     return @blockers;
 8219: }
 8220: }
 8221: 
 8222: # -------------------------------- Deversion and split uri into path an filename   
 8223: 
 8224: #
 8225: #   Removes the version from a URI and
 8226: #   splits it in to its filename and path to the filename.
 8227: #   Seems like File::Basename could have done this more clearly.
 8228: #   Parameters:
 8229: #      $uri   - input URI
 8230: #   Returns:
 8231: #     Two element list consisting of 
 8232: #     $pathname  - the URI up to and excluding the trailing /
 8233: #     $filename  - The part of the URI following the last /
 8234: #  NOTE:
 8235: #    Another realization of this is simply:
 8236: #    use File::Basename;
 8237: #    ...
 8238: #    $uri = shift;
 8239: #    $filename = basename($uri);
 8240: #    $path     = dirname($uri);
 8241: #    return ($filename, $path);
 8242: #
 8243: #     The implementation below is probably faster however.
 8244: #
 8245: sub split_uri_for_cond {
 8246:     my $uri=&deversion(&declutter(shift));
 8247:     my @uriparts=split(/\//,$uri);
 8248:     my $filename=pop(@uriparts);
 8249:     my $pathname=join('/',@uriparts);
 8250:     return ($pathname,$filename);
 8251: }
 8252: # --------------------------------------------------- Is a resource on the map?
 8253: 
 8254: sub is_on_map {
 8255:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 8256:     #Trying to find the conditional for the file
 8257:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 8258: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 8259:     if ($match) {
 8260: 	return (1,$1);
 8261:     } else {
 8262: 	return (0,0);
 8263:     }
 8264: }
 8265: 
 8266: # --------------------------------------------------------- Get symb from alias
 8267: 
 8268: sub get_symb_from_alias {
 8269:     my $symb=shift;
 8270:     my ($map,$resid,$url)=&decode_symb($symb);
 8271: # Already is a symb
 8272:     if ($url) { return $symb; }
 8273: # Must be an alias
 8274:     my $aliassymb='';
 8275:     my %bighash;
 8276:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8277:                             &GDBM_READER(),0640)) {
 8278:         my $rid=$bighash{'mapalias_'.$symb};
 8279: 	if ($rid) {
 8280: 	    my ($mapid,$resid)=split(/\./,$rid);
 8281: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 8282: 				    $resid,$bighash{'src_'.$rid});
 8283: 	}
 8284:         untie %bighash;
 8285:     }
 8286:     return $aliassymb;
 8287: }
 8288: 
 8289: # ----------------------------------------------------------------- Define Role
 8290: 
 8291: sub definerole {
 8292:   if (allowed('mcr','/')) {
 8293:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
 8294:     foreach my $role (split(':',$sysrole)) {
 8295: 	my ($crole,$cqual)=split(/\&/,$role);
 8296:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 8297:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 8298: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 8299:                return "refused:s:$crole&$cqual"; 
 8300:             }
 8301:         }
 8302:     }
 8303:     foreach my $role (split(':',$domrole)) {
 8304: 	my ($crole,$cqual)=split(/\&/,$role);
 8305:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 8306:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 8307: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 8308:                return "refused:d:$crole&$cqual"; 
 8309:             }
 8310:         }
 8311:     }
 8312:     foreach my $role (split(':',$courole)) {
 8313: 	my ($crole,$cqual)=split(/\&/,$role);
 8314:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 8315:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 8316: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 8317:                return "refused:c:$crole&$cqual"; 
 8318:             }
 8319:         }
 8320:     }
 8321:     my $uhome;
 8322:     if (($uname ne '') && ($udom ne '')) {
 8323:         $uhome = &homeserver($uname,$udom);
 8324:         return $uhome if ($uhome eq 'no_host');
 8325:     } else {
 8326:         $uname = $env{'user.name'};
 8327:         $udom = $env{'user.domain'};
 8328:         $uhome = $env{'user.home'};
 8329:     }
 8330:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 8331:                 "$udom:$uname:rolesdef_$rolename=".
 8332:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 8333:     return reply($command,$uhome);
 8334:   } else {
 8335:     return 'refused';
 8336:   }
 8337: }
 8338: 
 8339: # ---------------- Make a metadata query against the network of library servers
 8340: 
 8341: sub metadata_query {
 8342:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 8343:     my %rhash;
 8344:     my %libserv = &all_library();
 8345:     my @server_list = (defined($server_array) ? @$server_array
 8346:                                               : keys(%libserv) );
 8347:     for my $server (@server_list) {
 8348:         my $domains = ''; 
 8349:         if (ref($domains_hash) eq 'HASH') {
 8350:             $domains = $domains_hash->{$server}; 
 8351:         }
 8352: 	unless ($custom or $customshow) {
 8353: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 8354: 	    $rhash{$server}=$reply;
 8355: 	}
 8356: 	else {
 8357: 	    my $reply=&reply("querysend:".&escape($query).':'.
 8358: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 8359: 			     $server);
 8360: 	    $rhash{$server}=$reply;
 8361: 	}
 8362:     }
 8363:     return \%rhash;
 8364: }
 8365: 
 8366: # ----------------------------------------- Send log queries and wait for reply
 8367: 
 8368: sub log_query {
 8369:     my ($uname,$udom,$query,%filters)=@_;
 8370:     my $uhome=&homeserver($uname,$udom);
 8371:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 8372:     my $uhost=&hostname($uhome);
 8373:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 8374:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 8375:                        $uhome);
 8376:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 8377:     return get_query_reply($queryid);
 8378: }
 8379: 
 8380: # -------------------------- Update MySQL table for portfolio file
 8381: 
 8382: sub update_portfolio_table {
 8383:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 8384:     if ($group ne '') {
 8385:         $file_name =~s /^\Q$group\E//;
 8386:     }
 8387:     my $homeserver = &homeserver($uname,$udom);
 8388:     my $queryid=
 8389:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 8390:                ':'.&escape($file_name).':'.$action,$homeserver);
 8391:     my $reply = &get_query_reply($queryid);
 8392:     return $reply;
 8393: }
 8394: 
 8395: # -------------------------- Update MySQL allusers table
 8396: 
 8397: sub update_allusers_table {
 8398:     my ($uname,$udom,$names) = @_;
 8399:     my $homeserver = &homeserver($uname,$udom);
 8400:     my $queryid=
 8401:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 8402:                'lastname='.&escape($names->{'lastname'}).'%%'.
 8403:                'firstname='.&escape($names->{'firstname'}).'%%'.
 8404:                'middlename='.&escape($names->{'middlename'}).'%%'.
 8405:                'generation='.&escape($names->{'generation'}).'%%'.
 8406:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 8407:                'id='.&escape($names->{'id'}),$homeserver);
 8408:     return;
 8409: }
 8410: 
 8411: # ------- Request retrieval of institutional classlists for course(s)
 8412: 
 8413: sub fetch_enrollment_query {
 8414:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 8415:     my ($homeserver,$sleep,$loopmax);
 8416:     my $maxtries = 1;
 8417:     if ($context eq 'automated') {
 8418:         $homeserver = $perlvar{'lonHostID'};
 8419:         $sleep = 2;
 8420:         $loopmax = 100;
 8421:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 8422:     } else {
 8423:         $homeserver = &homeserver($cnum,$dom);
 8424:     }
 8425:     my $host=&hostname($homeserver);
 8426:     my $cmd = '';
 8427:     foreach my $affiliate (keys(%{$affiliatesref})) {
 8428:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 8429:     }
 8430:     $cmd =~ s/%%$//;
 8431:     $cmd = &escape($cmd);
 8432:     my $query = 'fetchenrollment';
 8433:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 8434:     unless ($queryid=~/^\Q$host\E\_/) { 
 8435:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 8436:         return 'error: '.$queryid;
 8437:     }
 8438:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
 8439:     my $tries = 1;
 8440:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 8441:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
 8442:         $tries ++;
 8443:     }
 8444:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 8445:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 8446:     } else {
 8447:         my @responses = split(/:/,$reply);
 8448:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
 8449:             foreach my $line (@responses) {
 8450:                 my ($key,$value) = split(/=/,$line,2);
 8451:                 $$replyref{$key} = $value;
 8452:             }
 8453:         } else {
 8454:             my $pathname = LONCAPA::tempdir();
 8455:             foreach my $line (@responses) {
 8456:                 my ($key,$value) = split(/=/,$line);
 8457:                 $$replyref{$key} = $value;
 8458:                 if ($value > 0) {
 8459:                     foreach my $item (@{$$affiliatesref{$key}}) {
 8460:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 8461:                         my $destname = $pathname.'/'.$filename;
 8462:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 8463:                         if ($xml_classlist =~ /^error/) {
 8464:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 8465:                         } else {
 8466:                             if ( open(FILE,">$destname") ) {
 8467:                                 print FILE &unescape($xml_classlist);
 8468:                                 close(FILE);
 8469:                             } else {
 8470:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 8471:                             }
 8472:                         }
 8473:                     }
 8474:                 }
 8475:             }
 8476:         }
 8477:         return 'ok';
 8478:     }
 8479:     return 'error';
 8480: }
 8481: 
 8482: sub get_query_reply {
 8483:     my ($queryid,$sleep,$loopmax) = @_;;
 8484:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
 8485:         $sleep = 0.2;
 8486:     }
 8487:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
 8488:         $loopmax = 100;
 8489:     }
 8490:     my $replyfile=LONCAPA::tempdir().$queryid;
 8491:     my $reply='';
 8492:     for (1..$loopmax) {
 8493: 	sleep($sleep);
 8494:         if (-e $replyfile.'.end') {
 8495: 	    if (open(my $fh,$replyfile)) {
 8496: 		$reply = join('',<$fh>);
 8497: 		close($fh);
 8498: 	   } else { return 'error: reply_file_error'; }
 8499:            return &unescape($reply);
 8500: 	}
 8501:     }
 8502:     return 'timeout:'.$queryid;
 8503: }
 8504: 
 8505: sub courselog_query {
 8506: #
 8507: # possible filters:
 8508: # url: url or symb
 8509: # username
 8510: # domain
 8511: # action: view, submit, grade
 8512: # start: timestamp
 8513: # end: timestamp
 8514: #
 8515:     my (%filters)=@_;
 8516:     unless ($env{'request.course.id'}) { return 'no_course'; }
 8517:     if ($filters{'url'}) {
 8518: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 8519:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 8520:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 8521:     }
 8522:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 8523:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 8524:     return &log_query($cname,$cdom,'courselog',%filters);
 8525: }
 8526: 
 8527: sub userlog_query {
 8528: #
 8529: # possible filters:
 8530: # action: log check role
 8531: # start: timestamp
 8532: # end: timestamp
 8533: #
 8534:     my ($uname,$udom,%filters)=@_;
 8535:     return &log_query($uname,$udom,'userlog',%filters);
 8536: }
 8537: 
 8538: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 8539: 
 8540: sub auto_run {
 8541:     my ($cnum,$cdom) = @_;
 8542:     my $response = 0;
 8543:     my $settings;
 8544:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 8545:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 8546:         $settings = $domconfig{'autoenroll'};
 8547:         if ($settings->{'run'} eq '1') {
 8548:             $response = 1;
 8549:         }
 8550:     } else {
 8551:         my $homeserver;
 8552:         if (&is_course($cdom,$cnum)) {
 8553:             $homeserver = &homeserver($cnum,$cdom);
 8554:         } else {
 8555:             $homeserver = &domain($cdom,'primary');
 8556:         }
 8557:         if ($homeserver ne 'no_host') {
 8558:             $response = &reply('autorun:'.$cdom,$homeserver);
 8559:         }
 8560:     }
 8561:     return $response;
 8562: }
 8563: 
 8564: sub auto_get_sections {
 8565:     my ($cnum,$cdom,$inst_coursecode) = @_;
 8566:     my $homeserver;
 8567:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 8568:         $homeserver = &homeserver($cnum,$cdom);
 8569:     }
 8570:     if (!defined($homeserver)) { 
 8571:         if ($cdom =~ /^$match_domain$/) {
 8572:             $homeserver = &domain($cdom,'primary');
 8573:         }
 8574:     }
 8575:     my @secs;
 8576:     if (defined($homeserver)) {
 8577:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 8578:         unless ($response eq 'refused') {
 8579:             @secs = split(/:/,$response);
 8580:         }
 8581:     }
 8582:     return @secs;
 8583: }
 8584: 
 8585: sub auto_new_course {
 8586:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 8587:     my $homeserver = &homeserver($cnum,$cdom);
 8588:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 8589:     return $response;
 8590: }
 8591: 
 8592: sub auto_validate_courseID {
 8593:     my ($cnum,$cdom,$inst_course_id) = @_;
 8594:     my $homeserver = &homeserver($cnum,$cdom);
 8595:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 8596:     return $response;
 8597: }
 8598: 
 8599: sub auto_validate_instcode {
 8600:     my ($cnum,$cdom,$instcode,$owner) = @_;
 8601:     my ($homeserver,$response);
 8602:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 8603:         $homeserver = &homeserver($cnum,$cdom);
 8604:     }
 8605:     if (!defined($homeserver)) {
 8606:         if ($cdom =~ /^$match_domain$/) {
 8607:             $homeserver = &domain($cdom,'primary');
 8608:         }
 8609:     }
 8610:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 8611:                         &escape($instcode).':'.&escape($owner),$homeserver));
 8612:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 8613:     return ($outcome,$description,$defaultcredits);
 8614: }
 8615: 
 8616: sub auto_create_password {
 8617:     my ($cnum,$cdom,$authparam,$udom) = @_;
 8618:     my ($homeserver,$response);
 8619:     my $create_passwd = 0;
 8620:     my $authchk = '';
 8621:     if ($udom =~ /^$match_domain$/) {
 8622:         $homeserver = &domain($udom,'primary');
 8623:     }
 8624:     if ($homeserver eq '') {
 8625:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 8626:             $homeserver = &homeserver($cnum,$cdom);
 8627:         }
 8628:     }
 8629:     if ($homeserver eq '') {
 8630:         $authchk = 'nodomain';
 8631:     } else {
 8632:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 8633:         if ($response eq 'refused') {
 8634:             $authchk = 'refused';
 8635:         } else {
 8636:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 8637:         }
 8638:     }
 8639:     return ($authparam,$create_passwd,$authchk);
 8640: }
 8641: 
 8642: sub auto_photo_permission {
 8643:     my ($cnum,$cdom,$students) = @_;
 8644:     my $homeserver = &homeserver($cnum,$cdom);
 8645:     my ($outcome,$perm_reqd,$conditions) = 
 8646: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 8647:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 8648: 	return (undef,undef);
 8649:     }
 8650:     return ($outcome,$perm_reqd,$conditions);
 8651: }
 8652: 
 8653: sub auto_checkphotos {
 8654:     my ($uname,$udom,$pid) = @_;
 8655:     my $homeserver = &homeserver($uname,$udom);
 8656:     my ($result,$resulttype);
 8657:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 8658: 				   &escape($uname).':'.&escape($pid),
 8659: 				   $homeserver));
 8660:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 8661: 	return (undef,undef);
 8662:     }
 8663:     if ($outcome) {
 8664:         ($result,$resulttype) = split(/:/,$outcome);
 8665:     } 
 8666:     return ($result,$resulttype);
 8667: }
 8668: 
 8669: sub auto_photochoice {
 8670:     my ($cnum,$cdom) = @_;
 8671:     my $homeserver = &homeserver($cnum,$cdom);
 8672:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 8673: 						       &escape($cdom),
 8674: 						       $homeserver)));
 8675:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 8676: 	return (undef,undef);
 8677:     }
 8678:     return ($update,$comment);
 8679: }
 8680: 
 8681: sub auto_photoupdate {
 8682:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 8683:     my $homeserver = &homeserver($cnum,$dom);
 8684:     my $host=&hostname($homeserver);
 8685:     my $cmd = '';
 8686:     my $maxtries = 1;
 8687:     foreach my $affiliate (keys(%{$affiliatesref})) {
 8688:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 8689:     }
 8690:     $cmd =~ s/%%$//;
 8691:     $cmd = &escape($cmd);
 8692:     my $query = 'institutionalphotos';
 8693:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 8694:     unless ($queryid=~/^\Q$host\E\_/) {
 8695:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 8696:         return 'error: '.$queryid;
 8697:     }
 8698:     my $reply = &get_query_reply($queryid);
 8699:     my $tries = 1;
 8700:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 8701:         $reply = &get_query_reply($queryid);
 8702:         $tries ++;
 8703:     }
 8704:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 8705:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 8706:     } else {
 8707:         my @responses = split(/:/,$reply);
 8708:         my $outcome = shift(@responses); 
 8709:         foreach my $item (@responses) {
 8710:             my ($key,$value) = split(/=/,$item);
 8711:             $$photo{$key} = $value;
 8712:         }
 8713:         return $outcome;
 8714:     }
 8715:     return 'error';
 8716: }
 8717: 
 8718: sub auto_instcode_format {
 8719:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 8720: 	$cat_order) = @_;
 8721:     my $courses = '';
 8722:     my @homeservers;
 8723:     if ($caller eq 'global') {
 8724: 	my %servers = &get_servers($codedom,'library');
 8725: 	foreach my $tryserver (keys(%servers)) {
 8726: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 8727: 		push(@homeservers,$tryserver);
 8728: 	    }
 8729:         }
 8730:     } elsif ($caller eq 'requests') {
 8731:         if ($codedom =~ /^$match_domain$/) {
 8732:             my $chome = &domain($codedom,'primary');
 8733:             unless ($chome eq 'no_host') {
 8734:                 push(@homeservers,$chome);
 8735:             }
 8736:         }
 8737:     } else {
 8738:         push(@homeservers,&homeserver($caller,$codedom));
 8739:     }
 8740:     foreach my $code (keys(%{$instcodes})) {
 8741:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 8742:     }
 8743:     chop($courses);
 8744:     my $ok_response = 0;
 8745:     my $response;
 8746:     while (@homeservers > 0 && $ok_response == 0) {
 8747:         my $server = shift(@homeservers); 
 8748:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 8749:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 8750:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 8751: 		split(/:/,$response);
 8752:             %{$codes} = (%{$codes},&str2hash($codes_str));
 8753:             push(@{$codetitles},&str2array($codetitles_str));
 8754:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 8755:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 8756:             $ok_response = 1;
 8757:         }
 8758:     }
 8759:     if ($ok_response) {
 8760:         return 'ok';
 8761:     } else {
 8762:         return $response;
 8763:     }
 8764: }
 8765: 
 8766: sub auto_instcode_defaults {
 8767:     my ($domain,$returnhash,$code_order) = @_;
 8768:     my @homeservers;
 8769: 
 8770:     my %servers = &get_servers($domain,'library');
 8771:     foreach my $tryserver (keys(%servers)) {
 8772: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 8773: 	    push(@homeservers,$tryserver);
 8774: 	}
 8775:     }
 8776: 
 8777:     my $response;
 8778:     foreach my $server (@homeservers) {
 8779:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 8780:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 8781: 	
 8782: 	foreach my $pair (split(/\&/,$response)) {
 8783: 	    my ($name,$value)=split(/\=/,$pair);
 8784: 	    if ($name eq 'code_order') {
 8785: 		@{$code_order} = split(/\&/,&unescape($value));
 8786: 	    } else {
 8787: 		$returnhash->{&unescape($name)}=&unescape($value);
 8788: 	    }
 8789: 	}
 8790: 	return 'ok';
 8791:     }
 8792: 
 8793:     return $response;
 8794: }
 8795: 
 8796: sub auto_possible_instcodes {
 8797:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 8798:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 8799:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 8800:         return;
 8801:     }
 8802:     my (@homeservers,$uhome);
 8803:     if (defined(&domain($domain,'primary'))) {
 8804:         $uhome=&domain($domain,'primary');
 8805:         push(@homeservers,&domain($domain,'primary'));
 8806:     } else {
 8807:         my %servers = &get_servers($domain,'library');
 8808:         foreach my $tryserver (keys(%servers)) {
 8809:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 8810:                 push(@homeservers,$tryserver);
 8811:             }
 8812:         }
 8813:     }
 8814:     my $response;
 8815:     foreach my $server (@homeservers) {
 8816:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 8817:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 8818:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 8819:             split(':',$response);
 8820:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 8821:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 8822:         foreach my $item (split('&',$cat_title)) {   
 8823:             my ($name,$value)=split('=',$item);
 8824:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 8825:         }
 8826:         foreach my $item (split('&',$cat_order)) {
 8827:             my ($name,$value)=split('=',$item);
 8828:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 8829:         }
 8830:         return 'ok';
 8831:     }
 8832:     return $response;
 8833: }
 8834: 
 8835: sub auto_courserequest_checks {
 8836:     my ($dom) = @_;
 8837:     my ($homeserver,%validations);
 8838:     if ($dom =~ /^$match_domain$/) {
 8839:         $homeserver = &domain($dom,'primary');
 8840:     }
 8841:     unless ($homeserver eq 'no_host') {
 8842:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 8843:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 8844:             my @items = split(/&/,$response);
 8845:             foreach my $item (@items) {
 8846:                 my ($key,$value) = split('=',$item);
 8847:                 $validations{&unescape($key)} = &thaw_unescape($value);
 8848:             }
 8849:         }
 8850:     }
 8851:     return %validations; 
 8852: }
 8853: 
 8854: sub auto_courserequest_validation {
 8855:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
 8856:     my ($homeserver,$response);
 8857:     if ($dom =~ /^$match_domain$/) {
 8858:         $homeserver = &domain($dom,'primary');
 8859:     }
 8860:     unless ($homeserver eq 'no_host') {
 8861:         my $customdata;
 8862:         if (ref($custominfo) eq 'HASH') {
 8863:             $customdata = &freeze_escape($custominfo);
 8864:         }
 8865:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 8866:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 8867:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
 8868:                                     $customdata,$homeserver));
 8869:     }
 8870:     return $response;
 8871: }
 8872: 
 8873: sub auto_validate_class_sec {
 8874:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 8875:     my $homeserver = &homeserver($cnum,$cdom);
 8876:     my $ownerlist;
 8877:     if (ref($owners) eq 'ARRAY') {
 8878:         $ownerlist = join(',',@{$owners});
 8879:     } else {
 8880:         $ownerlist = $owners;
 8881:     }
 8882:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 8883:                         &escape($ownerlist).':'.$cdom,$homeserver);
 8884:     return $response;
 8885: }
 8886: 
 8887: sub auto_crsreq_update {
 8888:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
 8889:         $code,$accessstart,$accessend,$inbound) = @_;
 8890:     my ($homeserver,%crsreqresponse);
 8891:     if ($cdom =~ /^$match_domain$/) {
 8892:         $homeserver = &domain($cdom,'primary');
 8893:     }
 8894:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 8895:         my $info;
 8896:         if (ref($inbound) eq 'HASH') {
 8897:             $info = &freeze_escape($inbound);
 8898:         }
 8899:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
 8900:                             ':'.&escape($action).':'.&escape($ownername).':'.
 8901:                             &escape($ownerdomain).':'.&escape($fullname).':'.
 8902:                             &escape($title).':'.&escape($code).':'.
 8903:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
 8904:                             $homeserver);
 8905:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 8906:             my @items = split(/&/,$response);
 8907:             foreach my $item (@items) {
 8908:                 my ($key,$value) = split('=',$item);
 8909:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
 8910:             }
 8911:         }
 8912:     }
 8913:     return \%crsreqresponse;
 8914: }
 8915: 
 8916: sub auto_export_grades {
 8917:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
 8918:     my ($homeserver,%exportresponse);
 8919:     if ($cdom =~ /^$match_domain$/) {
 8920:         $homeserver = &domain($cdom,'primary');
 8921:     }
 8922:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 8923:         my $info;
 8924:         if (ref($inforef) eq 'HASH') {
 8925:             $info = &freeze_escape($inforef);
 8926:         }
 8927:         if (ref($gradesref) eq 'HASH') {
 8928:             my $grades = &freeze_escape($gradesref);
 8929:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
 8930:                                 $info.':'.$grades,$homeserver);
 8931:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
 8932:                 my @items = split(/&/,$response);
 8933:                 foreach my $item (@items) {
 8934:                     my ($key,$value) = split('=',$item);
 8935:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
 8936:                 }
 8937:             }
 8938:         }
 8939:     }
 8940:     return \%exportresponse;
 8941: }
 8942: 
 8943: sub check_instcode_cloning {
 8944:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
 8945:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 8946:         return;
 8947:     }
 8948:     my $canclone;
 8949:     if (@{$code_order} > 0) {
 8950:         my $instcoderegexp ='^';
 8951:         my @clonecodes = split(/\&/,$cloner);
 8952:         foreach my $item (@{$code_order}) {
 8953:             if (grep(/^\Q$item\E=/,@clonecodes)) {
 8954:                 foreach my $pair (@clonecodes) {
 8955:                     my ($key,$val) = split(/\=/,$pair,2);
 8956:                     $val = &unescape($val);
 8957:                     if ($key eq $item) {
 8958:                         $instcoderegexp .= '('.$val.')';
 8959:                         last;
 8960:                     }
 8961:                 }
 8962:             } else {
 8963:                 $instcoderegexp .= $codedefaults->{$item};
 8964:             }
 8965:         }
 8966:         $instcoderegexp .= '$';
 8967:         my (@from,@to);
 8968:         eval {
 8969:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
 8970:                (@to) = ($clonetocode =~ /$instcoderegexp/);
 8971:         };
 8972:         if ((@from > 0) && (@to > 0)) {
 8973:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 8974:             if (!@diffs) {
 8975:                 $canclone = 1;
 8976:             }
 8977:         }
 8978:     }
 8979:     return $canclone;
 8980: }
 8981: 
 8982: sub default_instcode_cloning {
 8983:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
 8984:     my (%codedefaults,@code_order,$canclone);
 8985:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
 8986:         %codedefaults = %{$codedefaultsref};
 8987:         @code_order = @{$codeorderref};
 8988:     } elsif ($clonedom) {
 8989:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
 8990:     }
 8991:     if (($domdefclone) && (@code_order)) {
 8992:         my @clonecodes = split(/\+/,$domdefclone);
 8993:         my $instcoderegexp ='^';
 8994:         foreach my $item (@code_order) {
 8995:             if (grep(/^\Q$item\E$/,@clonecodes)) {
 8996:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
 8997:             } else {
 8998:                 $instcoderegexp .= $codedefaults{$item};
 8999:             }
 9000:         }
 9001:         $instcoderegexp .= '$';
 9002:         my (@from,@to);
 9003:         eval {
 9004:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
 9005:             (@to) = ($clonetocode =~ /$instcoderegexp/);
 9006:         };
 9007:         if ((@from > 0) && (@to > 0)) {
 9008:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 9009:             if (!@diffs) {
 9010:                 $canclone = 1;
 9011:             }
 9012:         }
 9013:     }
 9014:     return $canclone;
 9015: }
 9016: 
 9017: # ------------------------------------------------------- Course Group routines
 9018: 
 9019: sub get_coursegroups {
 9020:     my ($cdom,$cnum,$group,$namespace) = @_;
 9021:     return(&dump($namespace,$cdom,$cnum,$group));
 9022: }
 9023: 
 9024: sub modify_coursegroup {
 9025:     my ($cdom,$cnum,$groupsettings) = @_;
 9026:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 9027: }
 9028: 
 9029: sub toggle_coursegroup_status {
 9030:     my ($cdom,$cnum,$group,$action) = @_;
 9031:     my ($from_namespace,$to_namespace);
 9032:     if ($action eq 'delete') {
 9033:         $from_namespace = 'coursegroups';
 9034:         $to_namespace = 'deleted_groups';
 9035:     } else {
 9036:         $from_namespace = 'deleted_groups';
 9037:         $to_namespace = 'coursegroups';
 9038:     }
 9039:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 9040:     if (my $tmp = &error(%curr_group)) {
 9041:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 9042:         return ('read error',$tmp);
 9043:     } else {
 9044:         my %savedsettings = %curr_group; 
 9045:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 9046:         my $deloutcome;
 9047:         if ($result eq 'ok') {
 9048:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 9049:         } else {
 9050:             return ('write error',$result);
 9051:         }
 9052:         if ($deloutcome eq 'ok') {
 9053:             return 'ok';
 9054:         } else {
 9055:             return ('delete error',$deloutcome);
 9056:         }
 9057:     }
 9058: }
 9059: 
 9060: sub modify_group_roles {
 9061:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 9062:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 9063:     my $role = 'gr/'.&escape($userprivs);
 9064:     my ($uname,$udom) = split(/:/,$user);
 9065:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 9066:     if ($result eq 'ok') {
 9067:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 9068:     }
 9069:     return $result;
 9070: }
 9071: 
 9072: sub modify_coursegroup_membership {
 9073:     my ($cdom,$cnum,$membership) = @_;
 9074:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 9075:     return $result;
 9076: }
 9077: 
 9078: sub get_active_groups {
 9079:     my ($udom,$uname,$cdom,$cnum) = @_;
 9080:     my $now = time;
 9081:     my %groups = ();
 9082:     foreach my $key (keys(%env)) {
 9083:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 9084:             my ($start,$end) = split(/\./,$env{$key});
 9085:             if (($end!=0) && ($end<$now)) { next; }
 9086:             if (($start!=0) && ($start>$now)) { next; }
 9087:             if ($1 eq $cdom && $2 eq $cnum) {
 9088:                 $groups{$3} = $env{$key} ;
 9089:             }
 9090:         }
 9091:     }
 9092:     return %groups;
 9093: }
 9094: 
 9095: sub get_group_membership {
 9096:     my ($cdom,$cnum,$group) = @_;
 9097:     return(&dump('groupmembership',$cdom,$cnum,$group));
 9098: }
 9099: 
 9100: sub get_users_groups {
 9101:     my ($udom,$uname,$courseid) = @_;
 9102:     my @usersgroups;
 9103:     my $cachetime=1800;
 9104: 
 9105:     my $hashid="$udom:$uname:$courseid";
 9106:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 9107:     if (defined($cached)) {
 9108:         @usersgroups = split(/:/,$grouplist);
 9109:     } else {  
 9110:         $grouplist = '';
 9111:         my $courseurl = &courseid_to_courseurl($courseid);
 9112:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 9113:         my $access_end = $env{'course.'.$courseid.
 9114:                               '.default_enrollment_end_date'};
 9115:         my $now = time;
 9116:         foreach my $key (keys(%roleshash)) {
 9117:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 9118:                 my $group = $1;
 9119:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 9120:                     my $start = $2;
 9121:                     my $end = $1;
 9122:                     if ($start == -1) { next; } # deleted from group
 9123:                     if (($start!=0) && ($start>$now)) { next; }
 9124:                     if (($end!=0) && ($end<$now)) {
 9125:                         if ($access_end && $access_end < $now) {
 9126:                             if ($access_end - $end < 86400) {
 9127:                                 push(@usersgroups,$group);
 9128:                             }
 9129:                         }
 9130:                         next;
 9131:                     }
 9132:                     push(@usersgroups,$group);
 9133:                 }
 9134:             }
 9135:         }
 9136:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 9137:         $grouplist = join(':',@usersgroups);
 9138:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 9139:     }
 9140:     return @usersgroups;
 9141: }
 9142: 
 9143: sub devalidate_getgroups_cache {
 9144:     my ($udom,$uname,$cdom,$cnum)=@_;
 9145:     my $courseid = $cdom.'_'.$cnum;
 9146: 
 9147:     my $hashid="$udom:$uname:$courseid";
 9148:     &devalidate_cache_new('getgroups',$hashid);
 9149: }
 9150: 
 9151: # ------------------------------------------------------------------ Plain Text
 9152: 
 9153: sub plaintext {
 9154:     my ($short,$type,$cid,$forcedefault) = @_;
 9155:     if ($short =~ m{^cr/}) {
 9156: 	return (split('/',$short))[-1];
 9157:     }
 9158:     if (!defined($cid)) {
 9159:         $cid = $env{'request.course.id'};
 9160:     }
 9161:     my %rolenames = (
 9162:                       Course    => 'std',
 9163:                       Community => 'alt1',
 9164:                       Placement => 'std',
 9165:                     );
 9166:     if ($cid ne '') {
 9167:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 9168:             unless ($forcedefault) {
 9169:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 9170:                 &Apache::lonlocal::mt_escape(\$roletext);
 9171:                 return &Apache::lonlocal::mt($roletext);
 9172:             }
 9173:         }
 9174:     }
 9175:     if ((defined($type)) && (defined($rolenames{$type})) &&
 9176:         (defined($rolenames{$type})) && 
 9177:         (defined($prp{$short}{$rolenames{$type}}))) {
 9178:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 9179:     } elsif ($cid ne '') {
 9180:         my $crstype = $env{'course.'.$cid.'.type'};
 9181:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 9182:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 9183:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 9184:         }
 9185:     }
 9186:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 9187: }
 9188: 
 9189: # ----------------------------------------------------------------- Assign Role
 9190: 
 9191: sub assignrole {
 9192:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 9193:         $context)=@_;
 9194:     my $mrole;
 9195:     if ($role =~ /^cr\//) {
 9196:         my $cwosec=$url;
 9197:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 9198: 	unless (&allowed('ccr',$cwosec)) {
 9199:            my $refused = 1;
 9200:            if ($context eq 'requestcourses') {
 9201:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 9202:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 9203:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 9204:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 9205:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9206:                            if ($crsenv{'internal.courseowner'} eq
 9207:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 9208:                                $refused = '';
 9209:                            }
 9210:                        }
 9211:                    }
 9212:                }
 9213:            }
 9214:            if ($refused) {
 9215:                &logthis('Refused custom assignrole: '.
 9216:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 9217:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 9218:                return 'refused';
 9219:            }
 9220:         }
 9221:         $mrole='cr';
 9222:     } elsif ($role =~ /^gr\//) {
 9223:         my $cwogrp=$url;
 9224:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 9225:         unless (&allowed('mdg',$cwogrp)) {
 9226:             &logthis('Refused group assignrole: '.
 9227:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 9228:                     $env{'user.name'}.' at '.$env{'user.domain'});
 9229:             return 'refused';
 9230:         }
 9231:         $mrole='gr';
 9232:     } else {
 9233:         my $cwosec=$url;
 9234:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 9235:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 9236:             my $refused;
 9237:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 9238:                 if (!(&allowed('c'.$role,$url))) {
 9239:                     $refused = 1;
 9240:                 }
 9241:             } else {
 9242:                 $refused = 1;
 9243:             }
 9244:             if ($refused) {
 9245:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 9246:                 if (!$selfenroll && $context eq 'course') {
 9247:                     my %crsenv;
 9248:                     if ($role eq 'cc' || $role eq 'co') {
 9249:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9250:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 9251:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 9252:                                 if ($crsenv{'internal.courseowner'} eq 
 9253:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 9254:                                     $refused = '';
 9255:                                 }
 9256:                             }
 9257:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 9258:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 9259:                                 if ($crsenv{'internal.courseowner'} eq 
 9260:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 9261:                                     $refused = '';
 9262:                                 }
 9263:                             }
 9264:                         }
 9265:                     }
 9266:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 9267:                     $refused = '';
 9268:                 } elsif ($context eq 'requestcourses') {
 9269:                     my @possroles = ('st','ta','ep','in','cc','co');
 9270:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 9271:                         my $wrongcc;
 9272:                         if ($cnum =~ /^$match_community$/) {
 9273:                             $wrongcc = 1 if ($role eq 'cc');
 9274:                         } else {
 9275:                             $wrongcc = 1 if ($role eq 'co');
 9276:                         }
 9277:                         unless ($wrongcc) {
 9278:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 9279:                             if ($crsenv{'internal.courseowner'} eq 
 9280:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 9281:                                 $refused = '';
 9282:                             }
 9283:                         }
 9284:                     }
 9285:                 } elsif ($context eq 'requestauthor') {
 9286:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
 9287:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 9288:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 9289:                             $refused = '';
 9290:                         } else {
 9291:                             my %domdefaults = &get_domain_defaults($udom);
 9292:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 9293:                                 my $checkbystatus;
 9294:                                 if ($env{'user.adv'}) { 
 9295:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 9296:                                     if ($disposition eq 'automatic') {
 9297:                                         $refused = '';
 9298:                                     } elsif ($disposition eq '') {
 9299:                                         $checkbystatus = 1;
 9300:                                     } 
 9301:                                 } else {
 9302:                                     $checkbystatus = 1;
 9303:                                 }
 9304:                                 if ($checkbystatus) {
 9305:                                     if ($env{'environment.inststatus'}) {
 9306:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 9307:                                         foreach my $type (@inststatuses) {
 9308:                                             if (($type ne '') &&
 9309:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 9310:                                                 $refused = '';
 9311:                                             }
 9312:                                         }
 9313:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 9314:                                         $refused = '';
 9315:                                     }
 9316:                                 }
 9317:                             }
 9318:                         }
 9319:                     }
 9320:                 }
 9321:                 if ($refused) {
 9322:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 9323:                              ' '.$role.' '.$end.' '.$start.' by '.
 9324: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 9325:                     return 'refused';
 9326:                 }
 9327:             }
 9328:         } elsif ($role eq 'au') {
 9329:             if ($url ne '/'.$udom.'/') {
 9330:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 9331:                          ' to assign author role for '.$uname.':'.$udom.
 9332:                          ' in domain: '.$url.' refused (wrong domain).');
 9333:                 return 'refused';
 9334:             }
 9335:         }
 9336:         $mrole=$role;
 9337:     }
 9338:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 9339:                 "$udom:$uname:$url".'_'."$mrole=$role";
 9340:     if ($end) { $command.='_'.$end; }
 9341:     if ($start) {
 9342: 	if ($end) { 
 9343:            $command.='_'.$start; 
 9344:         } else {
 9345:            $command.='_0_'.$start;
 9346:         }
 9347:     }
 9348:     my $origstart = $start;
 9349:     my $origend = $end;
 9350:     my $delflag;
 9351: # actually delete
 9352:     if ($deleteflag) {
 9353: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 9354: # modify command to delete the role
 9355:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 9356:                 "$udom:$uname:$url".'_'."$mrole";
 9357: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 9358: # set start and finish to negative values for userrolelog
 9359:            $start=-1;
 9360:            $end=-1;
 9361:            $delflag = 1;
 9362:         }
 9363:     }
 9364: # send command
 9365:     my $answer=&reply($command,&homeserver($uname,$udom));
 9366: # log new user role if status is ok
 9367:     if ($answer eq 'ok') {
 9368: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 9369:         if (($role eq 'cc') || ($role eq 'in') ||
 9370:             ($role eq 'ep') || ($role eq 'ad') ||
 9371:             ($role eq 'ta') || ($role eq 'st') ||
 9372:             ($role=~/^cr/) || ($role eq 'gr') ||
 9373:             ($role eq 'co')) {
 9374: # for course roles, perform group memberships changes triggered by role change.
 9375:             unless ($role =~ /^gr/) {
 9376:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 9377:                                                  $origstart,$selfenroll,$context);
 9378:             }
 9379:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9380:                            $selfenroll,$context);
 9381:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
 9382:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
 9383:                  ($role eq 'da')) {
 9384:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9385:                            $context);
 9386:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
 9387:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 9388:                              $context); 
 9389:         }
 9390:         if ($role eq 'cc') {
 9391:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 9392:         }
 9393:     }
 9394:     return $answer;
 9395: }
 9396: 
 9397: sub autoupdate_coowners {
 9398:     my ($url,$end,$start,$uname,$udom) = @_;
 9399:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 9400:     if (($cdom ne '') && ($cnum ne '')) {
 9401:         my $now = time;
 9402:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 9403:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 9404:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 9405:             my $instcode = $coursehash{'internal.coursecode'};
 9406:             if ($instcode ne '') {
 9407:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 9408:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 9409:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 9410:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 9411:                         if ($result eq 'valid') {
 9412:                             if ($coursehash{'internal.co-owners'}) {
 9413:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 9414:                                     push(@newcoowners,$coowner);
 9415:                                 }
 9416:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 9417:                                     push(@newcoowners,$uname.':'.$udom);
 9418:                                 }
 9419:                                 @newcoowners = sort(@newcoowners);
 9420:                             } else {
 9421:                                 push(@newcoowners,$uname.':'.$udom);
 9422:                             }
 9423:                         } else {
 9424:                             if ($coursehash{'internal.co-owners'}) {
 9425:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 9426:                                     unless ($coowner eq $uname.':'.$udom) {
 9427:                                         push(@newcoowners,$coowner);
 9428:                                     }
 9429:                                 }
 9430:                                 unless (@newcoowners > 0) {
 9431:                                     $delcoowners = 1;
 9432:                                     $coowners = '';
 9433:                                 }
 9434:                             }
 9435:                         }
 9436:                         if (@newcoowners || $delcoowners) {
 9437:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 9438:                                             $delcoowners,@newcoowners);
 9439:                         }
 9440:                     }
 9441:                 }
 9442:             }
 9443:         }
 9444:     }
 9445: }
 9446: 
 9447: sub store_coowners {
 9448:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 9449:     my $cid = $cdom.'_'.$cnum;
 9450:     my ($coowners,$delresult,$putresult);
 9451:     if (@newcoowners) {
 9452:         $coowners = join(',',@newcoowners);
 9453:         my %coownershash = (
 9454:                             'internal.co-owners' => $coowners,
 9455:                            );
 9456:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 9457:         if ($putresult eq 'ok') {
 9458:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 9459:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 9460:             }
 9461:         }
 9462:     }
 9463:     if ($delcoowners) {
 9464:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 9465:         if ($delresult eq 'ok') {
 9466:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 9467:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 9468:             }
 9469:         }
 9470:     }
 9471:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 9472:         my %crsinfo =
 9473:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 9474:         if (ref($crsinfo{$cid}) eq 'HASH') {
 9475:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 9476:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 9477:         }
 9478:     }
 9479: }
 9480: 
 9481: # -------------------------------------------------- Modify user authentication
 9482: # Overrides without validation
 9483: 
 9484: sub modifyuserauth {
 9485:     my ($udom,$uname,$umode,$upass)=@_;
 9486:     my $uhome=&homeserver($uname,$udom);
 9487:     unless (&allowed('mau',$udom)) { return 'refused'; }
 9488:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 9489:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 9490:              ' in domain '.$env{'request.role.domain'});  
 9491:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 9492: 		     &escape($upass),$uhome);
 9493:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 9494:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 9495:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 9496:     &log($udom,,$uname,$uhome,
 9497:         'Authentication changed by '.$env{'user.domain'}.', '.
 9498:                                      $env{'user.name'}.', '.$umode.
 9499:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 9500:     unless ($reply eq 'ok') {
 9501:         &logthis('Authentication mode error: '.$reply);
 9502: 	return 'error: '.$reply;
 9503:     }   
 9504:     return 'ok';
 9505: }
 9506: 
 9507: # --------------------------------------------------------------- Modify a user
 9508: 
 9509: sub modifyuser {
 9510:     my ($udom,    $uname, $uid,
 9511:         $umode,   $upass, $first,
 9512:         $middle,  $last,  $gene,
 9513:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 9514:     $udom= &LONCAPA::clean_domain($udom);
 9515:     $uname=&LONCAPA::clean_username($uname);
 9516:     my $showcandelete = 'none';
 9517:     if (ref($candelete) eq 'ARRAY') {
 9518:         if (@{$candelete} > 0) {
 9519:             $showcandelete = join(', ',@{$candelete});
 9520:         }
 9521:     }
 9522:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 9523:              $umode.', '.$first.', '.$middle.', '.
 9524: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 9525:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 9526:                                      ' desiredhome not specified'). 
 9527:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 9528:              ' in domain '.$env{'request.role.domain'});
 9529:     my $uhome=&homeserver($uname,$udom,'true');
 9530:     my $newuser;
 9531:     if ($uhome eq 'no_host') {
 9532:         $newuser = 1;
 9533:     }
 9534: # ----------------------------------------------------------------- Create User
 9535:     if (($uhome eq 'no_host') && 
 9536: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 9537:         my $unhome='';
 9538:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 9539:             $unhome = $desiredhome;
 9540: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 9541: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 9542:         } else { # load balancing routine for determining $unhome
 9543:             my $loadm=10000000;
 9544: 	    my %servers = &get_servers($udom,'library');
 9545: 	    foreach my $tryserver (keys(%servers)) {
 9546: 		my $answer=reply('load',$tryserver);
 9547: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 9548: 		    $loadm=$answer;
 9549: 		    $unhome=$tryserver;
 9550: 		}
 9551: 	    }
 9552:         }
 9553:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 9554: 	    return 'error: unable to find a home server for '.$uname.
 9555:                    ' in domain '.$udom;
 9556:         }
 9557:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 9558:                          &escape($upass),$unhome);
 9559: 	unless ($reply eq 'ok') {
 9560:             return 'error: '.$reply;
 9561:         }   
 9562:         $uhome=&homeserver($uname,$udom,'true');
 9563:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 9564: 	    return 'error: unable verify users home machine.';
 9565:         }
 9566:     }   # End of creation of new user
 9567: # ---------------------------------------------------------------------- Add ID
 9568:     if ($uid) {
 9569:        $uid=~tr/A-Z/a-z/;
 9570:        my %uidhash=&idrget($udom,$uname);
 9571:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 9572:          && (!$forceid)) {
 9573: 	  unless ($uid eq $uidhash{$uname}) {
 9574: 	      return 'error: user id "'.$uid.'" does not match '.
 9575:                   'current user id "'.$uidhash{$uname}.'".';
 9576:           }
 9577:        } else {
 9578: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
 9579:        }
 9580:     }
 9581: # -------------------------------------------------------------- Add names, etc
 9582:     my @tmp=&get('environment',
 9583: 		   ['firstname','middlename','lastname','generation','id',
 9584:                     'permanentemail','inststatus'],
 9585: 		   $udom,$uname);
 9586:     my (%names,%oldnames);
 9587:     if ($tmp[0] =~ m/^error:.*/) { 
 9588:         %names=(); 
 9589:     } else {
 9590:         %names = @tmp;
 9591:         %oldnames = %names;
 9592:     }
 9593: #
 9594: # If name, email and/or uid are blank (e.g., because an uploaded file
 9595: # of users did not contain them), do not overwrite existing values
 9596: # unless field is in $candelete array ref.  
 9597: #
 9598: 
 9599:     my @fields = ('firstname','middlename','lastname','generation',
 9600:                   'permanentemail','id');
 9601:     my %newvalues;
 9602:     if (ref($candelete) eq 'ARRAY') {
 9603:         foreach my $field (@fields) {
 9604:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 9605:                 if ($field eq 'firstname') {
 9606:                     $names{$field} = $first;
 9607:                 } elsif ($field eq 'middlename') {
 9608:                     $names{$field} = $middle;
 9609:                 } elsif ($field eq 'lastname') {
 9610:                     $names{$field} = $last;
 9611:                 } elsif ($field eq 'generation') { 
 9612:                     $names{$field} = $gene;
 9613:                 } elsif ($field eq 'permanentemail') {
 9614:                     $names{$field} = $email;
 9615:                 } elsif ($field eq 'id') {
 9616:                     $names{$field}  = $uid;
 9617:                 }
 9618:             }
 9619:         }
 9620:     }
 9621:     if ($first)  { $names{'firstname'}  = $first; }
 9622:     if (defined($middle)) { $names{'middlename'} = $middle; }
 9623:     if ($last)   { $names{'lastname'}   = $last; }
 9624:     if (defined($gene))   { $names{'generation'} = $gene; }
 9625:     if ($email) {
 9626:        $email=~s/[^\w\@\.\-\,]//gs;
 9627:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 9628:     }
 9629:     if ($uid) { $names{'id'}  = $uid; }
 9630:     if (defined($inststatus)) {
 9631:         $names{'inststatus'} = '';
 9632:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 9633:         if (ref($usertypes) eq 'HASH') {
 9634:             my @okstatuses; 
 9635:             foreach my $item (split(/:/,$inststatus)) {
 9636:                 if (defined($usertypes->{$item})) {
 9637:                     push(@okstatuses,$item);  
 9638:                 }
 9639:             }
 9640:             if (@okstatuses) {
 9641:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 9642:             }
 9643:         }
 9644:     }
 9645:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 9646:                  $umode.', '.$first.', '.$middle.', '.
 9647:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 9648:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 9649:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 9650:     } else {
 9651:         $logmsg .= ' during self creation';
 9652:     }
 9653:     my $changed;
 9654:     if ($newuser) {
 9655:         $changed = 1;
 9656:     } else {
 9657:         foreach my $field (@fields) {
 9658:             if ($names{$field} ne $oldnames{$field}) {
 9659:                 $changed = 1;
 9660:                 last;
 9661:             }
 9662:         }
 9663:     }
 9664:     unless ($changed) {
 9665:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 9666:         &logthis($logmsg);
 9667:         return 'ok';
 9668:     }
 9669:     my $reply = &put('environment', \%names, $udom,$uname);
 9670:     if ($reply ne 'ok') { 
 9671:         return 'error: '.$reply;
 9672:     }
 9673:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
 9674:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
 9675:     }
 9676:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 9677:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 9678:     $logmsg = 'Success modifying user '.$logmsg;
 9679:     &logthis($logmsg);
 9680:     return 'ok';
 9681: }
 9682: 
 9683: # -------------------------------------------------------------- Modify student
 9684: 
 9685: sub modifystudent {
 9686:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 9687:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 9688:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
 9689:     if (!$cid) {
 9690: 	unless ($cid=$env{'request.course.id'}) {
 9691: 	    return 'not_in_class';
 9692: 	}
 9693:     }
 9694: # --------------------------------------------------------------- Make the user
 9695:     my $reply=&modifyuser
 9696: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 9697:          $desiredhome,$email,$inststatus);
 9698:     unless ($reply eq 'ok') { return $reply; }
 9699:     # This will cause &modify_student_enrollment to get the uid from the
 9700:     # student's environment
 9701:     $uid = undef if (!$forceid);
 9702:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 9703:                                         $gene,$usec,$end,$start,$type,$locktype,
 9704:                                         $cid,$selfenroll,$context,$credits,$instsec);
 9705:     return $reply;
 9706: }
 9707: 
 9708: sub modify_student_enrollment {
 9709:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
 9710:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
 9711:     my ($cdom,$cnum,$chome);
 9712:     if (!$cid) {
 9713: 	unless ($cid=$env{'request.course.id'}) {
 9714: 	    return 'not_in_class';
 9715: 	}
 9716: 	$cdom=$env{'course.'.$cid.'.domain'};
 9717: 	$cnum=$env{'course.'.$cid.'.num'};
 9718:     } else {
 9719: 	($cdom,$cnum)=split(/_/,$cid);
 9720:     }
 9721:     $chome=$env{'course.'.$cid.'.home'};
 9722:     if (!$chome) {
 9723: 	$chome=&homeserver($cnum,$cdom);
 9724:     }
 9725:     if (!$chome) { return 'unknown_course'; }
 9726:     # Make sure the user exists
 9727:     my $uhome=&homeserver($uname,$udom);
 9728:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 9729: 	return 'error: no such user';
 9730:     }
 9731:     # Get student data if we were not given enough information
 9732:     if (!defined($first)  || $first  eq '' || 
 9733:         !defined($last)   || $last   eq '' || 
 9734:         !defined($uid)    || $uid    eq '' || 
 9735:         !defined($middle) || $middle eq '' || 
 9736:         !defined($gene)   || $gene   eq '') {
 9737:         # They did not supply us with enough data to enroll the student, so
 9738:         # we need to pick up more information.
 9739:         my %tmp = &get('environment',
 9740:                        ['firstname','middlename','lastname', 'generation','id']
 9741:                        ,$udom,$uname);
 9742: 
 9743:         #foreach my $key (keys(%tmp)) {
 9744:         #    &logthis("key $key = ".$tmp{$key});
 9745:         #}
 9746:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 9747:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 9748:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 9749:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 9750:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 9751:     }
 9752:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 9753:     my $user = "$uname:$udom";
 9754:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
 9755:     my $reply=cput('classlist',
 9756: 		   {$user => 
 9757: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
 9758: 		   $cdom,$cnum);
 9759:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
 9760:         &devalidate_getsection_cache($udom,$uname,$cid);
 9761:     } else { 
 9762: 	return 'error: '.$reply;
 9763:     }
 9764:     # Add student role to user
 9765:     my $uurl='/'.$cid;
 9766:     $uurl=~s/\_/\//g;
 9767:     if ($usec) {
 9768: 	$uurl.='/'.$usec;
 9769:     }
 9770:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
 9771:                              $selfenroll,$context);
 9772:     if ($result ne 'ok') {
 9773:         if ($old_entry{$user} ne '') {
 9774:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
 9775:         } else {
 9776:             $reply = &del('classlist',[$user],$cdom,$cnum);
 9777:         }
 9778:     }
 9779:     return $result; 
 9780: }
 9781: 
 9782: sub format_name {
 9783:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 9784:     my $name;
 9785:     if ($first ne 'lastname') {
 9786: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 9787:     } else {
 9788: 	if ($lastname=~/\S/) {
 9789: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 9790: 	    $name=~s/\s+,/,/;
 9791: 	} else {
 9792: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 9793: 	}
 9794:     }
 9795:     $name=~s/^\s+//;
 9796:     $name=~s/\s+$//;
 9797:     $name=~s/\s+/ /g;
 9798:     return $name;
 9799: }
 9800: 
 9801: # ------------------------------------------------- Write to course preferences
 9802: 
 9803: sub writecoursepref {
 9804:     my ($courseid,%prefs)=@_;
 9805:     $courseid=~s/^\///;
 9806:     $courseid=~s/\_/\//g;
 9807:     my ($cdomain,$cnum)=split(/\//,$courseid);
 9808:     my $chome=homeserver($cnum,$cdomain);
 9809:     if (($chome eq '') || ($chome eq 'no_host')) { 
 9810: 	return 'error: no such course';
 9811:     }
 9812:     my $cstring='';
 9813:     foreach my $pref (keys(%prefs)) {
 9814: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 9815:     }
 9816:     $cstring=~s/\&$//;
 9817:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 9818: }
 9819: 
 9820: # ---------------------------------------------------------- Make/modify course
 9821: 
 9822: sub createcourse {
 9823:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 9824:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 9825:     $url=&declutter($url);
 9826:     my $cid='';
 9827:     if ($context eq 'requestcourses') {
 9828:         my $can_create = 0;
 9829:         my ($ownername,$ownerdom) = split(':',$course_owner);
 9830:         if ($udom eq $ownerdom) {
 9831:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 9832:                                   $context)) {
 9833:                 $can_create = 1;
 9834:             }
 9835:         } else {
 9836:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 9837:                                            $category);
 9838:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 9839:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 9840:                 if (@curr > 0) {
 9841:                     my @options = qw(approval validate autolimit);
 9842:                     my $optregex = join('|',@options);
 9843:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 9844:                         $can_create = 1;
 9845:                     }
 9846:                 }
 9847:             }
 9848:         }
 9849:         if ($can_create) {
 9850:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 9851:                 unless (&allowed('ccc',$udom)) {
 9852:                     return 'refused'; 
 9853:                 }
 9854:             }
 9855:         } else {
 9856:             return 'refused';
 9857:         }
 9858:     } elsif (!&allowed('ccc',$udom)) {
 9859:         return 'refused';
 9860:     }
 9861: # --------------------------------------------------------------- Get Unique ID
 9862:     my $uname;
 9863:     if ($cnum =~ /^$match_courseid$/) {
 9864:         my $chome=&homeserver($cnum,$udom,'true');
 9865:         if (($chome eq '') || ($chome eq 'no_host')) {
 9866:             $uname = $cnum;
 9867:         } else {
 9868:             $uname = &generate_coursenum($udom,$crstype);
 9869:         }
 9870:     } else {
 9871:         $uname = &generate_coursenum($udom,$crstype);
 9872:     }
 9873:     return $uname if ($uname =~ /^error/);
 9874: # -------------------------------------------------- Check supplied server name
 9875:     if (!defined($course_server)) {
 9876:         if (defined(&domain($udom,'primary'))) {
 9877:             $course_server = &domain($udom,'primary');
 9878:         } else {
 9879:             $course_server = $env{'user.home'}; 
 9880:         }
 9881:     }
 9882:     my %host_servers =
 9883:         &Apache::lonnet::get_servers($udom,'library');
 9884:     unless ($host_servers{$course_server}) {
 9885:         return 'error: invalid home server for course: '.$course_server;
 9886:     }
 9887: # ------------------------------------------------------------- Make the course
 9888:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 9889:                       $course_server);
 9890:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 9891:     my $uhome=&homeserver($uname,$udom,'true');
 9892:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 9893: 	return 'error: no such course';
 9894:     }
 9895: # ----------------------------------------------------------------- Course made
 9896: # log existence
 9897:     my $now = time;
 9898:     my $newcourse = {
 9899:                     $udom.'_'.$uname => {
 9900:                                      description => $description,
 9901:                                      inst_code   => $inst_code,
 9902:                                      owner       => $course_owner,
 9903:                                      type        => $crstype,
 9904:                                      creator     => $env{'user.name'}.':'.
 9905:                                                     $env{'user.domain'},
 9906:                                      created     => $now,
 9907:                                      context     => $context,
 9908:                                                 },
 9909:                     };
 9910:     &courseidput($udom,$newcourse,$uhome,'notime');
 9911: # set toplevel url
 9912:     my $topurl=$url;
 9913:     unless ($nonstandard) {
 9914: # ------------------------------------------ For standard courses, make top url
 9915:         my $mapurl=&clutter($url);
 9916:         if ($mapurl eq '/res/') { $mapurl=''; }
 9917:         $env{'form.initmap'}=(<<ENDINITMAP);
 9918: <map>
 9919: <resource id="1" type="start"></resource>
 9920: <resource id="2" src="$mapurl"></resource>
 9921: <resource id="3" type="finish"></resource>
 9922: <link index="1" from="1" to="2"></link>
 9923: <link index="2" from="2" to="3"></link>
 9924: </map>
 9925: ENDINITMAP
 9926:         $topurl=&declutter(
 9927:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 9928:                           );
 9929:     }
 9930: # ----------------------------------------------------------- Write preferences
 9931:     &writecoursepref($udom.'_'.$uname,
 9932:                      ('description'              => $description,
 9933:                       'url'                      => $topurl,
 9934:                       'internal.creator'         => $env{'user.name'}.':'.
 9935:                                                     $env{'user.domain'},
 9936:                       'internal.created'         => $now,
 9937:                       'internal.creationcontext' => $context)
 9938:                     );
 9939:     return '/'.$udom.'/'.$uname;
 9940: }
 9941: 
 9942: # ------------------------------------------------------------------- Create ID
 9943: sub generate_coursenum {
 9944:     my ($udom,$crstype) = @_;
 9945:     my $domdesc = &domain($udom);
 9946:     return 'error: invalid domain' if ($domdesc eq '');
 9947:     my $first;
 9948:     if ($crstype eq 'Community') {
 9949:         $first = '0';
 9950:     } else {
 9951:         $first = int(1+rand(9)); 
 9952:     } 
 9953:     my $uname=$first.
 9954:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 9955:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
 9956:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 9957: # ----------------------------------------------- Make sure that does not exist
 9958:     my $uhome=&homeserver($uname,$udom,'true');
 9959:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
 9960:         if ($crstype eq 'Community') {
 9961:             $first = '0';
 9962:         } else {
 9963:             $first = int(1+rand(9));
 9964:         }
 9965:         $uname=$first.
 9966:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 9967:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
 9968:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 9969:         $uhome=&homeserver($uname,$udom,'true');
 9970:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
 9971:             return 'error: unable to generate unique course-ID';
 9972:         }
 9973:     }
 9974:     return $uname;
 9975: }
 9976: 
 9977: sub is_course {
 9978:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
 9979:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
 9980: 
 9981:     return unless $cdom and $cnum;
 9982: 
 9983:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
 9984:         '.');
 9985: 
 9986:     return unless(exists($courses{$cdom.'_'.$cnum}));
 9987:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
 9988: }
 9989: 
 9990: sub store_userdata {
 9991:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
 9992:     my $result;
 9993:     if ($datakey ne '') {
 9994:         if (ref($storehash) eq 'HASH') {
 9995:             if ($udom eq '' || $uname eq '') {
 9996:                 $udom = $env{'user.domain'};
 9997:                 $uname = $env{'user.name'};
 9998:             }
 9999:             my $uhome=&homeserver($uname,$udom);
10000:             if (($uhome eq '') || ($uhome eq 'no_host')) {
10001:                 $result = 'error: no_host';
10002:             } else {
10003:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
10004:                 $storehash->{'host'} = $perlvar{'lonHostID'};
10005: 
10006:                 my $namevalue='';
10007:                 foreach my $key (keys(%{$storehash})) {
10008:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
10009:                 }
10010:                 $namevalue=~s/\&$//;
10011:                 unless ($namespace eq 'courserequests') {
10012:                     $datakey = &escape($datakey);
10013:                 }
10014:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
10015:                                   $namevalue,$uhome);
10016:             }
10017:         } else {
10018:             $result = 'error: data to store was not a hash reference'; 
10019:         }
10020:     } else {
10021:         $result= 'error: invalid requestkey'; 
10022:     }
10023:     return $result;
10024: }
10025: 
10026: # ---------------------------------------------------------- Assign Custom Role
10027: 
10028: sub assigncustomrole {
10029:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
10030:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
10031:                        $end,$start,$deleteflag,$selfenroll,$context);
10032: }
10033: 
10034: # ----------------------------------------------------------------- Revoke Role
10035: 
10036: sub revokerole {
10037:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
10038:     my $now=time;
10039:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
10040: }
10041: 
10042: # ---------------------------------------------------------- Revoke Custom Role
10043: 
10044: sub revokecustomrole {
10045:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
10046:     my $now=time;
10047:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
10048:            $deleteflag,$selfenroll,$context);
10049: }
10050: 
10051: # ------------------------------------------------------------ Disk usage
10052: sub diskusage {
10053:     my ($udom,$uname,$directorypath,$getpropath)=@_;
10054:     $directorypath =~ s/\/$//;
10055:     my $listing=&reply('du2:'.&escape($directorypath).':'
10056:                        .&escape($getpropath).':'.&escape($uname).':'
10057:                        .&escape($udom),homeserver($uname,$udom));
10058:     if ($listing eq 'unknown_cmd') {
10059:         if ($getpropath) {
10060:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
10061:         }
10062:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
10063:     }
10064:     return $listing;
10065: }
10066: 
10067: sub is_locked {
10068:     my ($file_name, $domain, $user, $which) = @_;
10069:     my @check;
10070:     my $is_locked;
10071:     push (@check,$file_name);
10072:     my %locked = &get('file_permissions',\@check,
10073: 		      $env{'user.domain'},$env{'user.name'});
10074:     my ($tmp)=keys(%locked);
10075:     if ($tmp=~/^error:/) { undef(%locked); }
10076:     
10077:     if (ref($locked{$file_name}) eq 'ARRAY') {
10078:         $is_locked = 'false';
10079:         foreach my $entry (@{$locked{$file_name}}) {
10080:            if (ref($entry) eq 'ARRAY') {
10081:                $is_locked = 'true';
10082:                if (ref($which) eq 'ARRAY') {
10083:                    push(@{$which},$entry);
10084:                } else {
10085:                    last;
10086:                }
10087:            }
10088:        }
10089:     } else {
10090:         $is_locked = 'false';
10091:     }
10092:     return $is_locked;
10093: }
10094: 
10095: sub declutter_portfile {
10096:     my ($file) = @_;
10097:     $file =~ s{^(/portfolio/|portfolio/)}{/};
10098:     return $file;
10099: }
10100: 
10101: # ------------------------------------------------------------- Mark as Read Only
10102: 
10103: sub mark_as_readonly {
10104:     my ($domain,$user,$files,$what) = @_;
10105:     my %current_permissions = &dump('file_permissions',$domain,$user);
10106:     my ($tmp)=keys(%current_permissions);
10107:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10108:     foreach my $file (@{$files}) {
10109: 	$file = &declutter_portfile($file);
10110:         push(@{$current_permissions{$file}},$what);
10111:     }
10112:     &put('file_permissions',\%current_permissions,$domain,$user);
10113:     return;
10114: }
10115: 
10116: # ------------------------------------------------------------Save Selected Files
10117: 
10118: sub save_selected_files {
10119:     my ($user, $path, @files) = @_;
10120:     my $filename = $user."savedfiles";
10121:     my @other_files = &files_not_in_path($user, $path);
10122:     open (OUT, '>'.$tmpdir.$filename);
10123:     foreach my $file (@files) {
10124:         print (OUT $env{'form.currentpath'}.$file."\n");
10125:     }
10126:     foreach my $file (@other_files) {
10127:         print (OUT $file."\n");
10128:     }
10129:     close (OUT);
10130:     return 'ok';
10131: }
10132: 
10133: sub clear_selected_files {
10134:     my ($user) = @_;
10135:     my $filename = $user."savedfiles";
10136:     open (OUT, '>'.LONCAPA::tempdir().$filename);
10137:     print (OUT undef);
10138:     close (OUT);
10139:     return ("ok");    
10140: }
10141: 
10142: sub files_in_path {
10143:     my ($user, $path) = @_;
10144:     my $filename = $user."savedfiles";
10145:     my %return_files;
10146:     open (IN, '<'.LONCAPA::tempdir().$filename);
10147:     while (my $line_in = <IN>) {
10148:         chomp ($line_in);
10149:         my @paths_and_file = split (m!/!, $line_in);
10150:         my $file_part = pop (@paths_and_file);
10151:         my $path_part = join ('/', @paths_and_file);
10152:         $path_part.='/';
10153:         my $path_and_file = $path_part.$file_part;
10154:         if ($path_part eq $path) {
10155:             $return_files{$file_part}= 'selected';
10156:         }
10157:     }
10158:     close (IN);
10159:     return (\%return_files);
10160: }
10161: 
10162: # called in portfolio select mode, to show files selected NOT in current directory
10163: sub files_not_in_path {
10164:     my ($user, $path) = @_;
10165:     my $filename = $user."savedfiles";
10166:     my @return_files;
10167:     my $path_part;
10168:     open(IN, '<'.LONCAPA::tempdir().$filename);
10169:     while (my $line = <IN>) {
10170:         #ok, I know it's clunky, but I want it to work
10171:         my @paths_and_file = split(m|/|, $line);
10172:         my $file_part = pop(@paths_and_file);
10173:         chomp($file_part);
10174:         my $path_part = join('/', @paths_and_file);
10175:         $path_part .= '/';
10176:         my $path_and_file = $path_part.$file_part;
10177:         if ($path_part ne $path) {
10178:             push(@return_files, ($path_and_file));
10179:         }
10180:     }
10181:     close(OUT);
10182:     return (@return_files);
10183: }
10184: 
10185: #------------------------------Submitted/Handedback Portfolio Files Versioning
10186:  
10187: sub portfiles_versioning {
10188:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
10189:     my $portfolio_root = '/userfiles/portfolio';
10190:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
10191:     foreach my $file (@{$portfiles}) {
10192:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
10193:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
10194:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
10195:         my $getpropath = 1;
10196:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
10197:                                              $stu_name,$getpropath);
10198:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
10199:         my $new_answer = 
10200:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
10201:         if ($new_answer ne 'problem getting file') {
10202:             push(@{$versioned_portfiles}, $directory.$new_answer);
10203:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
10204:                               [$symb,$env{'request.course.id'},'graded']);
10205:         }
10206:     }
10207: }
10208: 
10209: sub get_next_version {
10210:     my ($answer_name, $answer_ext, $dir_list) = @_;
10211:     my $version;
10212:     if (ref($dir_list) eq 'ARRAY') {
10213:         foreach my $row (@{$dir_list}) {
10214:             my ($file) = split(/\&/,$row,2);
10215:             my ($file_name,$file_version,$file_ext) =
10216:                 &file_name_version_ext($file);
10217:             if (($file_name eq $answer_name) &&
10218:                 ($file_ext eq $answer_ext)) {
10219:                      # gets here if filename and extension match,
10220:                      # regardless of version
10221:                 if ($file_version ne '') {
10222:                     # a versioned file is found  so save it for later
10223:                     if ($file_version > $version) {
10224:                         $version = $file_version;
10225:                     }
10226:                 }
10227:             }
10228:         }
10229:     }
10230:     $version ++;
10231:     return($version);
10232: }
10233: 
10234: sub version_selected_portfile {
10235:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
10236:     my ($answer_name,$answer_ver,$answer_ext) =
10237:         &file_name_version_ext($file_name);
10238:     my $new_answer;
10239:     $env{'form.copy'} =
10240:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
10241:     if($env{'form.copy'} eq '-1') {
10242:         $new_answer = 'problem getting file';
10243:     } else {
10244:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
10245:         my $copy_result = 
10246:             &finishuserfileupload($stu_name,$domain,'copy',
10247:                                   '/portfolio'.$directory.$new_answer);
10248:     }
10249:     undef($env{'form.copy'});
10250:     return ($new_answer);
10251: }
10252: 
10253: sub file_name_version_ext {
10254:     my ($file)=@_;
10255:     my @file_parts = split(/\./, $file);
10256:     my ($name,$version,$ext);
10257:     if (@file_parts > 1) {
10258:         $ext=pop(@file_parts);
10259:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
10260:             $version=pop(@file_parts);
10261:         }
10262:         $name=join('.',@file_parts);
10263:     } else {
10264:         $name=join('.',@file_parts);
10265:     }
10266:     return($name,$version,$ext);
10267: }
10268: 
10269: #----------------------------------------------Get portfolio file permissions
10270: 
10271: sub get_portfile_permissions {
10272:     my ($domain,$user) = @_;
10273:     my %current_permissions = &dump('file_permissions',$domain,$user);
10274:     my ($tmp)=keys(%current_permissions);
10275:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10276:     return \%current_permissions;
10277: }
10278: 
10279: #---------------------------------------------Get portfolio file access controls
10280: 
10281: sub get_access_controls {
10282:     my ($current_permissions,$group,$file) = @_;
10283:     my %access;
10284:     my $real_file = $file;
10285:     $file =~ s/\.meta$//;
10286:     if (defined($file)) {
10287:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
10288:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
10289:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
10290:             }
10291:         }
10292:     } else {
10293:         foreach my $key (keys(%{$current_permissions})) {
10294:             if ($key =~ /\0accesscontrol$/) {
10295:                 if (defined($group)) {
10296:                     if ($key !~ m-^\Q$group\E/-) {
10297:                         next;
10298:                     }
10299:                 }
10300:                 my ($fullpath) = split(/\0/,$key);
10301:                 if (ref($$current_permissions{$key}) eq 'HASH') {
10302:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
10303:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
10304:                     }
10305:                 }
10306:             }
10307:         }
10308:     }
10309:     return %access;
10310: }
10311: 
10312: sub modify_access_controls {
10313:     my ($file_name,$changes,$domain,$user)=@_;
10314:     my ($outcome,$deloutcome);
10315:     my %store_permissions;
10316:     my %new_values;
10317:     my %new_control;
10318:     my %translation;
10319:     my @deletions = ();
10320:     my $now = time;
10321:     if (exists($$changes{'activate'})) {
10322:         if (ref($$changes{'activate'}) eq 'HASH') {
10323:             my @newitems = sort(keys(%{$$changes{'activate'}}));
10324:             my $numnew = scalar(@newitems);
10325:             for (my $i=0; $i<$numnew; $i++) {
10326:                 my $newkey = $newitems[$i];
10327:                 my $newid = &Apache::loncommon::get_cgi_id();
10328:                 if ($newkey =~ /^\d+:/) { 
10329:                     $newkey =~ s/^(\d+)/$newid/;
10330:                     $translation{$1} = $newid;
10331:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
10332:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
10333:                     $translation{$1} = $newid;
10334:                 }
10335:                 $new_values{$file_name."\0".$newkey} = 
10336:                                           $$changes{'activate'}{$newitems[$i]};
10337:                 $new_control{$newkey} = $now;
10338:             }
10339:         }
10340:     }
10341:     my %todelete;
10342:     my %changed_items;
10343:     foreach my $action ('delete','update') {
10344:         if (exists($$changes{$action})) {
10345:             if (ref($$changes{$action}) eq 'HASH') {
10346:                 foreach my $key (keys(%{$$changes{$action}})) {
10347:                     my ($itemnum) = ($key =~ /^([^:]+):/);
10348:                     if ($action eq 'delete') { 
10349:                         $todelete{$itemnum} = 1;
10350:                     } else {
10351:                         $changed_items{$itemnum} = $key;
10352:                     }
10353:                 }
10354:             }
10355:         }
10356:     }
10357:     # get lock on access controls for file.
10358:     my $lockhash = {
10359:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
10360:                                                        ':'.$env{'user.domain'},
10361:                    }; 
10362:     my $tries = 0;
10363:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10364:    
10365:     while (($gotlock ne 'ok') && $tries < 10) {
10366:         $tries ++;
10367:         sleep(0.1);
10368:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10369:     }
10370:     if ($gotlock eq 'ok') {
10371:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
10372:         my ($tmp)=keys(%curr_permissions);
10373:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
10374:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
10375:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
10376:             if (ref($curr_controls) eq 'HASH') {
10377:                 foreach my $control_item (keys(%{$curr_controls})) {
10378:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
10379:                     if (defined($todelete{$itemnum})) {
10380:                         push(@deletions,$file_name."\0".$control_item);
10381:                     } else {
10382:                         if (defined($changed_items{$itemnum})) {
10383:                             $new_control{$changed_items{$itemnum}} = $now;
10384:                             push(@deletions,$file_name."\0".$control_item);
10385:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
10386:                         } else {
10387:                             $new_control{$control_item} = $$curr_controls{$control_item};
10388:                         }
10389:                     }
10390:                 }
10391:             }
10392:         }
10393:         my ($group);
10394:         if (&is_course($domain,$user)) {
10395:             ($group,my $file) = split(/\//,$file_name,2);
10396:         }
10397:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
10398:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
10399:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
10400:         #  remove lock
10401:         my @del_lock = ($file_name."\0".'locked_access_records');
10402:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
10403:         my $sqlresult =
10404:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
10405:                                     $group);
10406:     } else {
10407:         $outcome = "error: could not obtain lockfile\n";  
10408:     }
10409:     return ($outcome,$deloutcome,\%new_values,\%translation);
10410: }
10411: 
10412: sub make_public_indefinitely {
10413:     my (@requrl) = @_;
10414:     return &automated_portfile_access('public',\@requrl);
10415: }
10416: 
10417: sub automated_portfile_access {
10418:     my ($accesstype,$addsref,$delsref,$info) = @_;
10419:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
10420:         return 'invalid';
10421:     }
10422:     my %urls;
10423:     if (ref($addsref) eq 'ARRAY') {
10424:         foreach my $requrl (@{$addsref}) {
10425:             if (&is_portfolio_url($requrl)) {
10426:                 unless (exists($urls{$requrl})) {
10427:                     $urls{$requrl} = 'add';
10428:                 }
10429:             }
10430:         }
10431:     }
10432:     if (ref($delsref) eq 'ARRAY') {
10433:         foreach my $requrl (@{$delsref}) { 
10434:             if (&is_portfolio_url($requrl)) {
10435:                 unless (exists($urls{$requrl})) {
10436:                     $urls{$requrl} = 'delete'; 
10437:                 }
10438:             }
10439:         }
10440:     }
10441:     unless (keys(%urls)) {
10442:         return 'invalid';
10443:     }
10444:     my $ip;
10445:     if ($accesstype eq 'ip') {
10446:         if (ref($info) eq 'HASH') {
10447:             if ($info->{'ip'} ne '') {
10448:                 $ip = $info->{'ip'};
10449:             }
10450:         }
10451:         if ($ip eq '') {
10452:             return 'invalid';
10453:         }
10454:     }
10455:     my $errors;
10456:     my $now = time;
10457:     my %current_perms;
10458:     foreach my $requrl (sort(keys(%urls))) {
10459:         my $action;
10460:         if ($urls{$requrl} eq 'add') {
10461:             $action = 'activate';
10462:         } else {
10463:             $action = 'none';
10464:         }
10465:         my $aclnum = 0;
10466:         my (undef,$udom,$unum,$file_name,$group) =
10467:             &parse_portfolio_url($requrl);
10468:         unless (exists($current_perms{$unum.':'.$udom})) {
10469:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
10470:         }
10471:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
10472:                                                    $group,$file_name);
10473:         foreach my $key (keys(%{$access_controls{$file_name}})) {
10474:             my ($num,$scope,$end,$start) = 
10475:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
10476:             if ($scope eq $accesstype) {
10477:                 if (($start <= $now) && ($end == 0)) {
10478:                     if ($accesstype eq 'ip') {
10479:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
10480:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
10481:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
10482:                                     if ($urls{$requrl} eq 'add') {
10483:                                         $action = 'none';
10484:                                         last;
10485:                                     } else {
10486:                                         $action = 'delete';
10487:                                         $aclnum = $num;
10488:                                         last;
10489:                                     }
10490:                                 }
10491:                             }
10492:                         }
10493:                     } elsif ($accesstype eq 'public') {
10494:                         if ($urls{$requrl} eq 'add') {
10495:                             $action = 'none';
10496:                             last;
10497:                         } else {
10498:                             $action = 'delete';
10499:                             $aclnum = $num;
10500:                             last;
10501:                         }
10502:                     }
10503:                 } elsif ($accesstype eq 'public') {
10504:                     $action = 'update';
10505:                     $aclnum = $num;
10506:                     last;
10507:                 }
10508:             }
10509:         }
10510:         if ($action eq 'none') {
10511:             next;
10512:         } else {
10513:             my %changes;
10514:             my $newend = 0;
10515:             my $newstart = $now;
10516:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
10517:             $changes{$action}{$newkey} = {
10518:                 type => $accesstype,
10519:                 time => {
10520:                     start => $newstart,
10521:                     end   => $newend,
10522:                 },
10523:             };
10524:             if ($accesstype eq 'ip') {
10525:                 $changes{$action}{$newkey}{'ip'} = [$ip];
10526:             }
10527:             my ($outcome,$deloutcome,$new_values,$translation) =
10528:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
10529:             unless ($outcome eq 'ok') {
10530:                 $errors .= $outcome.' ';
10531:             }
10532:         }
10533:     }
10534:     if ($errors) {
10535:         $errors =~ s/\s$//;
10536:         return $errors;
10537:     } else {
10538:         return 'ok';
10539:     }
10540: }
10541: 
10542: #------------------------------------------------------Get Marked as Read Only
10543: 
10544: sub get_marked_as_readonly {
10545:     my ($domain,$user,$what,$group) = @_;
10546:     my $current_permissions = &get_portfile_permissions($domain,$user);
10547:     my @readonly_files;
10548:     my $cmp1=$what;
10549:     if (ref($what)) { $cmp1=join('',@{$what}) };
10550:     while (my ($file_name,$value) = each(%{$current_permissions})) {
10551:         if (defined($group)) {
10552:             if ($file_name !~ m-^\Q$group\E/-) {
10553:                 next;
10554:             }
10555:         }
10556:         if (ref($value) eq "ARRAY"){
10557:             foreach my $stored_what (@{$value}) {
10558:                 my $cmp2=$stored_what;
10559:                 if (ref($stored_what) eq 'ARRAY') {
10560:                     $cmp2=join('',@{$stored_what});
10561:                 }
10562:                 if ($cmp1 eq $cmp2) {
10563:                     push(@readonly_files, $file_name);
10564:                     last;
10565:                 } elsif (!defined($what)) {
10566:                     push(@readonly_files, $file_name);
10567:                     last;
10568:                 }
10569:             }
10570:         }
10571:     }
10572:     return @readonly_files;
10573: }
10574: #-----------------------------------------------------------Get Marked as Read Only Hash
10575: 
10576: sub get_marked_as_readonly_hash {
10577:     my ($current_permissions,$group,$what) = @_;
10578:     my %readonly_files;
10579:     while (my ($file_name,$value) = each(%{$current_permissions})) {
10580:         if (defined($group)) {
10581:             if ($file_name !~ m-^\Q$group\E/-) {
10582:                 next;
10583:             }
10584:         }
10585:         if (ref($value) eq "ARRAY"){
10586:             foreach my $stored_what (@{$value}) {
10587:                 if (ref($stored_what) eq 'ARRAY') {
10588:                     foreach my $lock_descriptor(@{$stored_what}) {
10589:                         if ($lock_descriptor eq 'graded') {
10590:                             $readonly_files{$file_name} = 'graded';
10591:                         } elsif ($lock_descriptor eq 'handback') {
10592:                             $readonly_files{$file_name} = 'handback';
10593:                         } else {
10594:                             if (!exists($readonly_files{$file_name})) {
10595:                                 $readonly_files{$file_name} = 'locked';
10596:                             }
10597:                         }
10598:                     }
10599:                 } 
10600:             }
10601:         } 
10602:     }
10603:     return %readonly_files;
10604: }
10605: # ------------------------------------------------------------ Unmark as Read Only
10606: 
10607: sub unmark_as_readonly {
10608:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
10609:     # for portfolio submissions, $what contains [$symb,$crsid] 
10610:     my ($domain,$user,$what,$file_name,$group) = @_;
10611:     $file_name = &declutter_portfile($file_name);
10612:     my $symb_crs = $what;
10613:     if (ref($what)) { $symb_crs=join('',@$what); }
10614:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
10615:     my ($tmp)=keys(%current_permissions);
10616:     if ($tmp=~/^error:/) { undef(%current_permissions); }
10617:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
10618:     foreach my $file (@readonly_files) {
10619: 	my $clean_file = &declutter_portfile($file);
10620: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
10621: 	my $current_locks = $current_permissions{$file};
10622:         my @new_locks;
10623:         my @del_keys;
10624:         if (ref($current_locks) eq "ARRAY"){
10625:             foreach my $locker (@{$current_locks}) {
10626:                 my $compare=$locker;
10627:                 if (ref($locker) eq 'ARRAY') {
10628:                     $compare=join('',@{$locker});
10629:                     if ($compare ne $symb_crs) {
10630:                         push(@new_locks, $locker);
10631:                     }
10632:                 }
10633:             }
10634:             if (scalar(@new_locks) > 0) {
10635:                 $current_permissions{$file} = \@new_locks;
10636:             } else {
10637:                 push(@del_keys, $file);
10638:                 &del('file_permissions',\@del_keys, $domain, $user);
10639:                 delete($current_permissions{$file});
10640:             }
10641:         }
10642:     }
10643:     &put('file_permissions',\%current_permissions,$domain,$user);
10644:     return;
10645: }
10646: 
10647: # ------------------------------------------------------------ Directory lister
10648: 
10649: sub dirlist {
10650:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
10651:     $uri=~s/^\///;
10652:     $uri=~s/\/$//;
10653:     my ($udom, $uname);
10654:     if ($getuserdir) {
10655:         $udom = $userdomain;
10656:         $uname = $username;
10657:     } else {
10658:         (undef,$udom,$uname)=split(/\//,$uri);
10659:         if(defined($userdomain)) {
10660:             $udom = $userdomain;
10661:         }
10662:         if(defined($username)) {
10663:             $uname = $username;
10664:         }
10665:     }
10666:     my ($dirRoot,$listing,@listing_results);
10667: 
10668:     $dirRoot = $perlvar{'lonDocRoot'};
10669:     if (defined($getpropath)) {
10670:         $dirRoot = &propath($udom,$uname);
10671:         $dirRoot =~ s/\/$//;
10672:     } elsif (defined($getuserdir)) {
10673:         my $subdir=$uname.'__';
10674:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
10675:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
10676:                    ."/$udom/$subdir/$uname";
10677:     } elsif (defined($alternateRoot)) {
10678:         $dirRoot = $alternateRoot;
10679:     }
10680: 
10681:     if($udom) {
10682:         if($uname) {
10683:             my $uhome = &homeserver($uname,$udom);
10684:             if ($uhome eq 'no_host') {
10685:                 return ([],'no_host');
10686:             }
10687:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
10688:                               .$getuserdir.':'.&escape($dirRoot)
10689:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
10690:             if ($listing eq 'unknown_cmd') {
10691:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
10692:             } else {
10693:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
10694:             }
10695:             if ($listing eq 'unknown_cmd') {
10696:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
10697:                 @listing_results = split(/:/,$listing);
10698:             } else {
10699:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
10700:             }
10701:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
10702:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
10703:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10704:                 return ([],$listing);
10705:             } else {
10706:                 return (\@listing_results);
10707:             }
10708:         } elsif(!$alternateRoot) {
10709:             my (%allusers,%listerror);
10710: 	    my %servers = &get_servers($udom,'library');
10711:  	    foreach my $tryserver (keys(%servers)) {
10712:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
10713:                                   &escape($udom),$tryserver);
10714:                 if ($listing eq 'unknown_cmd') {
10715: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
10716: 				      $udom, $tryserver);
10717:                 } else {
10718:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
10719:                 }
10720: 		if ($listing eq 'unknown_cmd') {
10721: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
10722: 				      $udom, $tryserver);
10723: 		    @listing_results = split(/:/,$listing);
10724: 		} else {
10725: 		    @listing_results =
10726: 			map { &unescape($_); } split(/:/,$listing);
10727: 		}
10728:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
10729:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
10730:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10731:                     $listerror{$tryserver} = $listing;
10732:                 } else {
10733: 		    foreach my $line (@listing_results) {
10734: 			my ($entry) = split(/&/,$line,2);
10735: 			$allusers{$entry} = 1;
10736: 		    }
10737: 		}
10738:             }
10739:             my @alluserslist=();
10740:             foreach my $user (sort(keys(%allusers))) {
10741:                 push(@alluserslist,$user.'&user');
10742:             }
10743: 
10744:             if (!%listerror) {
10745:                 # no errors
10746:                 return (\@alluserslist);
10747:             } elsif (scalar(keys(%servers)) == 1) {
10748:                 # one library server, one error 
10749:                 my ($key) = keys(%listerror);
10750:                 return (\@alluserslist, $listerror{$key});
10751:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
10752:                 # con_lost indicates that we might miss data from at least one
10753:                 # library server
10754:                 return (\@alluserslist, 'con_lost');
10755:             } else {
10756:                 # multiple library servers and no con_lost -> data should be
10757:                 # complete. 
10758:                 return (\@alluserslist);
10759:             }
10760: 
10761:         } else {
10762:             return ([],'missing username');
10763:         }
10764:     } elsif(!defined($getpropath)) {
10765:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
10766:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
10767:         return (\@all_domains);
10768:     } else {
10769:         return ([],'missing domain');
10770:     }
10771: }
10772: 
10773: # --------------------------------------------- GetFileTimestamp
10774: # This function utilizes dirlist and returns the date stamp for
10775: # when it was last modified.  It will also return an error of -1
10776: # if an error occurs
10777: 
10778: sub GetFileTimestamp {
10779:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
10780:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
10781:     $studentName   = &LONCAPA::clean_username($studentName);
10782:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
10783:                                     undef,$getuserdir);
10784:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10785:         return -1;
10786:     }
10787:     if (ref($fileref) eq 'ARRAY') {
10788:         my @stats = split('&',$fileref->[0]);
10789:         # @stats contains first the filename, then the stat output
10790:         return $stats[10]; # so this is 10 instead of 9.
10791:     } else {
10792:         return -1;
10793:     }
10794: }
10795: 
10796: sub stat_file {
10797:     my ($uri) = @_;
10798:     $uri = &clutter_with_no_wrapper($uri);
10799: 
10800:     my ($udom,$uname,$file);
10801:     if ($uri =~ m-^/(uploaded|editupload)/-) {
10802: 	($udom,$uname,$file) =
10803: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
10804: 	$file = 'userfiles/'.$file;
10805:     }
10806:     if ($uri =~ m-^/res/-) {
10807: 	($udom,$uname) = 
10808: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
10809: 	$file = $uri;
10810:     }
10811: 
10812:     if (!$udom || !$uname || !$file) {
10813: 	# unable to handle the uri
10814: 	return ();
10815:     }
10816:     my $getpropath;
10817:     if ($file =~ /^userfiles\//) {
10818:         $getpropath = 1;
10819:     }
10820:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
10821:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10822:         return ();
10823:     } else {
10824:         if (ref($listref) eq 'ARRAY') {
10825:             my @stats = split('&',$listref->[0]);
10826: 	    shift(@stats); #filename is first
10827: 	    return @stats;
10828:         }
10829:     }
10830:     return ();
10831: }
10832: 
10833: # --------------------------------------------------------- recursedirs
10834: # Recursive function to traverse either a specific user's Authoring Space
10835: # or corresponding Published Resource Space, and populate the hash ref:
10836: # $dirhashref with URLs of all directories, and if $filehashref hash
10837: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
10838: # or .rights files in resource space, and .meta, .save, .log, and .bak
10839: # files in Authoring Space.
10840: #
10841: # Inputs:
10842: #
10843: # $is_home - true if current server is home server for user's space
10844: # $context - either: priv, or res respectively for Authoring or Resource Space.
10845: # $docroot - Document root (i.e., /home/httpd/html
10846: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
10847: # $relpath - Current path (relative to top level).
10848: # $dirhashref - reference to hash to populate with URLs of directories (Required)
10849: # $filehashref - reference to hash to populate with URLs of files (Optional)
10850: #
10851: # Returns: nothing
10852: #
10853: # Side Effects: populates $dirhashref, and $filehashref (if provided).
10854: #
10855: # Currently used by interface/londocs.pm to create linked select boxes for
10856: # directory and filename to import a Course "Author" resource into a course, and
10857: # also to create linked select boxes for Authoring Space and Directory to choose
10858: # save location for creation of a new "standard" problem from the Course Editor.
10859: #
10860: 
10861: sub recursedirs {
10862:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
10863:     return unless (ref($dirhashref) eq 'HASH');
10864:     my $currpath = $docroot.$toppath;
10865:     if ($relpath) {
10866:         $currpath .= "/$relpath";
10867:     }
10868:     my $savefile;
10869:     if (ref($filehashref)) {
10870:         $savefile = 1;
10871:     }
10872:     if ($is_home) {
10873:         if (opendir(my $dirh,$currpath)) {
10874:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
10875:                 next if ($item eq '');
10876:                 if (-d "$currpath/$item") {
10877:                     my $newpath;
10878:                     if ($relpath) {
10879:                         $newpath = "$relpath/$item";
10880:                     } else {
10881:                         $newpath = $item;
10882:                     }
10883:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
10884:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
10885:                 } elsif ($savefile) {
10886:                     if ($context eq 'priv') {
10887:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
10888:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
10889:                         }
10890:                     } else {
10891:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
10892:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
10893:                         }
10894:                     }
10895:                 }
10896:             }
10897:             closedir($dirh);
10898:         }
10899:     } else {
10900:         my ($dirlistref,$listerror) =
10901:             &dirlist($toppath.$relpath);
10902:         my @dir_lines;
10903:         my $dirptr=16384;
10904:         if (ref($dirlistref) eq 'ARRAY') {
10905:             foreach my $dir_line (sort
10906:                               {
10907:                                   my ($afile)=split('&',$a,2);
10908:                                   my ($bfile)=split('&',$b,2);
10909:                                   return (lc($afile) cmp lc($bfile));
10910:                               } (@{$dirlistref})) {
10911:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
10912:                     split(/\&/,$dir_line,16);
10913:                 $item =~ s/\s+$//;
10914:                 next if (($item =~ /^\.\.?$/) || ($obs));
10915:                 if ($dirptr&$testdir) {
10916:                     my $newpath;
10917:                     if ($relpath) {
10918:                         $newpath = "$relpath/$item";
10919:                     } else {
10920:                         $relpath = '/';
10921:                         $newpath = $item;
10922:                     }
10923:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
10924:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
10925:                 } elsif ($savefile) {
10926:                     if ($context eq 'priv') {
10927:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
10928:                             $filehashref->{$relpath}{$item} = 1;
10929:                         }
10930:                     } else {
10931:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
10932:                             $filehashref->{$relpath}{$item} = 1;
10933:                         }
10934:                     }
10935:                 }
10936:             }
10937:         }
10938:     }
10939:     return;
10940: }
10941: 
10942: # -------------------------------------------------------- Value of a Condition
10943: 
10944: # gets the value of a specific preevaluated condition
10945: #    stored in the string  $env{user.state.<cid>}
10946: # or looks up a condition reference in the bighash and if if hasn't
10947: # already been evaluated recurses into docondval to get the value of
10948: # the condition, then memoizing it to 
10949: #   $env{user.state.<cid>.<condition>}
10950: sub directcondval {
10951:     my $number=shift;
10952:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
10953: 	&Apache::lonuserstate::evalstate();
10954:     }
10955:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
10956: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
10957:     } elsif ($number =~ /^_/) {
10958: 	my $sub_condition;
10959: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10960: 		&GDBM_READER(),0640)) {
10961: 	    $sub_condition=$bighash{'conditions'.$number};
10962: 	    untie(%bighash);
10963: 	}
10964: 	my $value = &docondval($sub_condition);
10965: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
10966: 	return $value;
10967:     }
10968:     if ($env{'user.state.'.$env{'request.course.id'}}) {
10969:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
10970:     } else {
10971:        return 2;
10972:     }
10973: }
10974: 
10975: # get the collection of conditions for this resource
10976: sub condval {
10977:     my $condidx=shift;
10978:     my $allpathcond='';
10979:     foreach my $cond (split(/\|/,$condidx)) {
10980: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
10981: 	    $allpathcond.=
10982: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
10983: 	}
10984:     }
10985:     $allpathcond=~s/\|$//;
10986:     return &docondval($allpathcond);
10987: }
10988: 
10989: #evaluates an expression of conditions
10990: sub docondval {
10991:     my ($allpathcond) = @_;
10992:     my $result=0;
10993:     if ($env{'request.course.id'}
10994: 	&& defined($allpathcond)) {
10995: 	my $operand='|';
10996: 	my @stack;
10997: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
10998: 	    if ($chunk eq '(') {
10999: 		push @stack,($operand,$result);
11000: 	    } elsif ($chunk eq ')') {
11001: 		my $before=pop @stack;
11002: 		if (pop @stack eq '&') {
11003: 		    $result=$result>$before?$before:$result;
11004: 		} else {
11005: 		    $result=$result>$before?$result:$before;
11006: 		}
11007: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
11008: 		$operand=$chunk;
11009: 	    } else {
11010: 		my $new=directcondval($chunk);
11011: 		if ($operand eq '&') {
11012: 		    $result=$result>$new?$new:$result;
11013: 		} else {
11014: 		    $result=$result>$new?$result:$new;
11015: 		}
11016: 	    }
11017: 	}
11018:     }
11019:     return $result;
11020: }
11021: 
11022: # ---------------------------------------------------- Devalidate courseresdata
11023: 
11024: sub devalidatecourseresdata {
11025:     my ($coursenum,$coursedomain)=@_;
11026:     my $hashid=$coursenum.':'.$coursedomain;
11027:     &devalidate_cache_new('courseres',$hashid);
11028: }
11029: 
11030: 
11031: # --------------------------------------------------- Course Resourcedata Query
11032: #
11033: #  Parameters:
11034: #      $coursenum    - Number of the course.
11035: #      $coursedomain - Domain at which the course was created.
11036: #  Returns:
11037: #     A hash of the course parameters along (I think) with timestamps
11038: #     and version info.
11039: 
11040: sub get_courseresdata {
11041:     my ($coursenum,$coursedomain)=@_;
11042:     my $coursehom=&homeserver($coursenum,$coursedomain);
11043:     my $hashid=$coursenum.':'.$coursedomain;
11044:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
11045:     my %dumpreply;
11046:     unless (defined($cached)) {
11047: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
11048: 	$result=\%dumpreply;
11049: 	my ($tmp) = keys(%dumpreply);
11050: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
11051: 	    &do_cache_new('courseres',$hashid,$result,600);
11052: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
11053: 	    return $tmp;
11054: 	} elsif ($tmp =~ /^(error)/) {
11055: 	    $result=undef;
11056: 	    &do_cache_new('courseres',$hashid,$result,600);
11057: 	}
11058:     }
11059:     return $result;
11060: }
11061: 
11062: sub devalidateuserresdata {
11063:     my ($uname,$udom)=@_;
11064:     my $hashid="$udom:$uname";
11065:     &devalidate_cache_new('userres',$hashid);
11066: }
11067: 
11068: sub get_userresdata {
11069:     my ($uname,$udom)=@_;
11070:     #most student don\'t have any data set, check if there is some data
11071:     if (&EXT_cache_status($udom,$uname)) { return undef; }
11072: 
11073:     my $hashid="$udom:$uname";
11074:     my ($result,$cached)=&is_cached_new('userres',$hashid);
11075:     if (!defined($cached)) {
11076: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
11077: 	$result=\%resourcedata;
11078: 	&do_cache_new('userres',$hashid,$result,600);
11079:     }
11080:     my ($tmp)=keys(%$result);
11081:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
11082: 	return $result;
11083:     }
11084:     #error 2 occurs when the .db doesn't exist
11085:     if ($tmp!~/error: 2 /) {
11086:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
11087: 	    &logthis("<font color=\"blue\">WARNING:".
11088: 		     " Trying to get resource data for ".
11089: 		     $uname." at ".$udom.": ".
11090: 		     $tmp."</font>");
11091:         }
11092:     } elsif ($tmp=~/error: 2 /) {
11093: 	#&EXT_cache_set($udom,$uname);
11094: 	&do_cache_new('userres',$hashid,undef,600);
11095: 	undef($tmp); # not really an error so don't send it back
11096:     }
11097:     return $tmp;
11098: }
11099: #----------------------------------------------- resdata - return resource data
11100: #  Purpose:
11101: #    Return resource data for either users or for a course.
11102: #  Parameters:
11103: #     $name      - Course/user name.
11104: #     $domain    - Name of the domain the user/course is registered on.
11105: #     $type      - Type of thing $name is (must be 'course' or 'user')
11106: #     $mapp      - decluttered URL of enclosing map  
11107: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
11108: #     $recurseup - Ref to array of map URLs, starting with map containing
11109: #                  $mapp up through hierarchy of nested maps to top level map.  
11110: #     $courseid  - CourseID (first part of param identifier).
11111: #     $modifier  - Middle part of param identifier.
11112: #     $what      - Last part of param identifier.
11113: #     @which     - Array of names of resources desired.
11114: #  Returns:
11115: #     The value of the first reasource in @which that is found in the
11116: #     resource hash.
11117: #  Exceptional Conditions:
11118: #     If the $type passed in is not valid (not the string 'course' or 
11119: #     'user', an undefined  reference is returned.
11120: #     If none of the resources are found, an undef is returned
11121: sub resdata {
11122:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
11123:         $modifier,$what,@which)=@_;
11124:     my $result;
11125:     if ($type eq 'course') {
11126: 	$result=&get_courseresdata($name,$domain);
11127:     } elsif ($type eq 'user') {
11128: 	$result=&get_userresdata($name,$domain);
11129:     }
11130:     if (!ref($result)) { return $result; }    
11131:     foreach my $item (@which) {
11132:         if ($item->[1] eq 'course') {
11133:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
11134:                 unless ($$recursed) {
11135:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
11136:                     $$recursed = 1;
11137:                 }
11138:                 foreach my $item (@${recurseup}) {
11139:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
11140:                     last if (defined($result->{$norecursechk}));
11141:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
11142:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
11143:                 }
11144:             }
11145:         }
11146:         if (defined($result->{$item->[0]})) {
11147: 	    return [$result->{$item->[0]},$item->[1]];
11148: 	}
11149:     }
11150:     return undef;
11151: }
11152: 
11153: sub get_domain_ltitools {
11154:     my ($cdom) = @_;
11155:     my %ltitools;
11156:     my ($result,$cached)=&is_cached_new('ltitools',$cdom);
11157:     if (defined($cached)) {
11158:         if (ref($result) eq 'HASH') {
11159:             %ltitools = %{$result};
11160:         }
11161:     } else {
11162:         my %domconfig = &get_dom('configuration',['ltitools'],$cdom);
11163:         if (ref($domconfig{'ltitools'}) eq 'HASH') {
11164:             %ltitools = %{$domconfig{'ltitools'}};
11165:             my %encdomconfig = &get_dom('encconfig',['ltitools'],$cdom);
11166:             if (ref($encdomconfig{'ltitools'}) eq 'HASH') {
11167:                 foreach my $id (keys(%ltitools)) {
11168:                     if (ref($encdomconfig{'ltitools'}{$id}) eq 'HASH') {
11169:                         foreach my $item ('key','secret') {
11170:                             $ltitools{$id}{$item} = $encdomconfig{'ltitools'}{$id}{$item};
11171:                         }
11172:                     }
11173:                 }
11174:             }
11175:         }
11176:         my $cachetime = 24*60*60;
11177:         &do_cache_new('ltitools',$cdom,\%ltitools,$cachetime);
11178:     }
11179:     return %ltitools;
11180: }
11181: 
11182: sub get_numsuppfiles {
11183:     my ($cnum,$cdom,$ignorecache)=@_;
11184:     my $hashid=$cnum.':'.$cdom;
11185:     my ($suppcount,$cached);
11186:     unless ($ignorecache) {
11187:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
11188:     }
11189:     unless (defined($cached)) {
11190:         my $chome=&homeserver($cnum,$cdom);
11191:         unless ($chome eq 'no_host') {
11192:             ($suppcount,my $errors) = (0,0);
11193:             my $suppmap = 'supplemental.sequence';
11194:             ($suppcount,$errors) = 
11195:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
11196:         }
11197:         &do_cache_new('suppcount',$hashid,$suppcount,600);
11198:     }
11199:     return $suppcount;
11200: }
11201: 
11202: #
11203: # EXT resource caching routines
11204: #
11205: 
11206: {
11207: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
11208: #
11209: # The course for which we cache
11210: my $cachedmapkey='';
11211: # The cached recursive maps for this course
11212: my %cachedmaps=();
11213: # When this was last done
11214: my $cachedmaptime='';
11215: 
11216: sub clear_EXT_cache_status {
11217:     &delenv('cache.EXT.');
11218: }
11219: 
11220: sub EXT_cache_status {
11221:     my ($target_domain,$target_user) = @_;
11222:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11223:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
11224:         # We know already the user has no data
11225:         return 1;
11226:     } else {
11227:         return 0;
11228:     }
11229: }
11230: 
11231: sub EXT_cache_set {
11232:     my ($target_domain,$target_user) = @_;
11233:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11234:     #&appenv({$cachename => time});
11235: }
11236: 
11237: # --------------------------------------------------------- Value of a Variable
11238: sub EXT {
11239: 
11240:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
11241:     unless ($varname) { return ''; }
11242:     #get real user name/domain, courseid and symb
11243:     my $courseid;
11244:     my $publicuser;
11245:     if ($symbparm) {
11246: 	$symbparm=&get_symb_from_alias($symbparm);
11247:     }
11248:     if (!($uname && $udom)) {
11249:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
11250:       if (!$symbparm) {	$symbparm=$cursymb; }
11251:     } else {
11252: 	$courseid=$env{'request.course.id'};
11253:     }
11254:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
11255:     my $rest;
11256:     if (defined($therest[0])) {
11257:        $rest=join('.',@therest);
11258:     } else {
11259:        $rest='';
11260:     }
11261: 
11262:     my $qualifierrest=$qualifier;
11263:     if ($rest) { $qualifierrest.='.'.$rest; }
11264:     my $spacequalifierrest=$space;
11265:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
11266:     if ($realm eq 'user') {
11267: # --------------------------------------------------------------- user.resource
11268: 	if ($space eq 'resource') {
11269: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
11270: 		  || defined($Apache::lonhomework::parsing_a_task))
11271: 		 &&
11272: 		 ($symbparm eq &symbread()) ) {	
11273: 		# if we are in the middle of processing the resource the
11274: 		# get the value we are planning on committing
11275:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
11276:                     return $Apache::lonhomework::results{$qualifierrest};
11277:                 } else {
11278:                     return $Apache::lonhomework::history{$qualifierrest};
11279:                 }
11280: 	    } else {
11281: 		my %restored;
11282: 		if ($publicuser || $env{'request.state'} eq 'construct') {
11283: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
11284: 		} else {
11285: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
11286: 		}
11287: 		return $restored{$qualifierrest};
11288: 	    }
11289: # ----------------------------------------------------------------- user.access
11290:         } elsif ($space eq 'access') {
11291: 	    # FIXME - not supporting calls for a specific user
11292:             return &allowed($qualifier,$rest);
11293: # ------------------------------------------ user.preferences, user.environment
11294:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
11295: 	    if (($uname eq $env{'user.name'}) &&
11296: 		($udom eq $env{'user.domain'})) {
11297: 		return $env{join('.',('environment',$qualifierrest))};
11298: 	    } else {
11299: 		my %returnhash;
11300: 		if (!$publicuser) {
11301: 		    %returnhash=&userenvironment($udom,$uname,
11302: 						 $qualifierrest);
11303: 		}
11304: 		return $returnhash{$qualifierrest};
11305: 	    }
11306: # ----------------------------------------------------------------- user.course
11307:         } elsif ($space eq 'course') {
11308: 	    # FIXME - not supporting calls for a specific user
11309:             return $env{join('.',('request.course',$qualifier))};
11310: # ------------------------------------------------------------------- user.role
11311:         } elsif ($space eq 'role') {
11312: 	    # FIXME - not supporting calls for a specific user
11313:             my ($role,$where)=split(/\./,$env{'request.role'});
11314:             if ($qualifier eq 'value') {
11315: 		return $role;
11316:             } elsif ($qualifier eq 'extent') {
11317:                 return $where;
11318:             }
11319: # ----------------------------------------------------------------- user.domain
11320:         } elsif ($space eq 'domain') {
11321:             return $udom;
11322: # ------------------------------------------------------------------- user.name
11323:         } elsif ($space eq 'name') {
11324:             return $uname;
11325: # ---------------------------------------------------- Any other user namespace
11326:         } else {
11327: 	    my %reply;
11328: 	    if (!$publicuser) {
11329: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
11330: 	    }
11331: 	    return $reply{$qualifierrest};
11332:         }
11333:     } elsif ($realm eq 'query') {
11334: # ---------------------------------------------- pull stuff out of query string
11335:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
11336: 						[$spacequalifierrest]);
11337: 	return $env{'form.'.$spacequalifierrest}; 
11338:    } elsif ($realm eq 'request') {
11339: # ------------------------------------------------------------- request.browser
11340:         if ($space eq 'browser') {
11341:             return $env{'browser.'.$qualifier};
11342: # ------------------------------------------------------------ request.filename
11343:         } else {
11344:             return $env{'request.'.$spacequalifierrest};
11345:         }
11346:     } elsif ($realm eq 'course') {
11347: # ---------------------------------------------------------- course.description
11348:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
11349:     } elsif ($realm eq 'resource') {
11350: 
11351: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
11352: 	    if (!$symbparm) { $symbparm=&symbread(); }
11353: 	}
11354: 
11355:         if ($qualifier eq '') {
11356: 	    if ($space eq 'title') {
11357: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
11358: 	        return &gettitle($symbparm);
11359: 	    }
11360: 	
11361: 	    if ($space eq 'map') {
11362: 	        my ($map) = &decode_symb($symbparm);
11363: 	        return &symbread($map);
11364: 	    }
11365:             if ($space eq 'maptitle') {
11366:                 my ($map) = &decode_symb($symbparm);
11367:                 return &gettitle($map);
11368:             }
11369: 	    if ($space eq 'filename') {
11370: 	        if ($symbparm) {
11371: 		    return &clutter((&decode_symb($symbparm))[2]);
11372: 	        }
11373: 	        return &hreflocation('',$env{'request.filename'});
11374: 	    }
11375: 
11376:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
11377:                 if ($space eq 'visibleparts') {
11378:                     my $navmap = Apache::lonnavmaps::navmap->new();
11379:                     my $item;
11380:                     if (ref($navmap)) {
11381:                         my $res = $navmap->getBySymb($symbparm);
11382:                         my $parts = $res->parts();
11383:                         if (ref($parts) eq 'ARRAY') {
11384:                             $item = join(',',@{$parts});
11385:                         }
11386:                         undef($navmap);
11387:                     }
11388:                     return $item;
11389:                 }
11390:             }
11391:         }
11392: 
11393: 	my ($section, $group, @groups, @recurseup, $recursed);
11394: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
11395:         if (($courseid eq '') && ($cid)) {
11396:             $courseid = $cid;
11397:         }
11398: 	if (($symbparm && $courseid) && 
11399: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
11400: 
11401: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
11402: 
11403: # ----------------------------------------------------- Cascading lookup scheme
11404: 	    my $symbp=$symbparm;
11405: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
11406: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
11407:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
11408: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
11409: 	    if (($env{'user.name'} eq $uname) &&
11410: 		($env{'user.domain'} eq $udom)) {
11411: 		$section=$env{'request.course.sec'};
11412:                 @groups = split(/:/,$env{'request.course.groups'});  
11413:                 @groups=&sort_course_groups($courseid,@groups); 
11414: 	    } else {
11415: 		if (! defined($usection)) {
11416: 		    $section=&getsection($udom,$uname,$courseid);
11417: 		} else {
11418: 		    $section = $usection;
11419: 		}
11420:                 @groups = &get_users_groups($udom,$uname,$courseid);
11421: 	    }
11422: 
11423: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
11424: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
11425:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
11426: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
11427: 
11428: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
11429: 	    my $courselevelr=$courseid.'.'.$symbparm;
11430:             $courseleveli=$courseid.'.'.$recurseparm;
11431: 	    $courselevelm=$courseid.'.'.$mapparm;
11432: 
11433: # ----------------------------------------------------------- first, check user
11434: 
11435: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
11436:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
11437: 				       ([$courselevelr,'resource'],
11438: 					[$courselevelm,'map'     ],
11439:                                         [$courseleveli,'map'     ],
11440: 					[$courselevel, 'course'  ]));
11441: 	    if (defined($userreply)) { return &get_reply($userreply); }
11442: 
11443: # ------------------------------------------------ second, check some of course
11444:             my $coursereply;
11445:             if (@groups > 0) {
11446:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
11447:                                        $recurseparm,$mapparm,$spacequalifierrest,
11448:                                        $mapp,\$recursed,\@recurseup);
11449:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
11450:             }
11451: 
11452: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11453: 				  $env{'course.'.$courseid.'.domain'},
11454: 				  'course',$mapp,\$recursed,\@recurseup,
11455:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
11456: 				  ([$seclevelr,   'resource'],
11457: 				   [$seclevelm,   'map'     ],
11458:                                    [$secleveli,   'map'     ],
11459: 				   [$seclevel,    'course'  ],
11460: 				   [$courselevelr,'resource']));
11461: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
11462: 
11463: # ------------------------------------------------------ third, check map parms
11464: 	    my %parmhash=();
11465: 	    my $thisparm='';
11466: 	    if (tie(%parmhash,'GDBM_File',
11467: 		    $env{'request.course.fn'}.'_parms.db',
11468: 		    &GDBM_READER(),0640)) {
11469: 		$thisparm=$parmhash{$symbparm};
11470: 		untie(%parmhash);
11471: 	    }
11472: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
11473: 	}
11474: # ------------------------------------------ fourth, look in resource metadata
11475:  
11476:         my $what = $spacequalifierrest;
11477: 	$what=~s/\./\_/;
11478: 	my $filename;
11479: 	if (!$symbparm) { $symbparm=&symbread(); }
11480: 	if ($symbparm) {
11481: 	    $filename=(&decode_symb($symbparm))[2];
11482: 	} else {
11483: 	    $filename=$env{'request.filename'};
11484: 	}
11485: 	my $metadata=&metadata($filename,$what);
11486: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
11487: 	$metadata=&metadata($filename,'parameter_'.$what);
11488: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
11489: 
11490: # ----------------------------------------------- fifth, look in rest of course
11491: 	if ($symbparm && defined($courseid) && 
11492: 	    $courseid eq $env{'request.course.id'}) {
11493: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11494: 				     $env{'course.'.$courseid.'.domain'},
11495: 				     'course',$mapp,\$recursed,\@recurseup,
11496:                                      $courseid,'.',$spacequalifierrest,
11497: 				     ([$courselevelm,'map'   ],
11498:                                       [$courseleveli,'map'   ],
11499: 				      [$courselevel, 'course']));
11500: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
11501: 	}
11502: # ------------------------------------------------------------------ Cascade up
11503: 	unless ($space eq '0') {
11504: 	    my @parts=split(/_/,$space);
11505: 	    my $id=pop(@parts);
11506: 	    my $part=join('_',@parts);
11507: 	    if ($part eq '') { $part='0'; }
11508: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
11509: 				 $symbparm,$udom,$uname,$section,1);
11510: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
11511: 	}
11512: 	if ($recurse) { return undef; }
11513: 	my $pack_def=&packages_tab_default($filename,$varname);
11514: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
11515: # ---------------------------------------------------- Any other user namespace
11516:     } elsif ($realm eq 'environment') {
11517: # ----------------------------------------------------------------- environment
11518: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
11519: 	    return $env{'environment.'.$spacequalifierrest};
11520: 	} else {
11521: 	    if ($uname eq 'anonymous' && $udom eq '') {
11522: 		return '';
11523: 	    }
11524: 	    my %returnhash=&userenvironment($udom,$uname,
11525: 					    $spacequalifierrest);
11526: 	    return $returnhash{$spacequalifierrest};
11527: 	}
11528:     } elsif ($realm eq 'system') {
11529: # ----------------------------------------------------------------- system.time
11530: 	if ($space eq 'time') {
11531: 	    return time;
11532:         }
11533:     } elsif ($realm eq 'server') {
11534: # ----------------------------------------------------------------- system.time
11535: 	if ($space eq 'name') {
11536: 	    return $ENV{'SERVER_NAME'};
11537:         }
11538:     }
11539:     return '';
11540: }
11541: 
11542: sub get_reply {
11543:     my ($reply_value) = @_;
11544:     if (ref($reply_value) eq 'ARRAY') {
11545:         if (wantarray) {
11546: 	    return @$reply_value;
11547:         }
11548:         return $reply_value->[0];
11549:     } else {
11550:         return $reply_value;
11551:     }
11552: }
11553: 
11554: sub check_group_parms {
11555:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
11556:         $recursed,$recurseupref) = @_;
11557:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
11558:                   [$what,'course']);
11559:     my $coursereply;
11560:     foreach my $group (@{$groups}) {
11561:         my @groupitems = ();
11562:         foreach my $level (@levels) {
11563:              my $item = $courseid.'.['.$group.'].'.$level->[0];
11564:              push(@groupitems,[$item,$level->[1]]);
11565:         }
11566:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
11567:                                    $env{'course.'.$courseid.'.domain'},
11568:                                    'course',$mapp,$recursed,$recurseupref,
11569:                                    $courseid,'.['.$group.'].',$what,
11570:                                    @groupitems);
11571:         last if (defined($coursereply));
11572:     }
11573:     return $coursereply;
11574: }
11575: 
11576: sub get_map_hierarchy {
11577:     my ($mapname,$courseid) = @_;
11578:     my @recurseup = ();
11579:     if ($mapname) {
11580:         if (($cachedmapkey eq $courseid) &&
11581:             (abs($cachedmaptime-time)<5)) {
11582:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
11583:                 return @{$cachedmaps{$mapname}};
11584:             }
11585:         }
11586:         my $navmap = Apache::lonnavmaps::navmap->new();
11587:         if (ref($navmap)) {
11588:             @recurseup = $navmap->recurseup_maps($mapname);
11589:             undef($navmap);
11590:             $cachedmaps{$mapname} = \@recurseup;
11591:             $cachedmaptime=time;
11592:             $cachedmapkey=$courseid;
11593:         }
11594:     }
11595:     return @recurseup;
11596: }
11597: 
11598: }
11599: 
11600: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
11601:     my ($courseid,@groups) = @_;
11602:     @groups = sort(@groups);
11603:     return @groups;
11604: }
11605: 
11606: sub packages_tab_default {
11607:     my ($uri,$varname)=@_;
11608:     my (undef,$part,$name)=split(/\./,$varname);
11609: 
11610:     my (@extension,@specifics,$do_default);
11611:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
11612: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
11613: 	if ($pack_type eq 'default') {
11614: 	    $do_default=1;
11615: 	} elsif ($pack_type eq 'extension') {
11616: 	    push(@extension,[$package,$pack_type,$pack_part]);
11617: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
11618: 	    # only look at packages defaults for packages that this id is
11619: 	    push(@specifics,[$package,$pack_type,$pack_part]);
11620: 	}
11621:     }
11622:     # first look for a package that matches the requested part id
11623:     foreach my $package (@specifics) {
11624: 	my (undef,$pack_type,$pack_part)=@{$package};
11625: 	next if ($pack_part ne $part);
11626: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11627: 	    return $packagetab{"$pack_type&$name&default"};
11628: 	}
11629:     }
11630:     # look for any possible matching non extension_ package
11631:     foreach my $package (@specifics) {
11632: 	my (undef,$pack_type,$pack_part)=@{$package};
11633: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11634: 	    return $packagetab{"$pack_type&$name&default"};
11635: 	}
11636: 	if ($pack_type eq 'part') { $pack_part='0'; }
11637: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
11638: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
11639: 	}
11640:     }
11641:     # look for any posible extension_ match
11642:     foreach my $package (@extension) {
11643: 	my ($package,$pack_type)=@{$package};
11644: 	if (defined($packagetab{"$pack_type&$name&default"})) {
11645: 	    return $packagetab{"$pack_type&$name&default"};
11646: 	}
11647: 	if (defined($packagetab{$package."&$name&default"})) {
11648: 	    return $packagetab{$package."&$name&default"};
11649: 	}
11650:     }
11651:     # look for a global default setting
11652:     if ($do_default && defined($packagetab{"default&$name&default"})) {
11653: 	return $packagetab{"default&$name&default"};
11654:     }
11655:     return undef;
11656: }
11657: 
11658: sub add_prefix_and_part {
11659:     my ($prefix,$part)=@_;
11660:     my $keyroot;
11661:     if (defined($prefix) && $prefix !~ /^__/) {
11662: 	# prefix that has a part already
11663: 	$keyroot=$prefix;
11664:     } elsif (defined($prefix)) {
11665: 	# prefix that is missing a part
11666: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
11667:     } else {
11668: 	# no prefix at all
11669: 	if (defined($part)) { $keyroot='_'.$part; }
11670:     }
11671:     return $keyroot;
11672: }
11673: 
11674: # ---------------------------------------------------------------- Get metadata
11675: 
11676: my %metaentry;
11677: my %importedpartids;
11678: sub metadata {
11679:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
11680:     $uri=&declutter($uri);
11681:     # if it is a non metadata possible uri return quickly
11682:     if (($uri eq '') || 
11683: 	(($uri =~ m|^/*adm/|) && 
11684: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
11685:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
11686: 	return undef;
11687:     }
11688:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
11689: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
11690: 	return undef;
11691:     }
11692:     my $filename=$uri;
11693:     $uri=~s/\.meta$//;
11694: #
11695: # Is the metadata already cached?
11696: # Look at timestamp of caching
11697: # Everything is cached by the main uri, libraries are never directly cached
11698: #
11699:     if (!defined($liburi)) {
11700: 	my ($result,$cached)=&is_cached_new('meta',$uri);
11701: 	if (defined($cached)) { return $result->{':'.$what}; }
11702:     }
11703:     {
11704: # Imported parts would go here
11705:         my %importedids=();
11706:         my @origfileimportpartids=();
11707:         my $importedparts=0;
11708: #
11709: # Is this a recursive call for a library?
11710: #
11711: #	if (! exists($metacache{$uri})) {
11712: #	    $metacache{$uri}={};
11713: #	}
11714: 	my $cachetime = 60*60;
11715:         if ($liburi) {
11716: 	    $liburi=&declutter($liburi);
11717:             $filename=$liburi;
11718:         } else {
11719: 	    &devalidate_cache_new('meta',$uri);
11720: 	    undef(%metaentry);
11721: 	}
11722:         my %metathesekeys=();
11723:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
11724: 	my $metastring;
11725: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
11726: 	    my $which = &hreflocation('','/'.($liburi || $uri));
11727: 	    $metastring = 
11728: 		&Apache::lonnet::ssi_body($which,
11729: 					  ('grade_target' => 'meta'));
11730: 	    $cachetime = 1; # only want this cached in the child not long term
11731: 	} elsif (($uri !~ m -^(editupload)/-) && 
11732:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
11733: 	    my $file=&filelocation('',&clutter($filename));
11734: 	    #push(@{$metaentry{$uri.'.file'}},$file);
11735: 	    $metastring=&getfile($file);
11736: 	}
11737:         my $parser=HTML::LCParser->new(\$metastring);
11738:         my $token;
11739:         undef %metathesekeys;
11740:         while ($token=$parser->get_token) {
11741: 	    if ($token->[0] eq 'S') {
11742: 		if (defined($token->[2]->{'package'})) {
11743: #
11744: # This is a package - get package info
11745: #
11746: 		    my $package=$token->[2]->{'package'};
11747: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11748: 		    if (defined($token->[2]->{'id'})) { 
11749: 			$keyroot.='_'.$token->[2]->{'id'}; 
11750: 		    }
11751: 		    if ($metaentry{':packages'}) {
11752: 			$metaentry{':packages'}.=','.$package.$keyroot;
11753: 		    } else {
11754: 			$metaentry{':packages'}=$package.$keyroot;
11755: 		    }
11756: 		    foreach my $pack_entry (keys(%packagetab)) {
11757: 			my $part=$keyroot;
11758: 			$part=~s/^\_//;
11759: 			if ($pack_entry=~/^\Q$package\E\&/ || 
11760: 			    $pack_entry=~/^\Q$package\E_0\&/) {
11761: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
11762: 			    # ignore package.tab specified default values
11763:                             # here &package_tab_default() will fetch those
11764: 			    if ($subp eq 'default') { next; }
11765: 			    my $value=$packagetab{$pack_entry};
11766: 			    my $unikey;
11767: 			    if ($pack =~ /_0$/) {
11768: 				$unikey='parameter_0_'.$name;
11769: 				$part=0;
11770: 			    } else {
11771: 				$unikey='parameter'.$keyroot.'_'.$name;
11772: 			    }
11773: 			    if ($subp eq 'display') {
11774: 				$value.=' [Part: '.$part.']';
11775: 			    }
11776: 			    $metaentry{':'.$unikey.'.part'}=$part;
11777: 			    $metathesekeys{$unikey}=1;
11778: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11779: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
11780: 			    }
11781: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
11782: 				$metaentry{':'.$unikey}=
11783: 				    $metaentry{':'.$unikey.'.default'};
11784: 			    }
11785: 			}
11786: 		    }
11787: 		} else {
11788: #
11789: # This is not a package - some other kind of start tag
11790: #
11791: 		    my $entry=$token->[1];
11792: 		    my $unikey='';
11793: 
11794: 		    if ($entry eq 'import') {
11795: #
11796: # Importing a library here
11797: #
11798:                         my $location=$parser->get_text('/import');
11799:                         my $dir=$filename;
11800:                         $dir=~s|[^/]*$||;
11801:                         $location=&filelocation($dir,$location);
11802:                        
11803:                         my $importmode=$token->[2]->{'importmode'};
11804:                         if ($importmode eq 'problem') {
11805: # Import as problem/response
11806:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11807:                         } elsif ($importmode eq 'part') {
11808: # Import as part(s)
11809:                            $importedparts=1;
11810: # We need to get the original file and the imported file to get the part order correct
11811: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
11812: # Load and inspect original file
11813:                            if ($#origfileimportpartids<0) {
11814:                               undef(%importedpartids);
11815:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
11816:                               my $origfile=&getfile($origfilelocation);
11817:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11818:                            }
11819: 
11820: # Load and inspect imported file
11821:                            my $impfile=&getfile($location);
11822:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11823:                            if ($#impfilepartids>=0) {
11824: # This problem had parts
11825:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
11826:                            } else {
11827: # Importing by turning a single problem into a problem part
11828: # It gets the import-tags ID as part-ID
11829:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
11830:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
11831:                            }
11832:                         } else {
11833: # Normal import
11834:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11835:                            if (defined($token->[2]->{'id'})) {
11836:                               $unikey.='_'.$token->[2]->{'id'};
11837:                            }
11838:                         }
11839: 
11840: 			if ($depthcount<20) {
11841: 			    my $metadata = 
11842: 				&metadata($uri,'keys', $location,$unikey,
11843: 					  $depthcount+1);
11844: 			    foreach my $meta (split(',',$metadata)) {
11845: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
11846: 				$metathesekeys{$meta}=1;
11847: 			    }
11848: 			
11849:                         }
11850: 		    } else {
11851: #
11852: # Not importing, some other kind of non-package, non-library start tag
11853: # 
11854:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
11855:                         if (defined($token->[2]->{'id'})) {
11856:                             $unikey.='_'.$token->[2]->{'id'};
11857:                         }
11858: 			if (defined($token->[2]->{'name'})) { 
11859: 			    $unikey.='_'.$token->[2]->{'name'}; 
11860: 			}
11861: 			$metathesekeys{$unikey}=1;
11862: 			foreach my $param (@{$token->[3]}) {
11863: 			    $metaentry{':'.$unikey.'.'.$param} =
11864: 				$token->[2]->{$param};
11865: 			}
11866: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
11867: 			my $default=$metaentry{':'.$unikey.'.default'};
11868: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
11869: 		 # only ws inside the tag, and not in default, so use default
11870: 		 # as value
11871: 			    $metaentry{':'.$unikey}=$default;
11872: 			} elsif ( $internaltext =~ /\S/ ) {
11873: 		  # something interesting inside the tag
11874: 			    $metaentry{':'.$unikey}=$internaltext;
11875: 			} else {
11876: 		  # no interesting values, don't set a default
11877: 			}
11878: # end of not-a-package not-a-library import
11879: 		    }
11880: # end of not-a-package start tag
11881: 		}
11882: # the next is the end of "start tag"
11883: 	    }
11884: 	}
11885: 	my ($extension) = ($uri =~ /\.(\w+)$/);
11886: 	$extension = lc($extension);
11887: 	if ($extension eq 'htm') { $extension='html'; }
11888: 
11889: 	foreach my $key (keys(%packagetab)) {
11890: 	    #no specific packages #how's our extension
11891: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
11892: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
11893: 					 \%metathesekeys);
11894: 	}
11895: 
11896: 	if (!exists($metaentry{':packages'})
11897: 	    || $packagetab{"import_defaults&extension_$extension"}) {
11898: 	    foreach my $key (keys(%packagetab)) {
11899: 		#no specific packages well let's get default then
11900: 		if ($key!~/^default&/) { next; }
11901: 		&metadata_create_package_def($uri,$key,'default',
11902: 					     \%metathesekeys);
11903: 	    }
11904: 	}
11905: # are there custom rights to evaluate
11906: 	if ($metaentry{':copyright'} eq 'custom') {
11907: 
11908:     #
11909:     # Importing a rights file here
11910:     #
11911: 	    unless ($depthcount) {
11912: 		my $location=$metaentry{':customdistributionfile'};
11913: 		my $dir=$filename;
11914: 		$dir=~s|[^/]*$||;
11915: 		$location=&filelocation($dir,$location);
11916: 		my $rights_metadata =
11917: 		    &metadata($uri,'keys',$location,'_rights',
11918: 			      $depthcount+1);
11919: 		foreach my $rights (split(',',$rights_metadata)) {
11920: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
11921: 		    $metathesekeys{$rights}=1;
11922: 		}
11923: 	    }
11924: 	}
11925: 	# uniqifiy package listing
11926: 	my %seen;
11927: 	my @uniq_packages =
11928: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
11929: 	$metaentry{':packages'} = join(',',@uniq_packages);
11930: 
11931:         if ($importedparts) {
11932: # We had imported parts and need to rebuild partorder
11933:            $metaentry{':partorder'}='';
11934:            $metathesekeys{'partorder'}=1;
11935:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
11936:                if ($origfileimportpartids[$index] eq 'part') {
11937: # original part, part of the problem
11938:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
11939:                } else {
11940: # we have imported parts at this position
11941:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
11942:                }
11943:            }
11944:            $metaentry{':partorder'}=~s/^\,//;
11945:         }
11946: 
11947: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
11948: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
11949: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
11950: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
11951: # this is the end of "was not already recently cached
11952:     }
11953:     return $metaentry{':'.$what};
11954: }
11955: 
11956: sub metadata_create_package_def {
11957:     my ($uri,$key,$package,$metathesekeys)=@_;
11958:     my ($pack,$name,$subp)=split(/\&/,$key);
11959:     if ($subp eq 'default') { next; }
11960:     
11961:     if (defined($metaentry{':packages'})) {
11962: 	$metaentry{':packages'}.=','.$package;
11963:     } else {
11964: 	$metaentry{':packages'}=$package;
11965:     }
11966:     my $value=$packagetab{$key};
11967:     my $unikey;
11968:     $unikey='parameter_0_'.$name;
11969:     $metaentry{':'.$unikey.'.part'}=0;
11970:     $$metathesekeys{$unikey}=1;
11971:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11972: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
11973:     }
11974:     if (defined($metaentry{':'.$unikey.'.default'})) {
11975: 	$metaentry{':'.$unikey}=
11976: 	    $metaentry{':'.$unikey.'.default'};
11977:     }
11978: }
11979: 
11980: sub metadata_generate_part0 {
11981:     my ($metadata,$metacache,$uri) = @_;
11982:     my %allnames;
11983:     foreach my $metakey (keys(%$metadata)) {
11984: 	if ($metakey=~/^parameter\_(.*)/) {
11985: 	  my $part=$$metacache{':'.$metakey.'.part'};
11986: 	  my $name=$$metacache{':'.$metakey.'.name'};
11987: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
11988: 	    $allnames{$name}=$part;
11989: 	  }
11990: 	}
11991:     }
11992:     foreach my $name (keys(%allnames)) {
11993:       $$metadata{"parameter_0_$name"}=1;
11994:       my $key=":parameter_0_$name";
11995:       $$metacache{"$key.part"}='0';
11996:       $$metacache{"$key.name"}=$name;
11997:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
11998: 					   $allnames{$name}.'_'.$name.
11999: 					   '.type'};
12000:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
12001: 			     '.display'};
12002:       my $expr='[Part: '.$allnames{$name}.']';
12003:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
12004:       $$metacache{"$key.display"}=$olddis;
12005:     }
12006: }
12007: 
12008: # ------------------------------------------------------ Devalidate title cache
12009: 
12010: sub devalidate_title_cache {
12011:     my ($url)=@_;
12012:     if (!$env{'request.course.id'}) { return; }
12013:     my $symb=&symbread($url);
12014:     if (!$symb) { return; }
12015:     my $key=$env{'request.course.id'}."\0".$symb;
12016:     &devalidate_cache_new('title',$key);
12017: }
12018: 
12019: # ------------------------------------------------- Get the title of a course
12020: 
12021: sub current_course_title {
12022:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
12023: }
12024: # ------------------------------------------------- Get the title of a resource
12025: 
12026: sub gettitle {
12027:     my $urlsymb=shift;
12028:     my $symb=&symbread($urlsymb);
12029:     if ($symb) {
12030: 	my $key=$env{'request.course.id'}."\0".$symb;
12031: 	my ($result,$cached)=&is_cached_new('title',$key);
12032: 	if (defined($cached)) { 
12033: 	    return $result;
12034: 	}
12035: 	my ($map,$resid,$url)=&decode_symb($symb);
12036: 	my $title='';
12037: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
12038: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
12039: 	} else {
12040: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12041: 		    &GDBM_READER(),0640)) {
12042: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
12043: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
12044: 		untie(%bighash);
12045: 	    }
12046: 	}
12047: 	$title=~s/\&colon\;/\:/gs;
12048: 	if ($title) {
12049: # Remember both $symb and $title for dynamic metadata
12050:             $accesshash{$symb.'___crstitle'}=$title;
12051:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
12052: # Cache this title and then return it
12053: 	    return &do_cache_new('title',$key,$title,600);
12054: 	}
12055: 	$urlsymb=$url;
12056:     }
12057:     my $title=&metadata($urlsymb,'title');
12058:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
12059:     return $title;
12060: }
12061: 
12062: sub get_slot {
12063:     my ($which,$cnum,$cdom)=@_;
12064:     if (!$cnum || !$cdom) {
12065: 	(undef,my $courseid)=&whichuser();
12066: 	$cdom=$env{'course.'.$courseid.'.domain'};
12067: 	$cnum=$env{'course.'.$courseid.'.num'};
12068:     }
12069:     my $key=join("\0",'slots',$cdom,$cnum,$which);
12070:     my %slotinfo;
12071:     if (exists($remembered{$key})) {
12072: 	$slotinfo{$which} = $remembered{$key};
12073:     } else {
12074: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
12075: 	&Apache::lonhomework::showhash(%slotinfo);
12076: 	my ($tmp)=keys(%slotinfo);
12077: 	if ($tmp=~/^error:/) { return (); }
12078: 	$remembered{$key} = $slotinfo{$which};
12079:     }
12080:     if (ref($slotinfo{$which}) eq 'HASH') {
12081: 	return %{$slotinfo{$which}};
12082:     }
12083:     return $slotinfo{$which};
12084: }
12085: 
12086: sub get_reservable_slots {
12087:     my ($cnum,$cdom,$uname,$udom) = @_;
12088:     my $now = time;
12089:     my $reservable_info;
12090:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
12091:     if (exists($remembered{$key})) {
12092:         $reservable_info = $remembered{$key};
12093:     } else {
12094:         my %resv;
12095:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
12096:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
12097:         $reservable_info = \%resv;
12098:         $remembered{$key} = $reservable_info;
12099:     }
12100:     return $reservable_info;
12101: }
12102: 
12103: sub get_course_slots {
12104:     my ($cnum,$cdom) = @_;
12105:     my $hashid=$cnum.':'.$cdom;
12106:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
12107:     if (defined($cached)) {
12108:         if (ref($result) eq 'HASH') {
12109:             return %{$result};
12110:         }
12111:     } else {
12112:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
12113:         my ($tmp) = keys(%slots);
12114:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
12115:             &do_cache_new('allslots',$hashid,\%slots,600);
12116:             return %slots;
12117:         }
12118:     }
12119:     return;
12120: }
12121: 
12122: sub devalidate_slots_cache {
12123:     my ($cnum,$cdom)=@_;
12124:     my $hashid=$cnum.':'.$cdom;
12125:     &devalidate_cache_new('allslots',$hashid);
12126: }
12127: 
12128: sub get_coursechange {
12129:     my ($cdom,$cnum) = @_;
12130:     if ($cdom eq '' || $cnum eq '') {
12131:         return unless ($env{'request.course.id'});
12132:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
12133:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
12134:     }
12135:     my $hashid=$cdom.'_'.$cnum;
12136:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
12137:     if ((defined($cached)) && ($change ne '')) {
12138:         return $change;
12139:     } else {
12140:         my %crshash;
12141:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
12142:         if ($crshash{'internal.contentchange'} eq '') {
12143:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
12144:             if ($change eq '') {
12145:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
12146:                 $change = $crshash{'internal.created'};
12147:             }
12148:         } else {
12149:             $change = $crshash{'internal.contentchange'};
12150:         }
12151:         my $cachetime = 600;
12152:         &do_cache_new('crschange',$hashid,$change,$cachetime);
12153:     }
12154:     return $change;
12155: }
12156: 
12157: sub devalidate_coursechange_cache {
12158:     my ($cnum,$cdom)=@_;
12159:     my $hashid=$cnum.':'.$cdom;
12160:     &devalidate_cache_new('crschange',$hashid);
12161: }
12162: 
12163: # ------------------------------------------------- Update symbolic store links
12164: 
12165: sub symblist {
12166:     my ($mapname,%newhash)=@_;
12167:     $mapname=&deversion(&declutter($mapname));
12168:     my %hash;
12169:     if (($env{'request.course.fn'}) && (%newhash)) {
12170:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12171:                       &GDBM_WRCREAT(),0640)) {
12172: 	    foreach my $url (keys(%newhash)) {
12173: 		next if ($url eq 'last_known'
12174: 			 && $env{'form.no_update_last_known'});
12175: 		$hash{declutter($url)}=&encode_symb($mapname,
12176: 						    $newhash{$url}->[1],
12177: 						    $newhash{$url}->[0]);
12178:             }
12179:             if (untie(%hash)) {
12180: 		return 'ok';
12181:             }
12182:         }
12183:     }
12184:     return 'error';
12185: }
12186: 
12187: # --------------------------------------------------------------- Verify a symb
12188: 
12189: sub symbverify {
12190:     my ($symb,$thisurl,$encstate)=@_;
12191:     my $thisfn=$thisurl;
12192:     $thisfn=&declutter($thisfn);
12193: # direct jump to resource in page or to a sequence - will construct own symbs
12194:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
12195: # check URL part
12196:     my ($map,$resid,$url)=&decode_symb($symb);
12197: 
12198:     unless ($url eq $thisfn) { return 0; }
12199: 
12200:     $symb=&symbclean($symb);
12201:     $thisurl=&deversion($thisurl);
12202:     $thisfn=&deversion($thisfn);
12203: 
12204:     my %bighash;
12205:     my $okay=0;
12206: 
12207:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12208:                             &GDBM_READER(),0640)) {
12209:         my $noclutter;
12210:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
12211:             $thisurl =~ s/\?.+$//;
12212:             if ($map =~ m{^uploaded/.+\.page$}) {
12213:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
12214:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
12215:                 $noclutter = 1;
12216:             }
12217:         }
12218:         my $ids;
12219:         if ($noclutter) {
12220:             $ids=$bighash{'ids_'.$thisurl};
12221:         } else {
12222:             $ids=$bighash{'ids_'.&clutter($thisurl)};
12223:         }
12224:         unless ($ids) {
12225:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
12226:             $ids=$bighash{$idkey};
12227:         }
12228:         if ($ids) {
12229: # ------------------------------------------------------------------- Has ID(s)
12230:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
12231:                 $symb =~ s/\?.+$//;
12232:             }
12233: 	    foreach my $id (split(/\,/,$ids)) {
12234: 	       my ($mapid,$resid)=split(/\./,$id);
12235:                if (
12236:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
12237:    eq $symb) {
12238:                    if (ref($encstate)) {
12239:                        $$encstate = $bighash{'encrypted_'.$id};
12240:                    }
12241: 		   if (($env{'request.role.adv'}) ||
12242: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
12243:                        ($thisurl eq '/adm/navmaps')) {
12244: 		       $okay=1;
12245:                        last;
12246: 		   }
12247: 	       }
12248: 	   }
12249:         }
12250: 	untie(%bighash);
12251:     }
12252:     return $okay;
12253: }
12254: 
12255: # --------------------------------------------------------------- Clean-up symb
12256: 
12257: sub symbclean {
12258:     my $symb=shift;
12259:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12260: # remove version from map
12261:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
12262: 
12263: # remove version from URL
12264:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
12265: 
12266: # remove wrapper
12267: 
12268:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
12269:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
12270:     return $symb;
12271: }
12272: 
12273: # ---------------------------------------------- Split symb to find map and url
12274: 
12275: sub encode_symb {
12276:     my ($map,$resid,$url)=@_;
12277:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
12278: }
12279: 
12280: sub decode_symb {
12281:     my $symb=shift;
12282:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12283:     my ($map,$resid,$url)=split(/___/,$symb);
12284:     return (&fixversion($map),$resid,&fixversion($url));
12285: }
12286: 
12287: sub fixversion {
12288:     my $fn=shift;
12289:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
12290:     my %bighash;
12291:     my $uri=&clutter($fn);
12292:     my $key=$env{'request.course.id'}.'_'.$uri;
12293: # is this cached?
12294:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
12295:     if (defined($cached)) { return $result; }
12296: # unfortunately not cached, or expired
12297:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12298: 	    &GDBM_READER(),0640)) {
12299:  	if ($bighash{'version_'.$uri}) {
12300:  	    my $version=$bighash{'version_'.$uri};
12301:  	    unless (($version eq 'mostrecent') || 
12302: 		    ($version==&getversion($uri))) {
12303:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
12304:  	    }
12305:  	}
12306:  	untie %bighash;
12307:     }
12308:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
12309: }
12310: 
12311: sub deversion {
12312:     my $url=shift;
12313:     $url=~s/\.\d+\.(\w+)$/\.$1/;
12314:     return $url;
12315: }
12316: 
12317: # ------------------------------------------------------ Return symb list entry
12318: 
12319: sub symbread {
12320:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
12321:     my $cache_str='request.symbread.cached.'.$thisfn;
12322:     if (defined($env{$cache_str})) {
12323:         if ($ignorecachednull) {
12324:             return $env{$cache_str} unless ($env{$cache_str} eq '');
12325:         } else {
12326:             return $env{$cache_str};
12327:         }
12328:     }
12329: # no filename provided? try from environment
12330:     unless ($thisfn) {
12331:         if ($env{'request.symb'}) {
12332: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
12333: 	}
12334: 	$thisfn=$env{'request.filename'};
12335:     }
12336:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
12337: # is that filename actually a symb? Verify, clean, and return
12338:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
12339: 	if (&symbverify($thisfn,$1)) {
12340: 	    return $env{$cache_str}=&symbclean($thisfn);
12341: 	}
12342:     }
12343:     $thisfn=declutter($thisfn);
12344:     my %hash;
12345:     my %bighash;
12346:     my $syval='';
12347:     if (($env{'request.course.fn'}) && ($thisfn)) {
12348:         my $targetfn = $thisfn;
12349:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
12350:             $targetfn = 'adm/wrapper/'.$thisfn;
12351:         }
12352: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
12353: 	    $targetfn=$1;
12354: 	}
12355:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12356:                       &GDBM_READER(),0640)) {
12357: 	    $syval=$hash{$targetfn};
12358:             untie(%hash);
12359:         }
12360: # ---------------------------------------------------------- There was an entry
12361:         if ($syval) {
12362: 	    #unless ($syval=~/\_\d+$/) {
12363: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
12364: 		    #&appenv({'request.ambiguous' => $thisfn});
12365: 		    #return $env{$cache_str}='';
12366: 		#}    
12367: 		#$syval.=$1;
12368: 	    #}
12369:         } else {
12370: # ------------------------------------------------------- Was not in symb table
12371:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12372:                             &GDBM_READER(),0640)) {
12373: # ---------------------------------------------- Get ID(s) for current resource
12374:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
12375:               unless ($ids) { 
12376:                  $ids=$bighash{'ids_/'.$thisfn};
12377:               }
12378:               unless ($ids) {
12379: # alias?
12380: 		  $ids=$bighash{'mapalias_'.$thisfn};
12381:               }
12382:               if ($ids) {
12383: # ------------------------------------------------------------------- Has ID(s)
12384:                  my @possibilities=split(/\,/,$ids);
12385:                  if ($#possibilities==0) {
12386: # ----------------------------------------------- There is only one possibility
12387: 		     my ($mapid,$resid)=split(/\./,$ids);
12388: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
12389: 						    $resid,$thisfn);
12390:                      if (ref($possibles) eq 'HASH') {
12391:                          $possibles->{$syval} = 1;    
12392:                      }
12393:                      if ($checkforblock) {
12394:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
12395:                          if (@blockers) {
12396:                              $syval = '';
12397:                              return;
12398:                          }
12399:                      }
12400:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
12401: # ------------------------------------------ There is more than one possibility
12402:                      my $realpossible=0;
12403:                      foreach my $id (@possibilities) {
12404: 			 my $file=$bighash{'src_'.$id};
12405:                          my $canaccess;
12406:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
12407:                              $canaccess = 1;
12408:                          } else { 
12409:                              $canaccess = &allowed('bre',$file);
12410:                          }
12411:                          if ($canaccess) {
12412:          		     my ($mapid,$resid)=split(/\./,$id);
12413:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
12414:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
12415: 						             $resid,$thisfn);
12416:                                  if (ref($possibles) eq 'HASH') {
12417:                                      $possibles->{$syval} = 1;
12418:                                  }
12419:                                  if ($checkforblock) {
12420:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
12421:                                      unless (@blockers > 0) {
12422:                                          $syval = $poss_syval;
12423:                                          $realpossible++;
12424:                                      }
12425:                                  } else {
12426:                                      $syval = $poss_syval;
12427:                                      $realpossible++;
12428:                                  }
12429:                              }
12430: 			 }
12431:                      }
12432: 		     if ($realpossible!=1) { $syval=''; }
12433:                  } else {
12434:                      $syval='';
12435:                  }
12436: 	      }
12437:               untie(%bighash);
12438:            }
12439:         }
12440:         if ($syval) {
12441: 	    return $env{$cache_str}=$syval;
12442:         }
12443:     }
12444:     &appenv({'request.ambiguous' => $thisfn});
12445:     return $env{$cache_str}='';
12446: }
12447: 
12448: # ---------------------------------------------------------- Return random seed
12449: 
12450: sub numval {
12451:     my $txt=shift;
12452:     $txt=~tr/A-J/0-9/;
12453:     $txt=~tr/a-j/0-9/;
12454:     $txt=~tr/K-T/0-9/;
12455:     $txt=~tr/k-t/0-9/;
12456:     $txt=~tr/U-Z/0-5/;
12457:     $txt=~tr/u-z/0-5/;
12458:     $txt=~s/\D//g;
12459:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
12460:     return int($txt);
12461: }
12462: 
12463: sub numval2 {
12464:     my $txt=shift;
12465:     $txt=~tr/A-J/0-9/;
12466:     $txt=~tr/a-j/0-9/;
12467:     $txt=~tr/K-T/0-9/;
12468:     $txt=~tr/k-t/0-9/;
12469:     $txt=~tr/U-Z/0-5/;
12470:     $txt=~tr/u-z/0-5/;
12471:     $txt=~s/\D//g;
12472:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12473:     my $total;
12474:     foreach my $val (@txts) { $total+=$val; }
12475:     if ($_64bit) { if ($total > 2**32) { return -1; } }
12476:     return int($total);
12477: }
12478: 
12479: sub numval3 {
12480:     use integer;
12481:     my $txt=shift;
12482:     $txt=~tr/A-J/0-9/;
12483:     $txt=~tr/a-j/0-9/;
12484:     $txt=~tr/K-T/0-9/;
12485:     $txt=~tr/k-t/0-9/;
12486:     $txt=~tr/U-Z/0-5/;
12487:     $txt=~tr/u-z/0-5/;
12488:     $txt=~s/\D//g;
12489:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12490:     my $total;
12491:     foreach my $val (@txts) { $total+=$val; }
12492:     if ($_64bit) { $total=(($total<<32)>>32); }
12493:     return $total;
12494: }
12495: 
12496: sub digest {
12497:     my ($data)=@_;
12498:     my $digest=&Digest::MD5::md5($data);
12499:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
12500:     my ($e,$f);
12501:     {
12502:         use integer;
12503:         $e=($a+$b);
12504:         $f=($c+$d);
12505:         if ($_64bit) {
12506:             $e=(($e<<32)>>32);
12507:             $f=(($f<<32)>>32);
12508:         }
12509:     }
12510:     if (wantarray) {
12511: 	return ($e,$f);
12512:     } else {
12513: 	my $g;
12514: 	{
12515: 	    use integer;
12516: 	    $g=($e+$f);
12517: 	    if ($_64bit) {
12518: 		$g=(($g<<32)>>32);
12519: 	    }
12520: 	}
12521: 	return $g;
12522:     }
12523: }
12524: 
12525: sub latest_rnd_algorithm_id {
12526:     return '64bit5';
12527: }
12528: 
12529: sub get_rand_alg {
12530:     my ($courseid)=@_;
12531:     if (!$courseid) { $courseid=(&whichuser())[1]; }
12532:     if ($courseid) {
12533: 	return $env{"course.$courseid.rndseed"};
12534:     }
12535:     return &latest_rnd_algorithm_id();
12536: }
12537: 
12538: sub validCODE {
12539:     my ($CODE)=@_;
12540:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
12541:     return 0;
12542: }
12543: 
12544: sub getCODE {
12545:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
12546:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
12547: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
12548: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
12549: 	return $Apache::lonhomework::history{'resource.CODE'};
12550:     }
12551:     return undef;
12552: }
12553: #
12554: #  Determines the random seed for a specific context:
12555: #
12556: # parameters:
12557: #   symb      - in course context the symb for the seed.
12558: #   course_id - The course id of the form domain_coursenum.
12559: #   domain    - Domain for the user.
12560: #   course    - Course for the user.
12561: #   cenv      - environment of the course.
12562: #
12563: # NOTE:
12564: #   All parameters are picked out of the environment if missing
12565: #   or not defined.
12566: #   If a symb cannot be determined the current time is used instead.
12567: #
12568: #  For a given well defined symb, courside, domain, username,
12569: #  and course environment, the seed is reproducible.
12570: #
12571: sub rndseed {
12572:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
12573:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
12574:     if (!defined($symb)) {
12575: 	unless ($symb=$wsymb) { return time; }
12576:     }
12577:     if (!defined $courseid) { 
12578: 	$courseid=$wcourseid; 
12579:     }
12580:     if (!defined $domain) { $domain=$wdomain; }
12581:     if (!defined $username) { $username=$wusername }
12582: 
12583:     my $which;
12584:     if (defined($cenv->{'rndseed'})) {
12585: 	$which = $cenv->{'rndseed'};
12586:     } else {
12587: 	$which =&get_rand_alg($courseid);
12588:     }
12589:     if (defined(&getCODE())) {
12590: 
12591: 	if ($which eq '64bit5') {
12592: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
12593: 	} elsif ($which eq '64bit4') {
12594: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
12595: 	} else {
12596: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
12597: 	}
12598:     } elsif ($which eq '64bit5') {
12599: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
12600:     } elsif ($which eq '64bit4') {
12601: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
12602:     } elsif ($which eq '64bit3') {
12603: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
12604:     } elsif ($which eq '64bit2') {
12605: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
12606:     } elsif ($which eq '64bit') {
12607: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
12608:     }
12609:     return &rndseed_32bit($symb,$courseid,$domain,$username);
12610: }
12611: 
12612: sub rndseed_32bit {
12613:     my ($symb,$courseid,$domain,$username)=@_;
12614:     {
12615: 	use integer;
12616: 	my $symbchck=unpack("%32C*",$symb) << 27;
12617: 	my $symbseed=numval($symb) << 22;
12618: 	my $namechck=unpack("%32C*",$username) << 17;
12619: 	my $nameseed=numval($username) << 12;
12620: 	my $domainseed=unpack("%32C*",$domain) << 7;
12621: 	my $courseseed=unpack("%32C*",$courseid);
12622: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
12623: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12624: 	#&logthis("rndseed :$num:$symb");
12625: 	if ($_64bit) { $num=(($num<<32)>>32); }
12626: 	return $num;
12627:     }
12628: }
12629: 
12630: sub rndseed_64bit {
12631:     my ($symb,$courseid,$domain,$username)=@_;
12632:     {
12633: 	use integer;
12634: 	my $symbchck=unpack("%32S*",$symb) << 21;
12635: 	my $symbseed=numval($symb) << 10;
12636: 	my $namechck=unpack("%32S*",$username);
12637: 	
12638: 	my $nameseed=numval($username) << 21;
12639: 	my $domainseed=unpack("%32S*",$domain) << 10;
12640: 	my $courseseed=unpack("%32S*",$courseid);
12641: 	
12642: 	my $num1=$symbchck+$symbseed+$namechck;
12643: 	my $num2=$nameseed+$domainseed+$courseseed;
12644: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12645: 	#&logthis("rndseed :$num:$symb");
12646: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12647: 	return "$num1,$num2";
12648:     }
12649: }
12650: 
12651: sub rndseed_64bit2 {
12652:     my ($symb,$courseid,$domain,$username)=@_;
12653:     {
12654: 	use integer;
12655: 	# strings need to be an even # of cahracters long, it it is odd the
12656:         # last characters gets thrown away
12657: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
12658: 	my $symbseed=numval($symb) << 10;
12659: 	my $namechck=unpack("%32S*",$username.' ');
12660: 	
12661: 	my $nameseed=numval($username) << 21;
12662: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
12663: 	my $courseseed=unpack("%32S*",$courseid.' ');
12664: 	
12665: 	my $num1=$symbchck+$symbseed+$namechck;
12666: 	my $num2=$nameseed+$domainseed+$courseseed;
12667: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12668: 	#&logthis("rndseed :$num:$symb");
12669: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12670: 	return "$num1,$num2";
12671:     }
12672: }
12673: 
12674: sub rndseed_64bit3 {
12675:     my ($symb,$courseid,$domain,$username)=@_;
12676:     {
12677: 	use integer;
12678: 	# strings need to be an even # of cahracters long, it it is odd the
12679:         # last characters gets thrown away
12680: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
12681: 	my $symbseed=numval2($symb) << 10;
12682: 	my $namechck=unpack("%32S*",$username.' ');
12683: 	
12684: 	my $nameseed=numval2($username) << 21;
12685: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
12686: 	my $courseseed=unpack("%32S*",$courseid.' ');
12687: 	
12688: 	my $num1=$symbchck+$symbseed+$namechck;
12689: 	my $num2=$nameseed+$domainseed+$courseseed;
12690: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12691: 	#&logthis("rndseed :$num1:$num2:$_64bit");
12692: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12693: 	
12694: 	return "$num1:$num2";
12695:     }
12696: }
12697: 
12698: sub rndseed_64bit4 {
12699:     my ($symb,$courseid,$domain,$username)=@_;
12700:     {
12701: 	use integer;
12702: 	# strings need to be an even # of cahracters long, it it is odd the
12703:         # last characters gets thrown away
12704: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
12705: 	my $symbseed=numval3($symb) << 10;
12706: 	my $namechck=unpack("%32S*",$username.' ');
12707: 	
12708: 	my $nameseed=numval3($username) << 21;
12709: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
12710: 	my $courseseed=unpack("%32S*",$courseid.' ');
12711: 	
12712: 	my $num1=$symbchck+$symbseed+$namechck;
12713: 	my $num2=$nameseed+$domainseed+$courseseed;
12714: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12715: 	#&logthis("rndseed :$num1:$num2:$_64bit");
12716: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12717: 	
12718: 	return "$num1:$num2";
12719:     }
12720: }
12721: 
12722: sub rndseed_64bit5 {
12723:     my ($symb,$courseid,$domain,$username)=@_;
12724:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
12725:     return "$num1:$num2";
12726: }
12727: 
12728: sub rndseed_CODE_64bit {
12729:     my ($symb,$courseid,$domain,$username)=@_;
12730:     {
12731: 	use integer;
12732: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
12733: 	my $symbseed=numval2($symb);
12734: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12735: 	my $CODEseed=numval(&getCODE());
12736: 	my $courseseed=unpack("%32S*",$courseid.' ');
12737: 	my $num1=$symbseed+$CODEchck;
12738: 	my $num2=$CODEseed+$courseseed+$symbchck;
12739: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12740: 	#&logthis("rndseed :$num1:$num2:$symb");
12741: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
12742: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
12743: 	return "$num1:$num2";
12744:     }
12745: }
12746: 
12747: sub rndseed_CODE_64bit4 {
12748:     my ($symb,$courseid,$domain,$username)=@_;
12749:     {
12750: 	use integer;
12751: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
12752: 	my $symbseed=numval3($symb);
12753: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12754: 	my $CODEseed=numval3(&getCODE());
12755: 	my $courseseed=unpack("%32S*",$courseid.' ');
12756: 	my $num1=$symbseed+$CODEchck;
12757: 	my $num2=$CODEseed+$courseseed+$symbchck;
12758: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12759: 	#&logthis("rndseed :$num1:$num2:$symb");
12760: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
12761: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
12762: 	return "$num1:$num2";
12763:     }
12764: }
12765: 
12766: sub rndseed_CODE_64bit5 {
12767:     my ($symb,$courseid,$domain,$username)=@_;
12768:     my $code = &getCODE();
12769:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
12770:     return "$num1:$num2";
12771: }
12772: 
12773: sub setup_random_from_rndseed {
12774:     my ($rndseed)=@_;
12775:     if ($rndseed =~/([,:])/) {
12776:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
12777:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
12778:             &Math::Random::random_set_seed_from_phrase($rndseed);
12779:         } else {
12780:             &Math::Random::random_set_seed($num1,$num2);
12781:         }
12782:     } else {
12783: 	&Math::Random::random_set_seed_from_phrase($rndseed);
12784:     }
12785: }
12786: 
12787: sub latest_receipt_algorithm_id {
12788:     return 'receipt3';
12789: }
12790: 
12791: sub recunique {
12792:     my $fucourseid=shift;
12793:     my $unique;
12794:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
12795: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
12796: 	$unique=$env{"course.$fucourseid.internal.encseed"};
12797:     } else {
12798: 	$unique=$perlvar{'lonReceipt'};
12799:     }
12800:     return unpack("%32C*",$unique);
12801: }
12802: 
12803: sub recprefix {
12804:     my $fucourseid=shift;
12805:     my $prefix;
12806:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
12807: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
12808: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
12809:     } else {
12810: 	$prefix=$perlvar{'lonHostID'};
12811:     }
12812:     return unpack("%32C*",$prefix);
12813: }
12814: 
12815: sub ireceipt {
12816:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
12817: 
12818:     my $return =&recprefix($fucourseid).'-';
12819: 
12820:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
12821: 	$env{'request.state'} eq 'construct') {
12822: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
12823: 	return $return;
12824:     }
12825: 
12826:     my $cuname=unpack("%32C*",$funame);
12827:     my $cudom=unpack("%32C*",$fudom);
12828:     my $cucourseid=unpack("%32C*",$fucourseid);
12829:     my $cusymb=unpack("%32C*",$fusymb);
12830:     my $cunique=&recunique($fucourseid);
12831:     my $cpart=unpack("%32S*",$part);
12832:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
12833: 
12834: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
12835: 			       
12836: 	$return.= ($cunique%$cuname+
12837: 		   $cunique%$cudom+
12838: 		   $cusymb%$cuname+
12839: 		   $cusymb%$cudom+
12840: 		   $cucourseid%$cuname+
12841: 		   $cucourseid%$cudom+
12842: 		   $cpart%$cuname+
12843: 		   $cpart%$cudom);
12844:     } else {
12845: 	$return.= ($cunique%$cuname+
12846: 		   $cunique%$cudom+
12847: 		   $cusymb%$cuname+
12848: 		   $cusymb%$cudom+
12849: 		   $cucourseid%$cuname+
12850: 		   $cucourseid%$cudom);
12851:     }
12852:     return $return;
12853: }
12854: 
12855: sub receipt {
12856:     my ($part)=@_;
12857:     my ($symb,$courseid,$domain,$name) = &whichuser();
12858:     return &ireceipt($name,$domain,$courseid,$symb,$part);
12859: }
12860: 
12861: sub whichuser {
12862:     my ($passedsymb)=@_;
12863:     my ($symb,$courseid,$domain,$name,$publicuser);
12864:     if (defined($env{'form.grade_symb'})) {
12865: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
12866: 	my $allowed=&allowed('vgr',$tmp_courseid);
12867: 	if (!$allowed &&
12868: 	    exists($env{'request.course.sec'}) &&
12869: 	    $env{'request.course.sec'} !~ /^\s*$/) {
12870: 	    $allowed=&allowed('vgr',$tmp_courseid.
12871: 			      '/'.$env{'request.course.sec'});
12872: 	}
12873: 	if ($allowed) {
12874: 	    ($symb)=&get_env_multiple('form.grade_symb');
12875: 	    $courseid=$tmp_courseid;
12876: 	    ($domain)=&get_env_multiple('form.grade_domain');
12877: 	    ($name)=&get_env_multiple('form.grade_username');
12878: 	    return ($symb,$courseid,$domain,$name,$publicuser);
12879: 	}
12880:     }
12881:     if (!$passedsymb) {
12882: 	$symb=&symbread();
12883:     } else {
12884: 	$symb=$passedsymb;
12885:     }
12886:     $courseid=$env{'request.course.id'};
12887:     $domain=$env{'user.domain'};
12888:     $name=$env{'user.name'};
12889:     if ($name eq 'public' && $domain eq 'public') {
12890: 	if (!defined($env{'form.username'})) {
12891: 	    $env{'form.username'}.=time.rand(10000000);
12892: 	}
12893: 	$name.=$env{'form.username'};
12894:     }
12895:     return ($symb,$courseid,$domain,$name,$publicuser);
12896: 
12897: }
12898: 
12899: # ------------------------------------------------------------ Serves up a file
12900: # returns either the contents of the file or 
12901: # -1 if the file doesn't exist
12902: #
12903: # if the target is a file that was uploaded via DOCS, 
12904: # a check will be made to see if a current copy exists on the local server,
12905: # if it does this will be served, otherwise a copy will be retrieved from
12906: # the home server for the course and stored in /home/httpd/html/userfiles on
12907: # the local server.   
12908: 
12909: sub getfile {
12910:     my ($file) = @_;
12911:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
12912:     &repcopy($file);
12913:     return &readfile($file);
12914: }
12915: 
12916: sub repcopy_userfile {
12917:     my ($file)=@_;
12918:     my $londocroot = $perlvar{'lonDocRoot'};
12919:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
12920:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
12921:     my ($cdom,$cnum,$filename) = 
12922: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
12923:     my $uri="/uploaded/$cdom/$cnum/$filename";
12924:     if (-e "$file") {
12925: # we already have a local copy, check it out
12926: 	my @fileinfo = stat($file);
12927: 	my $rtncode;
12928: 	my $info;
12929: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
12930: 	if ($lwpresp ne 'ok') {
12931: # there is no such file anymore, even though we had a local copy
12932: 	    if ($rtncode eq '404') {
12933: 		unlink($file);
12934: 	    }
12935: 	    return -1;
12936: 	}
12937: 	if ($info < $fileinfo[9]) {
12938: # nice, the file we have is up-to-date, just say okay
12939: 	    return 'ok';
12940: 	} else {
12941: # the file is outdated, get rid of it
12942: 	    unlink($file);
12943: 	}
12944:     }
12945: # one way or the other, at this point, we don't have the file
12946: # construct the correct path for the file
12947:     my @parts = ($cdom,$cnum); 
12948:     if ($filename =~ m|^(.+)/[^/]+$|) {
12949: 	push @parts, split(/\//,$1);
12950:     }
12951:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
12952:     foreach my $part (@parts) {
12953: 	$path .= '/'.$part;
12954: 	if (!-e $path) {
12955: 	    mkdir($path,0770);
12956: 	}
12957:     }
12958: # now the path exists for sure
12959: # get a user agent
12960:     my $transferfile=$file.'.in.transfer';
12961: # FIXME: this should flock
12962:     if (-e $transferfile) { return 'ok'; }
12963:     my $request;
12964:     $uri=~s/^\///;
12965:     my $homeserver = &homeserver($cnum,$cdom);
12966:     my $protocol = $protocol{$homeserver};
12967:     $protocol = 'http' if ($protocol ne 'https');
12968:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
12969:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
12970: # did it work?
12971:     if ($response->is_error()) {
12972: 	unlink($transferfile);
12973: 	&logthis("Userfile repcopy failed for $uri");
12974: 	return -1;
12975:     }
12976: # worked, rename the transfer file
12977:     rename($transferfile,$file);
12978:     return 'ok';
12979: }
12980: 
12981: sub tokenwrapper {
12982:     my $uri=shift;
12983:     $uri=~s|^https?\://([^/]+)||;
12984:     $uri=~s|^/||;
12985:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
12986:     my $token=$1;
12987:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
12988:     if ($udom && $uname && $file) {
12989: 	$file=~s|(\?\.*)*$||;
12990:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
12991:         my $homeserver = &homeserver($uname,$udom);
12992:         my $protocol = $protocol{$homeserver};
12993:         $protocol = 'http' if ($protocol ne 'https');
12994:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
12995:                (($uri=~/\?/)?'&':'?').'token='.$token.
12996:                                '&tokenissued='.$perlvar{'lonHostID'};
12997:     } else {
12998:         return '/adm/notfound.html';
12999:     }
13000: }
13001: 
13002: # call with reqtype HEAD: get last modification time
13003: # call with reqtype GET: get the file contents
13004: # Do not call this with reqtype GET for large files! It loads everything into memory
13005: #
13006: sub getuploaded {
13007:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
13008:     $uri=~s/^\///;
13009:     my $homeserver = &homeserver($cnum,$cdom);
13010:     my $protocol = $protocol{$homeserver};
13011:     $protocol = 'http' if ($protocol ne 'https');
13012:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
13013:     my $request=new HTTP::Request($reqtype,$uri);
13014:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
13015:     $$rtncode = $response->code;
13016:     if (! $response->is_success()) {
13017: 	return 'failed';
13018:     }      
13019:     if ($reqtype eq 'HEAD') {
13020: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
13021:     } elsif ($reqtype eq 'GET') {
13022: 	$$info = $response->content;
13023:     }
13024:     return 'ok';
13025: }
13026: 
13027: sub readfile {
13028:     my $file = shift;
13029:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
13030:     my $fh;
13031:     open($fh,"<$file");
13032:     my $a='';
13033:     while (my $line = <$fh>) { $a .= $line; }
13034:     return $a;
13035: }
13036: 
13037: sub filelocation {
13038:     my ($dir,$file) = @_;
13039:     my $location;
13040:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
13041: 
13042:     if ($file =~ m-^/adm/-) {
13043: 	$file=~s-^/adm/wrapper/-/-;
13044: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
13045:     }
13046: 
13047:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
13048:         $location = $file;
13049:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
13050:         my ($udom,$uname,$filename)=
13051:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
13052:         my $home=&homeserver($uname,$udom);
13053:         my $is_me=0;
13054:         my @ids=&current_machine_ids();
13055:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
13056:         if ($is_me) {
13057:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
13058:         } else {
13059:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
13060:   	      $udom.'/'.$uname.'/'.$filename;
13061:         }
13062:     } elsif ($file =~ m-^/adm/-) {
13063: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
13064:     } else {
13065:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
13066:         $file=~s:^/(res|priv)/:/:;
13067:         my $space=$1;
13068:         if ( !( $file =~ m:^/:) ) {
13069:             $location = $dir. '/'.$file;
13070:         } else {
13071:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
13072:         }
13073:     }
13074:     $location=~s://+:/:g; # remove duplicate /
13075:     while ($location=~m{/\.\./}) {
13076: 	if ($location =~ m{/[^/]+/\.\./}) {
13077: 	    $location=~ s{/[^/]+/\.\./}{/}g;
13078: 	} else {
13079: 	    $location=~ s{/\.\./}{/}g;
13080: 	}
13081:     } #remove dir/..
13082:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
13083:     return $location;
13084: }
13085: 
13086: sub hreflocation {
13087:     my ($dir,$file)=@_;
13088:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
13089: 	$file=filelocation($dir,$file);
13090:     } elsif ($file=~m-^/adm/-) {
13091: 	$file=~s-^/adm/wrapper/-/-;
13092: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
13093:     }
13094:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
13095: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
13096:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
13097: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
13098: 	        {/uploaded/$1/$2/}x;
13099:     }
13100:     if ($file=~ m{^/userfiles/}) {
13101: 	$file =~ s{^/userfiles/}{/uploaded/};
13102:     }
13103:     return $file;
13104: }
13105: 
13106: 
13107: 
13108: 
13109: 
13110: sub current_machine_domains {
13111:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
13112: }
13113: 
13114: sub machine_domains {
13115:     my ($hostname) = @_;
13116:     my @domains;
13117:     my %hostname = &all_hostnames();
13118:     while( my($id, $name) = each(%hostname)) {
13119: #	&logthis("-$id-$name-$hostname-");
13120: 	if ($hostname eq $name) {
13121: 	    push(@domains,&host_domain($id));
13122: 	}
13123:     }
13124:     return @domains;
13125: }
13126: 
13127: sub current_machine_ids {
13128:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
13129: }
13130: 
13131: sub machine_ids {
13132:     my ($hostname) = @_;
13133:     $hostname ||= &hostname($perlvar{'lonHostID'});
13134:     my @ids;
13135:     my %name_to_host = &all_names();
13136:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
13137: 	return @{ $name_to_host{$hostname} };
13138:     }
13139:     return;
13140: }
13141: 
13142: sub additional_machine_domains {
13143:     my @domains;
13144:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
13145:     while( my $line = <$fh>) {
13146:         $line =~ s/\s//g;
13147:         push(@domains,$line);
13148:     }
13149:     return @domains;
13150: }
13151: 
13152: sub default_login_domain {
13153:     my $domain = $perlvar{'lonDefDomain'};
13154:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
13155:     foreach my $posdom (&current_machine_domains(),
13156:                         &additional_machine_domains()) {
13157:         if (lc($posdom) eq lc($testdomain)) {
13158:             $domain=$posdom;
13159:             last;
13160:         }
13161:     }
13162:     return $domain;
13163: }
13164: 
13165: # ------------------------------------------------------------- Declutters URLs
13166: 
13167: sub declutter {
13168:     my $thisfn=shift;
13169:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
13170:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
13171:         $thisfn=~s{^/home/httpd/html}{};
13172:     }
13173:     $thisfn=~s/^\///;
13174:     $thisfn=~s|^adm/wrapper/||;
13175:     $thisfn=~s|^adm/coursedocs/showdoc/||;
13176:     $thisfn=~s/^res\///;
13177:     $thisfn=~s/^priv\///;
13178:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
13179:         $thisfn=~s/\?.+$//;
13180:     }
13181:     return $thisfn;
13182: }
13183: 
13184: # ------------------------------------------------------------- Clutter up URLs
13185: 
13186: sub clutter {
13187:     my $thisfn='/'.&declutter(shift);
13188:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
13189: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
13190:        $thisfn='/res'.$thisfn; 
13191:     }
13192:     if ($thisfn !~m|^/adm|) {
13193: 	if ($thisfn =~ m|^/ext/|) {
13194: 	    $thisfn='/adm/wrapper'.$thisfn;
13195: 	} else {
13196: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
13197: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
13198: 	    if ($embstyle eq 'ssi'
13199: 		|| ($embstyle eq 'hdn')
13200: 		|| ($embstyle eq 'rat')
13201: 		|| ($embstyle eq 'prv')
13202: 		|| ($embstyle eq 'ign')) {
13203: 		#do nothing with these
13204: 	    } elsif (($embstyle eq 'img') 
13205: 		|| ($embstyle eq 'emb')
13206: 		|| ($embstyle eq 'wrp')) {
13207: 		$thisfn='/adm/wrapper'.$thisfn;
13208: 	    } elsif ($embstyle eq 'unk'
13209: 		     && $thisfn!~/\.(sequence|page)$/) {
13210: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
13211: 	    } else {
13212: #		&logthis("Got a blank emb style");
13213: 	    }
13214: 	}
13215:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
13216:         $thisfn='/adm/wrapper'.$thisfn;
13217:     }
13218:     return $thisfn;
13219: }
13220: 
13221: sub clutter_with_no_wrapper {
13222:     my $uri = &clutter(shift);
13223:     if ($uri =~ m-^/adm/-) {
13224: 	$uri =~ s-^/adm/wrapper/-/-;
13225: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
13226:     }
13227:     return $uri;
13228: }
13229: 
13230: sub freeze_escape {
13231:     my ($value)=@_;
13232:     if (ref($value)) {
13233: 	$value=&nfreeze($value);
13234: 	return '__FROZEN__'.&escape($value);
13235:     }
13236:     return &escape($value);
13237: }
13238: 
13239: 
13240: sub thaw_unescape {
13241:     my ($value)=@_;
13242:     if ($value =~ /^__FROZEN__/) {
13243: 	substr($value,0,10,undef);
13244: 	$value=&unescape($value);
13245: 	return &thaw($value);
13246:     }
13247:     return &unescape($value);
13248: }
13249: 
13250: sub correct_line_ends {
13251:     my ($result)=@_;
13252:     $$result =~s/\r\n/\n/mg;
13253:     $$result =~s/\r/\n/mg;
13254: }
13255: # ================================================================ Main Program
13256: 
13257: sub goodbye {
13258:    &logthis("Starting Shut down");
13259: #not converted to using infrastruture and probably shouldn't be
13260:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
13261: #converted
13262: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
13263:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
13264: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
13265: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
13266: #1.1 only
13267: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
13268: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
13269: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
13270: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
13271:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
13272:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
13273:    &logthis(sprintf("%-20s is %s",'hits',$hits));
13274:    &flushcourselogs();
13275:    &logthis("Shutting down");
13276: }
13277: 
13278: sub get_dns {
13279:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
13280:     if (!$ignore_cache) {
13281: 	my ($content,$cached)=
13282: 	    &Apache::lonnet::is_cached_new('dns',$url);
13283: 	if ($cached) {
13284: 	    &$func($content,$hashref);
13285: 	    return;
13286: 	}
13287:     }
13288: 
13289:     my %alldns;
13290:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
13291:     foreach my $dns (<$config>) {
13292: 	next if ($dns !~ /^\^(\S*)/x);
13293:         my $line = $1;
13294:         my ($host,$protocol) = split(/:/,$line);
13295:         if ($protocol ne 'https') {
13296:             $protocol = 'http';
13297:         }
13298: 	$alldns{$host} = $protocol;
13299:     }
13300:     while (%alldns) {
13301: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
13302: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
13303:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
13304:         delete($alldns{$dns});
13305: 	next if ($response->is_error());
13306: 	my @content = split("\n",$response->content);
13307: 	unless ($nocache) {
13308: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
13309: 	}
13310: 	&$func(\@content,$hashref);
13311: 	return;
13312:     }
13313:     close($config);
13314:     my $which = (split('/',$url))[3];
13315:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
13316:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
13317:     my @content = <$config>;
13318:     &$func(\@content,$hashref);
13319:     return;
13320: }
13321: 
13322: # ------------------------------------------------------Get DNS checksums file
13323: sub parse_dns_checksums_tab {
13324:     my ($lines,$hashref) = @_;
13325:     my $lonhost = $perlvar{'lonHostID'};
13326:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
13327:     my $loncaparev = &get_server_loncaparev($machine_dom);
13328:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
13329:     my $webconfdir = '/etc/httpd/conf';
13330:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
13331:         $webconfdir = '/etc/apache2';
13332:     } elsif ($distro =~ /^sles(\d+)$/) {
13333:         if ($1 >= 10) {
13334:             $webconfdir = '/etc/apache2';
13335:         }
13336:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
13337:         if ($1 >= 10.0) {
13338:             $webconfdir = '/etc/apache2';
13339:         }
13340:     }
13341:     my ($release,$timestamp) = split(/\-/,$loncaparev);
13342:     my (%chksum,%revnum);
13343:     if (ref($lines) eq 'ARRAY') {
13344:         chomp(@{$lines});
13345:         my $version = shift(@{$lines});
13346:         if ($version eq $release) {  
13347:             foreach my $line (@{$lines}) {
13348:                 my ($file,$version,$shasum) = split(/,/,$line);
13349:                 if ($file =~ m{^/etc/httpd/conf}) {
13350:                     if ($webconfdir eq '/etc/apache2') {
13351:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
13352:                     }
13353:                 }
13354:                 $chksum{$file} = $shasum;
13355:                 $revnum{$file} = $version;
13356:             }
13357:             if (ref($hashref) eq 'HASH') {
13358:                 %{$hashref} = (
13359:                                 sums     => \%chksum,
13360:                                 versions => \%revnum,
13361:                               );
13362:             }
13363:         }
13364:     }
13365:     return;
13366: }
13367: 
13368: sub fetch_dns_checksums {
13369:     my %checksums;
13370:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
13371:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
13372:     my ($release,$timestamp) = split(/\-/,$loncaparev);
13373:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
13374:              \%checksums);
13375:     return \%checksums;
13376: }
13377: 
13378: # ------------------------------------------------------------ Read domain file
13379: {
13380:     my $loaded;
13381:     my %domain;
13382: 
13383:     sub parse_domain_tab {
13384: 	my ($lines) = @_;
13385: 	foreach my $line (@$lines) {
13386: 	    next if ($line =~ /^(\#|\s*$ )/x);
13387: 
13388: 	    chomp($line);
13389: 	    my ($name,@elements) = split(/:/,$line,9);
13390: 	    my %this_domain;
13391: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
13392: 			       'lang_def', 'city', 'longi', 'lati',
13393: 			       'primary') {
13394: 		$this_domain{$field} = shift(@elements);
13395: 	    }
13396: 	    $domain{$name} = \%this_domain;
13397: 	}
13398:     }
13399: 
13400:     sub reset_domain_info {
13401: 	undef($loaded);
13402: 	undef(%domain);
13403:     }
13404: 
13405:     sub load_domain_tab {
13406: 	my ($ignore_cache,$nocache) = @_;
13407: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
13408: 	my $fh;
13409: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
13410: 	    my @lines = <$fh>;
13411: 	    &parse_domain_tab(\@lines);
13412: 	}
13413: 	close($fh);
13414: 	$loaded = 1;
13415:     }
13416: 
13417:     sub domain {
13418: 	&load_domain_tab() if (!$loaded);
13419: 
13420: 	my ($name,$what) = @_;
13421: 	return if ( !exists($domain{$name}) );
13422: 
13423: 	if (!$what) {
13424: 	    return $domain{$name}{'description'};
13425: 	}
13426: 	return $domain{$name}{$what};
13427:     }
13428: 
13429:     sub domain_info {
13430:         &load_domain_tab() if (!$loaded);
13431:         return %domain;
13432:     }
13433: 
13434: }
13435: 
13436: 
13437: # ------------------------------------------------------------- Read hosts file
13438: {
13439:     my %hostname;
13440:     my %hostdom;
13441:     my %libserv;
13442:     my $loaded;
13443:     my %name_to_host;
13444:     my %internetdom;
13445:     my %LC_dns_serv;
13446: 
13447:     sub parse_hosts_tab {
13448: 	my ($file) = @_;
13449: 	foreach my $configline (@$file) {
13450: 	    next if ($configline =~ /^(\#|\s*$ )/x);
13451:             chomp($configline);
13452: 	    if ($configline =~ /^\^/) {
13453:                 if ($configline =~ /^\^([\w.\-]+)/) {
13454:                     $LC_dns_serv{$1} = 1;
13455:                 }
13456:                 next;
13457:             }
13458: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
13459: 	    $name=~s/\s//g;
13460: 	    if ($id && $domain && $role && $name) {
13461:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
13462:                     my $curr = $hostname{$id};
13463:                     my $skip;
13464:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
13465:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
13466:                             $skip = 1;
13467:                         } else {
13468:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
13469:                         }
13470:                     }
13471:                     unless ($skip) {
13472:                         push(@{$name_to_host{$name}},$id);
13473:                     }
13474:                 } else {
13475:                     push(@{$name_to_host{$name}},$id);
13476:                 }
13477: 		$hostname{$id}=$name;
13478: 		$hostdom{$id}=$domain;
13479: 		if ($role eq 'library') { $libserv{$id}=$name; }
13480:                 if (defined($protocol)) {
13481:                     if ($protocol eq 'https') {
13482:                         $protocol{$id} = $protocol;
13483:                     } else {
13484:                         $protocol{$id} = 'http'; 
13485:                     }
13486:                 } else {
13487:                     $protocol{$id} = 'http';
13488:                 }
13489:                 if (defined($intdom)) {
13490:                     $internetdom{$id} = $intdom;
13491:                 }
13492: 	    }
13493: 	}
13494:     }
13495:     
13496:     sub reset_hosts_info {
13497: 	&purge_remembered();
13498: 	&reset_domain_info();
13499: 	&reset_hosts_ip_info();
13500:         undef(%internetdom);
13501: 	undef(%name_to_host);
13502: 	undef(%hostname);
13503: 	undef(%hostdom);
13504: 	undef(%libserv);
13505: 	undef($loaded);
13506:     }
13507: 
13508:     sub load_hosts_tab {
13509: 	my ($ignore_cache,$nocache) = @_;
13510: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
13511: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
13512: 	my @config = <$config>;
13513: 	&parse_hosts_tab(\@config);
13514: 	close($config);
13515: 	$loaded=1;
13516:     }
13517: 
13518:     sub hostname {
13519: 	&load_hosts_tab() if (!$loaded);
13520: 
13521: 	my ($lonid) = @_;
13522: 	return $hostname{$lonid};
13523:     }
13524: 
13525:     sub all_hostnames {
13526: 	&load_hosts_tab() if (!$loaded);
13527: 
13528: 	return %hostname;
13529:     }
13530: 
13531:     sub all_names {
13532:         my ($ignore_cache,$nocache) = @_;
13533: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
13534: 
13535: 	return %name_to_host;
13536:     }
13537: 
13538:     sub all_host_domain {
13539:         &load_hosts_tab() if (!$loaded);
13540:         return %hostdom;
13541:     }
13542: 
13543:     sub all_host_intdom {
13544:         &load_hosts_tab() if (!$loaded);
13545:         return %internetdom;
13546:     }
13547: 
13548:     sub is_library {
13549: 	&load_hosts_tab() if (!$loaded);
13550: 
13551: 	return exists($libserv{$_[0]});
13552:     }
13553: 
13554:     sub all_library {
13555: 	&load_hosts_tab() if (!$loaded);
13556: 
13557: 	return %libserv;
13558:     }
13559: 
13560:     sub unique_library {
13561: 	#2x reverse removes all hostnames that appear more than once
13562:         my %unique = reverse &all_library();
13563:         return reverse %unique;
13564:     }
13565: 
13566:     sub get_servers {
13567: 	&load_hosts_tab() if (!$loaded);
13568: 
13569: 	my ($domain,$type) = @_;
13570: 	my %possible_hosts = ($type eq 'library') ? %libserv
13571: 	                                          : %hostname;
13572: 	my %result;
13573: 	if (ref($domain) eq 'ARRAY') {
13574: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
13575: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
13576: 		    $result{$host} = $hostname;
13577: 		}
13578: 	    }
13579: 	} else {
13580: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
13581: 		if ($hostdom{$host} eq $domain) {
13582: 		    $result{$host} = $hostname;
13583: 		}
13584: 	    }
13585: 	}
13586: 	return %result;
13587:     }
13588: 
13589:     sub get_unique_servers {
13590:         my %unique = reverse &get_servers(@_);
13591: 	return reverse %unique;
13592:     }
13593: 
13594:     sub host_domain {
13595: 	&load_hosts_tab() if (!$loaded);
13596: 
13597: 	my ($lonid) = @_;
13598: 	return $hostdom{$lonid};
13599:     }
13600: 
13601:     sub all_domains {
13602: 	&load_hosts_tab() if (!$loaded);
13603: 
13604: 	my %seen;
13605: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
13606: 	return @uniq;
13607:     }
13608: 
13609:     sub internet_dom {
13610:         &load_hosts_tab() if (!$loaded);
13611: 
13612:         my ($lonid) = @_;
13613:         return $internetdom{$lonid};
13614:     }
13615: 
13616:     sub is_LC_dns {
13617:         &load_hosts_tab() if (!$loaded);
13618: 
13619:         my ($hostname) = @_;
13620:         return exists($LC_dns_serv{$hostname});
13621:     }
13622: 
13623: }
13624: 
13625: { 
13626:     my %iphost;
13627:     my %name_to_ip;
13628:     my %lonid_to_ip;
13629: 
13630:     sub get_hosts_from_ip {
13631: 	my ($ip) = @_;
13632: 	my %iphosts = &get_iphost();
13633: 	if (ref($iphosts{$ip})) {
13634: 	    return @{$iphosts{$ip}};
13635: 	}
13636: 	return;
13637:     }
13638:     
13639:     sub reset_hosts_ip_info {
13640: 	undef(%iphost);
13641: 	undef(%name_to_ip);
13642: 	undef(%lonid_to_ip);
13643:     }
13644: 
13645:     sub get_host_ip {
13646: 	my ($lonid) = @_;
13647: 	if (exists($lonid_to_ip{$lonid})) {
13648: 	    return $lonid_to_ip{$lonid};
13649: 	}
13650: 	my $name=&hostname($lonid);
13651:    	my $ip = gethostbyname($name);
13652: 	return if (!$ip || length($ip) ne 4);
13653: 	$ip=inet_ntoa($ip);
13654: 	$name_to_ip{$name}   = $ip;
13655: 	$lonid_to_ip{$lonid} = $ip;
13656: 	return $ip;
13657:     }
13658:     
13659:     sub get_iphost {
13660: 	my ($ignore_cache,$nocache) = @_;
13661: 
13662: 	if (!$ignore_cache) {
13663: 	    if (%iphost) {
13664: 		return %iphost;
13665: 	    }
13666: 	    my ($ip_info,$cached)=
13667: 		&Apache::lonnet::is_cached_new('iphost','iphost');
13668: 	    if ($cached) {
13669: 		%iphost      = %{$ip_info->[0]};
13670: 		%name_to_ip  = %{$ip_info->[1]};
13671: 		%lonid_to_ip = %{$ip_info->[2]};
13672: 		return %iphost;
13673: 	    }
13674: 	}
13675: 
13676: 	# get yesterday's info for fallback
13677: 	my %old_name_to_ip;
13678: 	my ($ip_info,$cached)=
13679: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
13680: 	if ($cached) {
13681: 	    %old_name_to_ip = %{$ip_info->[1]};
13682: 	}
13683: 
13684: 	my %name_to_host = &all_names($ignore_cache,$nocache);
13685: 	foreach my $name (keys(%name_to_host)) {
13686: 	    my $ip;
13687: 	    if (!exists($name_to_ip{$name})) {
13688: 		$ip = gethostbyname($name);
13689: 		if (!$ip || length($ip) ne 4) {
13690: 		    if (defined($old_name_to_ip{$name})) {
13691: 			$ip = $old_name_to_ip{$name};
13692: 			&logthis("Can't find $name defaulting to old $ip");
13693: 		    } else {
13694: 			&logthis("Name $name no IP found");
13695: 			next;
13696: 		    }
13697: 		} else {
13698: 		    $ip=inet_ntoa($ip);
13699: 		}
13700: 		$name_to_ip{$name} = $ip;
13701: 	    } else {
13702: 		$ip = $name_to_ip{$name};
13703: 	    }
13704: 	    foreach my $id (@{ $name_to_host{$name} }) {
13705: 		$lonid_to_ip{$id} = $ip;
13706: 	    }
13707: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
13708: 	}
13709:         unless ($nocache) {
13710: 	    &do_cache_new('iphost','iphost',
13711: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
13712: 		          48*60*60);
13713:         }
13714: 
13715: 	return %iphost;
13716:     }
13717: 
13718:     #
13719:     #  Given a DNS returns the loncapa host name for that DNS 
13720:     # 
13721:     sub host_from_dns {
13722:         my ($dns) = @_;
13723:         my @hosts;
13724:         my $ip;
13725: 
13726:         if (exists($name_to_ip{$dns})) {
13727:             $ip = $name_to_ip{$dns};
13728:         }
13729:         if (!$ip) {
13730:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
13731:             if (length($ip) == 4) { 
13732: 	        $ip   = &IO::Socket::inet_ntoa($ip);
13733:             }
13734:         }
13735:         if ($ip) {
13736: 	    @hosts = get_hosts_from_ip($ip);
13737: 	    return $hosts[0];
13738:         }
13739:         return undef;
13740:     }
13741: 
13742:     sub get_internet_names {
13743:         my ($lonid) = @_;
13744:         return if ($lonid eq '');
13745:         my ($idnref,$cached)=
13746:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
13747:         if ($cached) {
13748:             return $idnref;
13749:         }
13750:         my $ip = &get_host_ip($lonid);
13751:         my @hosts = &get_hosts_from_ip($ip);
13752:         my %iphost = &get_iphost();
13753:         my (@idns,%seen);
13754:         foreach my $id (@hosts) {
13755:             my $dom = &host_domain($id);
13756:             my $prim_id = &domain($dom,'primary');
13757:             my $prim_ip = &get_host_ip($prim_id);
13758:             next if ($seen{$prim_ip});
13759:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
13760:                 foreach my $id (@{$iphost{$prim_ip}}) {
13761:                     my $intdom = &internet_dom($id);
13762:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
13763:                         push(@idns,$intdom);
13764:                     }
13765:                 }
13766:             }
13767:             $seen{$prim_ip} = 1;
13768:         }
13769:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
13770:     }
13771: 
13772: }
13773: 
13774: sub all_loncaparevs {
13775:     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);
13776: }
13777: 
13778: # ---------------------------------------------------------- Read loncaparev table
13779: {
13780:     sub load_loncaparevs { 
13781:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
13782:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
13783:                 while (my $configline=<$config>) {
13784:                     chomp($configline);
13785:                     my ($hostid,$loncaparev)=split(/:/,$configline);
13786:                     $loncaparevs{$hostid}=$loncaparev;
13787:                 }
13788:                 close($config);
13789:             }
13790:         }
13791:     }
13792: }
13793: 
13794: # ---------------------------------------------------------- Read serverhostID table
13795: {
13796:     sub load_serverhomeIDs {
13797:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
13798:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
13799:                 while (my $configline=<$config>) {
13800:                     chomp($configline);
13801:                     my ($name,$id)=split(/:/,$configline);
13802:                     $serverhomeIDs{$name}=$id;
13803:                 }
13804:                 close($config);
13805:             }
13806:         }
13807:     }
13808: }
13809: 
13810: 
13811: BEGIN {
13812: 
13813: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
13814:     unless ($readit) {
13815: {
13816:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
13817:     %perlvar = (%perlvar,%{$configvars});
13818: }
13819: 
13820: 
13821: # ------------------------------------------------------ Read spare server file
13822: {
13823:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
13824: 
13825:     while (my $configline=<$config>) {
13826:        chomp($configline);
13827:        if ($configline) {
13828: 	   my ($host,$type) = split(':',$configline,2);
13829: 	   if (!defined($type) || $type eq '') { $type = 'default' };
13830: 	   push(@{ $spareid{$type} }, $host);
13831:        }
13832:     }
13833:     close($config);
13834: }
13835: # ------------------------------------------------------------ Read permissions
13836: {
13837:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
13838: 
13839:     while (my $configline=<$config>) {
13840: 	chomp($configline);
13841: 	if ($configline) {
13842: 	    my ($role,$perm)=split(/ /,$configline);
13843: 	    if ($perm ne '') { $pr{$role}=$perm; }
13844: 	}
13845:     }
13846:     close($config);
13847: }
13848: 
13849: # -------------------------------------------- Read plain texts for permissions
13850: {
13851:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
13852: 
13853:     while (my $configline=<$config>) {
13854: 	chomp($configline);
13855: 	if ($configline) {
13856: 	    my ($short,@plain)=split(/:/,$configline);
13857:             %{$prp{$short}} = ();
13858: 	    if (@plain > 0) {
13859:                 $prp{$short}{'std'} = $plain[0];
13860:                 for (my $i=1; $i<@plain; $i++) {
13861:                     $prp{$short}{'alt'.$i} = $plain[$i];  
13862:                 }
13863:             }
13864: 	}
13865:     }
13866:     close($config);
13867: }
13868: 
13869: # ---------------------------------------------------------- Read package table
13870: {
13871:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
13872: 
13873:     while (my $configline=<$config>) {
13874: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
13875: 	chomp($configline);
13876: 	my ($short,$plain)=split(/:/,$configline);
13877: 	my ($pack,$name)=split(/\&/,$short);
13878: 	if ($plain ne '') {
13879: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
13880: 	    $packagetab{$short}=$plain; 
13881: 	}
13882:     }
13883:     close($config);
13884: }
13885: 
13886: # ---------------------------------------------------------- Read loncaparev table
13887: 
13888: &load_loncaparevs();
13889: 
13890: # ---------------------------------------------------------- Read serverhostID table
13891: 
13892: &load_serverhomeIDs();
13893: 
13894: # ---------------------------------------------------------- Read releaseslist XML
13895: {
13896:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
13897:     if (-e $file) {
13898:         my $parser = HTML::LCParser->new($file);
13899:         while (my $token = $parser->get_token()) {
13900:             if ($token->[0] eq 'S') {
13901:                 my $item = $token->[1];
13902:                 my $name = $token->[2]{'name'};
13903:                 my $value = $token->[2]{'value'};
13904:                 my $valuematch = $token->[2]{'valuematch'};
13905:                 my $namematch = $token->[2]{'namematch'};
13906:                 if ($item eq 'parameter') {
13907:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
13908:                         my $release = $parser->get_text();
13909:                         $release =~ s/(^\s*|\s*$ )//gx;
13910:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
13911:                     }
13912:                 } elsif ($item ne '' && $name ne '') {
13913:                     my $release = $parser->get_text();
13914:                     $release =~ s/(^\s*|\s*$ )//gx;
13915:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
13916:                 }
13917:             }
13918:         }
13919:     }
13920: }
13921: 
13922: # ---------------------------------------------------------- Read managers table
13923: {
13924:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
13925:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
13926:             while (my $configline=<$config>) {
13927:                 chomp($configline);
13928:                 next if ($configline =~ /^\#/);
13929:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
13930:                     $managerstab{$configline} = 1;
13931:                 }
13932:             }
13933:             close($config);
13934:         }
13935:     }
13936: }
13937: 
13938: # ------------- set up temporary directory
13939: {
13940:     $tmpdir = LONCAPA::tempdir();
13941: 
13942: }
13943: 
13944: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
13945: 				'compress_threshold'=> 20_000,
13946:  			        });
13947: 
13948: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
13949: $dumpcount=0;
13950: $locknum=0;
13951: 
13952: &logtouch();
13953: &logthis('<font color="yellow">INFO: Read configuration</font>');
13954: $readit=1;
13955:     {
13956: 	use integer;
13957: 	my $test=(2**32)+1;
13958: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
13959: 	&logthis(" Detected 64bit platform ($_64bit)");
13960:     }
13961: }
13962: }
13963: 
13964: 1;
13965: __END__
13966: 
13967: =pod
13968: 
13969: =head1 NAME
13970: 
13971: Apache::lonnet - Subroutines to ask questions about things in the network.
13972: 
13973: =head1 SYNOPSIS
13974: 
13975: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
13976: 
13977:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
13978: 
13979: Common parameters:
13980: 
13981: =over 4
13982: 
13983: =item *
13984: 
13985: $uname : an internal username (if $cname expecting a course Id specifically)
13986: 
13987: =item *
13988: 
13989: $udom : a domain (if $cdom expecting a course's domain specifically)
13990: 
13991: =item *
13992: 
13993: $symb : a resource instance identifier
13994: 
13995: =item *
13996: 
13997: $namespace : the name of a .db file that contains the data needed or
13998: being set.
13999: 
14000: =back
14001: 
14002: =head1 OVERVIEW
14003: 
14004: lonnet provides subroutines which interact with the
14005: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
14006: about classes, users, and resources.
14007: 
14008: For many of these objects you can also use this to store data about
14009: them or modify them in various ways.
14010: 
14011: =head2 Symbs
14012: 
14013: To identify a specific instance of a resource, LON-CAPA uses symbols
14014: or "symbs"X<symb>. These identifiers are built from the URL of the
14015: map, the resource number of the resource in the map, and the URL of
14016: the resource itself. The latter is somewhat redundant, but might help
14017: if maps change.
14018: 
14019: An example is
14020: 
14021:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
14022: 
14023: The respective map entry is
14024: 
14025:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
14026:   title="Problem 2">
14027:  </resource>
14028: 
14029: Symbs are used by the random number generator, as well as to store and
14030: restore data specific to a certain instance of for example a problem.
14031: 
14032: =head2 Storing And Retrieving Data
14033: 
14034: X<store()>X<cstore()>X<restore()>Three of the most important functions
14035: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
14036: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
14037: is is the non-critical message twin of cstore. These functions are for
14038: handlers to store a perl hash to a user's permanent data space in an
14039: easy manner, and to retrieve it again on another call. It is expected
14040: that a handler would use this once at the beginning to retrieve data,
14041: and then again once at the end to send only the new data back.
14042: 
14043: The data is stored in the user's data directory on the user's
14044: homeserver under the ID of the course.
14045: 
14046: The hash that is returned by restore will have all of the previous
14047: value for all of the elements of the hash.
14048: 
14049: Example:
14050: 
14051:  #creating a hash
14052:  my %hash;
14053:  $hash{'foo'}='bar';
14054: 
14055:  #storing it
14056:  &Apache::lonnet::cstore(\%hash);
14057: 
14058:  #changing a value
14059:  $hash{'foo'}='notbar';
14060: 
14061:  #adding a new value
14062:  $hash{'bar'}='foo';
14063:  &Apache::lonnet::cstore(\%hash);
14064: 
14065:  #retrieving the hash
14066:  my %history=&Apache::lonnet::restore();
14067: 
14068:  #print the hash
14069:  foreach my $key (sort(keys(%history))) {
14070:    print("\%history{$key} = $history{$key}");
14071:  }
14072: 
14073: Will print out:
14074: 
14075:  %history{1:foo} = bar
14076:  %history{1:keys} = foo:timestamp
14077:  %history{1:timestamp} = 990455579
14078:  %history{2:bar} = foo
14079:  %history{2:foo} = notbar
14080:  %history{2:keys} = foo:bar:timestamp
14081:  %history{2:timestamp} = 990455580
14082:  %history{bar} = foo
14083:  %history{foo} = notbar
14084:  %history{timestamp} = 990455580
14085:  %history{version} = 2
14086: 
14087: Note that the special hash entries C<keys>, C<version> and
14088: C<timestamp> were added to the hash. C<version> will be equal to the
14089: total number of versions of the data that have been stored. The
14090: C<timestamp> attribute will be the UNIX time the hash was
14091: stored. C<keys> is available in every historical section to list which
14092: keys were added or changed at a specific historical revision of a
14093: hash.
14094: 
14095: B<Warning>: do not store the hash that restore returns directly. This
14096: will cause a mess since it will restore the historical keys as if the
14097: were new keys. I.E. 1:foo will become 1:1:foo etc.
14098: 
14099: Calling convention:
14100: 
14101:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
14102:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
14103: 
14104: For more detailed information, see lonnet specific documentation.
14105: 
14106: =head1 RETURN MESSAGES
14107: 
14108: =over 4
14109: 
14110: =item * B<con_lost>: unable to contact remote host
14111: 
14112: =item * B<con_delayed>: unable to contact remote host, message will be delivered
14113: when the connection is brought back up
14114: 
14115: =item * B<con_failed>: unable to contact remote host and unable to save message
14116: for later delivery
14117: 
14118: =item * B<error:>: an error a occurred, a description of the error follows the :
14119: 
14120: =item * B<no_such_host>: unable to fund a host associated with the user/domain
14121: that was requested
14122: 
14123: =back
14124: 
14125: =head1 PUBLIC SUBROUTINES
14126: 
14127: =head2 Session Environment Functions
14128: 
14129: =over 4
14130: 
14131: =item * 
14132: X<appenv()>
14133: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
14134: the user envirnoment file, and will be restored for each access this
14135: user makes during this session, also modifies the %env for the current
14136: process. Optional rolesarrayref - if defined contains a reference to an array
14137: of roles which are exempt from the restriction on modifying user.role entries 
14138: in the user's environment.db and in %env.    
14139: 
14140: =item *
14141: X<delenv()>
14142: B<delenv($delthis,$regexp)>: removes all items from the session
14143: environment file that begin with $delthis. If the 
14144: optional second arg - $regexp - is true, $delthis is treated as a 
14145: regular expression, otherwise \Q$delthis\E is used. 
14146: The values are also deleted from the current processes %env.
14147: 
14148: =item * get_env_multiple($name) 
14149: 
14150: gets $name from the %env hash, it seemlessly handles the cases where multiple
14151: values may be defined and end up as an array ref.
14152: 
14153: returns an array of values
14154: 
14155: =back
14156: 
14157: =head2 User Information
14158: 
14159: =over 4
14160: 
14161: =item *
14162: X<queryauthenticate()>
14163: B<queryauthenticate($uname,$udom)>: try to determine user's current 
14164: authentication scheme
14165: 
14166: =item *
14167: X<authenticate()>
14168: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
14169: authenticate user from domain's lib servers (first use the current
14170: one). C<$upass> should be the users password.
14171: $checkdefauth is optional (value is 1 if a check should be made to
14172:    authenticate user using default authentication method, and allow
14173:    account creation if username does not have account in the domain).
14174: $clientcancheckhost is optional (value is 1 if checking whether the
14175:    server can host will occur on the client side in lonauth.pm).   
14176: 
14177: =item *
14178: X<homeserver()>
14179: B<homeserver($uname,$udom)>: find the server which has
14180: the user's directory and files (there must be only one), this caches
14181: the answer, and also caches if there is a borken connection.
14182: 
14183: =item *
14184: X<idget()>
14185: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
14186: a list of student/employee IDs or clicker IDs
14187: (student/employee IDs are a unique resource in a domain, there must be 
14188: only 1 ID per username, and only 1 username per ID in a specific domain).
14189: clickerIDs are not necessarily unique, as students might share clickers.
14190: (returns hash: id=>name,id=>name)
14191: 
14192: =item *
14193: X<idrget()>
14194: B<idrget($udom,@unames)>: find the IDs behind a list of
14195: usernames (returns hash: name=>id,name=>id)
14196: 
14197: =item *
14198: X<idput()>
14199: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
14200: names and associated student/employee IDs or clicker IDs.
14201: 
14202: =item *
14203: X<iddel()>
14204: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
14205: student/employee ID or clicker ID username look-ups from domain.
14206: The homeserver ($uhome) and namespace ($namespace) are optional.
14207: If no $uhome is provided, it will be determined usig &homeserver()
14208: for each user.  If no $namespace is provided, the default is ids.
14209: 
14210: =item *
14211: X<updateclickers()>
14212: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
14213: clicker ID-to-username look-ups in clickers.db on library server.
14214: Permitted actions are add or del (i.e., add or delete). The 
14215: clickers.db contains clickerID as keys (escaped), and each corresponding
14216: value is an escaped comma-separated list of usernames (for whom the
14217: library server is the homeserver), who registered that particular ID.
14218: If $critical is true, the update will be sent via &critical, otherwise
14219: &reply() will be used.
14220: 
14221: =item *
14222: X<rolesinit()>
14223: B<rolesinit($udom,$username)>: get user privileges.
14224: returns user role, first access and timer interval hashes
14225: 
14226: =item *
14227: X<privileged()>
14228: B<privileged($username,$domain)>: returns a true if user has a
14229: privileged and active role (i.e. su or dc), false otherwise.
14230: 
14231: =item *
14232: X<getsection()>
14233: B<getsection($udom,$uname,$cname)>: finds the section of student in the
14234: course $cname, return section name/number or '' for "not in course"
14235: and '-1' for "no section"
14236: 
14237: =item *
14238: X<userenvironment()>
14239: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
14240: passed in @what from the requested user's environment, returns a hash
14241: 
14242: =item * 
14243: X<userlog_query()>
14244: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
14245: activity.log file. %filters defines filters applied when parsing the
14246: log file. These can be start or end timestamps, or the type of action
14247: - log to look for Login or Logout events, check for Checkin or
14248: Checkout, role for role selection. The response is in the form
14249: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
14250: escaped strings of the action recorded in the activity.log file.
14251: 
14252: =back
14253: 
14254: =head2 User Roles
14255: 
14256: =over 4
14257: 
14258: =item *
14259: 
14260: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
14261: returns codes for allowed actions.
14262: 
14263: The first argument is required, all others are optional.
14264: 
14265: $priv is the privilege being checked.
14266: $uri contains additional information about what is being checked for access (e.g.,
14267: URL, course ID etc.). 
14268: $symb is the unique resource instance identifier in a course; if needed,
14269: but not provided, it will be retrieved via a call to &symbread(). 
14270: $role is the role for which a priv is being checked (only used if priv is evb). 
14271: $clientip is the user's IP address (only used when checking for access to portfolio 
14272: files).
14273: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
14274: prevents recursive calls to &allowed.
14275: 
14276:  F: full access
14277:  U,I,K: authentication modes (cxx only)
14278:  '': forbidden
14279:  1: user needs to choose course
14280:  2: browse allowed
14281:  A: passphrase authentication needed
14282:  B: access temporarily blocked because of a blocking event in a course.
14283: 
14284: =item *
14285: 
14286: constructaccess($url,$setpriv) : check for access to construction space URL
14287: 
14288: See if the owner domain and name in the URL match those in the
14289: expected environment.  If so, return three element list
14290: ($ownername,$ownerdomain,$ownerhome).
14291: 
14292: Otherwise return the null string.
14293: 
14294: If second argument 'setpriv' is true, it assigns the privileges,
14295: and returns the same three element list, unless the owner has
14296: blocked "ad hoc" Domain Coordinator access to the Author Space,
14297: in which case the null string is returned.
14298: 
14299: =item *
14300: 
14301: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
14302: define a custom role rolename set privileges in format of lonTabs/roles.tab
14303: for system, domain, and course level. $uname and $udom are optional (current
14304: user's username and domain will be used when either of $uname or $udom are absent.
14305: 
14306: =item *
14307: 
14308: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
14309: (rolesplain.tab); plain text explanation of a user role term.
14310: $type is Course (default) or Community.
14311: If $forcedefault evaluates to true, text returned will be default 
14312: text for $type. Otherwise, if this is a course, the text returned 
14313: will be a custom name for the role (if defined in the course's 
14314: environment).  If no custom name is defined the default is returned.
14315:    
14316: =item *
14317: 
14318: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
14319: All arguments are optional. Returns a hash of a roles, either for
14320: co-author/assistant author roles for a user's Construction Space
14321: (default), or if $context is 'userroles', roles for the user himself,
14322: In the hash, keys are set to colon-separated $uname,$udom,$role, and
14323: (optionally) if $withsec is true, a fourth colon-separated item - $section.
14324: For each key, value is set to colon-separated start and end times for
14325: the role.  If no username and domain are specified, will default to
14326: current user/domain. Types, roles, and roledoms are references to arrays
14327: of role statuses (active, future or previous), roles 
14328: (e.g., cc,in, st etc.) and domains of the roles which can be used
14329: to restrict the list of roles reported. If no array ref is 
14330: provided for types, will default to return only active roles.
14331: 
14332: =item *
14333: 
14334: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
14335: user: $uname:$udom has a role in the course: $cdom_$cnum. 
14336: 
14337: Additional optional arguments are: $type (if role checking is to be restricted 
14338: to certain user status types -- previous (expired roles), active (currently
14339: available roles) or future (roles available in the future), and
14340: $hideprivileged -- if true will not report course roles for users who
14341: have active Domain Coordinator role in course's domain or in additional
14342: domains (specified in 'Domains to check for privileged users' in course
14343: environment -- set via:  Course Settings -> Classlists and staff listing).
14344: 
14345: =item *
14346: 
14347: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
14348: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
14349: $possdomains and $possroles are optional array refs -- to domains to check and
14350: roles to check.  If $possdomains is not specified, a dump will be done of the
14351: users' roles.db to check for a dc or su role in any domain. This can be
14352: time consuming if &privileged is called repeatedly (e.g., when displaying a
14353: classlist), so in such cases, supplying a $possdomains array is preferred, as
14354: this then allows &privileged_by_domain() to be used, which caches the identity
14355: of privileged users, eliminating the need for repeated calls to &dump().
14356: 
14357: =item *
14358: 
14359: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
14360: where the outer hash keys are domains specified in the $possdomains array ref,
14361: next inner hash keys are privileged roles specified in the $roles array ref,
14362: and the innermost hash contains key = value pairs for username:domain = end:start
14363: for active or future "privileged" users with that role in that domain. To avoid
14364: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
14365: innerhash are cached using priv_$role and $dom as the identifiers.
14366: 
14367: =back
14368: 
14369: =head2 User Modification
14370: 
14371: =over 4
14372: 
14373: =item *
14374: 
14375: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
14376: user for the level given by URL.  Optional start and end dates (leave empty
14377: string or zero for "no date")
14378: 
14379: =item *
14380: 
14381: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
14382: change a users, password, possible return values are: ok,
14383: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
14384: refused
14385: 
14386: =item *
14387: 
14388: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
14389: 
14390: =item *
14391: 
14392: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
14393:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
14394: 
14395: will update user information (firstname,middlename,lastname,generation,
14396: permanentemail), and if forceid is true, student/employee ID also.
14397: A user's institutional affiliation(s) can also be updated.
14398: User information fields will not be overwritten with empty entries 
14399: unless the field is included in the $candelete array reference.
14400: This array is included when a single user is modified via "Manage Users",
14401: or when Autoupdate.pl is run by cron in a domain.
14402: 
14403: =item *
14404: 
14405: modifystudent
14406: 
14407: modify a student's enrollment and identification information.
14408: The course id is resolved based on the current user's environment.  
14409: This means the invoking user must be a course coordinator or otherwise
14410: associated with a course.
14411: 
14412: This call is essentially a wrapper for lonnet::modifyuser and
14413: lonnet::modify_student_enrollment
14414: 
14415: Inputs: 
14416: 
14417: =over 4
14418: 
14419: =item B<$udom> Student's loncapa domain
14420: 
14421: =item B<$uname> Student's loncapa login name
14422: 
14423: =item B<$uid> Student/Employee ID
14424: 
14425: =item B<$umode> Student's authentication mode
14426: 
14427: =item B<$upass> Student's password
14428: 
14429: =item B<$first> Student's first name
14430: 
14431: =item B<$middle> Student's middle name
14432: 
14433: =item B<$last> Student's last name
14434: 
14435: =item B<$gene> Student's generation
14436: 
14437: =item B<$usec> Student's section in course
14438: 
14439: =item B<$end> Unix time of the roles expiration
14440: 
14441: =item B<$start> Unix time of the roles start date
14442: 
14443: =item B<$forceid> If defined, allow $uid to be changed
14444: 
14445: =item B<$desiredhome> server to use as home server for student
14446: 
14447: =item B<$email> Student's permanent e-mail address
14448: 
14449: =item B<$type> Type of enrollment (auto or manual)
14450: 
14451: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
14452: 
14453: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
14454: 
14455: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
14456: 
14457: =item B<$context> role change context (shown in User Management Logs display in a course)
14458: 
14459: =item B<$inststatus> institutional status of user - : separated string of escaped status types
14460: 
14461: =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.
14462: 
14463: =back
14464: 
14465: =item *
14466: 
14467: modify_student_enrollment
14468: 
14469: Change a student's enrollment status in a class.  The environment variable
14470: 'role.request.course' must be defined for this function to proceed.
14471: 
14472: Inputs:
14473: 
14474: =over 4
14475: 
14476: =item $udom, student's domain
14477: 
14478: =item $uname, student's name
14479: 
14480: =item $uid, student's user id
14481: 
14482: =item $first, student's first name
14483: 
14484: =item $middle
14485: 
14486: =item $last
14487: 
14488: =item $gene
14489: 
14490: =item $usec
14491: 
14492: =item $end
14493: 
14494: =item $start
14495: 
14496: =item $type
14497: 
14498: =item $locktype
14499: 
14500: =item $cid
14501: 
14502: =item $selfenroll
14503: 
14504: =item $context
14505: 
14506: =item $credits, number of credits student will earn from this class
14507: 
14508: =item $instsec, institutional course section code for student
14509: 
14510: =back
14511: 
14512: 
14513: =item *
14514: 
14515: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
14516: custom role; give a custom role to a user for the level given by URL.  Specify
14517: name and domain of role author, and role name
14518: 
14519: =item *
14520: 
14521: revokerole($udom,$uname,$url,$role) : revoke a role for url
14522: 
14523: =item *
14524: 
14525: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
14526: 
14527: =back
14528: 
14529: =head2 Course Infomation
14530: 
14531: =over 4
14532: 
14533: =item *
14534: 
14535: coursedescription($courseid,$options) : returns a hash of information about the
14536: specified course id, including all environment settings for the
14537: course, the description of the course will be in the hash under the
14538: key 'description'
14539: 
14540: $options is an optional parameter that if supplied is a hash reference that controls
14541: what how this function works.  It has the following key/values:
14542: 
14543: =over 4
14544: 
14545: =item freshen_cache
14546: 
14547: If defined, and the environment cache for the course is valid, it is 
14548: returned in the returned hash.
14549: 
14550: =item one_time
14551: 
14552: If defined, the last cache time is set to _now_
14553: 
14554: =item user
14555: 
14556: If defined, the supplied username is used instead of the current user.
14557: 
14558: 
14559: =back
14560: 
14561: =item *
14562: 
14563: resdata($name,$domain,$type,@which) : request for current parameter
14564: setting for a specific $type, where $type is either 'course' or 'user',
14565: @what should be a list of parameters to ask about. This routine caches
14566: answers for 10 minutes.
14567: 
14568: =item *
14569: 
14570: get_courseresdata($courseid, $domain) : dump the entire course resource
14571: data base, returning a hash that is keyed by the resource name and has
14572: values that are the resource value.  I believe that the timestamps and
14573: versions are also returned.
14574: 
14575: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
14576: supplemental content area. This routine caches the number of files for 
14577: 10 minutes.
14578: 
14579: =back
14580: 
14581: =head2 Course Modification
14582: 
14583: =over 4
14584: 
14585: =item *
14586: 
14587: writecoursepref($courseid,%prefs) : write preferences (environment
14588: database) for a course
14589: 
14590: =item *
14591: 
14592: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
14593: 
14594: =item *
14595: 
14596: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
14597: 
14598: =item *
14599: 
14600: is_course($courseid), is_course($cdom, $cnum)
14601: 
14602: Accepts either a combined $courseid (in the form of domain_courseid) or the
14603: two component version $cdom, $cnum. It checks if the specified course exists.
14604: 
14605: Returns:
14606:     undef if the course doesn't exist, otherwise
14607:     in scalar context the combined courseid.
14608:     in list context the two components of the course identifier, domain and 
14609:     courseid.    
14610: 
14611: =back
14612: 
14613: =head2 Resource Subroutines
14614: 
14615: =over 4
14616: 
14617: =item *
14618: 
14619: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
14620: 
14621: =item *
14622: 
14623: repcopy($filename) : subscribes to the requested file, and attempts to
14624: replicate from the owning library server, Might return
14625: 'unavailable', 'not_found', 'forbidden', 'ok', or
14626: 'bad_request', also attempts to grab the metadata for the
14627: resource. Expects the local filesystem pathname
14628: (/home/httpd/html/res/....)
14629: 
14630: =back
14631: 
14632: =head2 Resource Information
14633: 
14634: =over 4
14635: 
14636: =item *
14637: 
14638: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
14639: and returns the value of a variety of different possible values,
14640: $varname should be a request string, and the other parameters can be
14641: used to specify who and what one is asking about. Ordinarily, $cid 
14642: does not need to be specified, as it is retrived from 
14643: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
14644: within lonuserstate::loadmap() when initializing a course, before
14645: $env{'request.course.id'} has been set, so it needs to be provided
14646: in that one case.
14647: 
14648: Possible values for $varname are environment.lastname (or other item
14649: from the envirnment hash), user.name (or someother aspect about the
14650: user), resource.0.maxtries (or some other part and parameter of a
14651: resource)
14652: 
14653: =item *
14654: 
14655: directcondval($number) : get current value of a condition; reads from a state
14656: string
14657: 
14658: =item *
14659: 
14660: condval($condidx) : value of condition index based on state
14661: 
14662: =item *
14663: 
14664: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
14665: resource's metadata, $what should be either a specific key, or either
14666: 'keys' (to get a list of possible keys) or 'packages' to get a list of
14667: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
14668: 
14669: this function automatically caches all requests
14670: 
14671: =item *
14672: 
14673: metadata_query($query,$custom,$customshow) : make a metadata query against the
14674: network of library servers; returns file handle of where SQL and regex results
14675: will be stored for query
14676: 
14677: =item *
14678: 
14679: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
14680: return symbolic list entry (all arguments optional). 
14681: 
14682: Args: filename is the filename (including path) for the file for which a symb 
14683: is required; donotrecurse, if true will prevent calls to allowed() being made 
14684: to check access status if more than one resource was found in the bighash 
14685: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
14686: a randompick); ignorecachednull, if true will prevent a symb of '' being 
14687: returned if $env{$cache_str} is defined as ''; checkforblock if true will
14688: cause possible symbs to be checked to determine if they are subject to content
14689: blocking, if so they will not be included as possible symbs; possibles is a
14690: ref to a hash, which, as a side effect, will be populated with all possible 
14691: symbs (content blocking not tested).
14692:  
14693: returns the data handle
14694: 
14695: =item *
14696: 
14697: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
14698: and is a possible symb for the URL in $thisfn, and if is an encrypted
14699: resource that the user accessed using /enc/ returns a 1 on success, 0
14700: on failure, user must be in a course, as it assumes the existence of
14701: the course initial hash, and uses $env('request.course.id'}.  The third
14702: arg is an optional reference to a scalar.  If this arg is passed in the 
14703: call to symbverify, it will be set to 1 if the symb has been set to be 
14704: encrypted; otherwise it will be null.  
14705: 
14706: =item *
14707: 
14708: symbclean($symb) : removes versions numbers from a symb, returns the
14709: cleaned symb
14710: 
14711: =item *
14712: 
14713: is_on_map($uri) : checks if the $uri is somewhere on the current
14714: course map, user must be in a course for it to work.
14715: 
14716: =item *
14717: 
14718: numval($salt) : return random seed value (addend for rndseed)
14719: 
14720: =item *
14721: 
14722: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
14723: a random seed, all arguments are optional, if they aren't sent it uses the
14724: environment to derive them. Note: if symb isn't sent and it can't get one
14725: from &symbread it will use the current time as its return value
14726: 
14727: =item *
14728: 
14729: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
14730: unfakeable, receipt
14731: 
14732: =item *
14733: 
14734: receipt() : API to ireceipt working off of env values; given out to users
14735: 
14736: =item *
14737: 
14738: countacc($url) : count the number of accesses to a given URL
14739: 
14740: =item *
14741: 
14742: 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
14743: 
14744: =item *
14745: 
14746: 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)
14747: 
14748: =item *
14749: 
14750: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
14751: 
14752: =item *
14753: 
14754: devalidate($symb) : devalidate temporary spreadsheet calculations,
14755: forcing spreadsheet to reevaluate the resource scores next time.
14756: 
14757: =item * 
14758: 
14759: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
14760: when viewing in course context.
14761: 
14762:  input: six args -- filename (decluttered), course number, course domain,
14763:                     url, symb (if registered) and group (if this is a 
14764:                     group item -- e.g., bulletin board, group page etc.).
14765: 
14766:  output: array of five scalars --
14767:          $cfile -- url for file editing if editable on current server
14768:          $home -- homeserver of resource (i.e., for author if published,
14769:                                           or course if uploaded.).
14770:          $switchserver --  1 if server switch will be needed.
14771:          $forceedit -- 1 if icon/link should be to go to edit mode 
14772:          $forceview -- 1 if icon/link should be to go to view mode
14773: 
14774: =item *
14775: 
14776: is_course_upload($file,$cnum,$cdom)
14777: 
14778: Used in course context to determine if current file was uploaded to 
14779: the course (i.e., would be found in /userfiles/docs on the course's 
14780: homeserver.
14781: 
14782:   input: 3 args -- filename (decluttered), course number and course domain.
14783:   output: boolean -- 1 if file was uploaded.
14784: 
14785: =back
14786: 
14787: =head2 Storing/Retreiving Data
14788: 
14789: =over 4
14790: 
14791: =item *
14792: 
14793: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
14794: permanently for this url; hashref needs to be given and should be a \%hashname;
14795: the remaining args aren't required and if they aren't passed or are '' they will
14796: be derived from the env (with the exception of $laststore, which is an 
14797: optional arg used when a user's submission is stored in grading).
14798: $laststore is $version=$timestamp, where $version is the most recent version
14799: number retrieved for the corresponding $symb in the $namespace db file, and
14800: $timestamp is the timestamp for that transaction (UNIX time).
14801: $laststore is currently only passed when cstore() is called by 
14802: structuretags::finalize_storage().
14803: 
14804: =item *
14805: 
14806: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
14807: but uses critical subroutine
14808: 
14809: =item *
14810: 
14811: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
14812: all args are optional
14813: 
14814: =item *
14815: 
14816: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
14817: dumps the complete (or key matching regexp) namespace into a hash
14818: ($udom, $uname, $regexp, $range are optional) for a namespace that is
14819: normally &store()ed into
14820: 
14821: $range should be either an integer '100' (give me the first 100
14822:                                            matching records)
14823:               or be  two integers sperated by a - with no spaces
14824:                  '30-50' (give me the 30th through the 50th matching
14825:                           records)
14826: 
14827: 
14828: =item *
14829: 
14830: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
14831: replaces a &store() version of data with a replacement set of data
14832: for a particular resource in a namespace passed in the $storehash hash 
14833: reference. If $tolog is true, the transaction is logged in the courselog
14834: with an action=PUTSTORE.
14835: 
14836: =item *
14837: 
14838: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
14839: works very similar to store/cstore, but all data is stored in a
14840: temporary location and can be reset using tmpreset, $storehash should
14841: be a hash reference, returns nothing on success
14842: 
14843: =item *
14844: 
14845: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
14846: similar to restore, but all data is stored in a temporary location and
14847: can be reset using tmpreset. Returns a hash of values on success,
14848: error string otherwise.
14849: 
14850: =item *
14851: 
14852: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
14853: deltes all keys for $symb form the temporary storage hash.
14854: 
14855: =item *
14856: 
14857: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
14858: reference filled in from namesp ($udom and $uname are optional)
14859: 
14860: =item *
14861: 
14862: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
14863: namesp ($udom and $uname are optional)
14864: 
14865: =item *
14866: 
14867: dump($namespace,$udom,$uname,$regexp,$range) : 
14868: dumps the complete (or key matching regexp) namespace into a hash
14869: ($udom, $uname, $regexp, $range are optional)
14870: 
14871: $range should be either an integer '100' (give me the first 100
14872:                                            matching records)
14873:               or be  two integers sperated by a - with no spaces
14874:                  '30-50' (give me the 30th through the 50th matching
14875:                           records)
14876: =item *
14877: 
14878: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
14879: $store can be a scalar, an array reference, or if the amount to be 
14880: incremented is > 1, a hash reference.
14881: 
14882: ($udom and $uname are optional)
14883: 
14884: =item *
14885: 
14886: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
14887: ($udom and $uname are optional)
14888: 
14889: =item *
14890: 
14891: cput($namespace,$storehash,$udom,$uname) : critical put
14892: ($udom and $uname are optional)
14893: 
14894: =item *
14895: 
14896: newput($namespace,$storehash,$udom,$uname) :
14897: 
14898: Attempts to store the items in the $storehash, but only if they don't
14899: currently exist, if this succeeds you can be certain that you have 
14900: successfully created a new key value pair in the $namespace db.
14901: 
14902: 
14903: Args:
14904:  $namespace: name of database to store values to
14905:  $storehash: hashref to store to the db
14906:  $udom: (optional) domain of user containing the db
14907:  $uname: (optional) name of user caontaining the db
14908: 
14909: Returns:
14910:  'ok' -> succeeded in storing all keys of $storehash
14911:  'key_exists: <key>' -> failed to anything out of $storehash, as at
14912:                         least <key> already existed in the db (other
14913:                         requested keys may also already exist)
14914:  'error: <msg>' -> unable to tie the DB or other error occurred
14915:  'con_lost' -> unable to contact request server
14916:  'refused' -> action was not allowed by remote machine
14917: 
14918: 
14919: =item *
14920: 
14921: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
14922: reference filled in from namesp (encrypts the return communication)
14923: ($udom and $uname are optional)
14924: 
14925: =item *
14926: 
14927: log($udom,$name,$home,$message) : write to permanent log for user; use
14928: critical subroutine
14929: 
14930: =item *
14931: 
14932: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
14933: array reference filled in from namespace found in domain level on either
14934: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
14935: 
14936: =item *
14937: 
14938: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
14939: domain level either on specified domain server ($uhome) or primary domain 
14940: server ($udom and $uhome are optional)
14941: 
14942: =item * 
14943: 
14944: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
14945: for: authentication, language, quotas, timezone, date locale, and portal URL in
14946: the target domain.
14947: 
14948: May also include additional key => value pairs for the following groups:
14949: 
14950: =over
14951: 
14952: =item
14953: disk quotas (MB allocated by default to portfolios and authoring spaces).
14954: 
14955: =over
14956: 
14957: =item defaultquota, authorquota
14958: 
14959: =back
14960: 
14961: =item
14962: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
14963: portfolio for users).
14964: 
14965: =over
14966: 
14967: =item
14968: aboutme, blog, webdav, portfolio
14969: 
14970: =back
14971: 
14972: =item
14973: requestcourses: ability to request courses, and how requests are processed.
14974: 
14975: =over
14976: 
14977: =item
14978: official, unofficial, community, textbook, placement
14979: 
14980: =back
14981: 
14982: =item
14983: inststatus: types of institutional affiliation, and order in which they are displayed.
14984: 
14985: =over
14986: 
14987: =item
14988: inststatustypes, inststatusorder, inststatusguest
14989: 
14990: =back
14991: 
14992: =item
14993: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
14994: for course's uploaded content.
14995: 
14996: =over
14997: 
14998: =item
14999: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
15000: communityquota, textbookquota, placementquota
15001: 
15002: =back
15003: 
15004: =item
15005: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
15006: on your servers.
15007: 
15008: =over
15009: 
15010: =item 
15011: remotesessions, hostedsessions
15012: 
15013: =back
15014: 
15015: =back
15016: 
15017: In cases where a domain coordinator has never used the "Set Domain Configuration"
15018: utility to create a configuration.db file on a domain's primary library server 
15019: only the following domain defaults: auth_def, auth_arg_def, lang_def
15020: -- corresponding values are authentication type (internal, krb4, krb5,
15021: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
15022: will be available. Values are retrieved from cache (if current), unless the
15023: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
15024: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
15025: 
15026: Typical usage:
15027: 
15028: %domdefaults = &get_domain_defaults($target_domain);
15029: 
15030: =back
15031: 
15032: =head2 Network Status Functions
15033: 
15034: =over 4
15035: 
15036: =item *
15037: 
15038: dirlist() : return directory list based on URI (first arg).
15039: 
15040: Inputs: 1 required, 5 optional.
15041: 
15042: =over
15043: 
15044: =item 
15045: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
15046: 
15047: =item
15048: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
15049: 
15050: =item
15051: $username -  username of user/course to be listed. Extracted from $uri if absent. 
15052: 
15053: =item
15054: $getpropath - boolean: 1 if prepend path using &propath(). 
15055: 
15056: =item
15057: $getuserdir - boolean: 1 if prepend path for "userfiles".
15058: 
15059: =item 
15060: $alternateRoot - path to prepend in place of path from $uri.
15061: 
15062: =back
15063: 
15064: Returns: Array of up to two items.
15065: 
15066: =over
15067: 
15068: a reference to an array of files/subdirectories
15069: 
15070: =over
15071: 
15072: Each element in the array of files/subdirectories is a & separated list of
15073: item name and the result of running stat on the item.  If dirlist was requested
15074: for a file instead of a directory, the item name will be ''. For a directory 
15075: listing, if the item is a metadata file, the element will end &N&M 
15076: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
15077: default copyright set (1).  
15078: 
15079: =back
15080: 
15081: a scalar containing error condition (if encountered).
15082: 
15083: =over
15084: 
15085: =item 
15086: no_host (no homeserver identified for $username:$domain).
15087: 
15088: =item 
15089: no_such_host (server contacted for listing not identified as valid host).
15090: 
15091: =item 
15092: con_lost (connection to remote server failed).
15093: 
15094: =item 
15095: refused (invalid $username:$domain received on lond side).
15096: 
15097: =item 
15098: no_such_dir (directory at specified path on lond side does not exist). 
15099: 
15100: =item 
15101: empty (directory at specified path on lond side is empty).
15102: 
15103: =over
15104: 
15105: This is currently not encountered because the &ls3, &ls2, 
15106: &ls (_handler) routines on the lond side do not filter out
15107: . and .. from a directory listing. 
15108: 
15109: =back
15110: 
15111: =back
15112: 
15113: =back
15114: 
15115: =item *
15116: 
15117: spareserver() : find server with least workload from spare.tab
15118: 
15119: 
15120: =item *
15121: 
15122: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
15123: if there is no corresponding loncapa host.
15124: 
15125: =back
15126: 
15127: 
15128: =head2 Apache Request
15129: 
15130: =over 4
15131: 
15132: =item *
15133: 
15134: ssi($url,%hash) : server side include, does a complete request cycle on url to
15135: localhost, posts hash
15136: 
15137: =back
15138: 
15139: =head2 Data to String to Data
15140: 
15141: =over 4
15142: 
15143: =item *
15144: 
15145: hash2str(%hash) : convert a hash into a string complete with escaping and '='
15146: and '&' separators, supports elements that are arrayrefs and hashrefs
15147: 
15148: =item *
15149: 
15150: hashref2str($hashref) : convert a hashref into a string complete with
15151: escaping and '=' and '&' separators, supports elements that are
15152: arrayrefs and hashrefs
15153: 
15154: =item *
15155: 
15156: arrayref2str($arrayref) : convert an arrayref into a string complete
15157: with escaping and '&' separators, supports elements that are arrayrefs
15158: and hashrefs
15159: 
15160: =item *
15161: 
15162: str2hash($string) : convert string to hash using unescaping and
15163: splitting on '=' and '&', supports elements that are arrayrefs and
15164: hashrefs
15165: 
15166: =item *
15167: 
15168: str2array($string) : convert string to hash using unescaping and
15169: splitting on '&', supports elements that are arrayrefs and hashrefs
15170: 
15171: =back
15172: 
15173: =head2 Logging Routines
15174: 
15175: 
15176: These routines allow one to make log messages in the lonnet.log and
15177: lonnet.perm logfiles.
15178: 
15179: =over 4
15180: 
15181: =item *
15182: 
15183: logtouch() : make sure the logfile, lonnet.log, exists
15184: 
15185: =item *
15186: 
15187: logthis() : append message to the normal lonnet.log file, it gets
15188: preiodically rolled over and deleted.
15189: 
15190: =item *
15191: 
15192: logperm() : append a permanent message to lonnet.perm.log, this log
15193: file never gets deleted by any automated portion of the system, only
15194: messages of critical importance should go in here.
15195: 
15196: 
15197: =back
15198: 
15199: =head2 General File Helper Routines
15200: 
15201: =over 4
15202: 
15203: =item *
15204: 
15205: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
15206: (a) files in /uploaded
15207:   (i) If a local copy of the file exists - 
15208:       compares modification date of local copy with last-modified date for 
15209:       definitive version stored on home server for course. If local copy is 
15210:       stale, requests a new version from the home server and stores it. 
15211:       If the original has been removed from the home server, then local copy 
15212:       is unlinked.
15213:   (ii) If local copy does not exist -
15214:       requests the file from the home server and stores it. 
15215:   
15216:   If $caller is 'uploadrep':  
15217:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
15218:     for request for files originally uploaded via DOCS. 
15219:      - returns 'ok' if fresh local copy now available, -1 otherwise.
15220:   
15221:   Otherwise:
15222:      This indicates a call from the content generation phase of the request.
15223:      -  returns the entire contents of the file or -1.
15224:      
15225: (b) files in /res
15226:    - returns the entire contents of a file or -1; 
15227:    it properly subscribes to and replicates the file if neccessary.
15228: 
15229: 
15230: =item *
15231: 
15232: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
15233:                   reference
15234: 
15235: returns either a stat() list of data about the file or an empty list
15236: if the file doesn't exist or couldn't find out about it (connection
15237: problems or user unknown)
15238: 
15239: =item *
15240: 
15241: filelocation($dir,$file) : returns file system location of a file
15242: based on URI; meant to be "fairly clean" absolute reference, $dir is a
15243: directory that relative $file lookups are to looked in ($dir of /a/dir
15244: and a file of ../bob will become /a/bob)
15245: 
15246: =item *
15247: 
15248: hreflocation($dir,$file) : returns file system location or a URL; same as
15249: filelocation except for hrefs
15250: 
15251: =item *
15252: 
15253: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
15254: also removes beginning /home/httpd/html unless /priv/ follows it.
15255: 
15256: =back
15257: 
15258: =head2 Usererfile file routines (/uploaded*)
15259: 
15260: =over 4
15261: 
15262: =item *
15263: 
15264: userfileupload(): main rotine for putting a file in a user or course's
15265:                   filespace, arguments are,
15266: 
15267:  formname - required - this is the name of the element in $env where the
15268:            filename, and the contents of the file to create/modifed exist
15269:            the filename is in $env{'form.'.$formname.'.filename'} and the
15270:            contents of the file is located in $env{'form.'.$formname}
15271:  context - if coursedoc, store the file in the course of the active role
15272:              of the current user; 
15273:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
15274:            if 'canceloverwrite': delete file in tmp/overwrites directory
15275:  subdir - required - subdirectory to put the file in under ../userfiles/
15276:          if undefined, it will be placed in "unknown"
15277: 
15278:  (This routine calls clean_filename() to remove any dangerous
15279:  characters from the filename, and then calls finuserfileupload() to
15280:  complete the transaction)
15281: 
15282:  returns either the url of the uploaded file (/uploaded/....) if successful
15283:  and /adm/notfound.html if unsuccessful
15284: 
15285: =item *
15286: 
15287: clean_filename(): routine for cleaing a filename up for storage in
15288:                  userfile space, argument is:
15289: 
15290:  filename - proposed filename
15291: 
15292: returns: the new clean filename
15293: 
15294: =item *
15295: 
15296: finishuserfileupload(): routine that creates and sends the file to
15297: userspace, probably shouldn't be called directly
15298: 
15299:   docuname: username or courseid of destination for the file
15300:   docudom: domain of user/course of destination for the file
15301:   formname: same as for userfileupload()
15302:   fname: filename (including subdirectories) for the file
15303:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
15304:   allfiles: reference to hash used to store objects found by parser
15305:   codebase: reference to hash used for codebases of java objects found by parser
15306:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
15307:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
15308:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
15309:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
15310:   context: if 'overwrite', will move the uploaded file from its temporary location to
15311:             userfiles to facilitate overwriting a previously uploaded file with same name.
15312:   mimetype: reference to scalar to accommodate mime type determined
15313:             from File::MMagic if $parser = parse.
15314: 
15315:  returns either the url of the uploaded file (/uploaded/....) if successful
15316:  and /adm/notfound.html if unsuccessful (or an error message if context 
15317:  was 'overwrite').
15318:  
15319: 
15320: =item *
15321: 
15322: renameuserfile(): renames an existing userfile to a new name
15323: 
15324:   Args:
15325:    docuname: username or courseid of destination for the file
15326:    docudom: domain of user/course of destination for the file
15327:    old: current file name (including any subdirs under userfiles)
15328:    new: desired file name (including any subdirs under userfiles)
15329: 
15330: =item *
15331: 
15332: mkdiruserfile(): creates a directory is a userfiles dir
15333: 
15334:   Args:
15335:    docuname: username or courseid of destination for the file
15336:    docudom: domain of user/course of destination for the file
15337:    dir: dir to create (including any subdirs under userfiles)
15338: 
15339: =item *
15340: 
15341: removeuserfile(): removes a file that exists in userfiles
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:    fname: filname to delete (including any subdirs under userfiles)
15347: 
15348: =item *
15349: 
15350: removeuploadedurl(): convience function for removeuserfile()
15351: 
15352:   Args:
15353:    url:  a full /uploaded/... url to delete
15354: 
15355: =item * 
15356: 
15357: get_portfile_permissions():
15358:   Args:
15359:     domain: domain of user or course contain the portfolio files
15360:     user: name of user or num of course contain the portfolio files
15361:   Returns:
15362:     hashref of a dump of the proper file_permissions.db
15363:    
15364: 
15365: =item * 
15366: 
15367: get_access_controls():
15368: 
15369: Args:
15370:   current_permissions: the hash ref returned from get_portfile_permissions()
15371:   group: (optional) the group you want the files associated with
15372:   file: (optional) the file you want access info on
15373: 
15374: Returns:
15375:     a hash (keys are file names) of hashes containing
15376:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
15377:         values are XML containing access control settings (see below) 
15378: 
15379: Internal notes:
15380: 
15381:  access controls are stored in file_permissions.db as key=value pairs.
15382:     key -> path to file/file_name\0uniqueID:scope_end_start
15383:         where scope -> public,guest,course,group,domains or users.
15384:               end -> UNIX time for end of access (0 -> no end date)
15385:               start -> UNIX time for start of access
15386: 
15387:     value -> XML description of access control
15388:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
15389:             <start></start>
15390:             <end></end>
15391: 
15392:             <password></password>  for scope type = guest
15393: 
15394:             <domain></domain>     for scope type = course or group
15395:             <number></number>
15396:             <roles id="">
15397:              <role></role>
15398:              <access></access>
15399:              <section></section>
15400:              <group></group>
15401:             </roles>
15402: 
15403:             <dom></dom>         for scope type = domains
15404: 
15405:             <users>             for scope type = users
15406:              <user>
15407:               <uname></uname>
15408:               <udom></udom>
15409:              </user>
15410:             </users>
15411:            </scope> 
15412:               
15413:  Access data is also aggregated for each file in an additional key=value pair:
15414:  key -> path to file/file_name\0accesscontrol 
15415:  value -> reference to hash
15416:           hash contains key = value pairs
15417:           where key = uniqueID:scope_end_start
15418:                 value = UNIX time record was last updated
15419: 
15420:           Used to improve speed of look-ups of access controls for each file.  
15421:  
15422:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
15423: 
15424: =item *
15425: 
15426: modify_access_controls():
15427: 
15428: Modifies access controls for a portfolio file
15429: Args
15430: 1. file name
15431: 2. reference to hash of required changes,
15432: 3. domain
15433: 4. username
15434:   where domain,username are the domain of the portfolio owner 
15435:   (either a user or a course) 
15436: 
15437: Returns:
15438: 1. result of additions or updates ('ok' or 'error', with error message). 
15439: 2. result of deletions ('ok' or 'error', with error message).
15440: 3. reference to hash of any new or updated access controls.
15441: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
15442:    key = integer (inbound ID)
15443:    value = uniqueID
15444: 
15445: =item *
15446: 
15447: get_timebased_id():
15448: 
15449: Attempts to get a unique timestamp-based suffix for use with items added to a 
15450: course via the Course Editor (e.g., folders, composite pages, 
15451: group bulletin boards).
15452: 
15453: Args: (first three required; six others optional)
15454: 
15455: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
15456:    docssequence, or name of group
15457: 
15458: 2. keyid (alphanumeric): name of temporary locking key in hash,
15459:    e.g., num, boardids
15460: 
15461: 3. namespace: name of gdbm file used to store suffixes already assigned;  
15462:    file will be named nohist_namespace.db
15463: 
15464: 4. cdom: domain of course; default is current course domain from %env
15465: 
15466: 5. cnum: course number; default is current course number from %env
15467: 
15468: 6. idtype: set to concat if an additional digit is to be appended to the 
15469:    unix timestamp to form the suffix, if the plain timestamp is already
15470:    in use.  Default is to not do this, but simply increment the unix 
15471:    timestamp by 1 until a unique key is obtained.
15472: 
15473: 7. who: holder of locking key; defaults to user:domain for user.
15474: 
15475: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
15476:    retrying); default is 3.
15477: 
15478: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
15479: 
15480: Returns:
15481: 
15482: 1. suffix obtained (numeric)
15483: 
15484: 2. result of deleting locking key (ok if deleted, or lock never obtained)
15485: 
15486: 3. error: contains (localized) error message if an error occurred.
15487: 
15488: 
15489: =back
15490: 
15491: =head2 HTTP Helper Routines
15492: 
15493: =over 4
15494: 
15495: =item *
15496: 
15497: escape() : unpack non-word characters into CGI-compatible hex codes
15498: 
15499: =item *
15500: 
15501: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
15502: 
15503: =back
15504: 
15505: =head1 PRIVATE SUBROUTINES
15506: 
15507: =head2 Underlying communication routines (Shouldn't call)
15508: 
15509: =over 4
15510: 
15511: =item *
15512: 
15513: subreply() : tries to pass a message to lonc, returns con_lost if incapable
15514: 
15515: =item *
15516: 
15517: reply() : uses subreply to send a message to remote machine, logs all failures
15518: 
15519: =item *
15520: 
15521: critical() : passes a critical message to another server; if cannot
15522: get through then place message in connection buffer directory and
15523: returns con_delayed, if incapable of saving message, returns
15524: con_failed
15525: 
15526: =item *
15527: 
15528: reconlonc() : tries to reconnect lonc client processes.
15529: 
15530: =back
15531: 
15532: =head2 Resource Access Logging
15533: 
15534: =over 4
15535: 
15536: =item *
15537: 
15538: flushcourselogs() : flush (save) buffer logs and access logs
15539: 
15540: =item *
15541: 
15542: courselog($what) : save message for course in hash
15543: 
15544: =item *
15545: 
15546: courseacclog($what) : save message for course using &courselog().  Perform
15547: special processing for specific resource types (problems, exams, quizzes, etc).
15548: 
15549: =item *
15550: 
15551: goodbye() : flush course logs and log shutting down; it is called in srm.conf
15552: as a PerlChildExitHandler
15553: 
15554: =back
15555: 
15556: =head2 Other
15557: 
15558: =over 4
15559: 
15560: =item *
15561: 
15562: symblist($mapname,%newhash) : update symbolic storage links
15563: 
15564: =back
15565: 
15566: =cut
15567: 

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