File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1269: download - view: text, annotated - select for diffs
Mon Nov 24 02:36:21 2014 UTC (9 years, 7 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6740 Out-of-order recording of submissions (by time).
  - Check for new transactions made immediately before call to lonnet::cstore()
    &Apache::inputtags::hidealldata() called if correct then incorrect,
    where awarded >= 1 when correct (feedback on correctness enabled).
  - Check for transactions made immediately after call to lonnet::cstore()
    if reply from lond::store_handler() is delay:N (where N s the number of
    transactions between the last retrieved in &initialize_storage() and the
    last stored immediately before permanent storage of the current transaction.
    &Apache::grades::makehidden() called if correct then incorrect,
    where awarded >= 1 when correct (feedback on correctness enabled).

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1269 2014/11/24 02:36:21 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 LWP::UserAgent();
   75: use HTTP::Date;
   76: use Image::Magick;
   77: 
   78: 
   79: use Encode;
   80: 
   81: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
   82:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
   83:             %managerstab);
   84: 
   85: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   86:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   87:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   88:     %courseownerbuf, %coursetypebuf,$locknum);
   89: 
   90: use IO::Socket;
   91: use GDBM_File;
   92: use HTML::LCParser;
   93: use Fcntl qw(:flock);
   94: use Storable qw(thaw nfreeze);
   95: use Time::HiRes qw( gettimeofday tv_interval );
   96: use Cache::Memcached;
   97: use Digest::MD5;
   98: use Math::Random;
   99: use File::MMagic;
  100: use LONCAPA qw(:DEFAULT :match);
  101: use LONCAPA::Configuration;
  102: use LONCAPA::lonmetadata;
  103: use LONCAPA::Lond;
  104: 
  105: use File::Copy;
  106: 
  107: my $readit;
  108: my $max_connection_retries = 10;     # 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_server_loncaparev {
  233:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  234:     if (defined($lonhost)) {
  235:         if (!defined(&hostname($lonhost))) {
  236:             undef($lonhost);
  237:         }
  238:     }
  239:     if (!defined($lonhost)) {
  240:         if (defined(&domain($dom,'primary'))) {
  241:             $lonhost=&domain($dom,'primary');
  242:             if ($lonhost eq 'no_host') {
  243:                 undef($lonhost);
  244:             }
  245:         }
  246:     }
  247:     if (defined($lonhost)) {
  248:         my $cachetime = 12*3600;
  249:         if (!$ignore_cache) {
  250:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  251:             if (defined($cached)) {
  252:                 return $loncaparev;
  253:             }
  254:         }
  255:         my ($answer,$loncaparev);
  256:         my @ids=&current_machine_ids();
  257:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  258:             $answer = $perlvar{'lonVersion'};
  259:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  260:                 $loncaparev = $1;
  261:             }
  262:         } else {
  263:             $answer = &reply('serverloncaparev',$lonhost);
  264:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  265:                 if ($caller eq 'loncron') {
  266:                     my $ua=new LWP::UserAgent;
  267:                     $ua->timeout(4);
  268:                     my $protocol = $protocol{$lonhost};
  269:                     $protocol = 'http' if ($protocol ne 'https');
  270:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
  271:                     my $request=new HTTP::Request('GET',$url);
  272:                     my $response=$ua->request($request);
  273:                     unless ($response->is_error()) {
  274:                         my $content = $response->content;
  275:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  276:                             $loncaparev = $1;
  277:                         }
  278:                     }
  279:                 } else {
  280:                     $loncaparev = $loncaparevs{$lonhost};
  281:                 }
  282:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  283:                 $loncaparev = $1;
  284:             }
  285:         }
  286:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  287:     }
  288: }
  289: 
  290: sub get_server_homeID {
  291:     my ($hostname,$ignore_cache,$caller) = @_;
  292:     unless ($ignore_cache) {
  293:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  294:         if (defined($cached)) {
  295:             return $serverhomeID;
  296:         }
  297:     }
  298:     my $cachetime = 12*3600;
  299:     my $serverhomeID;
  300:     if ($caller eq 'loncron') { 
  301:         my @machine_ids = &machine_ids($hostname);
  302:         foreach my $id (@machine_ids) {
  303:             my $response = &reply('serverhomeID',$id);
  304:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  305:                 $serverhomeID = $response;
  306:                 last;
  307:             }
  308:         }
  309:         if ($serverhomeID eq '') {
  310:             $serverhomeID = $machine_ids[-1];
  311:         }
  312:     } else {
  313:         $serverhomeID = $serverhomeIDs{$hostname};
  314:     }
  315:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  316: }
  317: 
  318: sub get_remote_globals {
  319:     my ($lonhost,$whathash,$ignore_cache) = @_;
  320:     my ($result,%returnhash,%whatneeded);
  321:     if (ref($whathash) eq 'HASH') {
  322:         foreach my $what (sort(keys(%{$whathash}))) {
  323:             my $hashid = $lonhost.'-'.$what;
  324:             my ($response,$cached);
  325:             unless ($ignore_cache) {
  326:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  327:             }
  328:             if (defined($cached)) {
  329:                 $returnhash{$what} = $response;
  330:             } else {
  331:                 $whatneeded{$what} = 1;
  332:             }
  333:         }
  334:         if (keys(%whatneeded) == 0) {
  335:             $result = 'ok';
  336:         } else {
  337:             my $requested = &freeze_escape(\%whatneeded);
  338:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  339:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  340:                 ($rep eq 'unknown_cmd')) {
  341:                 $result = $rep;
  342:             } else {
  343:                 $result = 'ok';
  344:                 my @pairs=split(/\&/,$rep);
  345:                 foreach my $item (@pairs) {
  346:                     my ($key,$value)=split(/=/,$item,2);
  347:                     my $what = &unescape($key);
  348:                     my $hashid = $lonhost.'-'.$what;
  349:                     $returnhash{$what}=&thaw_unescape($value);
  350:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  351:                 }
  352:             }
  353:         }
  354:     }
  355:     return ($result,\%returnhash);
  356: }
  357: 
  358: sub remote_devalidate_cache {
  359:     my ($lonhost,$cachekeys) = @_;
  360:     my $items;
  361:     return unless (ref($cachekeys) eq 'ARRAY');
  362:     my $cachestr = join('&',@{$cachekeys});
  363:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
  364:     return $response;
  365: }
  366: 
  367: # -------------------------------------------------- Non-critical communication
  368: sub subreply {
  369:     my ($cmd,$server)=@_;
  370:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  371:     #
  372:     #  With loncnew process trimming, there's a timing hole between lonc server
  373:     #  process exit and the master server picking up the listen on the AF_UNIX
  374:     #  socket.  In that time interval, a lock file will exist:
  375: 
  376:     my $lockfile=$peerfile.".lock";
  377:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  378: 	sleep(1);
  379:     }
  380:     # At this point, either a loncnew parent is listening or an old lonc
  381:     # or loncnew child is listening so we can connect or everything's dead.
  382:     #
  383:     #   We'll give the connection a few tries before abandoning it.  If
  384:     #   connection is not possible, we'll con_lost back to the client.
  385:     #   
  386:     my $client;
  387:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  388: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  389: 				      Type    => SOCK_STREAM,
  390: 				      Timeout => 10);
  391: 	if ($client) {
  392: 	    last;		# Connected!
  393: 	} else {
  394: 	    &create_connection(&hostname($server),$server);
  395: 	}
  396:         sleep(1);		# Try again later if failed connection.
  397:     }
  398:     my $answer;
  399:     if ($client) {
  400: 	print $client "sethost:$server:$cmd\n";
  401: 	$answer=<$client>;
  402: 	if (!$answer) { $answer="con_lost"; }
  403: 	chomp($answer);
  404:     } else {
  405: 	$answer = 'con_lost';	# Failed connection.
  406:     }
  407:     return $answer;
  408: }
  409: 
  410: sub reply {
  411:     my ($cmd,$server)=@_;
  412:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  413:     my $answer=subreply($cmd,$server);
  414:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  415:        &logthis("<font color=\"blue\">WARNING:".
  416:                 " $cmd to $server returned $answer</font>");
  417:     }
  418:     return $answer;
  419: }
  420: 
  421: # ----------------------------------------------------------- Send USR1 to lonc
  422: 
  423: sub reconlonc {
  424:     my ($lonid) = @_;
  425:     my $hostname = &hostname($lonid);
  426:     if ($lonid) {
  427: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  428: 	if ($hostname && -e $peerfile) {
  429: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  430: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  431: 					     Type    => SOCK_STREAM,
  432: 					     Timeout => 10);
  433: 	    if ($client) {
  434: 		print $client ("reset_retries\n");
  435: 		my $answer=<$client>;
  436: 		#reset just this one.
  437: 	    }
  438: 	}
  439: 	return;
  440:     }
  441: 
  442:     &logthis("Trying to reconnect lonc");
  443:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  444:     if (open(my $fh,"<$loncfile")) {
  445: 	my $loncpid=<$fh>;
  446:         chomp($loncpid);
  447:         if (kill 0 => $loncpid) {
  448: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  449:             kill USR1 => $loncpid;
  450:             sleep 1;
  451:          } else {
  452: 	    &logthis(
  453:                "<font color=\"blue\">WARNING:".
  454:                " lonc at pid $loncpid not responding, giving up</font>");
  455:         }
  456:     } else {
  457: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  458:     }
  459: }
  460: 
  461: # ------------------------------------------------------ Critical communication
  462: 
  463: sub critical {
  464:     my ($cmd,$server)=@_;
  465:     unless (&hostname($server)) {
  466:         &logthis("<font color=\"blue\">WARNING:".
  467:                " Critical message to unknown server ($server)</font>");
  468:         return 'no_such_host';
  469:     }
  470:     my $answer=reply($cmd,$server);
  471:     if ($answer eq 'con_lost') {
  472: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  473: 	my $answer=reply($cmd,$server);
  474:         if ($answer eq 'con_lost') {
  475:             my $now=time;
  476:             my $middlename=$cmd;
  477:             $middlename=substr($middlename,0,16);
  478:             $middlename=~s/\W//g;
  479:             my $dfilename=
  480:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  481:             $dumpcount++;
  482:             {
  483: 		my $dfh;
  484: 		if (open($dfh,">$dfilename")) {
  485: 		    print $dfh "$cmd\n"; 
  486: 		    close($dfh);
  487: 		}
  488:             }
  489:             sleep 2;
  490:             my $wcmd='';
  491:             {
  492: 		my $dfh;
  493: 		if (open($dfh,"<$dfilename")) {
  494: 		    $wcmd=<$dfh>; 
  495: 		    close($dfh);
  496: 		}
  497:             }
  498:             chomp($wcmd);
  499:             if ($wcmd eq $cmd) {
  500: 		&logthis("<font color=\"blue\">WARNING: ".
  501:                          "Connection buffer $dfilename: $cmd</font>");
  502:                 &logperm("D:$server:$cmd");
  503: 	        return 'con_delayed';
  504:             } else {
  505:                 &logthis("<font color=\"red\">CRITICAL:"
  506:                         ." Critical connection failed: $server $cmd</font>");
  507:                 &logperm("F:$server:$cmd");
  508:                 return 'con_failed';
  509:             }
  510:         }
  511:     }
  512:     return $answer;
  513: }
  514: 
  515: # ------------------------------------------- check if return value is an error
  516: 
  517: sub error {
  518:     my ($result) = @_;
  519:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  520: 	if ($2 == 2) { return undef; }
  521: 	return $1;
  522:     }
  523:     return undef;
  524: }
  525: 
  526: sub convert_and_load_session_env {
  527:     my ($lonidsdir,$handle)=@_;
  528:     my @profile;
  529:     {
  530: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  531: 	if (!$opened) {
  532: 	    return 0;
  533: 	}
  534: 	flock($idf,LOCK_SH);
  535: 	@profile=<$idf>;
  536: 	close($idf);
  537:     }
  538:     my %temp_env;
  539:     foreach my $line (@profile) {
  540: 	if ($line !~ m/=/) {
  541: 	    return 0;
  542: 	}
  543: 	chomp($line);
  544: 	my ($envname,$envvalue)=split(/=/,$line,2);
  545: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  546:     }
  547:     unlink("$lonidsdir/$handle.id");
  548:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  549: 	    0640)) {
  550: 	%disk_env = %temp_env;
  551: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  552: 	untie(%disk_env);
  553:     }
  554:     return 1;
  555: }
  556: 
  557: # ------------------------------------------- Transfer profile into environment
  558: my $env_loaded;
  559: sub transfer_profile_to_env {
  560:     my ($lonidsdir,$handle,$force_transfer) = @_;
  561:     if (!$force_transfer && $env_loaded) { return; } 
  562: 
  563:     if (!defined($lonidsdir)) {
  564: 	$lonidsdir = $perlvar{'lonIDsDir'};
  565:     }
  566:     if (!defined($handle)) {
  567:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  568:     }
  569: 
  570:     my $convert;
  571:     {
  572:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  573: 	if (!$opened) {
  574: 	    return;
  575: 	}
  576: 	flock($idf,LOCK_SH);
  577: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  578: 		&GDBM_READER(),0640)) {
  579: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  580: 	    untie(%disk_env);
  581: 	} else {
  582: 	    $convert = 1;
  583: 	}
  584:     }
  585:     if ($convert) {
  586: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  587: 	    &logthis("Failed to load session, or convert session.");
  588: 	}
  589:     }
  590: 
  591:     my %remove;
  592:     while ( my $envname = each(%env) ) {
  593:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  594:             if ($time < time-300) {
  595:                 $remove{$key}++;
  596:             }
  597:         }
  598:     }
  599: 
  600:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  601:     $env_loaded=1;
  602:     foreach my $expired_key (keys(%remove)) {
  603:         &delenv($expired_key);
  604:     }
  605: }
  606: 
  607: # ---------------------------------------------------- Check for valid session 
  608: sub check_for_valid_session {
  609:     my ($r,$name,$userhashref) = @_;
  610:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  611:     if ($name eq '') {
  612:         $name = 'lonID';
  613:     }
  614:     my $lonid=$cookies{$name};
  615:     return undef if (!$lonid);
  616: 
  617:     my $handle=&LONCAPA::clean_handle($lonid->value);
  618:     my $lonidsdir;
  619:     if ($name eq 'lonDAV') {
  620:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  621:     } else {
  622:         $lonidsdir=$r->dir_config('lonIDsDir');
  623:     }
  624:     return undef if (!-e "$lonidsdir/$handle.id");
  625: 
  626:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  627:     return undef if (!$opened);
  628: 
  629:     flock($idf,LOCK_SH);
  630:     my %disk_env;
  631:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  632: 	    &GDBM_READER(),0640)) {
  633: 	return undef;	
  634:     }
  635: 
  636:     if (!defined($disk_env{'user.name'})
  637: 	|| !defined($disk_env{'user.domain'})) {
  638: 	return undef;
  639:     }
  640: 
  641:     if (ref($userhashref) eq 'HASH') {
  642:         $userhashref->{'name'} = $disk_env{'user.name'};
  643:         $userhashref->{'domain'} = $disk_env{'user.domain'};
  644:     }
  645: 
  646:     return $handle;
  647: }
  648: 
  649: sub timed_flock {
  650:     my ($file,$lock_type) = @_;
  651:     my $failed=0;
  652:     eval {
  653: 	local $SIG{__DIE__}='DEFAULT';
  654: 	local $SIG{ALRM}=sub {
  655: 	    $failed=1;
  656: 	    die("failed lock");
  657: 	};
  658: 	alarm(13);
  659: 	flock($file,$lock_type);
  660: 	alarm(0);
  661:     };
  662:     if ($failed) {
  663: 	return undef;
  664:     } else {
  665: 	return 1;
  666:     }
  667: }
  668: 
  669: # ---------------------------------------------------------- Append Environment
  670: 
  671: sub appenv {
  672:     my ($newenv,$roles) = @_;
  673:     if (ref($newenv) eq 'HASH') {
  674:         foreach my $key (keys(%{$newenv})) {
  675:             my $refused = 0;
  676: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  677:                 $refused = 1;
  678:                 if (ref($roles) eq 'ARRAY') {
  679:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
  680:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  681:                         $refused = 0;
  682:                     }
  683:                 }
  684:             }
  685:             if ($refused) {
  686:                 &logthis("<font color=\"blue\">WARNING: ".
  687:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  688:                          .'</font>');
  689: 	        delete($newenv->{$key});
  690:             } else {
  691:                 $env{$key}=$newenv->{$key};
  692:             }
  693:         }
  694:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  695:         if ($opened
  696: 	    && &timed_flock($env_file,LOCK_EX)
  697: 	    &&
  698: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  699: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  700: 	    while (my ($key,$value) = each(%{$newenv})) {
  701: 	        $disk_env{$key} = $value;
  702: 	    }
  703: 	    untie(%disk_env);
  704:         }
  705:     }
  706:     return 'ok';
  707: }
  708: # ----------------------------------------------------- Delete from Environment
  709: 
  710: sub delenv {
  711:     my ($delthis,$regexp,$roles) = @_;
  712:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  713:         my $refused = 1;
  714:         if (ref($roles) eq 'ARRAY') {
  715:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  716:             if (grep(/^\Q$role\E$/,@{$roles})) {
  717:                 $refused = 0;
  718:             }
  719:         }
  720:         if ($refused) {
  721:             &logthis("<font color=\"blue\">WARNING: ".
  722:                      "Attempt to delete from environment ".$delthis);
  723:             return 'error';
  724:         }
  725:     }
  726:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  727:     if ($opened
  728: 	&& &timed_flock($env_file,LOCK_EX)
  729: 	&&
  730: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  731: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  732: 	foreach my $key (keys(%disk_env)) {
  733: 	    if ($regexp) {
  734:                 if ($key=~/^$delthis/) {
  735:                     delete($env{$key});
  736:                     delete($disk_env{$key});
  737:                 } 
  738:             } else {
  739:                 if ($key=~/^\Q$delthis\E/) {
  740: 		    delete($env{$key});
  741: 		    delete($disk_env{$key});
  742: 	        }
  743:             }
  744: 	}
  745: 	untie(%disk_env);
  746:     }
  747:     return 'ok';
  748: }
  749: 
  750: sub get_env_multiple {
  751:     my ($name) = @_;
  752:     my @values;
  753:     if (defined($env{$name})) {
  754:         # exists is it an array
  755:         if (ref($env{$name})) {
  756:             @values=@{ $env{$name} };
  757:         } else {
  758:             $values[0]=$env{$name};
  759:         }
  760:     }
  761:     return(@values);
  762: }
  763: 
  764: # ------------------------------------------------------------------- Locking
  765: 
  766: sub set_lock {
  767:     my ($text)=@_;
  768:     $locknum++;
  769:     my $id=$$.'-'.$locknum;
  770:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  771:              'session.lock.'.$id => $text});
  772:     return $id;
  773: }
  774: 
  775: sub get_locks {
  776:     my $num=0;
  777:     my %texts=();
  778:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  779:        if ($lock=~/\w/) {
  780:           $num++;
  781:           $texts{$lock}=$env{'session.lock.'.$lock};
  782:        }
  783:    }
  784:    return ($num,%texts);
  785: }
  786: 
  787: sub remove_lock {
  788:     my ($id)=@_;
  789:     my $newlocks='';
  790:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  791:        if (($lock=~/\w/) && ($lock ne $id)) {
  792:           $newlocks.=','.$lock;
  793:        }
  794:     }
  795:     &appenv({'session.locks' => $newlocks});
  796:     &delenv('session.lock.'.$id);
  797: }
  798: 
  799: sub remove_all_locks {
  800:     my $activelocks=$env{'session.locks'};
  801:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  802:        if ($lock=~/\w/) {
  803:           &remove_lock($lock);
  804:        }
  805:     }
  806: }
  807: 
  808: 
  809: # ------------------------------------------ Find out current server userload
  810: sub userload {
  811:     my $numusers=0;
  812:     {
  813: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  814: 	my $filename;
  815: 	my $curtime=time;
  816: 	while ($filename=readdir(LONIDS)) {
  817: 	    next if ($filename eq '.' || $filename eq '..');
  818: 	    next if ($filename =~ /publicuser_\d+\.id/);
  819: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  820: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  821: 	}
  822: 	closedir(LONIDS);
  823:     }
  824:     my $userloadpercent=0;
  825:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  826:     if ($maxuserload) {
  827: 	$userloadpercent=100*$numusers/$maxuserload;
  828:     }
  829:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  830:     return $userloadpercent;
  831: }
  832: 
  833: # ------------------------------ Find server with least workload from spare.tab
  834: 
  835: sub spareserver {
  836:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  837:     my $spare_server;
  838:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  839:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  840:                                                      :  $userloadpercent;
  841:     my ($uint_dom,$remotesessions);
  842:     if (($udom ne '') && (&domain($udom) ne '')) {
  843:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  844:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  845:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  846:         $remotesessions = $udomdefaults{'remotesessions'};
  847:     }
  848:     my $spareshash = &this_host_spares($udom);
  849:     if (ref($spareshash) eq 'HASH') {
  850:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  851:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  852:                 if ($uint_dom) {
  853:                     next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  854:                                                  $try_server));
  855:                 }
  856: 	        ($spare_server, $lowest_load) =
  857: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  858:             }
  859:         }
  860: 
  861:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
  862: 
  863:         if (!$found_server) {
  864:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
  865: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
  866:                     if ($uint_dom) {
  867:                         next unless (&spare_can_host($udom,$uint_dom,
  868:                                                      $remotesessions,$try_server));
  869:                     }
  870: 	            ($spare_server, $lowest_load) =
  871: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
  872:                 }
  873: 	    }
  874:         }
  875:     }
  876: 
  877:     if (!$want_server_name) {
  878:         my $protocol = 'http';
  879:         if ($protocol{$spare_server} eq 'https') {
  880:             $protocol = $protocol{$spare_server};
  881:         }
  882:         if (defined($spare_server)) {
  883:             my $hostname = &hostname($spare_server);
  884:             if (defined($hostname)) {
  885: 	        $spare_server = $protocol.'://'.$hostname;
  886:             }
  887:         }
  888:     }
  889:     return $spare_server;
  890: }
  891: 
  892: sub compare_server_load {
  893:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
  894: 
  895:     if ($required) {
  896:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
  897:         my $remoterev = &get_server_loncaparev(undef,$try_server);
  898:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
  899:         if (($major eq '' && $minor eq '') ||
  900:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
  901:             return ($spare_server,$lowest_load);
  902:         }
  903:     }
  904: 
  905:     my $loadans     = &reply('load',    $try_server);
  906:     my $userloadans = &reply('userload',$try_server);
  907: 
  908:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  909: 	return ($spare_server, $lowest_load); #didn't get a number from the server
  910:     }
  911: 
  912:     my $load;
  913:     if ($loadans =~ /\d/) {
  914: 	if ($userloadans =~ /\d/) {
  915: 	    #both are numbers, pick the bigger one
  916: 	    $load = ($loadans > $userloadans) ? $loadans 
  917: 		                              : $userloadans;
  918: 	} else {
  919: 	    $load = $loadans;
  920: 	}
  921:     } else {
  922: 	$load = $userloadans;
  923:     }
  924: 
  925:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  926: 	$spare_server = $try_server;
  927: 	$lowest_load  = $load;
  928:     }
  929:     return ($spare_server,$lowest_load);
  930: }
  931: 
  932: # --------------------------- ask offload servers if user already has a session
  933: sub find_existing_session {
  934:     my ($udom,$uname) = @_;
  935:     my $spareshash = &this_host_spares($udom);
  936:     if (ref($spareshash) eq 'HASH') {
  937:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  938:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  939:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  940:             }
  941:         }
  942:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
  943:             foreach my $try_server (@{ $spareshash->{'default'} }) {
  944:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  945:             }
  946:         }
  947:     }
  948:     return;
  949: }
  950: 
  951: # -------------------------------- ask if server already has a session for user
  952: sub has_user_session {
  953:     my ($lonid,$udom,$uname) = @_;
  954:     my $result = &reply(join(':','userhassession',
  955: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  956:     return 1 if ($result eq 'ok');
  957: 
  958:     return 0;
  959: }
  960: 
  961: # --------- determine least loaded server in a user's domain which allows login
  962: 
  963: sub choose_server {
  964:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
  965:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
  966:     my %servers = &get_servers($udom);
  967:     my $lowest_load = 30000;
  968:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
  969:     if ($skiploadbal) {
  970:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
  971:         unless (defined($cached)) {
  972:             my $cachetime = 60*60*24;
  973:             my %domconfig =
  974:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
  975:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
  976:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
  977:                                            $cachetime);
  978:             }
  979:         }
  980:     }
  981:     foreach my $lonhost (keys(%servers)) {
  982:         if ($skiploadbal) {
  983:             if (ref($balancers) eq 'HASH') {
  984:                 next if (exists($balancers->{$lonhost}));
  985:             }
  986:         }   
  987:         my $loginvia;
  988:         if ($checkloginvia) {
  989:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
  990:             if ($loginvia) {
  991:                 my ($server,$path) = split(/:/,$loginvia);
  992:                 ($login_host, $lowest_load) =
  993:                     &compare_server_load($server, $login_host, $lowest_load, $required);
  994:                 if ($login_host eq $server) {
  995:                     $portal_path = $path;
  996:                     $isredirect = 1;
  997:                 }
  998:             } else {
  999:                 ($login_host, $lowest_load) =
 1000:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1001:                 if ($login_host eq $lonhost) {
 1002:                     $portal_path = '';
 1003:                     $isredirect = ''; 
 1004:                 }
 1005:             }
 1006:         } else {
 1007:             ($login_host, $lowest_load) =
 1008:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1009:         }
 1010:     }
 1011:     if ($login_host ne '') {
 1012:         $hostname = &hostname($login_host);
 1013:     }
 1014:     return ($login_host,$hostname,$portal_path,$isredirect);
 1015: }
 1016: 
 1017: # --------------------------------------------- Try to change a user's password
 1018: 
 1019: sub changepass {
 1020:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
 1021:     $currentpass = &escape($currentpass);
 1022:     $newpass     = &escape($newpass);
 1023:     my $lonhost = $perlvar{'lonHostID'};
 1024:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
 1025: 		       $server);
 1026:     if (! $answer) {
 1027: 	&logthis("No reply on password change request to $server ".
 1028: 		 "by $uname in domain $udom.");
 1029:     } elsif ($answer =~ "^ok") {
 1030:         &logthis("$uname in $udom successfully changed their password ".
 1031: 		 "on $server.");
 1032:     } elsif ($answer =~ "^pwchange_failure") {
 1033: 	&logthis("$uname in $udom was unable to change their password ".
 1034: 		 "on $server.  The action was blocked by either lcpasswd ".
 1035: 		 "or pwchange");
 1036:     } elsif ($answer =~ "^non_authorized") {
 1037:         &logthis("$uname in $udom did not get their password correct when ".
 1038: 		 "attempting to change it on $server.");
 1039:     } elsif ($answer =~ "^auth_mode_error") {
 1040:         &logthis("$uname in $udom attempted to change their password despite ".
 1041: 		 "not being locally or internally authenticated on $server.");
 1042:     } elsif ($answer =~ "^unknown_user") {
 1043:         &logthis("$uname in $udom attempted to change their password ".
 1044: 		 "on $server but were unable to because $server is not ".
 1045: 		 "their home server.");
 1046:     } elsif ($answer =~ "^refused") {
 1047: 	&logthis("$server refused to change $uname in $udom password because ".
 1048: 		 "it was sent an unencrypted request to change the password.");
 1049:     } elsif ($answer =~ "invalid_client") {
 1050:         &logthis("$server refused to change $uname in $udom password because ".
 1051:                  "it was a reset by e-mail originating from an invalid server.");
 1052:     }
 1053:     return $answer;
 1054: }
 1055: 
 1056: # ----------------------- Try to determine user's current authentication scheme
 1057: 
 1058: sub queryauthenticate {
 1059:     my ($uname,$udom)=@_;
 1060:     my $uhome=&homeserver($uname,$udom);
 1061:     if (!$uhome) {
 1062: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1063: 	return 'no_host';
 1064:     }
 1065:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1066:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1067: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1068:     }
 1069:     return $answer;
 1070: }
 1071: 
 1072: # --------- Try to authenticate user from domain's lib servers (first this one)
 1073: 
 1074: sub authenticate {
 1075:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1076:     $upass=&escape($upass);
 1077:     $uname= &LONCAPA::clean_username($uname);
 1078:     my $uhome=&homeserver($uname,$udom,1);
 1079:     my $newhome;
 1080:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1081: # Maybe the machine was offline and only re-appeared again recently?
 1082:         &reconlonc();
 1083: # One more
 1084: 	$uhome=&homeserver($uname,$udom,1);
 1085:         if (($uhome eq 'no_host') && $checkdefauth) {
 1086:             if (defined(&domain($udom,'primary'))) {
 1087:                 $newhome=&domain($udom,'primary');
 1088:             }
 1089:             if ($newhome ne '') {
 1090:                 $uhome = $newhome;
 1091:             }
 1092:         }
 1093: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1094: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1095: 	    return 'no_host';
 1096:         }
 1097:     }
 1098:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1099:     if ($answer eq 'authorized') {
 1100:         if ($newhome) {
 1101:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1102:             return 'no_account_on_host'; 
 1103:         } else {
 1104:             &logthis("User $uname at $udom authorized by $uhome");
 1105:             return $uhome;
 1106:         }
 1107:     }
 1108:     if ($answer eq 'non_authorized') {
 1109: 	&logthis("User $uname at $udom rejected by $uhome");
 1110: 	return 'no_host'; 
 1111:     }
 1112:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1113:     return 'no_host';
 1114: }
 1115: 
 1116: sub can_host_session {
 1117:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1118:     my $canhost = 1;
 1119:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1120:     if (ref($remotesessions) eq 'HASH') {
 1121:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1122:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1123:                 $canhost = 0;
 1124:             } else {
 1125:                 $canhost = 1;
 1126:             }
 1127:         }
 1128:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1129:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1130:                 $canhost = 1;
 1131:             } else {
 1132:                 $canhost = 0;
 1133:             }
 1134:         }
 1135:         if ($canhost) {
 1136:             if ($remotesessions->{'version'} ne '') {
 1137:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1138:                 if ($reqmajor ne '' && $reqminor ne '') {
 1139:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1140:                         my $major = $1;
 1141:                         my $minor = $2;
 1142:                         if (($major < $reqmajor ) ||
 1143:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1144:                             $canhost = 0;
 1145:                         }
 1146:                     } else {
 1147:                         $canhost = 0;
 1148:                     }
 1149:                 }
 1150:             }
 1151:         }
 1152:     }
 1153:     if ($canhost) {
 1154:         if (ref($hostedsessions) eq 'HASH') {
 1155:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1156:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1157:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1158:                 if (($uint_dom ne '') && 
 1159:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1160:                     $canhost = 0;
 1161:                 } else {
 1162:                     $canhost = 1;
 1163:                 }
 1164:             }
 1165:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1166:                 if (($uint_dom ne '') && 
 1167:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1168:                     $canhost = 1;
 1169:                 } else {
 1170:                     $canhost = 0;
 1171:                 }
 1172:             }
 1173:         }
 1174:     }
 1175:     return $canhost;
 1176: }
 1177: 
 1178: sub spare_can_host {
 1179:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1180:     my $canhost=1;
 1181:     my @intdoms;
 1182:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
 1183:     if (ref($internet_names) eq 'ARRAY') {
 1184:         @intdoms = @{$internet_names};
 1185:     }
 1186:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1187:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
 1188:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
 1189:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
 1190:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
 1191:         $canhost = &can_host_session($udom,$try_server,$remoterev,
 1192:                                      $remotesessions,
 1193:                                      $defdomdefaults{'hostedsessions'});
 1194:     }
 1195:     return $canhost;
 1196: }
 1197: 
 1198: sub this_host_spares {
 1199:     my ($dom) = @_;
 1200:     my ($dom_in_use,$lonhost_in_use,$result);
 1201:     my @hosts = &current_machine_ids();
 1202:     foreach my $lonhost (@hosts) {
 1203:         if (&host_domain($lonhost) eq $dom) {
 1204:             $dom_in_use = $dom;
 1205:             $lonhost_in_use = $lonhost;
 1206:             last;
 1207:         }
 1208:     }
 1209:     if ($dom_in_use ne '') {
 1210:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1211:     }
 1212:     if (ref($result) ne 'HASH') {
 1213:         $lonhost_in_use = $perlvar{'lonHostID'};
 1214:         $dom_in_use = &host_domain($lonhost_in_use);
 1215:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1216:         if (ref($result) ne 'HASH') {
 1217:             $result = \%spareid;
 1218:         }
 1219:     }
 1220:     return $result;
 1221: }
 1222: 
 1223: sub spares_for_offload  {
 1224:     my ($dom_in_use,$lonhost_in_use) = @_;
 1225:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1226:     if (defined($cached)) {
 1227:         return $result;
 1228:     } else {
 1229:         my $cachetime = 60*60*24;
 1230:         my %domconfig =
 1231:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1232:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1233:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1234:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1235:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1236:                 }
 1237:             }
 1238:         }
 1239:     }
 1240:     return;
 1241: }
 1242: 
 1243: sub get_lonbalancer_config {
 1244:     my ($servers) = @_;
 1245:     my ($currbalancer,$currtargets);
 1246:     if (ref($servers) eq 'HASH') {
 1247:         foreach my $server (keys(%{$servers})) {
 1248:             my %what = (
 1249:                          spareid => 1,
 1250:                          perlvar => 1,
 1251:                        );
 1252:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1253:             if ($result eq 'ok') {
 1254:                 if (ref($returnhash) eq 'HASH') {
 1255:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1256:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1257:                             $currbalancer = $server;
 1258:                             $currtargets = {};
 1259:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1260:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1261:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1262:                                 }
 1263:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1264:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1265:                                 }
 1266:                             }
 1267:                             last;
 1268:                         }
 1269:                     }
 1270:                 }
 1271:             }
 1272:         }
 1273:     }
 1274:     return ($currbalancer,$currtargets);
 1275: }
 1276: 
 1277: sub check_loadbalancing {
 1278:     my ($uname,$udom) = @_;
 1279:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1280:         $rule_in_effect,$offloadto,$otherserver);
 1281:     my $lonhost = $perlvar{'lonHostID'};
 1282:     my @hosts = &current_machine_ids();
 1283:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1284:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1285:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1286:     my $serverhomedom = &host_domain($lonhost);
 1287: 
 1288:     my $cachetime = 60*60*24;
 1289: 
 1290:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1291:         $dom_in_use = $udom;
 1292:         $homeintdom = 1;
 1293:     } else {
 1294:         $dom_in_use = $serverhomedom;
 1295:     }
 1296:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1297:     unless (defined($cached)) {
 1298:         my %domconfig =
 1299:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1300:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1301:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1302:         }
 1303:     }
 1304:     if (ref($result) eq 'HASH') {
 1305:         ($is_balancer,$currtargets,$currrules) = 
 1306:             &check_balancer_result($result,@hosts);
 1307:         if ($is_balancer) {
 1308:             if (ref($currrules) eq 'HASH') {
 1309:                 if ($homeintdom) {
 1310:                     if ($uname ne '') {
 1311:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1312:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1313:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1314:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1315:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1316:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1317:                             }
 1318:                         }
 1319:                         if ($rule_in_effect eq '') {
 1320:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1321:                             if ($userenv{'inststatus'} ne '') {
 1322:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1323:                                 my ($othertitle,$usertypes,$types) =
 1324:                                     &Apache::loncommon::sorted_inst_types($udom);
 1325:                                 if (ref($types) eq 'ARRAY') {
 1326:                                     foreach my $type (@{$types}) {
 1327:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1328:                                             if (exists($currrules->{$type})) {
 1329:                                                 $rule_in_effect = $currrules->{$type};
 1330:                                             }
 1331:                                         }
 1332:                                     }
 1333:                                 }
 1334:                             } else {
 1335:                                 if (exists($currrules->{'default'})) {
 1336:                                     $rule_in_effect = $currrules->{'default'};
 1337:                                 }
 1338:                             }
 1339:                         }
 1340:                     } else {
 1341:                         if (exists($currrules->{'default'})) {
 1342:                             $rule_in_effect = $currrules->{'default'};
 1343:                         }
 1344:                     }
 1345:                 } else {
 1346:                     if ($currrules->{'_LC_external'} ne '') {
 1347:                         $rule_in_effect = $currrules->{'_LC_external'};
 1348:                     }
 1349:                 }
 1350:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1351:                                                        $uname,$udom);
 1352:             }
 1353:         }
 1354:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1355:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1356:         unless (defined($cached)) {
 1357:             my %domconfig =
 1358:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1359:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1360:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1361:             }
 1362:         }
 1363:         if (ref($result) eq 'HASH') {
 1364:             ($is_balancer,$currtargets,$currrules) = 
 1365:                 &check_balancer_result($result,@hosts);
 1366:             if ($is_balancer) {
 1367:                 if (ref($currrules) eq 'HASH') {
 1368:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1369:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1370:                     }
 1371:                 }
 1372:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1373:                                                        $uname,$udom);
 1374:             }
 1375:         } else {
 1376:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1377:                 $is_balancer = 1;
 1378:                 $offloadto = &this_host_spares($dom_in_use);
 1379:             }
 1380:         }
 1381:     } else {
 1382:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1383:             $is_balancer = 1;
 1384:             $offloadto = &this_host_spares($dom_in_use);
 1385:         }
 1386:     }
 1387:     if ($is_balancer) {
 1388:         my $lowest_load = 30000;
 1389:         if (ref($offloadto) eq 'HASH') {
 1390:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1391:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1392:                     ($otherserver,$lowest_load) =
 1393:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1394:                 }
 1395:             }
 1396:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1397: 
 1398:             if (!$found_server) {
 1399:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1400:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1401:                         ($otherserver,$lowest_load) =
 1402:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1403:                     }
 1404:                 }
 1405:             }
 1406:         } elsif (ref($offloadto) eq 'ARRAY') {
 1407:             if (@{$offloadto} == 1) {
 1408:                 $otherserver = $offloadto->[0];
 1409:             } elsif (@{$offloadto} > 1) {
 1410:                 foreach my $try_server (@{$offloadto}) {
 1411:                     ($otherserver,$lowest_load) =
 1412:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1413:                 }
 1414:             }
 1415:         }
 1416:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1417:             $is_balancer = 0;
 1418:             if ($uname ne '' && $udom ne '') {
 1419:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1420:                     
 1421:                     &appenv({'user.loadbalexempt'     => $lonhost,  
 1422:                              'user.loadbalcheck.time' => time});
 1423:                 }
 1424:             }
 1425:         }
 1426:     }
 1427:     return ($is_balancer,$otherserver);
 1428: }
 1429: 
 1430: sub check_balancer_result {
 1431:     my ($result,@hosts) = @_;
 1432:     my ($is_balancer,$currtargets,$currrules);
 1433:     if (ref($result) eq 'HASH') {
 1434:         if ($result->{'lonhost'} ne '') {
 1435:             my $currbalancer = $result->{'lonhost'};
 1436:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1437:                 $is_balancer = 1;
 1438:                 $currtargets = $result->{'targets'};
 1439:                 $currrules = $result->{'rules'};
 1440:             }
 1441:         } else {
 1442:             foreach my $key (keys(%{$result})) {
 1443:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1444:                     (ref($result->{$key}) eq 'HASH')) {
 1445:                     $is_balancer = 1;
 1446:                     $currrules = $result->{$key}{'rules'};
 1447:                     $currtargets = $result->{$key}{'targets'};
 1448:                     last;
 1449:                 }
 1450:             }
 1451:         }
 1452:     }
 1453:     return ($is_balancer,$currtargets,$currrules);
 1454: }
 1455: 
 1456: sub get_loadbalancer_targets {
 1457:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1458:     my $offloadto;
 1459:     if ($rule_in_effect eq 'none') {
 1460:         return [$perlvar{'lonHostID'}];
 1461:     } elsif ($rule_in_effect eq '') {
 1462:         $offloadto = $currtargets;
 1463:     } else {
 1464:         if ($rule_in_effect eq 'homeserver') {
 1465:             my $homeserver = &homeserver($uname,$udom);
 1466:             if ($homeserver ne 'no_host') {
 1467:                 $offloadto = [$homeserver];
 1468:             }
 1469:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1470:             my %domconfig =
 1471:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1472:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1473:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1474:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1475:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1476:                     }
 1477:                 }
 1478:             } else {
 1479:                 my %servers = &internet_dom_servers($udom);
 1480:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1481:                 if (&hostname($remotebalancer) ne '') {
 1482:                     $offloadto = [$remotebalancer];
 1483:                 }
 1484:             }
 1485:         } elsif (&hostname($rule_in_effect) ne '') {
 1486:             $offloadto = [$rule_in_effect];
 1487:         }
 1488:     }
 1489:     return $offloadto;
 1490: }
 1491: 
 1492: sub internet_dom_servers {
 1493:     my ($dom) = @_;
 1494:     my (%uniqservers,%servers);
 1495:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1496:     my @machinedoms = &machine_domains($primaryserver);
 1497:     foreach my $mdom (@machinedoms) {
 1498:         my %currservers = %servers;
 1499:         my %server = &get_servers($mdom);
 1500:         %servers = (%currservers,%server);
 1501:     }
 1502:     my %by_hostname;
 1503:     foreach my $id (keys(%servers)) {
 1504:         push(@{$by_hostname{$servers{$id}}},$id);
 1505:     }
 1506:     foreach my $hostname (sort(keys(%by_hostname))) {
 1507:         if (@{$by_hostname{$hostname}} > 1) {
 1508:             my $match = 0;
 1509:             foreach my $id (@{$by_hostname{$hostname}}) {
 1510:                 if (&host_domain($id) eq $dom) {
 1511:                     $uniqservers{$id} = $hostname;
 1512:                     $match = 1;
 1513:                 }
 1514:             }
 1515:             unless ($match) {
 1516:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1517:             }
 1518:         } else {
 1519:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1520:         }
 1521:     }
 1522:     return %uniqservers;
 1523: }
 1524: 
 1525: # ---------------------- Find the homebase for a user from domain's lib servers
 1526: 
 1527: my %homecache;
 1528: sub homeserver {
 1529:     my ($uname,$udom,$ignoreBadCache)=@_;
 1530:     my $index="$uname:$udom";
 1531: 
 1532:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1533: 
 1534:     my %servers = &get_servers($udom,'library');
 1535:     foreach my $tryserver (keys(%servers)) {
 1536:         next if ($ignoreBadCache ne 'true' && 
 1537: 		 exists($badServerCache{$tryserver}));
 1538: 
 1539: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1540: 	if ($answer eq 'found') {
 1541: 	    delete($badServerCache{$tryserver}); 
 1542: 	    return $homecache{$index}=$tryserver;
 1543: 	} elsif ($answer eq 'no_host') {
 1544: 	    $badServerCache{$tryserver}=1;
 1545: 	}
 1546:     }    
 1547:     return 'no_host';
 1548: }
 1549: 
 1550: # ------------------------------------- Find the usernames behind a list of IDs
 1551: 
 1552: sub idget {
 1553:     my ($udom,@ids)=@_;
 1554:     my %returnhash=();
 1555:     
 1556:     my %servers = &get_servers($udom,'library');
 1557:     foreach my $tryserver (keys(%servers)) {
 1558: 	my $idlist=join('&',@ids);
 1559: 	$idlist=~tr/A-Z/a-z/; 
 1560: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1561: 	my @answer=();
 1562: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1563: 	    @answer=split(/\&/,$reply);
 1564: 	}                    ;
 1565: 	my $i;
 1566: 	for ($i=0;$i<=$#ids;$i++) {
 1567: 	    if ($answer[$i]) {
 1568: 		$returnhash{$ids[$i]}=$answer[$i];
 1569: 	    } 
 1570: 	}
 1571:     } 
 1572:     return %returnhash;
 1573: }
 1574: 
 1575: # ------------------------------------- Find the IDs behind a list of usernames
 1576: 
 1577: sub idrget {
 1578:     my ($udom,@unames)=@_;
 1579:     my %returnhash=();
 1580:     foreach my $uname (@unames) {
 1581:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1582:     }
 1583:     return %returnhash;
 1584: }
 1585: 
 1586: # ------------------------------- Store away a list of names and associated IDs
 1587: 
 1588: sub idput {
 1589:     my ($udom,%ids)=@_;
 1590:     my %servers=();
 1591:     foreach my $uname (keys(%ids)) {
 1592: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1593:         my $uhom=&homeserver($uname,$udom);
 1594:         if ($uhom ne 'no_host') {
 1595:             my $id=&escape($ids{$uname});
 1596:             $id=~tr/A-Z/a-z/;
 1597:             my $esc_unam=&escape($uname);
 1598: 	    if ($servers{$uhom}) {
 1599: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
 1600:             } else {
 1601:                 $servers{$uhom}=$id.'='.$esc_unam;
 1602:             }
 1603:         }
 1604:     }
 1605:     foreach my $server (keys(%servers)) {
 1606:         &critical('idput:'.$udom.':'.$servers{$server},$server);
 1607:     }
 1608: }
 1609: 
 1610: # ---------------------------------------- Delete unwanted IDs from ids.db file 
 1611: 
 1612: sub iddel {
 1613:     my ($udom,$idshashref,$uhome)=@_;
 1614:     my %result=();
 1615:     unless (ref($idshashref) eq 'HASH') {
 1616:         return %result;
 1617:     }
 1618:     my %servers=();
 1619:     while (my ($id,$uname) = each(%{$idshashref})) {
 1620:         my $uhom;
 1621:         if ($uhome) {
 1622:             $uhom = $uhome;
 1623:         } else {
 1624:             $uhom=&homeserver($uname,$udom);
 1625:         }
 1626:         if ($uhom ne 'no_host') {
 1627:             if ($servers{$uhom}) {
 1628:                 $servers{$uhom}.='&'.&escape($id);
 1629:             } else {
 1630:                 $servers{$uhom}=&escape($id);
 1631:             }
 1632:         }
 1633:     }
 1634:     foreach my $server (keys(%servers)) {
 1635:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
 1636:     }
 1637:     return %result;
 1638: }
 1639: 
 1640: # ------------------------------dump from db file owned by domainconfig user
 1641: sub dump_dom {
 1642:     my ($namespace, $udom, $regexp) = @_;
 1643: 
 1644:     $udom ||= $env{'user.domain'};
 1645: 
 1646:     return () unless $udom;
 1647: 
 1648:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 1649: }
 1650: 
 1651: # ------------------------------------------ get items from domain db files   
 1652: 
 1653: sub get_dom {
 1654:     my ($namespace,$storearr,$udom,$uhome)=@_;
 1655:     return if ($udom eq 'public');
 1656:     my $items='';
 1657:     foreach my $item (@$storearr) {
 1658:         $items.=&escape($item).'&';
 1659:     }
 1660:     $items=~s/\&$//;
 1661:     if (!$udom) {
 1662:         $udom=$env{'user.domain'};
 1663:         return if ($udom eq 'public');
 1664:         if (defined(&domain($udom,'primary'))) {
 1665:             $uhome=&domain($udom,'primary');
 1666:         } else {
 1667:             undef($uhome);
 1668:         }
 1669:     } else {
 1670:         if (!$uhome) {
 1671:             if (defined(&domain($udom,'primary'))) {
 1672:                 $uhome=&domain($udom,'primary');
 1673:             }
 1674:         }
 1675:     }
 1676:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1677:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 1678:         my %returnhash;
 1679:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 1680:             return %returnhash;
 1681:         }
 1682:         my @pairs=split(/\&/,$rep);
 1683:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1684:             return @pairs;
 1685:         }
 1686:         my $i=0;
 1687:         foreach my $item (@$storearr) {
 1688:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 1689:             $i++;
 1690:         }
 1691:         return %returnhash;
 1692:     } else {
 1693:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1694:     }
 1695: }
 1696: 
 1697: # -------------------------------------------- put items in domain db files 
 1698: 
 1699: sub put_dom {
 1700:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1701:     if (!$udom) {
 1702:         $udom=$env{'user.domain'};
 1703:         if (defined(&domain($udom,'primary'))) {
 1704:             $uhome=&domain($udom,'primary');
 1705:         } else {
 1706:             undef($uhome);
 1707:         }
 1708:     } else {
 1709:         if (!$uhome) {
 1710:             if (defined(&domain($udom,'primary'))) {
 1711:                 $uhome=&domain($udom,'primary');
 1712:             }
 1713:         }
 1714:     } 
 1715:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1716:         my $items='';
 1717:         foreach my $item (keys(%$storehash)) {
 1718:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 1719:         }
 1720:         $items=~s/\&$//;
 1721:         return &reply("putdom:$udom:$namespace:$items",$uhome);
 1722:     } else {
 1723:         &logthis("put_dom failed - no homeserver and/or domain");
 1724:     }
 1725: }
 1726: 
 1727: # --------------------- newput for items in db file owned by domainconfig user
 1728: sub newput_dom {
 1729:     my ($namespace,$storehash,$udom) = @_;
 1730:     my $result;
 1731:     if (!$udom) {
 1732:         $udom=$env{'user.domain'};
 1733:     }
 1734:     if ($udom) {
 1735:         my $uname = &get_domainconfiguser($udom);
 1736:         $result = &newput($namespace,$storehash,$udom,$uname);
 1737:     }
 1738:     return $result;
 1739: }
 1740: 
 1741: # --------------------- delete for items in db file owned by domainconfig user
 1742: sub del_dom {
 1743:     my ($namespace,$storearr,$udom)=@_;
 1744:     if (ref($storearr) eq 'ARRAY') {
 1745:         if (!$udom) {
 1746:             $udom=$env{'user.domain'};
 1747:         }
 1748:         if ($udom) {
 1749:             my $uname = &get_domainconfiguser($udom); 
 1750:             return &del($namespace,$storearr,$udom,$uname);
 1751:         }
 1752:     }
 1753: }
 1754: 
 1755: # ----------------------------------construct domainconfig user for a domain 
 1756: sub get_domainconfiguser {
 1757:     my ($udom) = @_;
 1758:     return $udom.'-domainconfig';
 1759: }
 1760: 
 1761: sub retrieve_inst_usertypes {
 1762:     my ($udom) = @_;
 1763:     my (%returnhash,@order);
 1764:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 1765:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 1766:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 1767:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
 1768:     } else {
 1769:         if (defined(&domain($udom,'primary'))) {
 1770:             my $uhome=&domain($udom,'primary');
 1771:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 1772:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 1773:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
 1774:                 return (\%returnhash,\@order);
 1775:             }
 1776:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 1777:             my @pairs=split(/\&/,$hashitems);
 1778:             foreach my $item (@pairs) {
 1779:                 my ($key,$value)=split(/=/,$item,2);
 1780:                 $key = &unescape($key);
 1781:                 next if ($key =~ /^error: 2 /);
 1782:                 $returnhash{$key}=&thaw_unescape($value);
 1783:             }
 1784:             my @esc_order = split(/\&/,$orderitems);
 1785:             foreach my $item (@esc_order) {
 1786:                 push(@order,&unescape($item));
 1787:             }
 1788:         } else {
 1789:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
 1790:         }
 1791:         return (\%returnhash,\@order);
 1792:     }
 1793: }
 1794: 
 1795: sub is_domainimage {
 1796:     my ($url) = @_;
 1797:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1798:         if (&domain($1) ne '') {
 1799:             return '1';
 1800:         }
 1801:     }
 1802:     return;
 1803: }
 1804: 
 1805: sub inst_directory_query {
 1806:     my ($srch) = @_;
 1807:     my $udom = $srch->{'srchdomain'};
 1808:     my %results;
 1809:     my $homeserver = &domain($udom,'primary');
 1810:     my $outcome;
 1811:     if ($homeserver ne '') {
 1812: 	my $queryid=&reply("querysend:instdirsearch:".
 1813: 			   &escape($srch->{'srchby'}).':'.
 1814: 			   &escape($srch->{'srchterm'}).':'.
 1815: 			   &escape($srch->{'srchtype'}),$homeserver);
 1816: 	my $host=&hostname($homeserver);
 1817: 	if ($queryid !~/^\Q$host\E\_/) {
 1818: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1819: 	    return;
 1820: 	}
 1821: 	my $response = &get_query_reply($queryid);
 1822: 	my $maxtries = 5;
 1823: 	my $tries = 1;
 1824: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1825: 	    $response = &get_query_reply($queryid);
 1826: 	    $tries ++;
 1827: 	}
 1828: 
 1829:         if (!&error($response) && $response ne 'refused') {
 1830:             if ($response eq 'unavailable') {
 1831:                 $outcome = $response;
 1832:             } else {
 1833:                 $outcome = 'ok';
 1834:                 my @matches = split(/\n/,$response);
 1835:                 foreach my $match (@matches) {
 1836:                     my ($key,$value) = split(/=/,$match);
 1837:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1838:                 }
 1839:             }
 1840:         }
 1841:     }
 1842:     return ($outcome,%results);
 1843: }
 1844: 
 1845: sub usersearch {
 1846:     my ($srch) = @_;
 1847:     my $dom = $srch->{'srchdomain'};
 1848:     my %results;
 1849:     my %libserv = &all_library();
 1850:     my $query = 'usersearch';
 1851:     foreach my $tryserver (keys(%libserv)) {
 1852:         if (&host_domain($tryserver) eq $dom) {
 1853:             my $host=&hostname($tryserver);
 1854:             my $queryid=
 1855:                 &reply("querysend:".&escape($query).':'.
 1856:                        &escape($srch->{'srchby'}).':'.
 1857:                        &escape($srch->{'srchtype'}).':'.
 1858:                        &escape($srch->{'srchterm'}),$tryserver);
 1859:             if ($queryid !~/^\Q$host\E\_/) {
 1860:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1861:                 next;
 1862:             }
 1863:             my $reply = &get_query_reply($queryid);
 1864:             my $maxtries = 1;
 1865:             my $tries = 1;
 1866:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1867:                 $reply = &get_query_reply($queryid);
 1868:                 $tries ++;
 1869:             }
 1870:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1871:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1872:             } else {
 1873:                 my @matches;
 1874:                 if ($reply =~ /\n/) {
 1875:                     @matches = split(/\n/,$reply);
 1876:                 } else {
 1877:                     @matches = split(/\&/,$reply);
 1878:                 }
 1879:                 foreach my $match (@matches) {
 1880:                     my ($uname,$udom,%userhash);
 1881:                     foreach my $entry (split(/:/,$match)) {
 1882:                         my ($key,$value) =
 1883:                             map {&unescape($_);} split(/=/,$entry);
 1884:                         $userhash{$key} = $value;
 1885:                         if ($key eq 'username') {
 1886:                             $uname = $value;
 1887:                         } elsif ($key eq 'domain') {
 1888:                             $udom = $value;
 1889:                         }
 1890:                     }
 1891:                     $results{$uname.':'.$udom} = \%userhash;
 1892:                 }
 1893:             }
 1894:         }
 1895:     }
 1896:     return %results;
 1897: }
 1898: 
 1899: sub get_instuser {
 1900:     my ($udom,$uname,$id) = @_;
 1901:     my $homeserver = &domain($udom,'primary');
 1902:     my ($outcome,%results);
 1903:     if ($homeserver ne '') {
 1904:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1905:                            &escape($id).':'.&escape($udom),$homeserver);
 1906:         my $host=&hostname($homeserver);
 1907:         if ($queryid !~/^\Q$host\E\_/) {
 1908:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1909:             return;
 1910:         }
 1911:         my $response = &get_query_reply($queryid);
 1912:         my $maxtries = 5;
 1913:         my $tries = 1;
 1914:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1915:             $response = &get_query_reply($queryid);
 1916:             $tries ++;
 1917:         }
 1918:         if (!&error($response) && $response ne 'refused') {
 1919:             if ($response eq 'unavailable') {
 1920:                 $outcome = $response;
 1921:             } else {
 1922:                 $outcome = 'ok';
 1923:                 my @matches = split(/\n/,$response);
 1924:                 foreach my $match (@matches) {
 1925:                     my ($key,$value) = split(/=/,$match);
 1926:                     $results{&unescape($key)} = &thaw_unescape($value);
 1927:                 }
 1928:             }
 1929:         }
 1930:     }
 1931:     my %userinfo;
 1932:     if (ref($results{$uname}) eq 'HASH') {
 1933:         %userinfo = %{$results{$uname}};
 1934:     } 
 1935:     return ($outcome,%userinfo);
 1936: }
 1937: 
 1938: sub inst_rulecheck {
 1939:     my ($udom,$uname,$id,$item,$rules) = @_;
 1940:     my %returnhash;
 1941:     if ($udom ne '') {
 1942:         if (ref($rules) eq 'ARRAY') {
 1943:             @{$rules} = map {&escape($_);} (@{$rules});
 1944:             my $rulestr = join(':',@{$rules});
 1945:             my $homeserver=&domain($udom,'primary');
 1946:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1947:                 my $response;
 1948:                 if ($item eq 'username') {                
 1949:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1950:                                               ':'.&escape($uname).':'.$rulestr,
 1951:                                               $homeserver));
 1952:                 } elsif ($item eq 'id') {
 1953:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1954:                                               ':'.&escape($id).':'.$rulestr,
 1955:                                               $homeserver));
 1956:                 } elsif ($item eq 'selfcreate') {
 1957:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1958:                                                &escape($udom).':'.&escape($uname).
 1959:                                               ':'.$rulestr,$homeserver));
 1960:                 }
 1961:                 if ($response ne 'refused') {
 1962:                     my @pairs=split(/\&/,$response);
 1963:                     foreach my $item (@pairs) {
 1964:                         my ($key,$value)=split(/=/,$item,2);
 1965:                         $key = &unescape($key);
 1966:                         next if ($key =~ /^error: 2 /);
 1967:                         $returnhash{$key}=&thaw_unescape($value);
 1968:                     }
 1969:                 }
 1970:             }
 1971:         }
 1972:     }
 1973:     return %returnhash;
 1974: }
 1975: 
 1976: sub inst_userrules {
 1977:     my ($udom,$check) = @_;
 1978:     my (%ruleshash,@ruleorder);
 1979:     if ($udom ne '') {
 1980:         my $homeserver=&domain($udom,'primary');
 1981:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1982:             my $response;
 1983:             if ($check eq 'id') {
 1984:                 $response=&reply('instidrules:'.&escape($udom),
 1985:                                  $homeserver);
 1986:             } elsif ($check eq 'email') {
 1987:                 $response=&reply('instemailrules:'.&escape($udom),
 1988:                                  $homeserver);
 1989:             } else {
 1990:                 $response=&reply('instuserrules:'.&escape($udom),
 1991:                                  $homeserver);
 1992:             }
 1993:             if (($response ne 'refused') && ($response ne 'error') && 
 1994:                 ($response ne 'unknown_cmd') && 
 1995:                 ($response ne 'no_such_host')) {
 1996:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1997:                 my @pairs=split(/\&/,$hashitems);
 1998:                 foreach my $item (@pairs) {
 1999:                     my ($key,$value)=split(/=/,$item,2);
 2000:                     $key = &unescape($key);
 2001:                     next if ($key =~ /^error: 2 /);
 2002:                     $ruleshash{$key}=&thaw_unescape($value);
 2003:                 }
 2004:                 my @esc_order = split(/\&/,$orderitems);
 2005:                 foreach my $item (@esc_order) {
 2006:                     push(@ruleorder,&unescape($item));
 2007:                 }
 2008:             }
 2009:         }
 2010:     }
 2011:     return (\%ruleshash,\@ruleorder);
 2012: }
 2013: 
 2014: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 2015: 
 2016: sub get_domain_defaults {
 2017:     my ($domain,$ignore_cache) = @_;
 2018:     return if (($domain eq '') || ($domain eq 'public'));
 2019:     my $cachetime = 60*60*24;
 2020:     unless ($ignore_cache) {
 2021:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 2022:         if (defined($cached)) {
 2023:             if (ref($result) eq 'HASH') {
 2024:                 return %{$result};
 2025:             }
 2026:         }
 2027:     }
 2028:     my %domdefaults;
 2029:     my %domconfig =
 2030:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 2031:                                   'requestcourses','inststatus',
 2032:                                   'coursedefaults','usersessions',
 2033:                                   'requestauthor','selfenrollment',
 2034:                                   'coursecategories'],$domain);
 2035:     my @coursetypes = ('official','unofficial','community','textbook');
 2036:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2037:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2038:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2039:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2040:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2041:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2042:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2043:     } else {
 2044:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2045:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2046:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2047:     }
 2048:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2049:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2050:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2051:         } else {
 2052:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2053:         }
 2054:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2055:         foreach my $item (@usertools) {
 2056:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2057:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2058:             }
 2059:         }
 2060:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2061:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2062:         }
 2063:     }
 2064:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2065:         foreach my $item ('official','unofficial','community','textbook') {
 2066:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2067:         }
 2068:     }
 2069:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2070:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2071:     }
 2072:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2073:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
 2074:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2075:         }
 2076:     }
 2077:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2078:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
 2079:         foreach my $type (@coursetypes) {
 2080:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2081:                 unless ($type eq 'community') {
 2082:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
 2083:                 }
 2084:             }
 2085:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2086:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
 2087:             }
 2088:         }
 2089:     }
 2090:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2091:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2092:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2093:         }
 2094:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2095:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2096:         }
 2097:     }
 2098:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
 2099:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
 2100:             my @settings = ('types','registered','enroll_dates','access_dates','section',
 2101:                             'approval','limit');
 2102:             foreach my $type (@coursetypes) {
 2103:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
 2104:                     my @mgrdc = ();
 2105:                     foreach my $item (@settings) {
 2106:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
 2107:                             push(@mgrdc,$item);
 2108:                         }
 2109:                     }
 2110:                     if (@mgrdc) {
 2111:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
 2112:                     }
 2113:                 }
 2114:             }
 2115:         }
 2116:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
 2117:             foreach my $type (@coursetypes) {
 2118:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
 2119:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
 2120:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
 2121:                     }
 2122:                 }
 2123:             }
 2124:         }
 2125:     }
 2126:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2127:         $domdefaults{'catauth'} = 'std';
 2128:         $domdefaults{'catunauth'} = 'std';
 2129:         if ($domconfig{'coursecategories'}{'auth'}) { 
 2130:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
 2131:         }
 2132:         if ($domconfig{'coursecategories'}{'unauth'}) {
 2133:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
 2134:         }
 2135:     }
 2136:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2137:     return %domdefaults;
 2138: }
 2139: 
 2140: # --------------------------------------------------- Assign a key to a student
 2141: 
 2142: sub assign_access_key {
 2143: #
 2144: # a valid key looks like uname:udom#comments
 2145: # comments are being appended
 2146: #
 2147:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2148:     $kdom=
 2149:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2150:     $knum=
 2151:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2152:     $cdom=
 2153:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2154:     $cnum=
 2155:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2156:     $udom=$env{'user.name'} unless (defined($udom));
 2157:     $uname=$env{'user.domain'} unless (defined($uname));
 2158:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2159:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2160:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2161:                                                   # assigned to this person
 2162:                                                   # - this should not happen,
 2163:                                                   # unless something went wrong
 2164:                                                   # the first time around
 2165: # ready to assign
 2166:         $logentry=$1.'; '.$logentry;
 2167:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2168:                                                  $kdom,$knum) eq 'ok') {
 2169: # key now belongs to user
 2170: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2171:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2172:                 &appenv({'environment.'.$envkey => $ckey});
 2173:                 return 'ok';
 2174:             } else {
 2175:                 return 
 2176:   'error: Count not permanently assign key, will need to be re-entered later.';
 2177: 	    }
 2178:         } else {
 2179:             return 'error: Could not assign key, try again later.';
 2180:         }
 2181:     } elsif (!$existing{$ckey}) {
 2182: # the key does not exist
 2183: 	return 'error: The key does not exist';
 2184:     } else {
 2185: # the key is somebody else's
 2186: 	return 'error: The key is already in use';
 2187:     }
 2188: }
 2189: 
 2190: # ------------------------------------------ put an additional comment on a key
 2191: 
 2192: sub comment_access_key {
 2193: #
 2194: # a valid key looks like uname:udom#comments
 2195: # comments are being appended
 2196: #
 2197:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2198:     $cdom=
 2199:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2200:     $cnum=
 2201:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2202:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2203:     if ($existing{$ckey}) {
 2204:         $existing{$ckey}.='; '.$logentry;
 2205: # ready to assign
 2206:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2207:                                                  $cdom,$cnum) eq 'ok') {
 2208: 	    return 'ok';
 2209:         } else {
 2210: 	    return 'error: Count not store comment.';
 2211:         }
 2212:     } else {
 2213: # the key does not exist
 2214: 	return 'error: The key does not exist';
 2215:     }
 2216: }
 2217: 
 2218: # ------------------------------------------------------ Generate a set of keys
 2219: 
 2220: sub generate_access_keys {
 2221:     my ($number,$cdom,$cnum,$logentry)=@_;
 2222:     $cdom=
 2223:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2224:     $cnum=
 2225:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2226:     unless (&allowed('mky',$cdom)) { return 0; }
 2227:     unless (($cdom) && ($cnum)) { return 0; }
 2228:     if ($number>10000) { return 0; }
 2229:     sleep(2); # make sure don't get same seed twice
 2230:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2231:     my $total=0;
 2232:     for (my $i=1;$i<=$number;$i++) {
 2233:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2234:                   sprintf("%lx",int(100000*rand)).'-'.
 2235:                   sprintf("%lx",int(100000*rand));
 2236:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2237:        $newkey=~s/0/h/g; # and also 0 and O
 2238:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2239:        if ($existing{$newkey}) {
 2240:            $i--;
 2241:        } else {
 2242: 	  if (&put('accesskeys',
 2243:               { $newkey => '# generated '.localtime().
 2244:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2245:                            '; '.$logentry },
 2246: 		   $cdom,$cnum) eq 'ok') {
 2247:               $total++;
 2248: 	  }
 2249:        }
 2250:     }
 2251:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2252:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2253:     return $total;
 2254: }
 2255: 
 2256: # ------------------------------------------------------- Validate an accesskey
 2257: 
 2258: sub validate_access_key {
 2259:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2260:     $cdom=
 2261:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2262:     $cnum=
 2263:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2264:     $udom=$env{'user.domain'} unless (defined($udom));
 2265:     $uname=$env{'user.name'} unless (defined($uname));
 2266:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2267:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2268: }
 2269: 
 2270: # ------------------------------------- Find the section of student in a course
 2271: sub devalidate_getsection_cache {
 2272:     my ($udom,$unam,$courseid)=@_;
 2273:     my $hashid="$udom:$unam:$courseid";
 2274:     &devalidate_cache_new('getsection',$hashid);
 2275: }
 2276: 
 2277: sub courseid_to_courseurl {
 2278:     my ($courseid) = @_;
 2279:     #already url style courseid
 2280:     return $courseid if ($courseid =~ m{^/});
 2281: 
 2282:     if (exists($env{'course.'.$courseid.'.num'})) {
 2283: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2284: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2285: 	return "/$cdom/$cnum";
 2286:     }
 2287: 
 2288:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2289:     if (exists($courseinfo{'num'})) {
 2290: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2291:     }
 2292: 
 2293:     return undef;
 2294: }
 2295: 
 2296: sub getsection {
 2297:     my ($udom,$unam,$courseid)=@_;
 2298:     my $cachetime=1800;
 2299: 
 2300:     my $hashid="$udom:$unam:$courseid";
 2301:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2302:     if (defined($cached)) { return $result; }
 2303: 
 2304:     my %Pending; 
 2305:     my %Expired;
 2306:     #
 2307:     # Each role can either have not started yet (pending), be active, 
 2308:     #    or have expired.
 2309:     #
 2310:     # If there is an active role, we are done.
 2311:     #
 2312:     # If there is more than one role which has not started yet, 
 2313:     #     choose the one which will start sooner
 2314:     # If there is one role which has not started yet, return it.
 2315:     #
 2316:     # If there is more than one expired role, choose the one which ended last.
 2317:     # If there is a role which has expired, return it.
 2318:     #
 2319:     $courseid = &courseid_to_courseurl($courseid);
 2320:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 2321:     foreach my $key (keys(%roleshash)) {
 2322:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2323:         my $section=$1;
 2324:         if ($key eq $courseid.'_st') { $section=''; }
 2325:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2326:         my $now=time;
 2327:         if (defined($end) && $end && ($now > $end)) {
 2328:             $Expired{$end}=$section;
 2329:             next;
 2330:         }
 2331:         if (defined($start) && $start && ($now < $start)) {
 2332:             $Pending{$start}=$section;
 2333:             next;
 2334:         }
 2335:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2336:     }
 2337:     #
 2338:     # Presumedly there will be few matching roles from the above
 2339:     # loop and the sorting time will be negligible.
 2340:     if (scalar(keys(%Pending))) {
 2341:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2342:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2343:     } 
 2344:     if (scalar(keys(%Expired))) {
 2345:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2346:         my $time = pop(@sorted);
 2347:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2348:     }
 2349:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2350: }
 2351: 
 2352: sub save_cache {
 2353:     &purge_remembered();
 2354:     #&Apache::loncommon::validate_page();
 2355:     undef(%env);
 2356:     undef($env_loaded);
 2357: }
 2358: 
 2359: my $to_remember=-1;
 2360: my %remembered;
 2361: my %accessed;
 2362: my $kicks=0;
 2363: my $hits=0;
 2364: sub make_key {
 2365:     my ($name,$id) = @_;
 2366:     if (length($id) > 65 
 2367: 	&& length(&escape($id)) > 200) {
 2368: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2369:     }
 2370:     return &escape($name.':'.$id);
 2371: }
 2372: 
 2373: sub devalidate_cache_new {
 2374:     my ($name,$id,$debug) = @_;
 2375:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2376:     $id=&make_key($name,$id);
 2377:     $memcache->delete($id);
 2378:     delete($remembered{$id});
 2379:     delete($accessed{$id});
 2380: }
 2381: 
 2382: sub is_cached_new {
 2383:     my ($name,$id,$debug) = @_;
 2384:     $id=&make_key($name,$id);
 2385:     if (exists($remembered{$id})) {
 2386: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
 2387: 	$accessed{$id}=[&gettimeofday()];
 2388: 	$hits++;
 2389: 	return ($remembered{$id},1);
 2390:     }
 2391:     my $value = $memcache->get($id);
 2392:     if (!(defined($value))) {
 2393: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2394: 	return (undef,undef);
 2395:     }
 2396:     if ($value eq '__undef__') {
 2397: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2398: 	$value=undef;
 2399:     }
 2400:     &make_room($id,$value,$debug);
 2401:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2402:     return ($value,1);
 2403: }
 2404: 
 2405: sub do_cache_new {
 2406:     my ($name,$id,$value,$time,$debug) = @_;
 2407:     $id=&make_key($name,$id);
 2408:     my $setvalue=$value;
 2409:     if (!defined($setvalue)) {
 2410: 	$setvalue='__undef__';
 2411:     }
 2412:     if (!defined($time) ) {
 2413: 	$time=600;
 2414:     }
 2415:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 2416:     my $result = $memcache->set($id,$setvalue,$time);
 2417:     if (! $result) {
 2418: 	&logthis("caching of id -> $id  failed");
 2419: 	$memcache->disconnect_all();
 2420:     }
 2421:     # need to make a copy of $value
 2422:     &make_room($id,$value,$debug);
 2423:     return $value;
 2424: }
 2425: 
 2426: sub make_room {
 2427:     my ($id,$value,$debug)=@_;
 2428: 
 2429:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 2430:                                     : $value;
 2431:     if ($to_remember<0) { return; }
 2432:     $accessed{$id}=[&gettimeofday()];
 2433:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 2434:     my $to_kick;
 2435:     my $max_time=0;
 2436:     foreach my $other (keys(%accessed)) {
 2437: 	if (&tv_interval($accessed{$other}) > $max_time) {
 2438: 	    $to_kick=$other;
 2439: 	    $max_time=&tv_interval($accessed{$other});
 2440: 	}
 2441:     }
 2442:     delete($remembered{$to_kick});
 2443:     delete($accessed{$to_kick});
 2444:     $kicks++;
 2445:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 2446:     return;
 2447: }
 2448: 
 2449: sub purge_remembered {
 2450:     #&logthis("Tossing ".scalar(keys(%remembered)));
 2451:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 2452:     undef(%remembered);
 2453:     undef(%accessed);
 2454: }
 2455: # ------------------------------------- Read an entry from a user's environment
 2456: 
 2457: sub userenvironment {
 2458:     my ($udom,$unam,@what)=@_;
 2459:     my $items;
 2460:     foreach my $item (@what) {
 2461:         $items.=&escape($item).'&';
 2462:     }
 2463:     $items=~s/\&$//;
 2464:     my %returnhash=();
 2465:     my $uhome = &homeserver($unam,$udom);
 2466:     unless ($uhome eq 'no_host') {
 2467:         my @answer=split(/\&/, 
 2468:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 2469:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 2470:             return %returnhash;
 2471:         }
 2472:         my $i;
 2473:         for ($i=0;$i<=$#what;$i++) {
 2474: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 2475:         }
 2476:     }
 2477:     return %returnhash;
 2478: }
 2479: 
 2480: # ---------------------------------------------------------- Get a studentphoto
 2481: sub studentphoto {
 2482:     my ($udom,$unam,$ext) = @_;
 2483:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2484:     if (defined($env{'request.course.id'})) {
 2485:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 2486:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 2487:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 2488:             } else {
 2489:                 my ($result,$perm_reqd)=
 2490: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2491:                 if ($result eq 'ok') {
 2492:                     if (!($perm_reqd eq 'yes')) {
 2493:                         return(&retrievestudentphoto($udom,$unam,$ext));
 2494:                     }
 2495:                 }
 2496:             }
 2497:         }
 2498:     } else {
 2499:         my ($result,$perm_reqd) = 
 2500: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2501:         if ($result eq 'ok') {
 2502:             if (!($perm_reqd eq 'yes')) {
 2503:                 return(&retrievestudentphoto($udom,$unam,$ext));
 2504:             }
 2505:         }
 2506:     }
 2507:     return '/adm/lonKaputt/lonlogo_broken.gif';
 2508: }
 2509: 
 2510: sub retrievestudentphoto {
 2511:     my ($udom,$unam,$ext,$type) = @_;
 2512:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2513:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 2514:     if ($ret eq 'ok') {
 2515:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 2516:         if ($type eq 'thumbnail') {
 2517:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 2518:         }
 2519:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 2520:         return $tokenurl;
 2521:     } else {
 2522:         if ($type eq 'thumbnail') {
 2523:             return '/adm/lonKaputt/genericstudent_tn.gif';
 2524:         } else { 
 2525:             return '/adm/lonKaputt/lonlogo_broken.gif';
 2526:         }
 2527:     }
 2528: }
 2529: 
 2530: # -------------------------------------------------------------------- New chat
 2531: 
 2532: sub chatsend {
 2533:     my ($newentry,$anon,$group)=@_;
 2534:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 2535:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2536:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 2537:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 2538: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 2539: 		   &escape($newentry)).':'.$group,$chome);
 2540: }
 2541: 
 2542: # ------------------------------------------ Find current version of a resource
 2543: 
 2544: sub getversion {
 2545:     my $fname=&clutter(shift);
 2546:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 2547:     return &currentversion(&filelocation('',$fname));
 2548: }
 2549: 
 2550: sub currentversion {
 2551:     my $fname=shift;
 2552:     my $author=$fname;
 2553:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2554:     my ($udom,$uname)=split(/\//,$author);
 2555:     my $home=&homeserver($uname,$udom);
 2556:     if ($home eq 'no_host') { 
 2557:         return -1; 
 2558:     }
 2559:     my $answer=&reply("currentversion:$fname",$home);
 2560:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2561: 	return -1;
 2562:     }
 2563:     return $answer;
 2564: }
 2565: 
 2566: #
 2567: # Return special version number of resource if set by override, empty otherwise
 2568: #
 2569: sub usedversion {
 2570:     my $fname=shift;
 2571:     unless ($fname) { $fname=$env{'request.uri'}; }
 2572:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 2573:     if ($urlversion) { return $urlversion; }
 2574:     return '';
 2575: }
 2576: 
 2577: # ----------------------------- Subscribe to a resource, return URL if possible
 2578: 
 2579: sub subscribe {
 2580:     my $fname=shift;
 2581:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 2582:     $fname=~s/[\n\r]//g;
 2583:     my $author=$fname;
 2584:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2585:     my ($udom,$uname)=split(/\//,$author);
 2586:     my $home=homeserver($uname,$udom);
 2587:     if ($home eq 'no_host') {
 2588:         return 'not_found';
 2589:     }
 2590:     my $answer=reply("sub:$fname",$home);
 2591:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2592: 	$answer.=' by '.$home;
 2593:     }
 2594:     return $answer;
 2595: }
 2596:     
 2597: # -------------------------------------------------------------- Replicate file
 2598: 
 2599: sub repcopy {
 2600:     my $filename=shift;
 2601:     $filename=~s/\/+/\//g;
 2602:     my $londocroot = $perlvar{'lonDocRoot'};
 2603:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 2604:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 2605:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 2606: 	$filename=~m{^/*(uploaded|editupload)/}) {
 2607: 	return &repcopy_userfile($filename);
 2608:     }
 2609:     $filename=~s/[\n\r]//g;
 2610:     my $transname="$filename.in.transfer";
 2611: # FIXME: this should flock
 2612:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 2613:     my $remoteurl=subscribe($filename);
 2614:     if ($remoteurl =~ /^con_lost by/) {
 2615: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2616:            return 'unavailable';
 2617:     } elsif ($remoteurl eq 'not_found') {
 2618: 	   #&logthis("Subscribe returned not_found: $filename");
 2619: 	   return 'not_found';
 2620:     } elsif ($remoteurl =~ /^rejected by/) {
 2621: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2622:            return 'forbidden';
 2623:     } elsif ($remoteurl eq 'directory') {
 2624:            return 'ok';
 2625:     } else {
 2626:         my $author=$filename;
 2627:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2628:         my ($udom,$uname)=split(/\//,$author);
 2629:         my $home=homeserver($uname,$udom);
 2630:         unless ($home eq $perlvar{'lonHostID'}) {
 2631:            my @parts=split(/\//,$filename);
 2632:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 2633:            if ($path ne "$londocroot/res") {
 2634:                &logthis("Malconfiguration for replication: $filename");
 2635: 	       return 'bad_request';
 2636:            }
 2637:            my $count;
 2638:            for ($count=5;$count<$#parts;$count++) {
 2639:                $path.="/$parts[$count]";
 2640:                if ((-e $path)!=1) {
 2641: 		   mkdir($path,0777);
 2642:                }
 2643:            }
 2644:            my $ua=new LWP::UserAgent;
 2645:            my $request=new HTTP::Request('GET',"$remoteurl");
 2646:            my $response=$ua->request($request,$transname);
 2647:            if ($response->is_error()) {
 2648: 	       unlink($transname);
 2649:                my $message=$response->status_line;
 2650:                &logthis("<font color=\"blue\">WARNING:"
 2651:                        ." LWP get: $message: $filename</font>");
 2652:                return 'unavailable';
 2653:            } else {
 2654: 	       if ($remoteurl!~/\.meta$/) {
 2655:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 2656:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 2657:                   if ($mresponse->is_error()) {
 2658: 		      unlink($filename.'.meta');
 2659:                       &logthis(
 2660:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 2661:                   }
 2662: 	       }
 2663:                rename($transname,$filename);
 2664:                return 'ok';
 2665:            }
 2666:        }
 2667:     }
 2668: }
 2669: 
 2670: # ------------------------------------------------ Get server side include body
 2671: sub ssi_body {
 2672:     my ($filelink,%form)=@_;
 2673:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 2674:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 2675:     }
 2676:     my $output='';
 2677:     my $response;
 2678:     if ($filelink=~/^https?\:/) {
 2679:        ($output,$response)=&externalssi($filelink);
 2680:     } else {
 2681:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 2682:        $filelink .= 'inhibitmenu=yes';
 2683:        ($output,$response)=&ssi($filelink,%form);
 2684:     }
 2685:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 2686:     $output=~s/^.*?\<body[^\>]*\>//si;
 2687:     $output=~s/\<\/body\s*\>.*?$//si;
 2688:     if (wantarray) {
 2689:         return ($output, $response);
 2690:     } else {
 2691:         return $output;
 2692:     }
 2693: }
 2694: 
 2695: # --------------------------------------------------------- Server Side Include
 2696: 
 2697: sub absolute_url {
 2698:     my ($host_name) = @_;
 2699:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 2700:     if ($host_name eq '') {
 2701: 	$host_name = $ENV{'SERVER_NAME'};
 2702:     }
 2703:     return $protocol.$host_name;
 2704: }
 2705: 
 2706: #
 2707: #   Server side include.
 2708: # Parameters:
 2709: #  fn     Possibly encrypted resource name/id.
 2710: #  form   Hash that describes how the rendering should be done
 2711: #         and other things.
 2712: # Returns:
 2713: #   Scalar context: The content of the response.
 2714: #   Array context:  2 element list of the content and the full response object.
 2715: #     
 2716: sub ssi {
 2717: 
 2718:     my ($fn,%form)=@_;
 2719:     my $ua=new LWP::UserAgent;
 2720:     my $request;
 2721: 
 2722:     $form{'no_update_last_known'}=1;
 2723:     &Apache::lonenc::check_encrypt(\$fn);
 2724:     if (%form) {
 2725:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 2726:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
 2727:     } else {
 2728:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 2729:     }
 2730: 
 2731:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 2732:     my $response= $ua->request($request);
 2733:     my $content = $response->content;
 2734: 
 2735: 
 2736:     if (wantarray) {
 2737: 	return ($content, $response);
 2738:     } else {
 2739: 	return $content;
 2740:     }
 2741: }
 2742: 
 2743: sub externalssi {
 2744:     my ($url)=@_;
 2745:     my $ua=new LWP::UserAgent;
 2746:     my $request=new HTTP::Request('GET',$url);
 2747:     my $response=$ua->request($request);
 2748:     if (wantarray) {
 2749:         return ($response->content, $response);
 2750:     } else {
 2751:         return $response->content;
 2752:     }
 2753: }
 2754: 
 2755: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 2756: 
 2757: sub allowuploaded {
 2758:     my ($srcurl,$url)=@_;
 2759:     $url=&clutter(&declutter($url));
 2760:     my $dir=$url;
 2761:     $dir=~s/\/[^\/]+$//;
 2762:     my %httpref=();
 2763:     my $httpurl=&hreflocation('',$url);
 2764:     $httpref{'httpref.'.$httpurl}=$srcurl;
 2765:     &Apache::lonnet::appenv(\%httpref);
 2766: }
 2767: 
 2768: #
 2769: # Determine if the current user should be able to edit a particular resource,
 2770: # when viewing in course context.
 2771: # (a) When viewing resource used to determine if "Edit" item is included in 
 2772: #     Functions.
 2773: # (b) When displaying folder contents in course editor, used to determine if
 2774: #     "Edit" link will be displayed alongside resource.
 2775: #
 2776: #  input: six args -- filename (decluttered), course number, course domain,
 2777: #                   url, symb (if registered) and group (if this is a group
 2778: #                   item -- e.g., bulletin board, group page etc.).
 2779: #  output: array of five scalars -- 
 2780: #          $cfile -- url for file editing if editable on current server
 2781: #          $home -- homeserver of resource (i.e., for author if published,
 2782: #                                           or course if uploaded.).
 2783: #          $switchserver --  1 if server switch will be needed.
 2784: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 2785: #          $forceview -- 1 if icon/link should be to go to view mode
 2786: #
 2787: 
 2788: sub can_edit_resource {
 2789:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 2790:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 2791: #
 2792: # For aboutme pages user can only edit his/her own.
 2793: #
 2794:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 2795:         my ($sdom,$sname) = ($1,$2);
 2796:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 2797:             $home = $env{'user.home'};
 2798:             $cfile = $resurl;
 2799:             if ($env{'form.forceedit'}) {
 2800:                 $forceview = 1;
 2801:             } else {
 2802:                 $forceedit = 1;
 2803:             }
 2804:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 2805:         } else {
 2806:             return;
 2807:         }
 2808:     }
 2809: 
 2810:     if ($env{'request.course.id'}) {
 2811:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 2812:         if ($group ne '') {
 2813: # if this is a group homepage or group bulletin board, check group privs
 2814:             my $allowed = 0;
 2815:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 2816:                 if ((&allowed('mdg',$env{'request.course.id'}.
 2817:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 2818:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 2819:                     $allowed = 1;
 2820:                 }
 2821:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 2822:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 2823:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 2824:                     $allowed = 1;
 2825:                 }
 2826:             }
 2827:             if ($allowed) {
 2828:                 $home=&homeserver($cnum,$cdom);
 2829:                 if ($env{'form.forceedit'}) {
 2830:                     $forceview = 1;
 2831:                 } else {
 2832:                     $forceedit = 1;
 2833:                 }
 2834:                 $cfile = $resurl;
 2835:             } else {
 2836:                 return;
 2837:             }
 2838:         } else {
 2839:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 2840:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 2841:                     return;
 2842:                 }
 2843:             } elsif (!$crsedit) {
 2844: #
 2845: # No edit allowed where CC has switched to student role.
 2846: #
 2847:                 return;
 2848:             }
 2849:         }
 2850:     }
 2851: 
 2852:     if ($file ne '') {
 2853:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 2854:             if (&is_course_upload($file,$cnum,$cdom)) {
 2855:                 $uploaded = 1;
 2856:                 $incourse = 1;
 2857:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 2858:                     $cfile = &hreflocation('',$file);
 2859:                     if ($env{'form.forceedit'}) {
 2860:                         $forceview = 1;
 2861:                     } else {
 2862:                         $forceedit = 1;
 2863:                     }
 2864:                 }
 2865:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 2866:                 $incourse = 1;
 2867:                 if ($env{'form.forceedit'}) {
 2868:                     $forceview = 1;
 2869:                 } else {
 2870:                     $forceedit = 1;
 2871:                 }
 2872:                 $cfile = $resurl;
 2873:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 2874:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 2875:                     $incourse = 1;
 2876:                     if ($env{'form.forceedit'}) {
 2877:                         $forceview = 1;
 2878:                     } else {
 2879:                         $forceedit = 1;
 2880:                     }
 2881:                     $cfile = $resurl;
 2882:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 2883:                     $incourse = 1;
 2884:                     $cfile = $resurl.'/smpedit';
 2885:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 2886:                     $incourse = 1;
 2887:                     if ($env{'form.forceedit'}) {
 2888:                         $forceview = 1;
 2889:                     } else {
 2890:                         $forceedit = 1;
 2891:                     }
 2892:                     $cfile = $resurl;
 2893:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 2894:                     $incourse = 1;
 2895:                     if ($env{'form.forceedit'}) {
 2896:                         $forceview = 1;
 2897:                     } else {
 2898:                         $forceedit = 1;
 2899:                     }
 2900:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 2901:                 }
 2902:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 2903:                 my $template = '/res/lib/templates/simpleproblem.problem';
 2904:                 if (&is_on_map($template)) { 
 2905:                     $incourse = 1;
 2906:                     $forceview = 1;
 2907:                     $cfile = $template;
 2908:                 }
 2909:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 2910:                     $incourse = 1;
 2911:                     if ($env{'form.forceedit'}) {
 2912:                         $forceview = 1;
 2913:                     } else {
 2914:                         $forceedit = 1;
 2915:                     }
 2916:                     $cfile = $resurl;
 2917:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 2918:                 $incourse = 1;
 2919:                 $forceview = 1;
 2920:                 if ($symb) {
 2921:                     my ($map,$id,$res)=&decode_symb($symb);
 2922:                     $env{'request.symb'} = $symb;
 2923:                     $cfile = &clutter($res);
 2924:                 } else {
 2925:                     $cfile = $env{'form.suppurl'};
 2926:                     $cfile =~ s{^http://}{};
 2927:                     $cfile = '/adm/wrapper/ext/'.$cfile;
 2928:                 }
 2929:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 2930:                 if ($env{'form.forceedit'}) {
 2931:                     $forceview = 1;
 2932:                 } else {
 2933:                     $forceedit = 1;
 2934:                 }
 2935:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 2936:             }
 2937:         }
 2938:         if ($uploaded || $incourse) {
 2939:             $home=&homeserver($cnum,$cdom);
 2940:         } elsif ($file !~ m{/$}) {
 2941:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 2942:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 2943:             # Check that the user has permission to edit this resource
 2944:             my $setpriv = 1;
 2945:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 2946:             if (defined($cfudom)) {
 2947:                 $home=&homeserver($cfuname,$cfudom);
 2948:                 $cfile=$file;
 2949:             }
 2950:         }
 2951:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 2952:             (($home ne '') && ($home ne 'no_host'))) {
 2953:             my @ids=&current_machine_ids();
 2954:             unless (grep(/^\Q$home\E$/,@ids)) {
 2955:                 $switchserver=1;
 2956:             }
 2957:         }
 2958:     }
 2959:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 2960: }
 2961: 
 2962: sub is_course_upload {
 2963:     my ($file,$cnum,$cdom) = @_;
 2964:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 2965:     $uploadpath =~ s{^\/}{};
 2966:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 2967:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 2968:         return 1;
 2969:     }
 2970:     return;
 2971: }
 2972: 
 2973: sub in_course {
 2974:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 2975:     if ($hideprivileged) {
 2976:         my $skipuser;
 2977:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 2978:         my @possdoms = ($cdom);  
 2979:         if ($coursehash{'checkforpriv'}) { 
 2980:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 2981:         }
 2982:         if (&privileged($uname,$udom,\@possdoms)) {
 2983:             $skipuser = 1;
 2984:             if ($coursehash{'nothideprivileged'}) {
 2985:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2986:                     my $user;
 2987:                     if ($item =~ /:/) {
 2988:                         $user = $item;
 2989:                     } else {
 2990:                         $user = join(':',split(/[\@]/,$item));
 2991:                     }
 2992:                     if ($user eq $uname.':'.$udom) {
 2993:                         undef($skipuser);
 2994:                         last;
 2995:                     }
 2996:                 }
 2997:             }
 2998:             if ($skipuser) {
 2999:                 return 0;
 3000:             }
 3001:         }
 3002:     }
 3003:     $type ||= 'any';
 3004:     if (!defined($cdom) || !defined($cnum)) {
 3005:         my $cid  = $env{'request.course.id'};
 3006:         $cdom = $env{'course.'.$cid.'.domain'};
 3007:         $cnum = $env{'course.'.$cid.'.num'};
 3008:     }
 3009:     my $typesref;
 3010:     if (($type eq 'any') || ($type eq 'all')) {
 3011:         $typesref = ['active','previous','future'];
 3012:     } elsif ($type eq 'previous' || $type eq 'future') {
 3013:         $typesref = [$type];
 3014:     }
 3015:     my %roles = &get_my_roles($uname,$udom,'userroles',
 3016:                               $typesref,undef,[$cdom]);
 3017:     my ($tmp) = keys(%roles);
 3018:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 3019:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 3020:     if (@course_roles > 0) {
 3021:         return 1;
 3022:     }
 3023:     return 0;
 3024: }
 3025: 
 3026: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 3027: # input: action, courseID, current domain, intended
 3028: #        path to file, source of file, instruction to parse file for objects,
 3029: #        ref to hash for embedded objects,
 3030: #        ref to hash for codebase of java objects.
 3031: #        reference to scalar to accommodate mime type determined
 3032: #          from File::MMagic if $parser = parse.
 3033: #
 3034: # output: url to file (if action was uploaddoc), 
 3035: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 3036: #
 3037: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 3038: # course.
 3039: #
 3040: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3041: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 3042: #          course's home server.
 3043: #
 3044: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 3045: #          be copied from $source (current location) to 
 3046: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3047: #         and will then be copied to
 3048: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 3049: #         course's home server.
 3050: #
 3051: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3052: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 3053: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3054: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 3055: #         in course's home server.
 3056: #
 3057: 
 3058: sub process_coursefile {
 3059:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 3060:         $mimetype)=@_;
 3061:     my $fetchresult;
 3062:     my $home=&homeserver($docuname,$docudom);
 3063:     if ($action eq 'propagate') {
 3064:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3065: 			     $home);
 3066:     } else {
 3067:         my $fpath = '';
 3068:         my $fname = $file;
 3069:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3070:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3071:         my $filepath = &build_filepath($fpath);
 3072:         if ($action eq 'copy') {
 3073:             if ($source eq '') {
 3074:                 $fetchresult = 'no source file';
 3075:                 return $fetchresult;
 3076:             } else {
 3077:                 my $destination = $filepath.'/'.$fname;
 3078:                 rename($source,$destination);
 3079:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3080:                                  $home);
 3081:             }
 3082:         } elsif ($action eq 'uploaddoc') {
 3083:             open(my $fh,'>'.$filepath.'/'.$fname);
 3084:             print $fh $env{'form.'.$source};
 3085:             close($fh);
 3086:             if ($parser eq 'parse') {
 3087:                 my $mm = new File::MMagic;
 3088:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 3089:                 if ($type eq 'text/html') {
 3090:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 3091:                     unless ($parse_result eq 'ok') {
 3092:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 3093:                     }
 3094:                 }
 3095:                 if (ref($mimetype)) {
 3096:                     $$mimetype = $type;
 3097:                 } 
 3098:             }
 3099:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3100:                                  $home);
 3101:             if ($fetchresult eq 'ok') {
 3102:                 return '/uploaded/'.$fpath.'/'.$fname;
 3103:             } else {
 3104:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3105:                         ' to host '.$home.': '.$fetchresult);
 3106:                 return '/adm/notfound.html';
 3107:             }
 3108:         }
 3109:     }
 3110:     unless ( $fetchresult eq 'ok') {
 3111:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3112:              ' to host '.$home.': '.$fetchresult);
 3113:     }
 3114:     return $fetchresult;
 3115: }
 3116: 
 3117: sub build_filepath {
 3118:     my ($fpath) = @_;
 3119:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 3120:     unless ($fpath eq '') {
 3121:         my @parts=split('/',$fpath);
 3122:         foreach my $part (@parts) {
 3123:             $filepath.= '/'.$part;
 3124:             if ((-e $filepath)!=1) {
 3125:                 mkdir($filepath,0777);
 3126:             }
 3127:         }
 3128:     }
 3129:     return $filepath;
 3130: }
 3131: 
 3132: sub store_edited_file {
 3133:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 3134:     my $file = $primary_url;
 3135:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 3136:     my $fpath = '';
 3137:     my $fname = $file;
 3138:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3139:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3140:     my $filepath = &build_filepath($fpath);
 3141:     open(my $fh,'>'.$filepath.'/'.$fname);
 3142:     print $fh $content;
 3143:     close($fh);
 3144:     my $home=&homeserver($docuname,$docudom);
 3145:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3146: 			  $home);
 3147:     if ($$fetchresult eq 'ok') {
 3148:         return '/uploaded/'.$fpath.'/'.$fname;
 3149:     } else {
 3150:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3151: 		 ' to host '.$home.': '.$$fetchresult);
 3152:         return '/adm/notfound.html';
 3153:     }
 3154: }
 3155: 
 3156: sub clean_filename {
 3157:     my ($fname,$args)=@_;
 3158: # Replace Windows backslashes by forward slashes
 3159:     $fname=~s/\\/\//g;
 3160:     if (!$args->{'keep_path'}) {
 3161:         # Get rid of everything but the actual filename
 3162: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 3163:     }
 3164: # Replace spaces by underscores
 3165:     $fname=~s/\s+/\_/g;
 3166: # Replace all other weird characters by nothing
 3167:     $fname=~s{[^/\w\.\-]}{}g;
 3168: # Replace all .\d. sequences with _\d. so they no longer look like version
 3169: # numbers
 3170:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 3171:     return $fname;
 3172: }
 3173: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 3174: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 3175: # image with the same aspect ratio as the original, but with dimensions which do 
 3176: # not exceed $resizewidth and $resizeheight.
 3177:  
 3178: sub resizeImage {
 3179:     my ($img_path,$resizewidth,$resizeheight) = @_;
 3180:     my $ima = Image::Magick->new;
 3181:     my $resized;
 3182:     if (-e $img_path) {
 3183:         $ima->Read($img_path);
 3184:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 3185:             my $width = $ima->Get('width');
 3186:             my $height = $ima->Get('height');
 3187:             if ($width > $resizewidth) {
 3188: 	        my $factor = $width/$resizewidth;
 3189:                 my $newheight = $height/$factor;
 3190:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 3191:                 $resized = 1;
 3192:             }
 3193:         }
 3194:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 3195:             my $width = $ima->Get('width');
 3196:             my $height = $ima->Get('height');
 3197:             if ($height > $resizeheight) {
 3198:                 my $factor = $height/$resizeheight;
 3199:                 my $newwidth = $width/$factor;
 3200:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 3201:                 $resized = 1;
 3202:             }
 3203:         }
 3204:         if ($resized) {
 3205:             $ima->Write($img_path);
 3206:         }
 3207:     }
 3208:     return;
 3209: }
 3210: 
 3211: # --------------- Take an uploaded file and put it into the userfiles directory
 3212: # input: $formname - the contents of the file are in $env{"form.$formname"}
 3213: #                    the desired filename is in $env{"form.$formname.filename"}
 3214: #        $context - possible values: coursedoc, existingfile, overwrite, 
 3215: #                                    canceloverwrite, or ''. 
 3216: #                   if 'coursedoc': upload to the current course
 3217: #                   if 'existingfile': write file to tmp/overwrites directory 
 3218: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 3219: #                   $context is passed as argument to &finishuserfileupload
 3220: #        $subdir - directory in userfile to store the file into
 3221: #        $parser - instruction to parse file for objects ($parser = parse)    
 3222: #        $allfiles - reference to hash for embedded objects
 3223: #        $codebase - reference to hash for codebase of java objects
 3224: #        $desuname - username for permanent storage of uploaded file
 3225: #        $dsetudom - domain for permanaent storage of uploaded file
 3226: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 3227: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 3228: #        $resizewidth - width (pixels) to which to resize uploaded image
 3229: #        $resizeheight - height (pixels) to which to resize uploaded image
 3230: #        $mimetype - reference to scalar to accommodate mime type determined
 3231: #                    from File::MMagic.
 3232: # 
 3233: # output: url of file in userspace, or error: <message> 
 3234: #             or /adm/notfound.html if failure to upload occurse
 3235: 
 3236: sub userfileupload {
 3237:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 3238:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 3239:     if (!defined($subdir)) { $subdir='unknown'; }
 3240:     my $fname=$env{'form.'.$formname.'.filename'};
 3241:     $fname=&clean_filename($fname);
 3242:     # See if there is anything left
 3243:     unless ($fname) { return 'error: no uploaded file'; }
 3244:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 3245:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 3246:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 3247:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3248:         my $now = time;
 3249:         my $filepath;
 3250:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 3251:              $filepath = 'tmp/helprequests/'.$now;
 3252:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 3253:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 3254:                          '_'.$env{'user.domain'}.'/pending';
 3255:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3256:             my ($docuname,$docudom);
 3257:             if ($destudom) {
 3258:                 $docudom = $destudom;
 3259:             } else {
 3260:                 $docudom = $env{'user.domain'};
 3261:             }
 3262:             if ($destuname) {
 3263:                 $docuname = $destuname;
 3264:             } else {
 3265:                 $docuname = $env{'user.name'};
 3266:             }
 3267:             if (exists($env{'form.group'})) {
 3268:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3269:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3270:             }
 3271:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 3272:             if ($context eq 'canceloverwrite') {
 3273:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 3274:                 if (-e  $tempfile) {
 3275:                     my @info = stat($tempfile);
 3276:                     if ($info[9] eq $env{'form.timestamp'}) {
 3277:                         unlink($tempfile);
 3278:                     }
 3279:                 }
 3280:                 return;
 3281:             }
 3282:         }
 3283:         # Create the directory if not present
 3284:         my @parts=split(/\//,$filepath);
 3285:         my $fullpath = $perlvar{'lonDaemons'};
 3286:         for (my $i=0;$i<@parts;$i++) {
 3287:             $fullpath .= '/'.$parts[$i];
 3288:             if ((-e $fullpath)!=1) {
 3289:                 mkdir($fullpath,0777);
 3290:             }
 3291:         }
 3292:         open(my $fh,'>'.$fullpath.'/'.$fname);
 3293:         print $fh $env{'form.'.$formname};
 3294:         close($fh);
 3295:         if ($context eq 'existingfile') {
 3296:             my @info = stat($fullpath.'/'.$fname);
 3297:             return ($fullpath.'/'.$fname,$info[9]);
 3298:         } else {
 3299:             return $fullpath.'/'.$fname;
 3300:         }
 3301:     }
 3302:     if ($subdir eq 'scantron') {
 3303:         $fname = 'scantron_orig_'.$fname;
 3304:     } else {
 3305:         $fname="$subdir/$fname";
 3306:     }
 3307:     if ($context eq 'coursedoc') {
 3308: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3309: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3310:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 3311:             return &finishuserfileupload($docuname,$docudom,
 3312: 					 $formname,$fname,$parser,$allfiles,
 3313: 					 $codebase,$thumbwidth,$thumbheight,
 3314:                                          $resizewidth,$resizeheight,$context,$mimetype);
 3315:         } else {
 3316:             if ($env{'form.folder'}) {
 3317:                 $fname=$env{'form.folder'}.'/'.$fname;
 3318:             }
 3319:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 3320: 				       $fname,$formname,$parser,
 3321: 				       $allfiles,$codebase,$mimetype);
 3322:         }
 3323:     } elsif (defined($destuname)) {
 3324:         my $docuname=$destuname;
 3325:         my $docudom=$destudom;
 3326: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3327: 				     $parser,$allfiles,$codebase,
 3328:                                      $thumbwidth,$thumbheight,
 3329:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3330:     } else {
 3331:         my $docuname=$env{'user.name'};
 3332:         my $docudom=$env{'user.domain'};
 3333:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 3334:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3335:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3336:         }
 3337: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3338: 				     $parser,$allfiles,$codebase,
 3339:                                      $thumbwidth,$thumbheight,
 3340:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3341:     }
 3342: }
 3343: 
 3344: sub finishuserfileupload {
 3345:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 3346:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 3347:     my $path=$docudom.'/'.$docuname.'/';
 3348:     my $filepath=$perlvar{'lonDocRoot'};
 3349:   
 3350:     my ($fnamepath,$file,$fetchthumb);
 3351:     $file=$fname;
 3352:     if ($fname=~m|/|) {
 3353:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 3354: 	$path.=$fnamepath.'/';
 3355:     }
 3356:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 3357:     my $count;
 3358:     for ($count=4;$count<=$#parts;$count++) {
 3359:         $filepath.="/$parts[$count]";
 3360:         if ((-e $filepath)!=1) {
 3361: 	    mkdir($filepath,0777);
 3362:         }
 3363:     }
 3364: 
 3365: # Save the file
 3366:     {
 3367: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 3368: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 3369: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 3370: 	    return '/adm/notfound.html';
 3371: 	}
 3372:         if ($context eq 'overwrite') {
 3373:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 3374:             my $target = $filepath.'/'.$file;
 3375:             if (-e $source) {
 3376:                 my @info = stat($source);
 3377:                 if ($info[9] eq $env{'form.timestamp'}) {   
 3378:                     unless (&File::Copy::move($source,$target)) {
 3379:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 3380:                         return "Moving from $source failed";
 3381:                     }
 3382:                 } else {
 3383:                     return "Temporary file: $source had unexpected date/time for last modification";
 3384:                 }
 3385:             } else {
 3386:                 return "Temporary file: $source missing";
 3387:             }
 3388:         } elsif (!print FH ($env{'form.'.$formname})) {
 3389: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 3390: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 3391: 	    return '/adm/notfound.html';
 3392: 	}
 3393: 	close(FH);
 3394:         if ($resizewidth && $resizeheight) {
 3395:             my $mm = new File::MMagic;
 3396:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 3397:             if ($mime_type =~ m{^image/}) {
 3398: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 3399:             }  
 3400: 	}
 3401:     }
 3402:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 3403:         if (ref($mimetype)) {
 3404:             if ($$mimetype eq '') {
 3405:                 my $mm = new File::MMagic;
 3406:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 3407:                 $$mimetype = $type;
 3408:             }
 3409:         }
 3410:     }
 3411:     if ($parser eq 'parse') {
 3412:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 3413:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 3414:                                                        $allfiles,$codebase);
 3415:             unless ($parse_result eq 'ok') {
 3416:                 &logthis('Failed to parse '.$filepath.$file.
 3417: 	   	         ' for embedded media: '.$parse_result); 
 3418:             }
 3419:         }
 3420:     }
 3421:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 3422:         my $input = $filepath.'/'.$file;
 3423:         my $output = $filepath.'/'.'tn-'.$file;
 3424:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 3425:         system("convert -sample $thumbsize $input $output");
 3426:         if (-e $filepath.'/'.'tn-'.$file) {
 3427:             $fetchthumb  = 1; 
 3428:         }
 3429:     }
 3430:  
 3431: # Notify homeserver to grep it
 3432: #
 3433:     my $docuhome=&homeserver($docuname,$docudom);	
 3434:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 3435:     if ($fetchresult eq 'ok') {
 3436:         if ($fetchthumb) {
 3437:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 3438:             if ($thumbresult ne 'ok') {
 3439:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 3440:                          $docuhome.': '.$thumbresult);
 3441:             }
 3442:         }
 3443: #
 3444: # Return the URL to it
 3445:         return '/uploaded/'.$path.$file;
 3446:     } else {
 3447:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 3448: 		 ': '.$fetchresult);
 3449:         return '/adm/notfound.html';
 3450:     }
 3451: }
 3452: 
 3453: sub extract_embedded_items {
 3454:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 3455:     my @state = ();
 3456:     my (%lastids,%related,%shockwave,%flashvars);
 3457:     my %javafiles = (
 3458:                       codebase => '',
 3459:                       code => '',
 3460:                       archive => ''
 3461:                     );
 3462:     my %mediafiles = (
 3463:                       src => '',
 3464:                       movie => '',
 3465:                      );
 3466:     my $p;
 3467:     if ($content) {
 3468:         $p = HTML::LCParser->new($content);
 3469:     } else {
 3470:         $p = HTML::LCParser->new($fullpath);
 3471:     }
 3472:     while (my $t=$p->get_token()) {
 3473: 	if ($t->[0] eq 'S') {
 3474: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 3475: 	    push(@state, $tagname);
 3476:             if (lc($tagname) eq 'allow') {
 3477:                 &add_filetype($allfiles,$attr->{'src'},'src');
 3478:             }
 3479: 	    if (lc($tagname) eq 'img') {
 3480: 		&add_filetype($allfiles,$attr->{'src'},'src');
 3481: 	    }
 3482: 	    if (lc($tagname) eq 'a') {
 3483:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 3484:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3485:                 }
 3486: 	    }
 3487:             if (lc($tagname) eq 'script') {
 3488:                 my $src;
 3489:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 3490:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 3491:                 } else {
 3492:                     if ($attr->{'src'} ne '') {
 3493:                         $src = $attr->{'src'};
 3494:                         &add_filetype($allfiles,$src,'src');
 3495:                     }
 3496:                 }
 3497:                 my $text = $p->get_trimmed_text();
 3498:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 3499:                     my @swfargs = split(/,/,$1);
 3500:                     foreach my $item (@swfargs) {
 3501:                         $item =~ s/["']//g;
 3502:                         $item =~ s/^\s+//;
 3503:                         $item =~ s/\s+$//;
 3504:                     }
 3505:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 3506:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 3507:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 3508:                         } else {
 3509:                             $related{$swfargs[0]} = [$swfargs[2]];
 3510:                         }
 3511:                     }
 3512:                 }
 3513:             }
 3514:             if (lc($tagname) eq 'link') {
 3515:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 3516:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3517:                 }
 3518:             }
 3519: 	    if (lc($tagname) eq 'object' ||
 3520: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 3521: 		foreach my $item (keys(%javafiles)) {
 3522: 		    $javafiles{$item} = '';
 3523: 		}
 3524:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 3525:                     $lastids{lc($tagname)} = $attr->{'id'};
 3526:                 }
 3527: 	    }
 3528: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 3529: 		my $name = lc($attr->{'name'});
 3530: 		foreach my $item (keys(%javafiles)) {
 3531: 		    if ($name eq $item) {
 3532: 			$javafiles{$item} = $attr->{'value'};
 3533: 			last;
 3534: 		    }
 3535: 		}
 3536:                 my $pathfrom;
 3537: 		foreach my $item (keys(%mediafiles)) {
 3538: 		    if ($name eq $item) {
 3539:                         $pathfrom = $attr->{'value'};
 3540:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 3541: 			&add_filetype($allfiles,$pathfrom,$name);
 3542: 			last;
 3543: 		    }
 3544: 		}
 3545:                 if ($name eq 'flashvars') {
 3546:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 3547:                 }
 3548:                 if ($pathfrom ne '') {
 3549:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 3550:                                          $pathfrom);
 3551:                 }
 3552: 	    }
 3553: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 3554: 		foreach my $item (keys(%javafiles)) {
 3555: 		    if ($attr->{$item}) {
 3556: 			$javafiles{$item} = $attr->{$item};
 3557: 			last;
 3558: 		    }
 3559: 		}
 3560: 		foreach my $item (keys(%mediafiles)) {
 3561: 		    if ($attr->{$item}) {
 3562: 			&add_filetype($allfiles,$attr->{$item},$item);
 3563: 			last;
 3564: 		    }
 3565: 		}
 3566:                 if (lc($tagname) eq 'embed') {
 3567:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 3568:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 3569:                                              $attr->{'src'});
 3570:                     }
 3571:                 }
 3572: 	    }
 3573:             if (lc($tagname) eq 'iframe') {
 3574:                 my $src = $attr->{'src'} ;
 3575:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 3576:                     &add_filetype($allfiles,$src,'src');
 3577:                 } elsif ($src =~ m{^/}) {
 3578:                     if ($env{'request.course.id'}) {
 3579:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3580:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3581:                         my $url = &hreflocation('',$fullpath);
 3582:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 3583:                             my $relpath = $1;
 3584:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 3585:                                 &add_filetype($allfiles,$1,'src');
 3586:                             }
 3587:                         }
 3588:                     }
 3589:                 }
 3590:             }
 3591:             if ($t->[4] =~ m{/>$}) {
 3592:                 pop(@state);
 3593:             }
 3594: 	} elsif ($t->[0] eq 'E') {
 3595: 	    my ($tagname) = ($t->[1]);
 3596: 	    if ($javafiles{'codebase'} ne '') {
 3597: 		$javafiles{'codebase'} .= '/';
 3598: 	    }  
 3599: 	    if (lc($tagname) eq 'applet' ||
 3600: 		lc($tagname) eq 'object' ||
 3601: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 3602: 		) {
 3603: 		foreach my $item (keys(%javafiles)) {
 3604: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 3605: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 3606: 			&add_filetype($allfiles,$file,$item);
 3607: 		    }
 3608: 		}
 3609: 	    } 
 3610: 	    pop @state;
 3611: 	}
 3612:     }
 3613:     foreach my $id (sort(keys(%flashvars))) {
 3614:         if ($shockwave{$id} ne '') {
 3615:             my @pairs = split(/\&/,$flashvars{$id});
 3616:             foreach my $pair (@pairs) {
 3617:                 my ($key,$value) = split(/\=/,$pair);
 3618:                 if ($key eq 'thumb') {
 3619:                     &add_filetype($allfiles,$value,$key);
 3620:                 } elsif ($key eq 'content') {
 3621:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 3622:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 3623:                     if ($ext ne '') {
 3624:                         &add_filetype($allfiles,$path.$value,$ext);
 3625:                     }
 3626:                 }
 3627:             }
 3628:         }
 3629:     }
 3630:     return 'ok';
 3631: }
 3632: 
 3633: sub add_filetype {
 3634:     my ($allfiles,$file,$type)=@_;
 3635:     if (exists($allfiles->{$file})) {
 3636: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 3637: 	    push(@{$allfiles->{$file}}, &escape($type));
 3638: 	}
 3639:     } else {
 3640: 	@{$allfiles->{$file}} = (&escape($type));
 3641:     }
 3642: }
 3643: 
 3644: sub embedded_dependency {
 3645:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 3646:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 3647:         if (($identifier ne '') &&
 3648:             (ref($related->{$identifier}) eq 'ARRAY') &&
 3649:             ($pathfrom ne '')) {
 3650:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 3651:             foreach my $dep (@{$related->{$identifier}}) {
 3652:                 &add_filetype($allfiles,$path.$dep,'object');
 3653:             }
 3654:         }
 3655:     }
 3656:     return;
 3657: }
 3658: 
 3659: sub removeuploadedurl {
 3660:     my ($url)=@_;	
 3661:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 3662:     return &removeuserfile($uname,$udom,$fname);
 3663: }
 3664: 
 3665: sub removeuserfile {
 3666:     my ($docuname,$docudom,$fname)=@_;
 3667:     my $home=&homeserver($docuname,$docudom);    
 3668:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 3669:     if ($result eq 'ok') {	
 3670:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 3671:             my $metafile = $fname.'.meta';
 3672:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 3673: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 3674:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 3675:             my $sqlresult = 
 3676:                 &update_portfolio_table($docuname,$docudom,$file,
 3677:                                         'portfolio_metadata',$group,
 3678:                                         'delete');
 3679:         }
 3680:     }
 3681:     return $result;
 3682: }
 3683: 
 3684: sub mkdiruserfile {
 3685:     my ($docuname,$docudom,$dir)=@_;
 3686:     my $home=&homeserver($docuname,$docudom);
 3687:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 3688: }
 3689: 
 3690: sub renameuserfile {
 3691:     my ($docuname,$docudom,$old,$new)=@_;
 3692:     my $home=&homeserver($docuname,$docudom);
 3693:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 3694:                         &escape("$old").':'.&escape("$new"),$home);
 3695:     if ($result eq 'ok') {
 3696:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 3697:             my $oldmeta = $old.'.meta';
 3698:             my $newmeta = $new.'.meta';
 3699:             my $metaresult = 
 3700:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 3701: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 3702:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 3703:             my $sqlresult = 
 3704:                 &update_portfolio_table($docuname,$docudom,$file,
 3705:                                         'portfolio_metadata',$group,
 3706:                                         'delete');
 3707:         }
 3708:     }
 3709:     return $result;
 3710: }
 3711: 
 3712: # ------------------------------------------------------------------------- Log
 3713: 
 3714: sub log {
 3715:     my ($dom,$nam,$hom,$what)=@_;
 3716:     return critical("log:$dom:$nam:$what",$hom);
 3717: }
 3718: 
 3719: # ------------------------------------------------------------------ Course Log
 3720: #
 3721: # This routine flushes several buffers of non-mission-critical nature
 3722: #
 3723: 
 3724: sub flushcourselogs {
 3725:     &logthis('Flushing log buffers');
 3726: #
 3727: # course logs
 3728: # This is a log of all transactions in a course, which can be used
 3729: # for data mining purposes
 3730: #
 3731: # It also collects the courseid database, which lists last transaction
 3732: # times and course titles for all courseids
 3733: #
 3734:     my %courseidbuffer=();
 3735:     foreach my $crsid (keys(%courselogs)) {
 3736:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 3737: 		          &escape($courselogs{$crsid}),
 3738: 		          $coursehombuf{$crsid}) eq 'ok') {
 3739: 	    delete $courselogs{$crsid};
 3740:         } else {
 3741:             &logthis('Failed to flush log buffer for '.$crsid);
 3742:             if (length($courselogs{$crsid})>40000) {
 3743:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 3744:                         " exceeded maximum size, deleting.</font>");
 3745:                delete $courselogs{$crsid};
 3746:             }
 3747:         }
 3748:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 3749:             'description' => $coursedescrbuf{$crsid},
 3750:             'inst_code'    => $courseinstcodebuf{$crsid},
 3751:             'type'        => $coursetypebuf{$crsid},
 3752:             'owner'       => $courseownerbuf{$crsid},
 3753:         };
 3754:     }
 3755: #
 3756: # Write course id database (reverse lookup) to homeserver of courses 
 3757: # Is used in pickcourse
 3758: #
 3759:     foreach my $crs_home (keys(%courseidbuffer)) {
 3760:         my $response = &courseidput(&host_domain($crs_home),
 3761:                                     $courseidbuffer{$crs_home},
 3762:                                     $crs_home,'timeonly');
 3763:     }
 3764: #
 3765: # File accesses
 3766: # Writes to the dynamic metadata of resources to get hit counts, etc.
 3767: #
 3768:     foreach my $entry (keys(%accesshash)) {
 3769:         if ($entry =~ /___count$/) {
 3770:             my ($dom,$name);
 3771:             ($dom,$name,undef)=
 3772: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 3773:             if (! defined($dom) || $dom eq '' || 
 3774:                 ! defined($name) || $name eq '') {
 3775:                 my $cid = $env{'request.course.id'};
 3776:                 $dom  = $env{'request.'.$cid.'.domain'};
 3777:                 $name = $env{'request.'.$cid.'.num'};
 3778:             }
 3779:             my $value = $accesshash{$entry};
 3780:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 3781:             my %temphash=($url => $value);
 3782:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 3783:             if ($result eq 'ok') {
 3784:                 delete $accesshash{$entry};
 3785:             }
 3786:         } else {
 3787:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 3788:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 3789:             my %temphash=($entry => $accesshash{$entry});
 3790:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 3791:                 delete $accesshash{$entry};
 3792:             }
 3793:         }
 3794:     }
 3795: #
 3796: # Roles
 3797: # Reverse lookup of user roles for course faculty/staff and co-authorship
 3798: #
 3799:     foreach my $entry (keys(%userrolehash)) {
 3800:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 3801: 	    split(/\:/,$entry);
 3802:         if (&Apache::lonnet::put('nohist_userroles',
 3803:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 3804:                 $rudom,$runame) eq 'ok') {
 3805: 	    delete $userrolehash{$entry};
 3806:         }
 3807:     }
 3808: #
 3809: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 3810: #
 3811:     my %domrolebuffer = ();
 3812:     foreach my $entry (keys(%domainrolehash)) {
 3813:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 3814:         if ($domrolebuffer{$rudom}) {
 3815:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 3816:                       '='.&escape($domainrolehash{$entry});
 3817:         } else {
 3818:             $domrolebuffer{$rudom}.=&escape($entry).
 3819:                       '='.&escape($domainrolehash{$entry});
 3820:         }
 3821:         delete $domainrolehash{$entry};
 3822:     }
 3823:     foreach my $dom (keys(%domrolebuffer)) {
 3824: 	my %servers = &get_servers($dom,'library');
 3825: 	foreach my $tryserver (keys(%servers)) {
 3826: 	    unless (&reply('domroleput:'.$dom.':'.
 3827: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 3828: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 3829: 	    }
 3830:         }
 3831:     }
 3832:     $dumpcount++;
 3833: }
 3834: 
 3835: sub courselog {
 3836:     my $what=shift;
 3837:     $what=time.':'.$what;
 3838:     unless ($env{'request.course.id'}) { return ''; }
 3839:     $coursedombuf{$env{'request.course.id'}}=
 3840:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 3841:     $coursenumbuf{$env{'request.course.id'}}=
 3842:        $env{'course.'.$env{'request.course.id'}.'.num'};
 3843:     $coursehombuf{$env{'request.course.id'}}=
 3844:        $env{'course.'.$env{'request.course.id'}.'.home'};
 3845:     $coursedescrbuf{$env{'request.course.id'}}=
 3846:        $env{'course.'.$env{'request.course.id'}.'.description'};
 3847:     $courseinstcodebuf{$env{'request.course.id'}}=
 3848:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 3849:     $courseownerbuf{$env{'request.course.id'}}=
 3850:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 3851:     $coursetypebuf{$env{'request.course.id'}}=
 3852:        $env{'course.'.$env{'request.course.id'}.'.type'};
 3853:     if (defined $courselogs{$env{'request.course.id'}}) {
 3854: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 3855:     } else {
 3856: 	$courselogs{$env{'request.course.id'}}.=$what;
 3857:     }
 3858:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 3859: 	&flushcourselogs();
 3860:     }
 3861: }
 3862: 
 3863: sub courseacclog {
 3864:     my $fnsymb=shift;
 3865:     unless ($env{'request.course.id'}) { return ''; }
 3866:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 3867:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 3868:         $what.=':POST';
 3869:         # FIXME: Probably ought to escape things....
 3870: 	foreach my $key (keys(%env)) {
 3871:             if ($key=~/^form\.(.*)/) {
 3872:                 my $formitem = $1;
 3873:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 3874:                     $what.=':'.$formitem.'='.$env{$key};
 3875:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 3876:                     $what.=':'.$formitem.'='.$env{$key};
 3877:                 }
 3878:             }
 3879:         }
 3880:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 3881:         # FIXME: We should not be depending on a form parameter that someone
 3882:         # editing lonsearchcat.pm might change in the future.
 3883:         if ($env{'form.phase'} eq 'course_search') {
 3884:             $what.= ':POST';
 3885:             # FIXME: Probably ought to escape things....
 3886:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 3887:                                  'crsdiscuss') {
 3888:                 $what.=':'.$element.'='.$env{'form.'.$element};
 3889:             }
 3890:         }
 3891:     }
 3892:     &courselog($what);
 3893: }
 3894: 
 3895: sub countacc {
 3896:     my $url=&declutter(shift);
 3897:     return if (! defined($url) || $url eq '');
 3898:     unless ($env{'request.course.id'}) { return ''; }
 3899: #
 3900: # Mark that this url was used in this course
 3901: #
 3902:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 3903: #
 3904: # Increase the access count for this resource in this child process
 3905: #
 3906:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 3907:     $accesshash{$key}++;
 3908: }
 3909: 
 3910: sub linklog {
 3911:     my ($from,$to)=@_;
 3912:     $from=&declutter($from);
 3913:     $to=&declutter($to);
 3914:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 3915:     $accesshash{$to.'___'.$from.'___goto'}=1;
 3916: }
 3917: 
 3918: sub statslog {
 3919:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 3920:     if ($users<2) { return; }
 3921:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 3922:             'course'       => $env{'request.course.id'},
 3923:             'sections'     => '"all"',
 3924:             'num_students' => $users,
 3925:             'part'         => $part,
 3926:             'symb'         => $symb,
 3927:             'mean_tries'   => $av_attempts,
 3928:             'deg_of_diff'  => $degdiff});
 3929:     foreach my $key (keys(%dynstore)) {
 3930:         $accesshash{$key}=$dynstore{$key};
 3931:     }
 3932: }
 3933:   
 3934: sub userrolelog {
 3935:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 3936:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 3937:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3938:        $userrolehash
 3939:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3940:                     =$tend.':'.$tstart;
 3941:     }
 3942:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 3943:        $userrolehash
 3944:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 3945:                     =$tend.':'.$tstart;
 3946:     }
 3947:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
 3948:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3949:        $domainrolehash
 3950:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3951:                     = $tend.':'.$tstart;
 3952:     }
 3953: }
 3954: 
 3955: sub courserolelog {
 3956:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 3957:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 3958:         my $cdom = $1;
 3959:         my $cnum = $2;
 3960:         my $sec = $3;
 3961:         my $namespace = 'rolelog';
 3962:         my %storehash = (
 3963:                            role    => $trole,
 3964:                            start   => $tstart,
 3965:                            end     => $tend,
 3966:                            selfenroll => $selfenroll,
 3967:                            context    => $context,
 3968:                         );
 3969:         if ($trole eq 'gr') {
 3970:             $namespace = 'groupslog';
 3971:             $storehash{'group'} = $sec;
 3972:         } else {
 3973:             $storehash{'section'} = $sec;
 3974:         }
 3975:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 3976:                    $domain,$cnum,$cdom);
 3977:         if (($trole ne 'st') || ($sec ne '')) {
 3978:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 3979:         }
 3980:     }
 3981:     return;
 3982: }
 3983: 
 3984: sub domainrolelog {
 3985:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 3986:     if ($area =~ m{^/($match_domain)/$}) {
 3987:         my $cdom = $1;
 3988:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 3989:         my $namespace = 'rolelog';
 3990:         my %storehash = (
 3991:                            role    => $trole,
 3992:                            start   => $tstart,
 3993:                            end     => $tend,
 3994:                            context => $context,
 3995:                         );
 3996:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 3997:                    $domain,$domconfiguser,$cdom);
 3998:     }
 3999:     return;
 4000: 
 4001: }
 4002: 
 4003: sub coauthorrolelog {
 4004:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4005:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 4006:         my $audom = $1;
 4007:         my $auname = $2;
 4008:         my $namespace = 'rolelog';
 4009:         my %storehash = (
 4010:                            role    => $trole,
 4011:                            start   => $tstart,
 4012:                            end     => $tend,
 4013:                            context => $context,
 4014:                         );
 4015:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 4016:                    $domain,$auname,$audom);
 4017:     }
 4018:     return;
 4019: }
 4020: 
 4021: sub get_course_adv_roles {
 4022:     my ($cid,$codes) = @_;
 4023:     $cid=$env{'request.course.id'} unless (defined($cid));
 4024:     my %coursehash=&coursedescription($cid);
 4025:     my $crstype = &Apache::loncommon::course_type($cid);
 4026:     my %nothide=();
 4027:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4028:         if ($user !~ /:/) {
 4029: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 4030:         } else {
 4031:             $nothide{$user}=1;
 4032:         }
 4033:     }
 4034:     my @possdoms = ($coursehash{'domain'});
 4035:     if ($coursehash{'checkforpriv'}) {
 4036:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 4037:     }
 4038:     my %returnhash=();
 4039:     my %dumphash=
 4040:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 4041:     my $now=time;
 4042:     my %privileged;
 4043:     foreach my $entry (keys(%dumphash)) {
 4044: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4045:         if (($tstart) && ($tstart<0)) { next; }
 4046:         if (($tend) && ($tend<$now)) { next; }
 4047:         if (($tstart) && ($now<$tstart)) { next; }
 4048:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 4049: 	if ($username eq '' || $domain eq '') { next; }
 4050:         if ((&privileged($username,$domain,\@possdoms)) &&
 4051:             (!$nothide{$username.':'.$domain})) { next; }
 4052: 	if ($role eq 'cr') { next; }
 4053:         if ($codes) {
 4054:             if ($section) { $role .= ':'.$section; }
 4055:             if ($returnhash{$role}) {
 4056:                 $returnhash{$role}.=','.$username.':'.$domain;
 4057:             } else {
 4058:                 $returnhash{$role}=$username.':'.$domain;
 4059:             }
 4060:         } else {
 4061:             my $key=&plaintext($role,$crstype);
 4062:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 4063:             if ($returnhash{$key}) {
 4064: 	        $returnhash{$key}.=','.$username.':'.$domain;
 4065:             } else {
 4066:                 $returnhash{$key}=$username.':'.$domain;
 4067:             }
 4068:         }
 4069:     }
 4070:     return %returnhash;
 4071: }
 4072: 
 4073: sub get_my_roles {
 4074:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 4075:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 4076:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 4077:     my (%dumphash,%nothide);
 4078:     if ($context eq 'userroles') {
 4079:         %dumphash = &dump('roles',$udom,$uname);
 4080:     } else {
 4081:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 4082:         if ($hidepriv) {
 4083:             my %coursehash=&coursedescription($udom.'_'.$uname);
 4084:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4085:                 if ($user !~ /:/) {
 4086:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 4087:                 } else {
 4088:                     $nothide{$user} = 1;
 4089:                 }
 4090:             }
 4091:         }
 4092:     }
 4093:     my %returnhash=();
 4094:     my $now=time;
 4095:     my %privileged;
 4096:     foreach my $entry (keys(%dumphash)) {
 4097:         my ($role,$tend,$tstart);
 4098:         if ($context eq 'userroles') {
 4099:             next if ($entry =~ /^rolesdef/);
 4100: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 4101:         } else {
 4102:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4103:         }
 4104:         if (($tstart) && ($tstart<0)) { next; }
 4105:         my $status = 'active';
 4106:         if (($tend) && ($tend<=$now)) {
 4107:             $status = 'previous';
 4108:         } 
 4109:         if (($tstart) && ($now<$tstart)) {
 4110:             $status = 'future';
 4111:         }
 4112:         if (ref($types) eq 'ARRAY') {
 4113:             if (!grep(/^\Q$status\E$/,@{$types})) {
 4114:                 next;
 4115:             } 
 4116:         } else {
 4117:             if ($status ne 'active') {
 4118:                 next;
 4119:             }
 4120:         }
 4121:         my ($rolecode,$username,$domain,$section,$area);
 4122:         if ($context eq 'userroles') {
 4123:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 4124:             (undef,$domain,$username,$section) = split(/\//,$area);
 4125:         } else {
 4126:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 4127:         }
 4128:         if (ref($roledoms) eq 'ARRAY') {
 4129:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 4130:                 next;
 4131:             }
 4132:         }
 4133:         if (ref($roles) eq 'ARRAY') {
 4134:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 4135:                 if ($role =~ /^cr\//) {
 4136:                     if (!grep(/^cr$/,@{$roles})) {
 4137:                         next;
 4138:                     }
 4139:                 } elsif ($role =~ /^gr\//) {
 4140:                     if (!grep(/^gr$/,@{$roles})) {
 4141:                         next;
 4142:                     }
 4143:                 } else {
 4144:                     next;
 4145:                 }
 4146:             }
 4147:         }
 4148:         if ($hidepriv) {
 4149:             my @privroles = ('dc','su');
 4150:             if ($context eq 'userroles') {
 4151:                 next if (grep(/^\Q$role\E$/,@privroles));
 4152:             } else {
 4153:                 my $possdoms = [$domain];
 4154:                 if (ref($roledoms) eq 'ARRAY') {
 4155:                    push(@{$possdoms},@{$roledoms}); 
 4156:                 }
 4157:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 4158:                     if (!$nothide{$username.':'.$domain}) {
 4159:                         next;
 4160:                     }
 4161:                 }
 4162:             }
 4163:         }
 4164:         if ($withsec) {
 4165:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 4166:                 $tstart.':'.$tend;
 4167:         } else {
 4168:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 4169:         }
 4170:     }
 4171:     return %returnhash;
 4172: }
 4173: 
 4174: # ----------------------------------------------------- Frontpage Announcements
 4175: #
 4176: #
 4177: 
 4178: sub postannounce {
 4179:     my ($server,$text)=@_;
 4180:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 4181:     unless ($text=~/\w/) { $text=''; }
 4182:     return &reply('setannounce:'.&escape($text),$server);
 4183: }
 4184: 
 4185: sub getannounce {
 4186: 
 4187:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 4188: 	my $announcement='';
 4189: 	while (my $line = <$fh>) { $announcement .= $line; }
 4190: 	close($fh);
 4191: 	if ($announcement=~/\w/) { 
 4192: 	    return 
 4193:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 4194:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 4195: 	} else {
 4196: 	    return '';
 4197: 	}
 4198:     } else {
 4199: 	return '';
 4200:     }
 4201: }
 4202: 
 4203: # ---------------------------------------------------------- Course ID routines
 4204: # Deal with domain's nohist_courseid.db files
 4205: #
 4206: 
 4207: sub courseidput {
 4208:     my ($domain,$storehash,$coursehome,$caller) = @_;
 4209:     return unless (ref($storehash) eq 'HASH');
 4210:     my $outcome;
 4211:     if ($caller eq 'timeonly') {
 4212:         my $cids = '';
 4213:         foreach my $item (keys(%$storehash)) {
 4214:             $cids.=&escape($item).'&';
 4215:         }
 4216:         $cids=~s/\&$//;
 4217:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 4218:                           $coursehome);       
 4219:     } else {
 4220:         my $items = '';
 4221:         foreach my $item (keys(%$storehash)) {
 4222:             $items.= &escape($item).'='.
 4223:                      &freeze_escape($$storehash{$item}).'&';
 4224:         }
 4225:         $items=~s/\&$//;
 4226:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 4227:                           $coursehome);
 4228:     }
 4229:     if ($outcome eq 'unknown_cmd') {
 4230:         my $what;
 4231:         foreach my $cid (keys(%$storehash)) {
 4232:             $what .= &escape($cid).'=';
 4233:             foreach my $item ('description','inst_code','owner','type') {
 4234:                 $what .= &escape($storehash->{$cid}{$item}).':';
 4235:             }
 4236:             $what =~ s/\:$/&/;
 4237:         }
 4238:         $what =~ s/\&$//;  
 4239:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 4240:     } else {
 4241:         return $outcome;
 4242:     }
 4243: }
 4244: 
 4245: sub courseiddump {
 4246:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 4247:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 4248:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 4249:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 4250:         $hasuniquecode)=@_;
 4251:     my $as_hash = 1;
 4252:     my %returnhash;
 4253:     if (!$domfilter) { $domfilter=''; }
 4254:     my %libserv = &all_library();
 4255:     foreach my $tryserver (keys(%libserv)) {
 4256:         if ( (  $hostidflag == 1 
 4257: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 4258: 	     || (!defined($hostidflag)) ) {
 4259: 
 4260: 	    if (($domfilter eq '') ||
 4261: 		(&host_domain($tryserver) eq $domfilter)) {
 4262:                 my $rep;
 4263:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 4264:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 4265:                         join(":", (&host_domain($tryserver), $sincefilter, 
 4266:                                 &escape($descfilter), &escape($instcodefilter), 
 4267:                                 &escape($ownerfilter), &escape($coursefilter),
 4268:                                 &escape($typefilter), &escape($regexp_ok), 
 4269:                                 $as_hash, &escape($selfenrollonly), 
 4270:                                 &escape($catfilter), $showhidden, $caller, 
 4271:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 4272:                                 &escape($createdbefore), &escape($createdafter), 
 4273:                                 &escape($creationcontext), $domcloner, $hasuniquecode)));
 4274:                 } else {
 4275:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 4276:                              $sincefilter.':'.&escape($descfilter).':'.
 4277:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 4278:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 4279:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 4280:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 4281:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 4282:                              &escape($cc_clone).':'.$cloneonly.':'.
 4283:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 4284:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode,
 4285:                              $tryserver);
 4286:                 }
 4287:                      
 4288:                 my @pairs=split(/\&/,$rep);
 4289:                 foreach my $item (@pairs) {
 4290:                     my ($key,$value)=split(/\=/,$item,2);
 4291:                     $key = &unescape($key);
 4292:                     next if ($key =~ /^error: 2 /);
 4293:                     my $result = &thaw_unescape($value);
 4294:                     if (ref($result) eq 'HASH') {
 4295:                         $returnhash{$key}=$result;
 4296:                     } else {
 4297:                         my @responses = split(/:/,$value);
 4298:                         my @items = ('description','inst_code','owner','type');
 4299:                         for (my $i=0; $i<@responses; $i++) {
 4300:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 4301:                         }
 4302:                     }
 4303:                 }
 4304:             }
 4305:         }
 4306:     }
 4307:     return %returnhash;
 4308: }
 4309: 
 4310: sub courselastaccess {
 4311:     my ($cdom,$cnum,$hostidref) = @_;
 4312:     my %returnhash;
 4313:     if ($cdom && $cnum) {
 4314:         my $chome = &homeserver($cnum,$cdom);
 4315:         if ($chome ne 'no_host') {
 4316:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 4317:             &extract_lastaccess(\%returnhash,$rep);
 4318:         }
 4319:     } else {
 4320:         if (!$cdom) { $cdom=''; }
 4321:         my %libserv = &all_library();
 4322:         foreach my $tryserver (keys(%libserv)) {
 4323:             if (ref($hostidref) eq 'ARRAY') {
 4324:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 4325:             } 
 4326:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 4327:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 4328:                 &extract_lastaccess(\%returnhash,$rep);
 4329:             }
 4330:         }
 4331:     }
 4332:     return %returnhash;
 4333: }
 4334: 
 4335: sub extract_lastaccess {
 4336:     my ($returnhash,$rep) = @_;
 4337:     if (ref($returnhash) eq 'HASH') {
 4338:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 4339:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 4340:                  $rep eq '') {
 4341:             my @pairs=split(/\&/,$rep);
 4342:             foreach my $item (@pairs) {
 4343:                 my ($key,$value)=split(/\=/,$item,2);
 4344:                 $key = &unescape($key);
 4345:                 next if ($key =~ /^error: 2 /);
 4346:                 $returnhash->{$key} = &thaw_unescape($value);
 4347:             }
 4348:         }
 4349:     }
 4350:     return;
 4351: }
 4352: 
 4353: # ---------------------------------------------------------- DC e-mail
 4354: 
 4355: sub dcmailput {
 4356:     my ($domain,$msgid,$message,$server)=@_;
 4357:     my $status = &Apache::lonnet::critical(
 4358:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 4359:        &escape($message),$server);
 4360:     return $status;
 4361: }
 4362: 
 4363: sub dcmaildump {
 4364:     my ($dom,$startdate,$enddate,$senders) = @_;
 4365:     my %returnhash=();
 4366: 
 4367:     if (defined(&domain($dom,'primary'))) {
 4368:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 4369:                                                          &escape($enddate).':';
 4370: 	my @esc_senders=map { &escape($_)} @$senders;
 4371: 	$cmd.=&escape(join('&',@esc_senders));
 4372: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 4373:             my ($key,$value) = split(/\=/,$line,2);
 4374:             if (($key) && ($value)) {
 4375:                 $returnhash{&unescape($key)} = &unescape($value);
 4376:             }
 4377:         }
 4378:     }
 4379:     return %returnhash;
 4380: }
 4381: # ---------------------------------------------------------- Domain roles
 4382: 
 4383: sub get_domain_roles {
 4384:     my ($dom,$roles,$startdate,$enddate)=@_;
 4385:     if ((!defined($startdate)) || ($startdate eq '')) {
 4386:         $startdate = '.';
 4387:     }
 4388:     if ((!defined($enddate)) || ($enddate eq '')) {
 4389:         $enddate = '.';
 4390:     }
 4391:     my $rolelist;
 4392:     if (ref($roles) eq 'ARRAY') {
 4393:         $rolelist = join('&',@{$roles});
 4394:     }
 4395:     my %personnel = ();
 4396: 
 4397:     my %servers = &get_servers($dom,'library');
 4398:     foreach my $tryserver (keys(%servers)) {
 4399: 	%{$personnel{$tryserver}}=();
 4400: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 4401: 					    &escape($startdate).':'.
 4402: 					    &escape($enddate).':'.
 4403: 					    &escape($rolelist), $tryserver))) {
 4404: 	    my ($key,$value) = split(/\=/,$line,2);
 4405: 	    if (($key) && ($value)) {
 4406: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 4407: 	    }
 4408: 	}
 4409:     }
 4410:     return %personnel;
 4411: }
 4412: 
 4413: # ----------------------------------------------------------- Interval timing 
 4414: 
 4415: {
 4416: # Caches needed for speedup of navmaps
 4417: # We don't want to cache this for very long at all (5 seconds at most)
 4418: # 
 4419: # The user for whom we cache
 4420: my $cachedkey='';
 4421: # The cached times for this user
 4422: my %cachedtimes=();
 4423: # When this was last done
 4424: my $cachedtime=();
 4425: 
 4426: sub load_all_first_access {
 4427:     my ($uname,$udom)=@_;
 4428:     if (($cachedkey eq $uname.':'.$udom) &&
 4429:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
 4430:         return;
 4431:     }
 4432:     $cachedtime=time;
 4433:     $cachedkey=$uname.':'.$udom;
 4434:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 4435: }
 4436: 
 4437: sub get_first_access {
 4438:     my ($type,$argsymb,$argmap)=@_;
 4439:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4440:     if ($argsymb) { $symb=$argsymb; }
 4441:     my ($map,$id,$res)=&decode_symb($symb);
 4442:     if ($argmap) { $map = $argmap; }
 4443:     if ($type eq 'course') {
 4444: 	$res='course';
 4445:     } elsif ($type eq 'map') {
 4446: 	$res=&symbread($map);
 4447:     } else {
 4448: 	$res=$symb;
 4449:     }
 4450:     &load_all_first_access($uname,$udom);
 4451:     return $cachedtimes{"$courseid\0$res"};
 4452: }
 4453: 
 4454: sub set_first_access {
 4455:     my ($type,$interval)=@_;
 4456:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4457:     my ($map,$id,$res)=&decode_symb($symb);
 4458:     if ($type eq 'course') {
 4459: 	$res='course';
 4460:     } elsif ($type eq 'map') {
 4461: 	$res=&symbread($map);
 4462:     } else {
 4463: 	$res=$symb;
 4464:     }
 4465:     $cachedkey='';
 4466:     my $firstaccess=&get_first_access($type,$symb,$map);
 4467:     if (!$firstaccess) {
 4468:         my $start = time;
 4469: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 4470:                           $udom,$uname);
 4471:         if ($putres eq 'ok') {
 4472:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 4473:                  $udom,$uname); 
 4474:             &appenv(
 4475:                      {
 4476:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 4477:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 4478:                      }
 4479:                   );
 4480:         }
 4481:         return $putres;
 4482:     }
 4483:     return 'already_set';
 4484: }
 4485: }
 4486: # --------------------------------------------- Set Expire Date for Spreadsheet
 4487: 
 4488: sub expirespread {
 4489:     my ($uname,$udom,$stype,$usymb)=@_;
 4490:     my $cid=$env{'request.course.id'}; 
 4491:     if ($cid) {
 4492:        my $now=time;
 4493:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 4494:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 4495:                             $env{'course.'.$cid.'.num'}.
 4496: 	        	    ':nohist_expirationdates:'.
 4497:                             &escape($key).'='.$now,
 4498:                             $env{'course.'.$cid.'.home'})
 4499:     }
 4500:     return 'ok';
 4501: }
 4502: 
 4503: # ----------------------------------------------------- Devalidate Spreadsheets
 4504: 
 4505: sub devalidate {
 4506:     my ($symb,$uname,$udom)=@_;
 4507:     my $cid=$env{'request.course.id'}; 
 4508:     if ($cid) {
 4509:         # delete the stored spreadsheets for
 4510:         # - the student level sheet of this user in course's homespace
 4511:         # - the assessment level sheet for this resource 
 4512:         #   for this user in user's homespace
 4513: 	# - current conditional state info
 4514: 	my $key=$uname.':'.$udom.':';
 4515:         my $status=
 4516: 	    &del('nohist_calculatedsheets',
 4517: 		 [$key.'studentcalc:'],
 4518: 		 $env{'course.'.$cid.'.domain'},
 4519: 		 $env{'course.'.$cid.'.num'})
 4520: 		.' '.
 4521: 	    &del('nohist_calculatedsheets_'.$cid,
 4522: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 4523:         unless ($status eq 'ok ok') {
 4524:            &logthis('Could not devalidate spreadsheet '.
 4525:                     $uname.' at '.$udom.' for '.
 4526: 		    $symb.': '.$status);
 4527:         }
 4528: 	&delenv('user.state.'.$cid);
 4529:     }
 4530: }
 4531: 
 4532: sub get_scalar {
 4533:     my ($string,$end) = @_;
 4534:     my $value;
 4535:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 4536: 	$value = $1;
 4537:     } elsif ($$string =~ s/^([^&]*?)&//) {
 4538: 	$value = $1;
 4539:     }
 4540:     return &unescape($value);
 4541: }
 4542: 
 4543: sub array2str {
 4544:   my (@array) = @_;
 4545:   my $result=&arrayref2str(\@array);
 4546:   $result=~s/^__ARRAY_REF__//;
 4547:   $result=~s/__END_ARRAY_REF__$//;
 4548:   return $result;
 4549: }
 4550: 
 4551: sub arrayref2str {
 4552:   my ($arrayref) = @_;
 4553:   my $result='__ARRAY_REF__';
 4554:   foreach my $elem (@$arrayref) {
 4555:     if(ref($elem) eq 'ARRAY') {
 4556:       $result.=&arrayref2str($elem).'&';
 4557:     } elsif(ref($elem) eq 'HASH') {
 4558:       $result.=&hashref2str($elem).'&';
 4559:     } elsif(ref($elem)) {
 4560:       #print("Got a ref of ".(ref($elem))." skipping.");
 4561:     } else {
 4562:       $result.=&escape($elem).'&';
 4563:     }
 4564:   }
 4565:   $result=~s/\&$//;
 4566:   $result .= '__END_ARRAY_REF__';
 4567:   return $result;
 4568: }
 4569: 
 4570: sub hash2str {
 4571:   my (%hash) = @_;
 4572:   my $result=&hashref2str(\%hash);
 4573:   $result=~s/^__HASH_REF__//;
 4574:   $result=~s/__END_HASH_REF__$//;
 4575:   return $result;
 4576: }
 4577: 
 4578: sub hashref2str {
 4579:   my ($hashref)=@_;
 4580:   my $result='__HASH_REF__';
 4581:   foreach my $key (sort(keys(%$hashref))) {
 4582:     if (ref($key) eq 'ARRAY') {
 4583:       $result.=&arrayref2str($key).'=';
 4584:     } elsif (ref($key) eq 'HASH') {
 4585:       $result.=&hashref2str($key).'=';
 4586:     } elsif (ref($key)) {
 4587:       $result.='=';
 4588:       #print("Got a ref of ".(ref($key))." skipping.");
 4589:     } else {
 4590: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 4591:     }
 4592: 
 4593:     if(ref($hashref->{$key}) eq 'ARRAY') {
 4594:       $result.=&arrayref2str($hashref->{$key}).'&';
 4595:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 4596:       $result.=&hashref2str($hashref->{$key}).'&';
 4597:     } elsif(ref($hashref->{$key})) {
 4598:        $result.='&';
 4599:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 4600:     } else {
 4601:       $result.=&escape($hashref->{$key}).'&';
 4602:     }
 4603:   }
 4604:   $result=~s/\&$//;
 4605:   $result .= '__END_HASH_REF__';
 4606:   return $result;
 4607: }
 4608: 
 4609: sub str2hash {
 4610:     my ($string)=@_;
 4611:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 4612:     return %$hash;
 4613: }
 4614: 
 4615: sub str2hashref {
 4616:   my ($string) = @_;
 4617: 
 4618:   my %hash;
 4619: 
 4620:   if($string !~ /^__HASH_REF__/) {
 4621:       if (! ($string eq '' || !defined($string))) {
 4622: 	  $hash{'error'}='Not hash reference';
 4623:       }
 4624:       return (\%hash, $string);
 4625:   }
 4626: 
 4627:   $string =~ s/^__HASH_REF__//;
 4628: 
 4629:   while($string !~ /^__END_HASH_REF__/) {
 4630:       #key
 4631:       my $key='';
 4632:       if($string =~ /^__HASH_REF__/) {
 4633:           ($key, $string)=&str2hashref($string);
 4634:           if(defined($key->{'error'})) {
 4635:               $hash{'error'}='Bad data';
 4636:               return (\%hash, $string);
 4637:           }
 4638:       } elsif($string =~ /^__ARRAY_REF__/) {
 4639:           ($key, $string)=&str2arrayref($string);
 4640:           if($key->[0] eq 'Array reference error') {
 4641:               $hash{'error'}='Bad data';
 4642:               return (\%hash, $string);
 4643:           }
 4644:       } else {
 4645:           $string =~ s/^(.*?)=//;
 4646: 	  $key=&unescape($1);
 4647:       }
 4648:       $string =~ s/^=//;
 4649: 
 4650:       #value
 4651:       my $value='';
 4652:       if($string =~ /^__HASH_REF__/) {
 4653:           ($value, $string)=&str2hashref($string);
 4654:           if(defined($value->{'error'})) {
 4655:               $hash{'error'}='Bad data';
 4656:               return (\%hash, $string);
 4657:           }
 4658:       } elsif($string =~ /^__ARRAY_REF__/) {
 4659:           ($value, $string)=&str2arrayref($string);
 4660:           if($value->[0] eq 'Array reference error') {
 4661:               $hash{'error'}='Bad data';
 4662:               return (\%hash, $string);
 4663:           }
 4664:       } else {
 4665: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 4666:       }
 4667:       $string =~ s/^&//;
 4668: 
 4669:       $hash{$key}=$value;
 4670:   }
 4671: 
 4672:   $string =~ s/^__END_HASH_REF__//;
 4673: 
 4674:   return (\%hash, $string);
 4675: }
 4676: 
 4677: sub str2array {
 4678:     my ($string)=@_;
 4679:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 4680:     return @$array;
 4681: }
 4682: 
 4683: sub str2arrayref {
 4684:   my ($string) = @_;
 4685:   my @array;
 4686: 
 4687:   if($string !~ /^__ARRAY_REF__/) {
 4688:       if (! ($string eq '' || !defined($string))) {
 4689: 	  $array[0]='Array reference error';
 4690:       }
 4691:       return (\@array, $string);
 4692:   }
 4693: 
 4694:   $string =~ s/^__ARRAY_REF__//;
 4695: 
 4696:   while($string !~ /^__END_ARRAY_REF__/) {
 4697:       my $value='';
 4698:       if($string =~ /^__HASH_REF__/) {
 4699:           ($value, $string)=&str2hashref($string);
 4700:           if(defined($value->{'error'})) {
 4701:               $array[0] ='Array reference error';
 4702:               return (\@array, $string);
 4703:           }
 4704:       } elsif($string =~ /^__ARRAY_REF__/) {
 4705:           ($value, $string)=&str2arrayref($string);
 4706:           if($value->[0] eq 'Array reference error') {
 4707:               $array[0] ='Array reference error';
 4708:               return (\@array, $string);
 4709:           }
 4710:       } else {
 4711: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 4712:       }
 4713:       $string =~ s/^&//;
 4714: 
 4715:       push(@array, $value);
 4716:   }
 4717: 
 4718:   $string =~ s/^__END_ARRAY_REF__//;
 4719: 
 4720:   return (\@array, $string);
 4721: }
 4722: 
 4723: # -------------------------------------------------------------------Temp Store
 4724: 
 4725: sub tmpreset {
 4726:   my ($symb,$namespace,$domain,$stuname) = @_;
 4727:   if (!$symb) {
 4728:     $symb=&symbread();
 4729:     if (!$symb) { $symb= $env{'request.url'}; }
 4730:   }
 4731:   $symb=escape($symb);
 4732: 
 4733:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4734:   $namespace=~s/\//\_/g;
 4735:   $namespace=~s/\W//g;
 4736: 
 4737:   if (!$domain) { $domain=$env{'user.domain'}; }
 4738:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4739:   if ($domain eq 'public' && $stuname eq 'public') {
 4740:       $stuname=$ENV{'REMOTE_ADDR'};
 4741:   }
 4742:   my $path=LONCAPA::tempdir();
 4743:   my %hash;
 4744:   if (tie(%hash,'GDBM_File',
 4745: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4746: 	  &GDBM_WRCREAT(),0640)) {
 4747:     foreach my $key (keys(%hash)) {
 4748:       if ($key=~ /:$symb/) {
 4749: 	delete($hash{$key});
 4750:       }
 4751:     }
 4752:   }
 4753: }
 4754: 
 4755: sub tmpstore {
 4756:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4757: 
 4758:   if (!$symb) {
 4759:     $symb=&symbread();
 4760:     if (!$symb) { $symb= $env{'request.url'}; }
 4761:   }
 4762:   $symb=escape($symb);
 4763: 
 4764:   if (!$namespace) {
 4765:     # I don't think we would ever want to store this for a course.
 4766:     # it seems this will only be used if we don't have a course.
 4767:     #$namespace=$env{'request.course.id'};
 4768:     #if (!$namespace) {
 4769:       $namespace=$env{'request.state'};
 4770:     #}
 4771:   }
 4772:   $namespace=~s/\//\_/g;
 4773:   $namespace=~s/\W//g;
 4774:   if (!$domain) { $domain=$env{'user.domain'}; }
 4775:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4776:   if ($domain eq 'public' && $stuname eq 'public') {
 4777:       $stuname=$ENV{'REMOTE_ADDR'};
 4778:   }
 4779:   my $now=time;
 4780:   my %hash;
 4781:   my $path=LONCAPA::tempdir();
 4782:   if (tie(%hash,'GDBM_File',
 4783: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4784: 	  &GDBM_WRCREAT(),0640)) {
 4785:     $hash{"version:$symb"}++;
 4786:     my $version=$hash{"version:$symb"};
 4787:     my $allkeys=''; 
 4788:     foreach my $key (keys(%$storehash)) {
 4789:       $allkeys.=$key.':';
 4790:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 4791:     }
 4792:     $hash{"$version:$symb:timestamp"}=$now;
 4793:     $allkeys.='timestamp';
 4794:     $hash{"$version:keys:$symb"}=$allkeys;
 4795:     if (untie(%hash)) {
 4796:       return 'ok';
 4797:     } else {
 4798:       return "error:$!";
 4799:     }
 4800:   } else {
 4801:     return "error:$!";
 4802:   }
 4803: }
 4804: 
 4805: # -----------------------------------------------------------------Temp Restore
 4806: 
 4807: sub tmprestore {
 4808:   my ($symb,$namespace,$domain,$stuname) = @_;
 4809: 
 4810:   if (!$symb) {
 4811:     $symb=&symbread();
 4812:     if (!$symb) { $symb= $env{'request.url'}; }
 4813:   }
 4814:   $symb=escape($symb);
 4815: 
 4816:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4817: 
 4818:   if (!$domain) { $domain=$env{'user.domain'}; }
 4819:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4820:   if ($domain eq 'public' && $stuname eq 'public') {
 4821:       $stuname=$ENV{'REMOTE_ADDR'};
 4822:   }
 4823:   my %returnhash;
 4824:   $namespace=~s/\//\_/g;
 4825:   $namespace=~s/\W//g;
 4826:   my %hash;
 4827:   my $path=LONCAPA::tempdir();
 4828:   if (tie(%hash,'GDBM_File',
 4829: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4830: 	  &GDBM_READER(),0640)) {
 4831:     my $version=$hash{"version:$symb"};
 4832:     $returnhash{'version'}=$version;
 4833:     my $scope;
 4834:     for ($scope=1;$scope<=$version;$scope++) {
 4835:       my $vkeys=$hash{"$scope:keys:$symb"};
 4836:       my @keys=split(/:/,$vkeys);
 4837:       my $key;
 4838:       $returnhash{"$scope:keys"}=$vkeys;
 4839:       foreach $key (@keys) {
 4840: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4841: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4842:       }
 4843:     }
 4844:     if (!(untie(%hash))) {
 4845:       return "error:$!";
 4846:     }
 4847:   } else {
 4848:     return "error:$!";
 4849:   }
 4850:   return %returnhash;
 4851: }
 4852: 
 4853: # ----------------------------------------------------------------------- Store
 4854: 
 4855: sub store {
 4856:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 4857:     my $home='';
 4858: 
 4859:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4860: 
 4861:     $symb=&symbclean($symb);
 4862:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4863: 
 4864:     if (!$domain) { $domain=$env{'user.domain'}; }
 4865:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4866: 
 4867:     &devalidate($symb,$stuname,$domain);
 4868: 
 4869:     $symb=escape($symb);
 4870:     if (!$namespace) { 
 4871:        unless ($namespace=$env{'request.course.id'}) { 
 4872:           return ''; 
 4873:        } 
 4874:     }
 4875:     if (!$home) { $home=$env{'user.home'}; }
 4876: 
 4877:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4878:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4879: 
 4880:     my $namevalue='';
 4881:     foreach my $key (keys(%$storehash)) {
 4882:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4883:     }
 4884:     $namevalue=~s/\&$//;
 4885:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 4886:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 4887: }
 4888: 
 4889: # -------------------------------------------------------------- Critical Store
 4890: 
 4891: sub cstore {
 4892:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 4893:     my $home='';
 4894: 
 4895:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4896: 
 4897:     $symb=&symbclean($symb);
 4898:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4899: 
 4900:     if (!$domain) { $domain=$env{'user.domain'}; }
 4901:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4902: 
 4903:     &devalidate($symb,$stuname,$domain);
 4904: 
 4905:     $symb=escape($symb);
 4906:     if (!$namespace) { 
 4907:        unless ($namespace=$env{'request.course.id'}) { 
 4908:           return ''; 
 4909:        } 
 4910:     }
 4911:     if (!$home) { $home=$env{'user.home'}; }
 4912: 
 4913:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4914:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4915: 
 4916:     my $namevalue='';
 4917:     foreach my $key (keys(%$storehash)) {
 4918:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4919:     }
 4920:     $namevalue=~s/\&$//;
 4921:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 4922:     return critical
 4923:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 4924: }
 4925: 
 4926: # --------------------------------------------------------------------- Restore
 4927: 
 4928: sub restore {
 4929:     my ($symb,$namespace,$domain,$stuname) = @_;
 4930:     my $home='';
 4931: 
 4932:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4933: 
 4934:     if (!$symb) {
 4935:         return if ($namespace eq 'courserequests');
 4936:         unless ($symb=escape(&symbread())) { return ''; }
 4937:     } else {
 4938:         unless ($namespace eq 'courserequests') {
 4939:             $symb=&escape(&symbclean($symb));
 4940:         }
 4941:     }
 4942:     if (!$namespace) { 
 4943:        unless ($namespace=$env{'request.course.id'}) { 
 4944:           return ''; 
 4945:        } 
 4946:     }
 4947:     if (!$domain) { $domain=$env{'user.domain'}; }
 4948:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4949:     if (!$home) { $home=$env{'user.home'}; }
 4950:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 4951: 
 4952:     my %returnhash=();
 4953:     foreach my $line (split(/\&/,$answer)) {
 4954: 	my ($name,$value)=split(/\=/,$line);
 4955:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 4956:     }
 4957:     my $version;
 4958:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 4959:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 4960:           $returnhash{$item}=$returnhash{$version.':'.$item};
 4961:        }
 4962:     }
 4963:     return %returnhash;
 4964: }
 4965: 
 4966: # ---------------------------------------------------------- Course Description
 4967: #
 4968: #  
 4969: 
 4970: sub coursedescription {
 4971:     my ($courseid,$args)=@_;
 4972:     $courseid=~s/^\///;
 4973:     $courseid=~s/\_/\//g;
 4974:     my ($cdomain,$cnum)=split(/\//,$courseid);
 4975:     my $chome=&homeserver($cnum,$cdomain);
 4976:     my $normalid=$cdomain.'_'.$cnum;
 4977:     # need to always cache even if we get errors otherwise we keep 
 4978:     # trying and trying and trying to get the course description.
 4979:     my %envhash=();
 4980:     my %returnhash=();
 4981:     
 4982:     my $expiretime=600;
 4983:     if ($env{'request.course.id'} eq $normalid) {
 4984: 	$expiretime=120;
 4985:     }
 4986: 
 4987:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 4988:     if (!$args->{'freshen_cache'}
 4989: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 4990: 	foreach my $key (keys(%env)) {
 4991: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 4992: 	    my ($setting) = $1;
 4993: 	    $returnhash{$setting} = $env{$key};
 4994: 	}
 4995: 	return %returnhash;
 4996:     }
 4997: 
 4998:     # get the data again
 4999: 
 5000:     if (!$args->{'one_time'}) {
 5001: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 5002:     }
 5003: 
 5004:     if ($chome ne 'no_host') {
 5005:        %returnhash=&dump('environment',$cdomain,$cnum);
 5006:        if (!exists($returnhash{'con_lost'})) {
 5007: 	   my $username = $env{'user.name'}; # Defult username
 5008: 	   if(defined $args->{'user'}) {
 5009: 	       $username = $args->{'user'};
 5010: 	   }
 5011:            $returnhash{'home'}= $chome;
 5012: 	   $returnhash{'domain'} = $cdomain;
 5013: 	   $returnhash{'num'} = $cnum;
 5014:            if (!defined($returnhash{'type'})) {
 5015:                $returnhash{'type'} = 'Course';
 5016:            }
 5017:            while (my ($name,$value) = each %returnhash) {
 5018:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 5019:            }
 5020:            $returnhash{'url'}=&clutter($returnhash{'url'});
 5021:            $returnhash{'fn'}=LONCAPA::tempdir() .
 5022: 	       $username.'_'.$cdomain.'_'.$cnum;
 5023:            $envhash{'course.'.$normalid.'.home'}=$chome;
 5024:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 5025:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 5026:        }
 5027:     }
 5028:     if (!$args->{'one_time'}) {
 5029: 	&appenv(\%envhash);
 5030:     }
 5031:     return %returnhash;
 5032: }
 5033: 
 5034: sub update_released_required {
 5035:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 5036:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 5037:         $cid = $env{'request.course.id'};
 5038:         $cdom = $env{'course.'.$cid.'.domain'};
 5039:         $cnum = $env{'course.'.$cid.'.num'};
 5040:         $chome = $env{'course.'.$cid.'.home'};
 5041:     }
 5042:     if ($needsrelease) {
 5043:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 5044:         my $needsupdate;
 5045:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 5046:             $needsupdate = 1;
 5047:         } else {
 5048:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 5049:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 5050:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 5051:                 $needsupdate = 1;
 5052:             }
 5053:         }
 5054:         if ($needsupdate) {
 5055:             my %needshash = (
 5056:                              'internal.releaserequired' => $needsrelease,
 5057:                             );
 5058:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 5059:             if ($putresult eq 'ok') {
 5060:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 5061:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 5062:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 5063:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 5064:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 5065:                 }
 5066:             }
 5067:         }
 5068:     }
 5069:     return;
 5070: }
 5071: 
 5072: # -------------------------------------------------See if a user is privileged
 5073: 
 5074: sub privileged {
 5075:     my ($username,$domain,$possdomains,$possroles)=@_;
 5076:     my $now = time;
 5077:     my $roles;
 5078:     if (ref($possroles) eq 'ARRAY') {
 5079:         $roles = $possroles; 
 5080:     } else {
 5081:         $roles = ['dc','su'];
 5082:     }
 5083:     if (ref($possdomains) eq 'ARRAY') {
 5084:         my %privileged = &privileged_by_domain($possdomains,$roles);
 5085:         foreach my $dom (@{$possdomains}) {
 5086:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 5087:                 (ref($privileged{$dom}) eq 'HASH')) {
 5088:                 foreach my $role (@{$roles}) {
 5089:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5090:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 5091:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 5092:                             return 1 unless (($end && $end < $now) ||
 5093:                                              ($start && $start > $now));
 5094:                         }
 5095:                     }
 5096:                 }
 5097:             }
 5098:         }
 5099:     } else {
 5100:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 5101:         my $now = time;
 5102: 
 5103:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
 5104:             my ($trole, $tend, $tstart) = split(/_/, $role);
 5105:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 5106:                 return 1 unless ($tend && $tend < $now) 
 5107:                         or ($tstart && $tstart > $now);
 5108:             }
 5109:         }
 5110:     }
 5111:     return 0;
 5112: }
 5113: 
 5114: sub privileged_by_domain {
 5115:     my ($domains,$roles) = @_;
 5116:     my %privileged = ();
 5117:     my $cachetime = 60*60*24;
 5118:     my $now = time;
 5119:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 5120:         return %privileged;
 5121:     }
 5122:     foreach my $dom (@{$domains}) {
 5123:         next if (ref($privileged{$dom}) eq 'HASH');
 5124:         my $needroles;
 5125:         foreach my $role (@{$roles}) {
 5126:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 5127:             if (defined($cached)) {
 5128:                 if (ref($result) eq 'HASH') {
 5129:                     $privileged{$dom}{$role} = $result;
 5130:                 }
 5131:             } else {
 5132:                 $needroles = 1;
 5133:             }
 5134:         }
 5135:         if ($needroles) {
 5136:             my %dompersonnel = &get_domain_roles($dom,$roles);
 5137:             $privileged{$dom} = {};
 5138:             foreach my $server (keys(%dompersonnel)) {
 5139:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 5140:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 5141:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 5142:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 5143:                         next if ($end && $end < $now);
 5144:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 5145:                             $dompersonnel{$server}{$item};
 5146:                     }
 5147:                 }
 5148:             }
 5149:             if (ref($privileged{$dom}) eq 'HASH') {
 5150:                 foreach my $role (@{$roles}) {
 5151:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5152:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 5153:                     } else {
 5154:                         my %hash = ();
 5155:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 5156:                     }
 5157:                 }
 5158:             }
 5159:         }
 5160:     }
 5161:     return %privileged;
 5162: }
 5163: 
 5164: # -------------------------------------------------------- Get user privileges
 5165: 
 5166: sub rolesinit {
 5167:     my ($domain, $username) = @_;
 5168:     my %userroles = ('user.login.time' => time);
 5169:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 5170: 
 5171:     # firstaccess and timerinterval are related to timed maps/resources. 
 5172:     # also, blocking can be triggered by an activating timer
 5173:     # it's saved in the user's %env.
 5174:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 5175:     my %timerinterval = &dump('timerinterval', $domain, $username);
 5176:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 5177:         %timerintchk, %timerintenv);
 5178: 
 5179:     foreach my $key (keys(%firstaccess)) {
 5180:         my ($cid, $rest) = split(/\0/, $key);
 5181:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 5182:     }
 5183: 
 5184:     foreach my $key (keys(%timerinterval)) {
 5185:         my ($cid,$rest) = split(/\0/,$key);
 5186:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 5187:     }
 5188: 
 5189:     my %allroles=();
 5190:     my %allgroups=();
 5191: 
 5192:     for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
 5193:         my $role = $rolesdump{$area};
 5194:         $area =~ s/\_\w\w$//;
 5195: 
 5196:         my ($trole, $tend, $tstart, $group_privs);
 5197: 
 5198:         if ($role =~ /^cr/) {
 5199:         # Custom role, defined by a user 
 5200:         # e.g., user.role.cr/msu/smith/mynewrole
 5201:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 5202:                 $trole = $1;
 5203:                 ($tend, $tstart) = split('_', $2);
 5204:             } else {
 5205:                 $trole = $role;
 5206:             }
 5207:         } elsif ($role =~ m|^gr/|) {
 5208:         # Role of member in a group, defined within a course/community
 5209:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 5210:             ($trole, $tend, $tstart) = split(/_/, $role);
 5211:             next if $tstart eq '-1';
 5212:             ($trole, $group_privs) = split(/\//, $trole);
 5213:             $group_privs = &unescape($group_privs);
 5214:         } else {
 5215:         # Just a normal role, defined in roles.tab
 5216:             ($trole, $tend, $tstart) = split(/_/,$role);
 5217:         }
 5218: 
 5219:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 5220:                  $username);
 5221:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 5222: 
 5223:         # role expired or not available yet?
 5224:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 5225:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 5226: 
 5227:         next if $area eq '' or $trole eq '';
 5228: 
 5229:         my $spec = "$trole.$area";
 5230:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 5231: 
 5232:         if ($trole =~ /^cr\//) {
 5233:         # Custom role, defined by a user
 5234:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 5235:         } elsif ($trole eq 'gr') {
 5236:         # Role of a member in a group, defined within a course/community
 5237:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 5238:             next;
 5239:         } else {
 5240:         # Normal role, defined in roles.tab
 5241:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 5242:         }
 5243: 
 5244:         my $cid = $tdomain.'_'.$trest;
 5245:         unless ($firstaccchk{$cid}) {
 5246:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 5247:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 5248:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 5249:                         $coursetimerstarts{$cid}{$item}; 
 5250:                 }
 5251:             }
 5252:             $firstaccchk{$cid} = 1;
 5253:         }
 5254:         unless ($timerintchk{$cid}) {
 5255:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 5256:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 5257:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 5258:                        $coursetimerintervals{$cid}{$item};
 5259:                 }
 5260:             }
 5261:             $timerintchk{$cid} = 1;
 5262:         }
 5263:     }
 5264: 
 5265:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
 5266:         \%allroles, \%allgroups);
 5267:     $env{'user.adv'} = $userroles{'user.adv'};
 5268: 
 5269:     return (\%userroles,\%firstaccenv,\%timerintenv);
 5270: }
 5271: 
 5272: sub set_arearole {
 5273:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 5274:     unless ($nolog) {
 5275: # log the associated role with the area
 5276:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 5277:     }
 5278:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 5279: }
 5280: 
 5281: sub custom_roleprivs {
 5282:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 5283:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 5284:     my $homsvr = &homeserver($rauthor,$rdomain);
 5285:     if (&hostname($homsvr) ne '') {
 5286:         my ($rdummy,$roledef)=
 5287:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 5288:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 5289:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 5290:             if (defined($syspriv)) {
 5291:                 if ($trest =~ /^$match_community$/) {
 5292:                     $syspriv =~ s/bre\&S//; 
 5293:                 }
 5294:                 $$allroles{'cm./'}.=':'.$syspriv;
 5295:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 5296:             }
 5297:             if ($tdomain ne '') {
 5298:                 if (defined($dompriv)) {
 5299:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 5300:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 5301:                 }
 5302:                 if (($trest ne '') && (defined($coursepriv))) {
 5303:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 5304:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 5305:                 }
 5306:             }
 5307:         }
 5308:     }
 5309: }
 5310: 
 5311: sub group_roleprivs {
 5312:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 5313:     my $access = 1;
 5314:     my $now = time;
 5315:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 5316:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 5317:     if ($access) {
 5318:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 5319:         $$allgroups{$course}{$group} .=':'.$group_privs;
 5320:     }
 5321: }
 5322: 
 5323: sub standard_roleprivs {
 5324:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 5325:     if (defined($pr{$trole.':s'})) {
 5326:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 5327:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 5328:     }
 5329:     if ($tdomain ne '') {
 5330:         if (defined($pr{$trole.':d'})) {
 5331:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 5332:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 5333:         }
 5334:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 5335:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 5336:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 5337:         }
 5338:     }
 5339: }
 5340: 
 5341: sub set_userprivs {
 5342:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 5343:     my $author=0;
 5344:     my $adv=0;
 5345:     my %grouproles = ();
 5346:     if (keys(%{$allgroups}) > 0) {
 5347:         my @groupkeys; 
 5348:         foreach my $role (keys(%{$allroles})) {
 5349:             push(@groupkeys,$role);
 5350:         }
 5351:         if (ref($groups_roles) eq 'HASH') {
 5352:             foreach my $key (keys(%{$groups_roles})) {
 5353:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 5354:                     push(@groupkeys,$key);
 5355:                 }
 5356:             }
 5357:         }
 5358:         if (@groupkeys > 0) {
 5359:             foreach my $role (@groupkeys) {
 5360:                 my ($trole,$area,$sec,$extendedarea);
 5361:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 5362:                     $trole = $1;
 5363:                     $area = $2;
 5364:                     $sec = $3;
 5365:                     $extendedarea = $area.$sec;
 5366:                     if (exists($$allgroups{$area})) {
 5367:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 5368:                             my $spec = $trole.'.'.$extendedarea;
 5369:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 5370:                                                 $$allgroups{$area}{$group};
 5371:                         }
 5372:                     }
 5373:                 }
 5374:             }
 5375:         }
 5376:     }
 5377:     foreach my $group (keys(%grouproles)) {
 5378:         $$allroles{$group} = $grouproles{$group};
 5379:     }
 5380:     foreach my $role (keys(%{$allroles})) {
 5381:         my %thesepriv;
 5382:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 5383:         foreach my $item (split(/:/,$$allroles{$role})) {
 5384:             if ($item ne '') {
 5385:                 my ($privilege,$restrictions)=split(/&/,$item);
 5386:                 if ($restrictions eq '') {
 5387:                     $thesepriv{$privilege}='F';
 5388:                 } elsif ($thesepriv{$privilege} ne 'F') {
 5389:                     $thesepriv{$privilege}.=$restrictions;
 5390:                 }
 5391:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 5392:             }
 5393:         }
 5394:         my $thesestr='';
 5395:         foreach my $priv (sort(keys(%thesepriv))) {
 5396: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 5397: 	}
 5398:         $userroles->{'user.priv.'.$role} = $thesestr;
 5399:     }
 5400:     return ($author,$adv);
 5401: }
 5402: 
 5403: sub role_status {
 5404:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 5405:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 5406:         my ($one,$two) = split(m{\./},$rolekey,2);
 5407:         (undef,undef,$$role) = split(/\./,$one,3);
 5408:         unless (!defined($$role) || $$role eq '') {
 5409:             $$where = '/'.$two;
 5410:             $$trolecode=$$role.'.'.$$where;
 5411:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 5412:             $$tstatus='is';
 5413:             if ($$tstart && $$tstart>$update) {
 5414:                 $$tstatus='future';
 5415:                 if ($$tstart<$now) {
 5416:                     if ($$tstart && $$tstart>$refresh) {
 5417:                         if (($$where ne '') && ($$role ne '')) {
 5418:                             my (%allroles,%allgroups,$group_privs,
 5419:                                 %groups_roles,@rolecodes);
 5420:                             my %userroles = (
 5421:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 5422:                             );
 5423:                             @rolecodes = ('cm'); 
 5424:                             my $spec=$$role.'.'.$$where;
 5425:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 5426:                             if ($$role =~ /^cr\//) {
 5427:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 5428:                                 push(@rolecodes,'cr');
 5429:                             } elsif ($$role eq 'gr') {
 5430:                                 push(@rolecodes,$$role);
 5431:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 5432:                                                     $env{'user.name'});
 5433:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 5434:                                 (undef,my $group_privs) = split(/\//,$trole);
 5435:                                 $group_privs = &unescape($group_privs);
 5436:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 5437:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 5438:                                 &get_groups_roles($tdomain,$trest,
 5439:                                                   \%course_roles,\@rolecodes,
 5440:                                                   \%groups_roles);
 5441:                             } else {
 5442:                                 push(@rolecodes,$$role);
 5443:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 5444:                             }
 5445:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
 5446:                             &appenv(\%userroles,\@rolecodes);
 5447:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5448:                         }
 5449:                     }
 5450:                     $$tstatus = 'is';
 5451:                 }
 5452:             }
 5453:             if ($$tend) {
 5454:                 if ($$tend<$update) {
 5455:                     $$tstatus='expired';
 5456:                 } elsif ($$tend<$now) {
 5457:                     $$tstatus='will_not';
 5458:                 }
 5459:             }
 5460:         }
 5461:     }
 5462: }
 5463: 
 5464: sub get_groups_roles {
 5465:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 5466:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 5467:                   (ref($rolecodes) eq 'ARRAY') && 
 5468:                   (ref($groups_roles) eq 'HASH')); 
 5469:     if (keys(%{$cdom_courseroles}) > 0) {
 5470:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 5471:         if ($cdom ne '' && $cnum ne '') {
 5472:             foreach my $key (keys(%{$cdom_courseroles})) {
 5473:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 5474:                     my $crsrole = $1;
 5475:                     my $crssec = $2;
 5476:                     if ($crsrole =~ /^cr/) {
 5477:                         unless (grep(/^cr$/,@{$rolecodes})) {
 5478:                             push(@{$rolecodes},'cr');
 5479:                         }
 5480:                     } else {
 5481:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 5482:                             push(@{$rolecodes},$crsrole);
 5483:                         }
 5484:                     }
 5485:                     my $rolekey = "$crsrole./$cdom/$cnum";
 5486:                     if ($crssec ne '') {
 5487:                         $rolekey .= "/$crssec";
 5488:                     }
 5489:                     $rolekey .= './';
 5490:                     $groups_roles->{$rolekey} = $rolecodes;
 5491:                 }
 5492:             }
 5493:         }
 5494:     }
 5495:     return;
 5496: }
 5497: 
 5498: sub delete_env_groupprivs {
 5499:     my ($where,$courseroles,$possroles) = @_;
 5500:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 5501:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 5502:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 5503:         %{$courseroles->{$udom}} =
 5504:             &get_my_roles('','','userroles',['active'],
 5505:                           $possroles,[$udom],1);
 5506:     }
 5507:     if (ref($courseroles->{$udom}) eq 'HASH') {
 5508:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 5509:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 5510:             my $area = '/'.$cdom.'/'.$cnum;
 5511:             my $privkey = "user.priv.$crsrole.$area";
 5512:             if ($crssec ne '') {
 5513:                 $privkey .= '/'.$crssec;
 5514:             }
 5515:             $privkey .= ".$area/$group";
 5516:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 5517:         }
 5518:     }
 5519:     return;
 5520: }
 5521: 
 5522: sub check_adhoc_privs {
 5523:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
 5524:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 5525:     my $setprivs;
 5526:     if ($env{$cckey}) {
 5527:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 5528:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 5529:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 5530:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5531:             $setprivs = 1;
 5532:         }
 5533:     } else {
 5534:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5535:         $setprivs = 1;
 5536:     }
 5537:     return $setprivs;
 5538: }
 5539: 
 5540: sub set_adhoc_privileges {
 5541: # role can be cc or ca
 5542:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
 5543:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 5544:     my $spec = $role.'.'.$area;
 5545:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 5546:                                   $env{'user.name'},1);
 5547:     my %ccrole = ();
 5548:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
 5549:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
 5550:     &appenv(\%userroles,[$role,'cm']);
 5551:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5552:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 5553:         &appenv( {'request.role'        => $spec,
 5554:                   'request.role.domain' => $dcdom,
 5555:                   'request.course.sec'  => ''
 5556:                  }
 5557:                );
 5558:         my $tadv=0;
 5559:         if (&allowed('adv') eq 'F') { $tadv=1; }
 5560:         &appenv({'request.role.adv'    => $tadv});
 5561:     }
 5562: }
 5563: 
 5564: # --------------------------------------------------------------- get interface
 5565: 
 5566: sub get {
 5567:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5568:    my $items='';
 5569:    foreach my $item (@$storearr) {
 5570:        $items.=&escape($item).'&';
 5571:    }
 5572:    $items=~s/\&$//;
 5573:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5574:    if (!$uname) { $uname=$env{'user.name'}; }
 5575:    my $uhome=&homeserver($uname,$udomain);
 5576: 
 5577:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 5578:    my @pairs=split(/\&/,$rep);
 5579:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 5580:      return @pairs;
 5581:    }
 5582:    my %returnhash=();
 5583:    my $i=0;
 5584:    foreach my $item (@$storearr) {
 5585:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5586:       $i++;
 5587:    }
 5588:    return %returnhash;
 5589: }
 5590: 
 5591: # --------------------------------------------------------------- del interface
 5592: 
 5593: sub del {
 5594:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5595:    my $items='';
 5596:    foreach my $item (@$storearr) {
 5597:        $items.=&escape($item).'&';
 5598:    }
 5599: 
 5600:    $items=~s/\&$//;
 5601:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5602:    if (!$uname) { $uname=$env{'user.name'}; }
 5603:    my $uhome=&homeserver($uname,$udomain);
 5604:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 5605: }
 5606: 
 5607: # -------------------------------------------------------------- dump interface
 5608: 
 5609: sub unserialize {
 5610:     my ($rep, $escapedkeys) = @_;
 5611: 
 5612:     return {} if $rep =~ /^error/;
 5613: 
 5614:     my %returnhash=();
 5615: 	foreach my $item (split(/\&/,$rep)) {
 5616: 	    my ($key, $value) = split(/=/, $item, 2);
 5617: 	    $key = unescape($key) unless $escapedkeys;
 5618: 	    next if $key =~ /^error: 2 /;
 5619: 	    $returnhash{$key} = &thaw_unescape($value);
 5620: 	}
 5621:     #return %returnhash;
 5622:     return \%returnhash;
 5623: }        
 5624: 
 5625: # see Lond::dump_with_regexp
 5626: # if $escapedkeys hash keys won't get unescaped.
 5627: sub dump {
 5628:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 5629:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5630:     if (!$uname) { $uname=$env{'user.name'}; }
 5631:     my $uhome=&homeserver($uname,$udomain);
 5632: 
 5633:     if ($regexp) {
 5634:         $regexp=&escape($regexp);
 5635:     } else {
 5636:         $regexp='.';
 5637:     }
 5638:     if (grep { $_ eq $uhome } current_machine_ids()) {
 5639:         # user is hosted on this machine
 5640:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 5641:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 5642:         return %{unserialize($reply, $escapedkeys)};
 5643:     }
 5644:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 5645:     my @pairs=split(/\&/,$rep);
 5646:     my %returnhash=();
 5647:     if (!($rep =~ /^error/ )) {
 5648: 	foreach my $item (@pairs) {
 5649: 	    my ($key,$value)=split(/=/,$item,2);
 5650:         $key = unescape($key) unless $escapedkeys;
 5651:         #$key = &unescape($key);
 5652: 	    next if ($key =~ /^error: 2 /);
 5653: 	    $returnhash{$key}=&thaw_unescape($value);
 5654: 	}
 5655:     }
 5656:     return %returnhash;
 5657: }
 5658: 
 5659: 
 5660: # --------------------------------------------------------- dumpstore interface
 5661: 
 5662: sub dumpstore {
 5663:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 5664:    # same as dump but keys must be escaped. They may contain colon separated
 5665:    # lists of values that may themself contain colons (e.g. symbs).
 5666:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 5667: }
 5668: 
 5669: # -------------------------------------------------------------- keys interface
 5670: 
 5671: sub getkeys {
 5672:    my ($namespace,$udomain,$uname)=@_;
 5673:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5674:    if (!$uname) { $uname=$env{'user.name'}; }
 5675:    my $uhome=&homeserver($uname,$udomain);
 5676:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 5677:    my @keyarray=();
 5678:    foreach my $key (split(/\&/,$rep)) {
 5679:       next if ($key =~ /^error: 2 /);
 5680:       push(@keyarray,&unescape($key));
 5681:    }
 5682:    return @keyarray;
 5683: }
 5684: 
 5685: # --------------------------------------------------------------- currentdump
 5686: sub currentdump {
 5687:    my ($courseid,$sdom,$sname)=@_;
 5688:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 5689:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 5690:    $sname    = $env{'user.name'}         if (! defined($sname));
 5691:    my $uhome = &homeserver($sname,$sdom);
 5692:    my $rep;
 5693: 
 5694:    if (grep { $_ eq $uhome } current_machine_ids()) {
 5695:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 5696:                    $courseid)));
 5697:    } else {
 5698:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 5699:    }
 5700: 
 5701:    return if ($rep =~ /^(error:|no_such_host)/);
 5702:    #
 5703:    my %returnhash=();
 5704:    #
 5705:    if ($rep eq "unknown_cmd") { 
 5706:        # an old lond will not know currentdump
 5707:        # Do a dump and make it look like a currentdump
 5708:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 5709:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 5710:        my %hash = @tmp;
 5711:        @tmp=();
 5712:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 5713:    } else {
 5714:        my @pairs=split(/\&/,$rep);
 5715:        foreach my $pair (@pairs) {
 5716:            my ($key,$value)=split(/=/,$pair,2);
 5717:            my ($symb,$param) = split(/:/,$key);
 5718:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 5719:                                                         &thaw_unescape($value);
 5720:        }
 5721:    }
 5722:    return %returnhash;
 5723: }
 5724: 
 5725: sub convert_dump_to_currentdump{
 5726:     my %hash = %{shift()};
 5727:     my %returnhash;
 5728:     # Code ripped from lond, essentially.  The only difference
 5729:     # here is the unescaping done by lonnet::dump().  Conceivably
 5730:     # we might run in to problems with parameter names =~ /^v\./
 5731:     while (my ($key,$value) = each(%hash)) {
 5732:         my ($v,$symb,$param) = split(/:/,$key);
 5733: 	$symb  = &unescape($symb);
 5734: 	$param = &unescape($param);
 5735:         next if ($v eq 'version' || $symb eq 'keys');
 5736:         next if (exists($returnhash{$symb}) &&
 5737:                  exists($returnhash{$symb}->{$param}) &&
 5738:                  $returnhash{$symb}->{'v.'.$param} > $v);
 5739:         $returnhash{$symb}->{$param}=$value;
 5740:         $returnhash{$symb}->{'v.'.$param}=$v;
 5741:     }
 5742:     #
 5743:     # Remove all of the keys in the hashes which keep track of
 5744:     # the version of the parameter.
 5745:     while (my ($symb,$param_hash) = each(%returnhash)) {
 5746:         # use a foreach because we are going to delete from the hash.
 5747:         foreach my $key (keys(%$param_hash)) {
 5748:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 5749:         }
 5750:     }
 5751:     return \%returnhash;
 5752: }
 5753: 
 5754: # ------------------------------------------------------ critical inc interface
 5755: 
 5756: sub cinc {
 5757:     return &inc(@_,'critical');
 5758: }
 5759: 
 5760: # --------------------------------------------------------------- inc interface
 5761: 
 5762: sub inc {
 5763:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 5764:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5765:     if (!$uname) { $uname=$env{'user.name'}; }
 5766:     my $uhome=&homeserver($uname,$udomain);
 5767:     my $items='';
 5768:     if (! ref($store)) {
 5769:         # got a single value, so use that instead
 5770:         $items = &escape($store).'=&';
 5771:     } elsif (ref($store) eq 'SCALAR') {
 5772:         $items = &escape($$store).'=&';        
 5773:     } elsif (ref($store) eq 'ARRAY') {
 5774:         $items = join('=&',map {&escape($_);} @{$store});
 5775:     } elsif (ref($store) eq 'HASH') {
 5776:         while (my($key,$value) = each(%{$store})) {
 5777:             $items.= &escape($key).'='.&escape($value).'&';
 5778:         }
 5779:     }
 5780:     $items=~s/\&$//;
 5781:     if ($critical) {
 5782: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 5783:     } else {
 5784: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 5785:     }
 5786: }
 5787: 
 5788: # --------------------------------------------------------------- put interface
 5789: 
 5790: sub put {
 5791:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5792:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5793:    if (!$uname) { $uname=$env{'user.name'}; }
 5794:    my $uhome=&homeserver($uname,$udomain);
 5795:    my $items='';
 5796:    foreach my $item (keys(%$storehash)) {
 5797:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5798:    }
 5799:    $items=~s/\&$//;
 5800:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5801: }
 5802: 
 5803: # ------------------------------------------------------------ newput interface
 5804: 
 5805: sub newput {
 5806:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5807:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5808:    if (!$uname) { $uname=$env{'user.name'}; }
 5809:    my $uhome=&homeserver($uname,$udomain);
 5810:    my $items='';
 5811:    foreach my $key (keys(%$storehash)) {
 5812:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5813:    }
 5814:    $items=~s/\&$//;
 5815:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 5816: }
 5817: 
 5818: # ---------------------------------------------------------  putstore interface
 5819: 
 5820: sub putstore {
 5821:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
 5822:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5823:    if (!$uname) { $uname=$env{'user.name'}; }
 5824:    my $uhome=&homeserver($uname,$udomain);
 5825:    my $items='';
 5826:    foreach my $key (keys(%$storehash)) {
 5827:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 5828:    }
 5829:    $items=~s/\&$//;
 5830:    my $esc_symb=&escape($symb);
 5831:    my $esc_v=&escape($version);
 5832:    my $reply =
 5833:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 5834: 	      $uhome);
 5835:    if (($tolog) && ($reply eq 'ok')) {
 5836:        my $namevalue='';
 5837:        foreach my $key (keys(%{$storehash})) {
 5838:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 5839:        }
 5840:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
 5841:                      '&host='.&escape($perlvar{'lonHostID'}).
 5842:                      '&version='.$esc_v.
 5843:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
 5844:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
 5845:    }
 5846:    if ($reply eq 'unknown_cmd') {
 5847:        # gfall back to way things use to be done
 5848:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 5849: 			    $uname);
 5850:    }
 5851:    return $reply;
 5852: }
 5853: 
 5854: sub old_putstore {
 5855:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5856:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5857:     if (!$uname) { $uname=$env{'user.name'}; }
 5858:     my $uhome=&homeserver($uname,$udomain);
 5859:     my %newstorehash;
 5860:     foreach my $item (keys(%$storehash)) {
 5861: 	my $key = $version.':'.&escape($symb).':'.$item;
 5862: 	$newstorehash{$key} = $storehash->{$item};
 5863:     }
 5864:     my $items='';
 5865:     my %allitems = ();
 5866:     foreach my $item (keys(%newstorehash)) {
 5867: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 5868: 	    my $key = $1.':keys:'.$2;
 5869: 	    $allitems{$key} .= $3.':';
 5870: 	}
 5871: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 5872:     }
 5873:     foreach my $item (keys(%allitems)) {
 5874: 	$allitems{$item} =~ s/\:$//;
 5875: 	$items.= $item.'='.$allitems{$item}.'&';
 5876:     }
 5877:     $items=~s/\&$//;
 5878:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5879: }
 5880: 
 5881: # ------------------------------------------------------ critical put interface
 5882: 
 5883: sub cput {
 5884:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5885:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5886:    if (!$uname) { $uname=$env{'user.name'}; }
 5887:    my $uhome=&homeserver($uname,$udomain);
 5888:    my $items='';
 5889:    foreach my $item (keys(%$storehash)) {
 5890:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5891:    }
 5892:    $items=~s/\&$//;
 5893:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 5894: }
 5895: 
 5896: # -------------------------------------------------------------- eget interface
 5897: 
 5898: sub eget {
 5899:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5900:    my $items='';
 5901:    foreach my $item (@$storearr) {
 5902:        $items.=&escape($item).'&';
 5903:    }
 5904:    $items=~s/\&$//;
 5905:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5906:    if (!$uname) { $uname=$env{'user.name'}; }
 5907:    my $uhome=&homeserver($uname,$udomain);
 5908:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 5909:    my @pairs=split(/\&/,$rep);
 5910:    my %returnhash=();
 5911:    my $i=0;
 5912:    foreach my $item (@$storearr) {
 5913:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5914:       $i++;
 5915:    }
 5916:    return %returnhash;
 5917: }
 5918: 
 5919: # ------------------------------------------------------------ tmpput interface
 5920: sub tmpput {
 5921:     my ($storehash,$server,$context)=@_;
 5922:     my $items='';
 5923:     foreach my $item (keys(%$storehash)) {
 5924: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5925:     }
 5926:     $items=~s/\&$//;
 5927:     if (defined($context)) {
 5928:         $items .= ':'.&escape($context);
 5929:     }
 5930:     return &reply("tmpput:$items",$server);
 5931: }
 5932: 
 5933: # ------------------------------------------------------------ tmpget interface
 5934: sub tmpget {
 5935:     my ($token,$server)=@_;
 5936:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5937:     my $rep=&reply("tmpget:$token",$server);
 5938:     my %returnhash;
 5939:     foreach my $item (split(/\&/,$rep)) {
 5940: 	my ($key,$value)=split(/=/,$item);
 5941:         next if ($key =~ /^error: 2 /);
 5942: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 5943:     }
 5944:     return %returnhash;
 5945: }
 5946: 
 5947: # ------------------------------------------------------------ tmpdel interface
 5948: sub tmpdel {
 5949:     my ($token,$server)=@_;
 5950:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5951:     return &reply("tmpdel:$token",$server);
 5952: }
 5953: 
 5954: # ------------------------------------------------------------ get_timebased_id 
 5955: 
 5956: sub get_timebased_id {
 5957:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 5958:         $maxtries) = @_;
 5959:     my ($newid,$error,$dellock);
 5960:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 5961:         return ('','ok','invalid call to get suffix');
 5962:     }
 5963: 
 5964: # set defaults for any optional args for which values were not supplied
 5965:     if ($who eq '') {
 5966:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 5967:     }
 5968:     if (!$locktries) {
 5969:         $locktries = 3;
 5970:     }
 5971:     if (!$maxtries) {
 5972:         $maxtries = 10;
 5973:     }
 5974:     
 5975:     if (($cdom eq '') || ($cnum eq '')) {
 5976:         if ($env{'request.course.id'}) {
 5977:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5978:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5979:         }
 5980:         if (($cdom eq '') || ($cnum eq '')) {
 5981:             return ('','ok','call to get suffix not in course context');
 5982:         }
 5983:     }
 5984: 
 5985: # construct locking item
 5986:     my $lockhash = {
 5987:                       $prefix."\0".'locked_'.$keyid => $who,
 5988:                    };
 5989:     my $tries = 0;
 5990: 
 5991: # attempt to get lock on nohist_$namespace file
 5992:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 5993:     while (($gotlock ne 'ok') && $tries <$locktries) {
 5994:         $tries ++;
 5995:         sleep 1;
 5996:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 5997:     }
 5998: 
 5999: # attempt to get unique identifier, based on current timestamp
 6000:     if ($gotlock eq 'ok') {
 6001:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 6002:         my $id = time;
 6003:         $newid = $id;
 6004:         if ($idtype eq 'addcode') {
 6005:             $newid .= &sixnum_code();
 6006:         }
 6007:         my $idtries = 0;
 6008:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 6009:             if ($idtype eq 'concat') {
 6010:                 $newid = $id.$idtries;
 6011:             } elsif ($idtype eq 'addcode') {
 6012:                 $newid = $newid.&sixnum_code();
 6013:             } else {
 6014:                 $newid ++;
 6015:             }
 6016:             $idtries ++;
 6017:         }
 6018:         if (!exists($inuse{$prefix."\0".$newid})) {
 6019:             my %new_item =  (
 6020:                               $prefix."\0".$newid => $who,
 6021:                             );
 6022:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 6023:                                                  $cdom,$cnum);
 6024:             if ($putresult ne 'ok') {
 6025:                 undef($newid);
 6026:                 $error = 'error saving new item: '.$putresult;
 6027:             }
 6028:         } else {
 6029:              undef($newid);
 6030:              $error = ('error: no unique suffix available for the new item ');
 6031:         }
 6032: #  remove lock
 6033:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 6034:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 6035:     } else {
 6036:         $error = "error: could not obtain lockfile\n";
 6037:         $dellock = 'ok';
 6038:     }
 6039:     return ($newid,$dellock,$error);
 6040: }
 6041: 
 6042: sub sixnum_code {
 6043:     my $code;
 6044:     for (0..6) {
 6045:         $code .= int( rand(9) );
 6046:     }
 6047:     return $code;
 6048: }
 6049: 
 6050: # -------------------------------------------------- portfolio access checking
 6051: 
 6052: sub portfolio_access {
 6053:     my ($requrl) = @_;
 6054:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 6055:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 6056:     if ($result) {
 6057:         my %setters;
 6058:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 6059:             my ($startblock,$endblock) =
 6060:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 6061:             if ($startblock && $endblock) {
 6062:                 return 'B';
 6063:             }
 6064:         } else {
 6065:             my ($startblock,$endblock) =
 6066:                 &Apache::loncommon::blockcheck(\%setters,'port');
 6067:             if ($startblock && $endblock) {
 6068:                 return 'B';
 6069:             }
 6070:         }
 6071:     }
 6072:     if ($result eq 'ok') {
 6073:        return 'F';
 6074:     } elsif ($result =~ /^[^:]+:guest_/) {
 6075:        return 'A';
 6076:     }
 6077:     return '';
 6078: }
 6079: 
 6080: sub get_portfolio_access {
 6081:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 6082: 
 6083:     if (!ref($access_hash)) {
 6084: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 6085: 	my %access_controls = &get_access_controls($current_perms,$group,
 6086: 						   $file_name);
 6087: 	$access_hash = $access_controls{$file_name};
 6088:     }
 6089: 
 6090:     my ($public,$guest,@domains,@users,@courses,@groups);
 6091:     my $now = time;
 6092:     if (ref($access_hash) eq 'HASH') {
 6093:         foreach my $key (keys(%{$access_hash})) {
 6094:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 6095:             if ($start > $now) {
 6096:                 next;
 6097:             }
 6098:             if ($end && $end<$now) {
 6099:                 next;
 6100:             }
 6101:             if ($scope eq 'public') {
 6102:                 $public = $key;
 6103:                 last;
 6104:             } elsif ($scope eq 'guest') {
 6105:                 $guest = $key;
 6106:             } elsif ($scope eq 'domains') {
 6107:                 push(@domains,$key);
 6108:             } elsif ($scope eq 'users') {
 6109:                 push(@users,$key);
 6110:             } elsif ($scope eq 'course') {
 6111:                 push(@courses,$key);
 6112:             } elsif ($scope eq 'group') {
 6113:                 push(@groups,$key);
 6114:             }
 6115:         }
 6116:         if ($public) {
 6117:             return 'ok';
 6118:         }
 6119:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 6120:             if ($guest) {
 6121:                 return $guest;
 6122:             }
 6123:         } else {
 6124:             if (@domains > 0) {
 6125:                 foreach my $domkey (@domains) {
 6126:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 6127:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 6128:                             return 'ok';
 6129:                         }
 6130:                     }
 6131:                 }
 6132:             }
 6133:             if (@users > 0) {
 6134:                 foreach my $userkey (@users) {
 6135:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 6136:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 6137:                             if (ref($item) eq 'HASH') {
 6138:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 6139:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 6140:                                     return 'ok';
 6141:                                 }
 6142:                             }
 6143:                         }
 6144:                     } 
 6145:                 }
 6146:             }
 6147:             my %roleshash;
 6148:             my @courses_and_groups = @courses;
 6149:             push(@courses_and_groups,@groups); 
 6150:             if (@courses_and_groups > 0) {
 6151:                 my (%allgroups,%allroles); 
 6152:                 my ($start,$end,$role,$sec,$group);
 6153:                 foreach my $envkey (%env) {
 6154:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 6155:                         my $cid = $2.'_'.$3; 
 6156:                         if ($1 eq 'gr') {
 6157:                             $group = $4;
 6158:                             $allgroups{$cid}{$group} = $env{$envkey};
 6159:                         } else {
 6160:                             if ($4 eq '') {
 6161:                                 $sec = 'none';
 6162:                             } else {
 6163:                                 $sec = $4;
 6164:                             }
 6165:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 6166:                         }
 6167:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 6168:                         my $cid = $2.'_'.$3;
 6169:                         if ($4 eq '') {
 6170:                             $sec = 'none';
 6171:                         } else {
 6172:                             $sec = $4;
 6173:                         }
 6174:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 6175:                     }
 6176:                 }
 6177:                 if (keys(%allroles) == 0) {
 6178:                     return;
 6179:                 }
 6180:                 foreach my $key (@courses_and_groups) {
 6181:                     my %content = %{$$access_hash{$key}};
 6182:                     my $cnum = $content{'number'};
 6183:                     my $cdom = $content{'domain'};
 6184:                     my $cid = $cdom.'_'.$cnum;
 6185:                     if (!exists($allroles{$cid})) {
 6186:                         next;
 6187:                     }    
 6188:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 6189:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 6190:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 6191:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 6192:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 6193:                         foreach my $role (keys(%{$allroles{$cid}})) {
 6194:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 6195:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 6196:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 6197:                                         if (grep/^all$/,@sections) {
 6198:                                             return 'ok';
 6199:                                         } else {
 6200:                                             if (grep/^$sec$/,@sections) {
 6201:                                                 return 'ok';
 6202:                                             }
 6203:                                         }
 6204:                                     }
 6205:                                 }
 6206:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 6207:                                     if (grep/^none$/,@groups) {
 6208:                                         return 'ok';
 6209:                                     }
 6210:                                 } else {
 6211:                                     if (grep/^all$/,@groups) {
 6212:                                         return 'ok';
 6213:                                     } 
 6214:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 6215:                                         if (grep/^$group$/,@groups) {
 6216:                                             return 'ok';
 6217:                                         }
 6218:                                     }
 6219:                                 } 
 6220:                             }
 6221:                         }
 6222:                     }
 6223:                 }
 6224:             }
 6225:             if ($guest) {
 6226:                 return $guest;
 6227:             }
 6228:         }
 6229:     }
 6230:     return;
 6231: }
 6232: 
 6233: sub course_group_datechecker {
 6234:     my ($dates,$now,$status) = @_;
 6235:     my ($start,$end) = split(/\./,$dates);
 6236:     if (!$start && !$end) {
 6237:         return 'ok';
 6238:     }
 6239:     if (grep/^active$/,@{$status}) {
 6240:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 6241:             return 'ok';
 6242:         }
 6243:     }
 6244:     if (grep/^previous$/,@{$status}) {
 6245:         if ($end > $now ) {
 6246:             return 'ok';
 6247:         }
 6248:     }
 6249:     if (grep/^future$/,@{$status}) {
 6250:         if ($start > $now) {
 6251:             return 'ok';
 6252:         }
 6253:     }
 6254:     return; 
 6255: }
 6256: 
 6257: sub parse_portfolio_url {
 6258:     my ($url) = @_;
 6259: 
 6260:     my ($type,$udom,$unum,$group,$file_name);
 6261:     
 6262:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 6263: 	$type = 1;
 6264:         $udom = $1;
 6265:         $unum = $2;
 6266:         $file_name = $3;
 6267:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 6268: 	$type = 2;
 6269:         $udom = $1;
 6270:         $unum = $2;
 6271:         $group = $3;
 6272:         $file_name = $3.'/'.$4;
 6273:     }
 6274:     if (wantarray) {
 6275: 	return ($type,$udom,$unum,$file_name,$group);
 6276:     }
 6277:     return $type;
 6278: }
 6279: 
 6280: sub is_portfolio_url {
 6281:     my ($url) = @_;
 6282:     return scalar(&parse_portfolio_url($url));
 6283: }
 6284: 
 6285: sub is_portfolio_file {
 6286:     my ($file) = @_;
 6287:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 6288:         return 1;
 6289:     }
 6290:     return;
 6291: }
 6292: 
 6293: sub usertools_access {
 6294:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 6295:     my ($access,%tools);
 6296:     if ($context eq '') {
 6297:         $context = 'tools';
 6298:     }
 6299:     if ($context eq 'requestcourses') {
 6300:         %tools = (
 6301:                       official   => 1,
 6302:                       unofficial => 1,
 6303:                       community  => 1,
 6304:                       textbook   => 1,
 6305:                  );
 6306:     } elsif ($context eq 'requestauthor') {
 6307:         %tools = (
 6308:                       requestauthor => 1,
 6309:                  );
 6310:     } else {
 6311:         %tools = (
 6312:                       aboutme   => 1,
 6313:                       blog      => 1,
 6314:                       webdav    => 1,
 6315:                       portfolio => 1,
 6316:                  );
 6317:     }
 6318:     return if (!defined($tools{$tool}));
 6319: 
 6320:     if (($udom eq '') || ($uname eq '')) {
 6321:         $udom = $env{'user.domain'};
 6322:         $uname = $env{'user.name'};
 6323:     }
 6324: 
 6325:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6326:         if ($action ne 'reload') {
 6327:             if ($context eq 'requestcourses') {
 6328:                 return $env{'environment.canrequest.'.$tool};
 6329:             } elsif ($context eq 'requestauthor') {
 6330:                 return $env{'environment.canrequest.author'};
 6331:             } else {
 6332:                 return $env{'environment.availabletools.'.$tool};
 6333:             }
 6334:         }
 6335:     }
 6336: 
 6337:     my ($toolstatus,$inststatus,$envkey);
 6338:     if ($context eq 'requestauthor') {
 6339:         $envkey = $context; 
 6340:     } else {
 6341:         $envkey = $context.'.'.$tool;
 6342:     }
 6343: 
 6344:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 6345:          ($action ne 'reload')) {
 6346:         $toolstatus = $env{'environment.'.$envkey};
 6347:         $inststatus = $env{'environment.inststatus'};
 6348:     } else {
 6349:         if (ref($userenvref) eq 'HASH') {
 6350:             $toolstatus = $userenvref->{$envkey};
 6351:             $inststatus = $userenvref->{'inststatus'};
 6352:         } else {
 6353:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 6354:             $toolstatus = $userenv{$envkey};
 6355:             $inststatus = $userenv{'inststatus'};
 6356:         }
 6357:     }
 6358: 
 6359:     if ($toolstatus ne '') {
 6360:         if ($toolstatus) {
 6361:             $access = 1;
 6362:         } else {
 6363:             $access = 0;
 6364:         }
 6365:         return $access;
 6366:     }
 6367: 
 6368:     my ($is_adv,%domdef);
 6369:     if (ref($is_advref) eq 'HASH') {
 6370:         $is_adv = $is_advref->{'is_adv'};
 6371:     } else {
 6372:         $is_adv = &is_advanced_user($udom,$uname);
 6373:     }
 6374:     if (ref($domdefref) eq 'HASH') {
 6375:         %domdef = %{$domdefref};
 6376:     } else {
 6377:         %domdef = &get_domain_defaults($udom);
 6378:     }
 6379:     if (ref($domdef{$tool}) eq 'HASH') {
 6380:         if ($is_adv) {
 6381:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 6382:                 if ($domdef{$tool}{'_LC_adv'}) { 
 6383:                     $access = 1;
 6384:                 } else {
 6385:                     $access = 0;
 6386:                 }
 6387:                 return $access;
 6388:             }
 6389:         }
 6390:         if ($inststatus ne '') {
 6391:             my ($hasaccess,$hasnoaccess);
 6392:             foreach my $affiliation (split(/:/,$inststatus)) {
 6393:                 if ($domdef{$tool}{$affiliation} ne '') { 
 6394:                     if ($domdef{$tool}{$affiliation}) {
 6395:                         $hasaccess = 1;
 6396:                     } else {
 6397:                         $hasnoaccess = 1;
 6398:                     }
 6399:                 }
 6400:             }
 6401:             if ($hasaccess || $hasnoaccess) {
 6402:                 if ($hasaccess) {
 6403:                     $access = 1;
 6404:                 } elsif ($hasnoaccess) {
 6405:                     $access = 0; 
 6406:                 }
 6407:                 return $access;
 6408:             }
 6409:         } else {
 6410:             if ($domdef{$tool}{'default'} ne '') {
 6411:                 if ($domdef{$tool}{'default'}) {
 6412:                     $access = 1;
 6413:                 } elsif ($domdef{$tool}{'default'} == 0) {
 6414:                     $access = 0;
 6415:                 }
 6416:                 return $access;
 6417:             }
 6418:         }
 6419:     } else {
 6420:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 6421:             $access = 1;
 6422:         } else {
 6423:             $access = 0;
 6424:         }
 6425:         return $access;
 6426:     }
 6427: }
 6428: 
 6429: sub is_course_owner {
 6430:     my ($cdom,$cnum,$udom,$uname) = @_;
 6431:     if (($udom eq '') || ($uname eq '')) {
 6432:         $udom = $env{'user.domain'};
 6433:         $uname = $env{'user.name'};
 6434:     }
 6435:     unless (($udom eq '') || ($uname eq '')) {
 6436:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 6437:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 6438:                 return 1;
 6439:             } else {
 6440:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 6441:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 6442:                     return 1;
 6443:                 }
 6444:             }
 6445:         }
 6446:     }
 6447:     return;
 6448: }
 6449: 
 6450: sub is_advanced_user {
 6451:     my ($udom,$uname) = @_;
 6452:     if ($udom ne '' && $uname ne '') {
 6453:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6454:             if (wantarray) {
 6455:                 return ($env{'user.adv'},$env{'user.author'});
 6456:             } else {
 6457:                 return $env{'user.adv'};
 6458:             }
 6459:         }
 6460:     }
 6461:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 6462:     my %allroles;
 6463:     my ($is_adv,$is_author);
 6464:     foreach my $role (keys(%roleshash)) {
 6465:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 6466:         my $area = '/'.$tdomain.'/'.$trest;
 6467:         if ($sec ne '') {
 6468:             $area .= '/'.$sec;
 6469:         }
 6470:         if (($area ne '') && ($trole ne '')) {
 6471:             my $spec=$trole.'.'.$area;
 6472:             if ($trole =~ /^cr\//) {
 6473:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6474:             } elsif ($trole ne 'gr') {
 6475:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6476:             }
 6477:             if ($trole eq 'au') {
 6478:                 $is_author = 1;
 6479:             }
 6480:         }
 6481:     }
 6482:     foreach my $role (keys(%allroles)) {
 6483:         last if ($is_adv);
 6484:         foreach my $item (split(/:/,$allroles{$role})) {
 6485:             if ($item ne '') {
 6486:                 my ($privilege,$restrictions)=split(/&/,$item);
 6487:                 if ($privilege eq 'adv') {
 6488:                     $is_adv = 1;
 6489:                     last;
 6490:                 }
 6491:             }
 6492:         }
 6493:     }
 6494:     if (wantarray) {
 6495:         return ($is_adv,$is_author);
 6496:     }
 6497:     return $is_adv;
 6498: }
 6499: 
 6500: sub check_can_request {
 6501:     my ($dom,$can_request,$request_domains) = @_;
 6502:     my $canreq = 0;
 6503:     my ($types,$typename) = &Apache::loncommon::course_types();
 6504:     my @options = ('approval','validate','autolimit');
 6505:     my $optregex = join('|',@options);
 6506:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 6507:         foreach my $type (@{$types}) {
 6508:             if (&usertools_access($env{'user.name'},
 6509:                                   $env{'user.domain'},
 6510:                                   $type,undef,'requestcourses')) {
 6511:                 $canreq ++;
 6512:                 if (ref($request_domains) eq 'HASH') {
 6513:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 6514:                 }
 6515:                 if ($dom eq $env{'user.domain'}) {
 6516:                     $can_request->{$type} = 1;
 6517:                 }
 6518:             }
 6519:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 6520:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 6521:                 if (@curr > 0) {
 6522:                     foreach my $item (@curr) {
 6523:                         if (ref($request_domains) eq 'HASH') {
 6524:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 6525:                             if ($otherdom ne '') {
 6526:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 6527:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 6528:                                         push(@{$request_domains->{$type}},$otherdom);
 6529:                                     }
 6530:                                 } else {
 6531:                                     push(@{$request_domains->{$type}},$otherdom);
 6532:                                 }
 6533:                             }
 6534:                         }
 6535:                     }
 6536:                     unless($dom eq $env{'user.domain'}) {
 6537:                         $canreq ++;
 6538:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 6539:                             $can_request->{$type} = 1;
 6540:                         }
 6541:                     }
 6542:                 }
 6543:             }
 6544:         }
 6545:     }
 6546:     return $canreq;
 6547: }
 6548: 
 6549: # ---------------------------------------------- Custom access rule evaluation
 6550: 
 6551: sub customaccess {
 6552:     my ($priv,$uri)=@_;
 6553:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 6554:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 6555:     $udom = &LONCAPA::clean_domain($udom);
 6556:     $ucrs = &LONCAPA::clean_username($ucrs);
 6557:     my $access=0;
 6558:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 6559: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 6560: 	if ($type eq 'user') {
 6561: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 6562: 		my ($tdom,$tuname)=split(m{/},$scope);
 6563: 		if ($tdom) {
 6564: 		    if ($tdom ne $env{'user.domain'}) { next; }
 6565: 		}
 6566: 		if ($tuname) {
 6567: 		    if ($tuname ne $env{'user.name'}) { next; }
 6568: 		}
 6569: 		$access=($effect eq 'allow');
 6570: 		last;
 6571: 	    }
 6572: 	} else {
 6573: 	    if ($role) {
 6574: 		if ($role ne $urole) { next; }
 6575: 	    }
 6576: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 6577: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 6578: 		if ($tdom) {
 6579: 		    if ($tdom ne $udom) { next; }
 6580: 		}
 6581: 		if ($tcrs) {
 6582: 		    if ($tcrs ne $ucrs) { next; }
 6583: 		}
 6584: 		if ($tsec) {
 6585: 		    if ($tsec ne $usec) { next; }
 6586: 		}
 6587: 		$access=($effect eq 'allow');
 6588: 		last;
 6589: 	    }
 6590: 	    if ($realm eq '' && $role eq '') {
 6591: 		$access=($effect eq 'allow');
 6592: 	    }
 6593: 	}
 6594:     }
 6595:     return $access;
 6596: }
 6597: 
 6598: # ------------------------------------------------- Check for a user privilege
 6599: 
 6600: sub allowed {
 6601:     my ($priv,$uri,$symb,$role)=@_;
 6602:     my $ver_orguri=$uri;
 6603:     $uri=&deversion($uri);
 6604:     my $orguri=$uri;
 6605:     $uri=&declutter($uri);
 6606: 
 6607:     if ($priv eq 'evb') {
 6608: # Evade communication block restrictions for specified role in a course
 6609:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 6610:             return $1;
 6611:         } else {
 6612:             return;
 6613:         }
 6614:     }
 6615: 
 6616:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 6617: # Free bre access to adm and meta resources
 6618:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 6619: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 6620: 	&& ($priv eq 'bre')) {
 6621: 	return 'F';
 6622:     }
 6623: 
 6624: # Free bre access to user's own portfolio contents
 6625:     my ($space,$domain,$name,@dir)=split('/',$uri);
 6626:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 6627: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 6628:         my %setters;
 6629:         my ($startblock,$endblock) = 
 6630:             &Apache::loncommon::blockcheck(\%setters,'port');
 6631:         if ($startblock && $endblock) {
 6632:             return 'B';
 6633:         } else {
 6634:             return 'F';
 6635:         }
 6636:     }
 6637: 
 6638: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 6639:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 6640:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 6641:         if (exists($env{'request.course.id'})) {
 6642:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6643:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6644:             if (($domain eq $cdom) && ($name eq $cnum)) {
 6645:                 my $courseprivid=$env{'request.course.id'};
 6646:                 $courseprivid=~s/\_/\//;
 6647:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 6648:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 6649:                     return $1; 
 6650:                 } else {
 6651:                     if ($env{'request.course.sec'}) {
 6652:                         $courseprivid.='/'.$env{'request.course.sec'};
 6653:                     }
 6654:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 6655:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 6656:                         return $2;
 6657:                     }
 6658:                 }
 6659:             }
 6660:         }
 6661:     }
 6662: 
 6663: # Free bre to public access
 6664: 
 6665:     if ($priv eq 'bre') {
 6666:         my $copyright=&metadata($uri,'copyright');
 6667: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 6668:            return 'F'; 
 6669:         }
 6670:         if ($copyright eq 'priv') {
 6671:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6672: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 6673: 		return '';
 6674:             }
 6675:         }
 6676:         if ($copyright eq 'domain') {
 6677:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6678: 	    unless (($env{'user.domain'} eq $1) ||
 6679:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 6680: 		return '';
 6681:             }
 6682:         }
 6683:         if ($env{'request.role'}=~ /li\.\//) {
 6684:             # Library role, so allow browsing of resources in this domain.
 6685:             return 'F';
 6686:         }
 6687:         if ($copyright eq 'custom') {
 6688: 	    unless (&customaccess($priv,$uri)) { return ''; }
 6689:         }
 6690:     }
 6691:     # Domain coordinator is trying to create a course
 6692:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 6693:         # uri is the requested domain in this case.
 6694:         # comparison to 'request.role.domain' shows if the user has selected
 6695:         # a role of dc for the domain in question.
 6696:         return 'F' if ($uri eq $env{'request.role.domain'});
 6697:     }
 6698: 
 6699:     my $thisallowed='';
 6700:     my $statecond=0;
 6701:     my $courseprivid='';
 6702: 
 6703:     my $ownaccess;
 6704:     # Community Coordinator or Assistant Co-author browsing resource space.
 6705:     if (($priv eq 'bro') && ($env{'user.author'})) {
 6706:         if ($uri eq '') {
 6707:             $ownaccess = 1;
 6708:         } else {
 6709:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 6710:                 my $udom = $env{'user.domain'};
 6711:                 my $uname = $env{'user.name'};
 6712:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 6713:                     $ownaccess = 1;
 6714:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 6715:                     unless ($uri =~ m{\.\./}) {
 6716:                         $ownaccess = 1;
 6717:                     }
 6718:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 6719:                     my $now = time;
 6720:                     if ($uri =~ m{^([^/]+)/?$}) {
 6721:                         my $adom = $1;
 6722:                         foreach my $key (keys(%env)) {
 6723:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 6724:                                 my ($start,$end) = split('.',$env{$key});
 6725:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6726:                                     $ownaccess = 1;
 6727:                                     last;
 6728:                                 }
 6729:                             }
 6730:                         }
 6731:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 6732:                         my $adom = $1;
 6733:                         my $aname = $2;
 6734:                         foreach my $role ('ca','aa') { 
 6735:                             if ($env{"user.role.$role./$adom/$aname"}) {
 6736:                                 my ($start,$end) =
 6737:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 6738:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6739:                                     $ownaccess = 1;
 6740:                                     last;
 6741:                                 }
 6742:                             }
 6743:                         }
 6744:                     }
 6745:                 }
 6746:             }
 6747:         }
 6748:     }
 6749: 
 6750: # Course
 6751: 
 6752:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 6753:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6754:             $thisallowed.=$1;
 6755:         }
 6756:     }
 6757: 
 6758: # Domain
 6759: 
 6760:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 6761:        =~/\Q$priv\E\&([^\:]*)/) {
 6762:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6763:             $thisallowed.=$1;
 6764:         }
 6765:     }
 6766: 
 6767: # User who is not author or co-author might still be able to edit
 6768: # resource of an author in the domain (e.g., if Domain Coordinator).
 6769:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 6770:         (&allowed('mdc',$env{'request.course.id'}))) {
 6771:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 6772:             $thisallowed.=$1;
 6773:         }
 6774:     }
 6775: 
 6776: # Course: uri itself is a course
 6777:     my $courseuri=$uri;
 6778:     $courseuri=~s/\_(\d)/\/$1/;
 6779:     $courseuri=~s/^([^\/])/\/$1/;
 6780: 
 6781:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 6782:        =~/\Q$priv\E\&([^\:]*)/) {
 6783:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6784:             $thisallowed.=$1;
 6785:         }
 6786:     }
 6787: 
 6788: # URI is an uploaded document for this course, default permissions don't matter
 6789: # not allowing 'edit' access (editupload) to uploaded course docs
 6790:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 6791: 	$thisallowed='';
 6792:         my ($match)=&is_on_map($uri);
 6793:         if ($match) {
 6794:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 6795:                   =~/\Q$priv\E\&([^\:]*)/) {
 6796:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6797:                 if (@blockers > 0) {
 6798:                     $thisallowed = 'B';
 6799:                 } else {
 6800:                     $thisallowed.=$1;
 6801:                 }
 6802:             }
 6803:         } else {
 6804:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 6805:             if ($refuri) {
 6806:                 if ($refuri =~ m|^/adm/|) {
 6807:                     $thisallowed='F';
 6808:                 } else {
 6809:                     $refuri=&declutter($refuri);
 6810:                     my ($match) = &is_on_map($refuri);
 6811:                     if ($match) {
 6812:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6813:                         if (@blockers > 0) {
 6814:                             $thisallowed = 'B';
 6815:                         } else {
 6816:                             $thisallowed='F';
 6817:                         }
 6818:                     }
 6819:                 }
 6820:             }
 6821:         }
 6822:     }
 6823: 
 6824:     if ($priv eq 'bre'
 6825: 	&& $thisallowed ne 'F' 
 6826: 	&& $thisallowed ne '2'
 6827: 	&& &is_portfolio_url($uri)) {
 6828: 	$thisallowed = &portfolio_access($uri);
 6829:     }
 6830: 
 6831: # Full access at system, domain or course-wide level? Exit.
 6832:     if ($thisallowed=~/F/) {
 6833: 	return 'F';
 6834:     }
 6835: 
 6836: # If this is generating or modifying users, exit with special codes
 6837: 
 6838:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 6839: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 6840: 	    my ($audom,$auname)=split('/',$uri);
 6841: # no author name given, so this just checks on the general right to make a co-author in this domain
 6842: 	    unless ($auname) { return $thisallowed; }
 6843: # an author name is given, so we are about to actually make a co-author for a certain account
 6844: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 6845: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 6846: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 6847: 	}
 6848: 	return $thisallowed;
 6849:     }
 6850: #
 6851: # Gathered so far: system, domain and course wide privileges
 6852: #
 6853: # Course: See if uri or referer is an individual resource that is part of 
 6854: # the course
 6855: 
 6856:     if ($env{'request.course.id'}) {
 6857: 
 6858:        $courseprivid=$env{'request.course.id'};
 6859:        if ($env{'request.course.sec'}) {
 6860:           $courseprivid.='/'.$env{'request.course.sec'};
 6861:        }
 6862:        $courseprivid=~s/\_/\//;
 6863:        my $checkreferer=1;
 6864:        my ($match,$cond)=&is_on_map($uri);
 6865:        if ($match) {
 6866:            $statecond=$cond;
 6867:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6868:                =~/\Q$priv\E\&([^\:]*)/) {
 6869:                my $value = $1;
 6870:                if ($priv eq 'bre') {
 6871:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6872:                    if (@blockers > 0) {
 6873:                        $thisallowed = 'B';
 6874:                    } else {
 6875:                        $thisallowed.=$value;
 6876:                    }
 6877:                } else {
 6878:                    $thisallowed.=$value;
 6879:                }
 6880:                $checkreferer=0;
 6881:            }
 6882:        }
 6883:        
 6884:        if ($checkreferer) {
 6885: 	  my $refuri=$env{'httpref.'.$orguri};
 6886:             unless ($refuri) {
 6887:                 foreach my $key (keys(%env)) {
 6888: 		    if ($key=~/^httpref\..*\*/) {
 6889: 			my $pattern=$key;
 6890:                         $pattern=~s/^httpref\.\/res\///;
 6891:                         $pattern=~s/\*/\[\^\/\]\+/g;
 6892:                         $pattern=~s/\//\\\//g;
 6893:                         if ($orguri=~/$pattern/) {
 6894: 			    $refuri=$env{$key};
 6895:                         }
 6896:                     }
 6897:                 }
 6898:             }
 6899: 
 6900:          if ($refuri) { 
 6901: 	  $refuri=&declutter($refuri);
 6902:           my ($match,$cond)=&is_on_map($refuri);
 6903:             if ($match) {
 6904:               my $refstatecond=$cond;
 6905:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6906:                   =~/\Q$priv\E\&([^\:]*)/) {
 6907:                   my $value = $1;
 6908:                   if ($priv eq 'bre') {
 6909:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6910:                       if (@blockers > 0) {
 6911:                           $thisallowed = 'B';
 6912:                       } else {
 6913:                           $thisallowed.=$value;
 6914:                       }
 6915:                   } else {
 6916:                       $thisallowed.=$value;
 6917:                   }
 6918:                   $uri=$refuri;
 6919:                   $statecond=$refstatecond;
 6920:               }
 6921:           }
 6922:         }
 6923:        }
 6924:    }
 6925: 
 6926: #
 6927: # Gathered now: all privileges that could apply, and condition number
 6928: # 
 6929: #
 6930: # Full or no access?
 6931: #
 6932: 
 6933:     if ($thisallowed=~/F/) {
 6934: 	return 'F';
 6935:     }
 6936: 
 6937:     unless ($thisallowed) {
 6938:         return '';
 6939:     }
 6940: 
 6941: # Restrictions exist, deal with them
 6942: #
 6943: #   C:according to course preferences
 6944: #   R:according to resource settings
 6945: #   L:unless locked
 6946: #   X:according to user session state
 6947: #
 6948: 
 6949: # Possibly locked functionality, check all courses
 6950: # Locks might take effect only after 10 minutes cache expiration for other
 6951: # courses, and 2 minutes for current course
 6952: 
 6953:     my $envkey;
 6954:     if ($thisallowed=~/L/) {
 6955:         foreach $envkey (keys(%env)) {
 6956:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 6957:                my $courseid=$2;
 6958:                my $roleid=$1.'.'.$2;
 6959:                $courseid=~s/^\///;
 6960:                my $expiretime=600;
 6961:                if ($env{'request.role'} eq $roleid) {
 6962: 		  $expiretime=120;
 6963:                }
 6964: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 6965:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 6966:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 6967: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 6968:                }
 6969:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6970:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 6971: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 6972:                        &log($env{'user.domain'},$env{'user.name'},
 6973:                             $env{'user.home'},
 6974:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 6975:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6976:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6977: 		       return '';
 6978:                    }
 6979:                }
 6980:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6981:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 6982: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 6983:                        &log($env{'user.domain'},$env{'user.name'},
 6984:                             $env{'user.home'},
 6985:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 6986:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6987:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6988: 		       return '';
 6989:                    }
 6990:                }
 6991: 	   }
 6992:        }
 6993:     }
 6994:    
 6995: #
 6996: # Rest of the restrictions depend on selected course
 6997: #
 6998: 
 6999:     unless ($env{'request.course.id'}) {
 7000: 	if ($thisallowed eq 'A') {
 7001: 	    return 'A';
 7002:         } elsif ($thisallowed eq 'B') {
 7003:             return 'B';
 7004: 	} else {
 7005: 	    return '1';
 7006: 	}
 7007:     }
 7008: 
 7009: #
 7010: # Now user is definitely in a course
 7011: #
 7012: 
 7013: 
 7014: # Course preferences
 7015: 
 7016:    if ($thisallowed=~/C/) {
 7017:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 7018:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 7019:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 7020: 	   =~/\Q$rolecode\E/) {
 7021: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 7022: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 7023: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 7024: 			$env{'request.course.id'});
 7025: 	   }
 7026:            return '';
 7027:        }
 7028: 
 7029:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 7030: 	   =~/\Q$unamedom\E/) {
 7031: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 7032: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 7033: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 7034: 			$env{'request.course.id'});
 7035: 	   }
 7036:            return '';
 7037:        }
 7038:    }
 7039: 
 7040: # Resource preferences
 7041: 
 7042:    if ($thisallowed=~/R/) {
 7043:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 7044:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 7045: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 7046: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 7047: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 7048: 	   }
 7049: 	   return '';
 7050:        }
 7051:    }
 7052: 
 7053: # Restricted by state or randomout?
 7054: 
 7055:    if ($thisallowed=~/X/) {
 7056:       if ($env{'acc.randomout'}) {
 7057: 	 if (!$symb) { $symb=&symbread($uri,1); }
 7058:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 7059:             return ''; 
 7060:          }
 7061:       }
 7062:       if (&condval($statecond)) {
 7063: 	 return '2';
 7064:       } else {
 7065:          return '';
 7066:       }
 7067:    }
 7068: 
 7069:     if ($thisallowed eq 'A') {
 7070: 	return 'A';
 7071:     } elsif ($thisallowed eq 'B') {
 7072:         return 'B';
 7073:     }
 7074:    return 'F';
 7075: }
 7076: 
 7077: # ------------------------------------------- Check construction space access
 7078: 
 7079: sub constructaccess {
 7080:     my ($url,$setpriv)=@_;
 7081: 
 7082: # We do not allow editing of previous versions of files
 7083:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 7084: 
 7085: # Get username and domain from URL
 7086:     my ($ownername,$ownerdomain,$ownerhome);
 7087: 
 7088:     ($ownerdomain,$ownername) =
 7089:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
 7090: 
 7091: # The URL does not really point to any authorspace, forget it
 7092:     unless (($ownername) && ($ownerdomain)) { return ''; }
 7093: 
 7094: # Now we need to see if the user has access to the authorspace of
 7095: # $ownername at $ownerdomain
 7096: 
 7097:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 7098: # Real author for this?
 7099:        $ownerhome = $env{'user.home'};
 7100:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 7101:           return ($ownername,$ownerdomain,$ownerhome);
 7102:        }
 7103:     } else {
 7104: # Co-author for this?
 7105:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 7106:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 7107:             $ownerhome = &homeserver($ownername,$ownerdomain);
 7108:             return ($ownername,$ownerdomain,$ownerhome);
 7109:         }
 7110:     }
 7111: 
 7112: # We don't have any access right now. If we are not possibly going to do anything about this,
 7113: # we might as well leave
 7114:    unless ($setpriv) { return ''; }
 7115: 
 7116: # Backdoor access?
 7117:     my $allowed=&allowed('eco',$ownerdomain);
 7118: # Nope
 7119:     unless ($allowed) { return ''; }
 7120: # Looks like we may have access, but could be locked by the owner of the construction space
 7121:     if ($allowed eq 'U') {
 7122:         my %blocked=&get('environment',['domcoord.author'],
 7123:                          $ownerdomain,$ownername);
 7124: # Is blocked by owner
 7125:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 7126:     }
 7127:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 7128: # Grant temporary access
 7129:         my $then=$env{'user.login.time'};
 7130:         my $update=$env{'user.update.time'};
 7131:         if (!$update) { $update = $then; }
 7132:         my $refresh=$env{'user.refresh.time'};
 7133:         if (!$refresh) { $refresh = $update; }
 7134:         my $now = time;
 7135:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 7136:                            $now,'ca','constructaccess');
 7137:         $ownerhome = &homeserver($ownername,$ownerdomain);
 7138:         return($ownername,$ownerdomain,$ownerhome);
 7139:     }
 7140: # No business here
 7141:     return '';
 7142: }
 7143: 
 7144: sub get_comm_blocks {
 7145:     my ($cdom,$cnum) = @_;
 7146:     if ($cdom eq '' || $cnum eq '') {
 7147:         return unless ($env{'request.course.id'});
 7148:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7149:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7150:     }
 7151:     my %commblocks;
 7152:     my $hashid=$cdom.'_'.$cnum;
 7153:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 7154:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 7155:         %commblocks = %{$blocksref};
 7156:     } else {
 7157:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 7158:         my $cachetime = 600;
 7159:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 7160:     }
 7161:     return %commblocks;
 7162: }
 7163: 
 7164: sub has_comm_blocking {
 7165:     my ($priv,$symb,$uri,$blocks) = @_;
 7166:     return unless ($env{'request.course.id'});
 7167:     return unless ($priv eq 'bre');
 7168:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 7169:     my %commblocks;
 7170:     if (ref($blocks) eq 'HASH') {
 7171:         %commblocks = %{$blocks};
 7172:     } else {
 7173:         %commblocks = &get_comm_blocks();
 7174:     }
 7175:     return unless (keys(%commblocks) > 0);
 7176:     if (!$symb) { $symb=&symbread($uri,1); }
 7177:     my ($map,$resid,undef)=&decode_symb($symb);
 7178:     my %tocheck = (
 7179:                     maps      => $map,
 7180:                     resources => $symb,
 7181:                   );
 7182:     my @blockers;
 7183:     my $now = time;
 7184:     my $navmap = Apache::lonnavmaps::navmap->new();
 7185:     foreach my $block (keys(%commblocks)) {
 7186:         if ($block =~ /^(\d+)____(\d+)$/) {
 7187:             my ($start,$end) = ($1,$2);
 7188:             if ($start <= $now && $end >= $now) {
 7189:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 7190:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 7191:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 7192:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
 7193:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 7194:                                     push(@blockers,$block);
 7195:                                 }
 7196:                             }
 7197:                         }
 7198:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 7199:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
 7200:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
 7201:                                     push(@blockers,$block);
 7202:                                 }
 7203:                             }
 7204:                         }
 7205:                     }
 7206:                 }
 7207:             }
 7208:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 7209:             my $item = $1;
 7210:             my @to_test;
 7211:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 7212:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 7213:                     my $check_interval;
 7214:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
 7215:                         my @interval;
 7216:                         my $type = 'map';
 7217:                         if ($item eq 'course') {
 7218:                             $type = 'course';
 7219:                             @interval=&EXT("resource.0.interval");
 7220:                         } else {
 7221:                             if ($item =~ /___\d+___/) {
 7222:                                 $type = 'resource';
 7223:                                 @interval=&EXT("resource.0.interval",$item);
 7224:                                 if (ref($navmap)) {                        
 7225:                                     my $res = $navmap->getBySymb($item); 
 7226:                                     push(@to_test,$res);
 7227:                                 }
 7228:                             } else {
 7229:                                 my $mapsymb = &symbread($item,1);
 7230:                                 if ($mapsymb) {
 7231:                                     if (ref($navmap)) {
 7232:                                         my $mapres = $navmap->getBySymb($mapsymb);
 7233:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
 7234:                                         foreach my $res (@to_test) {
 7235:                                             my $symb = $res->symb();
 7236:                                             next if ($symb eq $mapsymb);
 7237:                                             if ($symb ne '') {
 7238:                                                 @interval=&EXT("resource.0.interval",$symb);
 7239:                                                 last;
 7240:                                             }
 7241:                                         }
 7242:                                     }
 7243:                                 }
 7244:                             }
 7245:                         }
 7246:                         if ($interval[0] =~ /\d+/) {
 7247:                             my $first_access;
 7248:                             if ($type eq 'resource') {
 7249:                                 $first_access=&get_first_access($interval[1],$item);
 7250:                             } elsif ($type eq 'map') {
 7251:                                 $first_access=&get_first_access($interval[1],undef,$item);
 7252:                             } else {
 7253:                                 $first_access=&get_first_access($interval[1]);
 7254:                             }
 7255:                             if ($first_access) {
 7256:                                 my $timesup = $first_access+$interval[0];
 7257:                                 if ($timesup > $now) {
 7258:                                     foreach my $res (@to_test) {
 7259:                                         if ($res->is_problem()) {
 7260:                                             if ($res->completable()) {
 7261:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 7262:                                                     push(@blockers,$block);
 7263:                                                 }
 7264:                                                 last;
 7265:                                             }
 7266:                                         }
 7267:                                     }
 7268:                                 }
 7269:                             }
 7270:                         }
 7271:                     }
 7272:                 }
 7273:             }
 7274:         }
 7275:     }
 7276:     return @blockers;
 7277: }
 7278: 
 7279: sub check_docs_block {
 7280:     my ($docsblock,$tocheck) =@_;
 7281:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
 7282:         return;
 7283:     }
 7284:     if (ref($docsblock->{'maps'}) eq 'HASH') {
 7285:         if ($tocheck->{'maps'}) {
 7286:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
 7287:                 return 1;
 7288:             }
 7289:         }
 7290:     }
 7291:     if (ref($docsblock->{'resources'}) eq 'HASH') {
 7292:         if ($tocheck->{'resources'}) {
 7293:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
 7294:                 return 1;
 7295:             }
 7296:         }
 7297:     }
 7298:     return;
 7299: }
 7300: 
 7301: #
 7302: #   Removes the versino from a URI and
 7303: #   splits it in to its filename and path to the filename.
 7304: #   Seems like File::Basename could have done this more clearly.
 7305: #   Parameters:
 7306: #      $uri   - input URI
 7307: #   Returns:
 7308: #     Two element list consisting of 
 7309: #     $pathname  - the URI up to and excluding the trailing /
 7310: #     $filename  - The part of the URI following the last /
 7311: #  NOTE:
 7312: #    Another realization of this is simply:
 7313: #    use File::Basename;
 7314: #    ...
 7315: #    $uri = shift;
 7316: #    $filename = basename($uri);
 7317: #    $path     = dirname($uri);
 7318: #    return ($filename, $path);
 7319: #
 7320: #     The implementation below is probably faster however.
 7321: #
 7322: sub split_uri_for_cond {
 7323:     my $uri=&deversion(&declutter(shift));
 7324:     my @uriparts=split(/\//,$uri);
 7325:     my $filename=pop(@uriparts);
 7326:     my $pathname=join('/',@uriparts);
 7327:     return ($pathname,$filename);
 7328: }
 7329: # --------------------------------------------------- Is a resource on the map?
 7330: 
 7331: sub is_on_map {
 7332:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 7333:     #Trying to find the conditional for the file
 7334:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 7335: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 7336:     if ($match) {
 7337: 	return (1,$1);
 7338:     } else {
 7339: 	return (0,0);
 7340:     }
 7341: }
 7342: 
 7343: # --------------------------------------------------------- Get symb from alias
 7344: 
 7345: sub get_symb_from_alias {
 7346:     my $symb=shift;
 7347:     my ($map,$resid,$url)=&decode_symb($symb);
 7348: # Already is a symb
 7349:     if ($url) { return $symb; }
 7350: # Must be an alias
 7351:     my $aliassymb='';
 7352:     my %bighash;
 7353:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7354:                             &GDBM_READER(),0640)) {
 7355:         my $rid=$bighash{'mapalias_'.$symb};
 7356: 	if ($rid) {
 7357: 	    my ($mapid,$resid)=split(/\./,$rid);
 7358: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 7359: 				    $resid,$bighash{'src_'.$rid});
 7360: 	}
 7361:         untie %bighash;
 7362:     }
 7363:     return $aliassymb;
 7364: }
 7365: 
 7366: # ----------------------------------------------------------------- Define Role
 7367: 
 7368: sub definerole {
 7369:   if (allowed('mcr','/')) {
 7370:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 7371:     foreach my $role (split(':',$sysrole)) {
 7372: 	my ($crole,$cqual)=split(/\&/,$role);
 7373:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 7374:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 7375: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 7376:                return "refused:s:$crole&$cqual"; 
 7377:             }
 7378:         }
 7379:     }
 7380:     foreach my $role (split(':',$domrole)) {
 7381: 	my ($crole,$cqual)=split(/\&/,$role);
 7382:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 7383:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 7384: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 7385:                return "refused:d:$crole&$cqual"; 
 7386:             }
 7387:         }
 7388:     }
 7389:     foreach my $role (split(':',$courole)) {
 7390: 	my ($crole,$cqual)=split(/\&/,$role);
 7391:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 7392:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 7393: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 7394:                return "refused:c:$crole&$cqual"; 
 7395:             }
 7396:         }
 7397:     }
 7398:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 7399:                 "$env{'user.domain'}:$env{'user.name'}:".
 7400: 	        "rolesdef_$rolename=".
 7401:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 7402:     return reply($command,$env{'user.home'});
 7403:   } else {
 7404:     return 'refused';
 7405:   }
 7406: }
 7407: 
 7408: # ---------------- Make a metadata query against the network of library servers
 7409: 
 7410: sub metadata_query {
 7411:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 7412:     my %rhash;
 7413:     my %libserv = &all_library();
 7414:     my @server_list = (defined($server_array) ? @$server_array
 7415:                                               : keys(%libserv) );
 7416:     for my $server (@server_list) {
 7417:         my $domains = ''; 
 7418:         if (ref($domains_hash) eq 'HASH') {
 7419:             $domains = $domains_hash->{$server}; 
 7420:         }
 7421: 	unless ($custom or $customshow) {
 7422: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 7423: 	    $rhash{$server}=$reply;
 7424: 	}
 7425: 	else {
 7426: 	    my $reply=&reply("querysend:".&escape($query).':'.
 7427: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 7428: 			     $server);
 7429: 	    $rhash{$server}=$reply;
 7430: 	}
 7431:     }
 7432:     return \%rhash;
 7433: }
 7434: 
 7435: # ----------------------------------------- Send log queries and wait for reply
 7436: 
 7437: sub log_query {
 7438:     my ($uname,$udom,$query,%filters)=@_;
 7439:     my $uhome=&homeserver($uname,$udom);
 7440:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 7441:     my $uhost=&hostname($uhome);
 7442:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 7443:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 7444:                        $uhome);
 7445:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 7446:     return get_query_reply($queryid);
 7447: }
 7448: 
 7449: # -------------------------- Update MySQL table for portfolio file
 7450: 
 7451: sub update_portfolio_table {
 7452:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 7453:     if ($group ne '') {
 7454:         $file_name =~s /^\Q$group\E//;
 7455:     }
 7456:     my $homeserver = &homeserver($uname,$udom);
 7457:     my $queryid=
 7458:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 7459:                ':'.&escape($file_name).':'.$action,$homeserver);
 7460:     my $reply = &get_query_reply($queryid);
 7461:     return $reply;
 7462: }
 7463: 
 7464: # -------------------------- Update MySQL allusers table
 7465: 
 7466: sub update_allusers_table {
 7467:     my ($uname,$udom,$names) = @_;
 7468:     my $homeserver = &homeserver($uname,$udom);
 7469:     my $queryid=
 7470:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 7471:                'lastname='.&escape($names->{'lastname'}).'%%'.
 7472:                'firstname='.&escape($names->{'firstname'}).'%%'.
 7473:                'middlename='.&escape($names->{'middlename'}).'%%'.
 7474:                'generation='.&escape($names->{'generation'}).'%%'.
 7475:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 7476:                'id='.&escape($names->{'id'}),$homeserver);
 7477:     return;
 7478: }
 7479: 
 7480: # ------- Request retrieval of institutional classlists for course(s)
 7481: 
 7482: sub fetch_enrollment_query {
 7483:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 7484:     my $homeserver;
 7485:     my $maxtries = 1;
 7486:     if ($context eq 'automated') {
 7487:         $homeserver = $perlvar{'lonHostID'};
 7488:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 7489:     } else {
 7490:         $homeserver = &homeserver($cnum,$dom);
 7491:     }
 7492:     my $host=&hostname($homeserver);
 7493:     my $cmd = '';
 7494:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7495:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7496:     }
 7497:     $cmd =~ s/%%$//;
 7498:     $cmd = &escape($cmd);
 7499:     my $query = 'fetchenrollment';
 7500:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 7501:     unless ($queryid=~/^\Q$host\E\_/) { 
 7502:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 7503:         return 'error: '.$queryid;
 7504:     }
 7505:     my $reply = &get_query_reply($queryid);
 7506:     my $tries = 1;
 7507:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7508:         $reply = &get_query_reply($queryid);
 7509:         $tries ++;
 7510:     }
 7511:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7512:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7513:     } else {
 7514:         my @responses = split(/:/,$reply);
 7515:         if ($homeserver eq $perlvar{'lonHostID'}) {
 7516:             foreach my $line (@responses) {
 7517:                 my ($key,$value) = split(/=/,$line,2);
 7518:                 $$replyref{$key} = $value;
 7519:             }
 7520:         } else {
 7521:             my $pathname = LONCAPA::tempdir();
 7522:             foreach my $line (@responses) {
 7523:                 my ($key,$value) = split(/=/,$line);
 7524:                 $$replyref{$key} = $value;
 7525:                 if ($value > 0) {
 7526:                     foreach my $item (@{$$affiliatesref{$key}}) {
 7527:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 7528:                         my $destname = $pathname.'/'.$filename;
 7529:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 7530:                         if ($xml_classlist =~ /^error/) {
 7531:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 7532:                         } else {
 7533:                             if ( open(FILE,">$destname") ) {
 7534:                                 print FILE &unescape($xml_classlist);
 7535:                                 close(FILE);
 7536:                             } else {
 7537:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 7538:                             }
 7539:                         }
 7540:                     }
 7541:                 }
 7542:             }
 7543:         }
 7544:         return 'ok';
 7545:     }
 7546:     return 'error';
 7547: }
 7548: 
 7549: sub get_query_reply {
 7550:     my $queryid=shift;
 7551:     my $replyfile=LONCAPA::tempdir().$queryid;
 7552:     my $reply='';
 7553:     for (1..100) {
 7554: 	sleep 2;
 7555:         if (-e $replyfile.'.end') {
 7556: 	    if (open(my $fh,$replyfile)) {
 7557: 		$reply = join('',<$fh>);
 7558: 		close($fh);
 7559: 	   } else { return 'error: reply_file_error'; }
 7560:            return &unescape($reply);
 7561: 	}
 7562:     }
 7563:     return 'timeout:'.$queryid;
 7564: }
 7565: 
 7566: sub courselog_query {
 7567: #
 7568: # possible filters:
 7569: # url: url or symb
 7570: # username
 7571: # domain
 7572: # action: view, submit, grade
 7573: # start: timestamp
 7574: # end: timestamp
 7575: #
 7576:     my (%filters)=@_;
 7577:     unless ($env{'request.course.id'}) { return 'no_course'; }
 7578:     if ($filters{'url'}) {
 7579: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 7580:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 7581:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 7582:     }
 7583:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7584:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7585:     return &log_query($cname,$cdom,'courselog',%filters);
 7586: }
 7587: 
 7588: sub userlog_query {
 7589: #
 7590: # possible filters:
 7591: # action: log check role
 7592: # start: timestamp
 7593: # end: timestamp
 7594: #
 7595:     my ($uname,$udom,%filters)=@_;
 7596:     return &log_query($uname,$udom,'userlog',%filters);
 7597: }
 7598: 
 7599: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 7600: 
 7601: sub auto_run {
 7602:     my ($cnum,$cdom) = @_;
 7603:     my $response = 0;
 7604:     my $settings;
 7605:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 7606:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 7607:         $settings = $domconfig{'autoenroll'};
 7608:         if ($settings->{'run'} eq '1') {
 7609:             $response = 1;
 7610:         }
 7611:     } else {
 7612:         my $homeserver;
 7613:         if (&is_course($cdom,$cnum)) {
 7614:             $homeserver = &homeserver($cnum,$cdom);
 7615:         } else {
 7616:             $homeserver = &domain($cdom,'primary');
 7617:         }
 7618:         if ($homeserver ne 'no_host') {
 7619:             $response = &reply('autorun:'.$cdom,$homeserver);
 7620:         }
 7621:     }
 7622:     return $response;
 7623: }
 7624: 
 7625: sub auto_get_sections {
 7626:     my ($cnum,$cdom,$inst_coursecode) = @_;
 7627:     my $homeserver;
 7628:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 7629:         $homeserver = &homeserver($cnum,$cdom);
 7630:     }
 7631:     if (!defined($homeserver)) { 
 7632:         if ($cdom =~ /^$match_domain$/) {
 7633:             $homeserver = &domain($cdom,'primary');
 7634:         }
 7635:     }
 7636:     my @secs;
 7637:     if (defined($homeserver)) {
 7638:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 7639:         unless ($response eq 'refused') {
 7640:             @secs = split(/:/,$response);
 7641:         }
 7642:     }
 7643:     return @secs;
 7644: }
 7645: 
 7646: sub auto_new_course {
 7647:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 7648:     my $homeserver = &homeserver($cnum,$cdom);
 7649:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 7650:     return $response;
 7651: }
 7652: 
 7653: sub auto_validate_courseID {
 7654:     my ($cnum,$cdom,$inst_course_id) = @_;
 7655:     my $homeserver = &homeserver($cnum,$cdom);
 7656:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 7657:     return $response;
 7658: }
 7659: 
 7660: sub auto_validate_instcode {
 7661:     my ($cnum,$cdom,$instcode,$owner) = @_;
 7662:     my ($homeserver,$response);
 7663:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7664:         $homeserver = &homeserver($cnum,$cdom);
 7665:     }
 7666:     if (!defined($homeserver)) {
 7667:         if ($cdom =~ /^$match_domain$/) {
 7668:             $homeserver = &domain($cdom,'primary');
 7669:         }
 7670:     }
 7671:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 7672:                         &escape($instcode).':'.&escape($owner),$homeserver));
 7673:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 7674:     return ($outcome,$description,$defaultcredits);
 7675: }
 7676: 
 7677: sub auto_create_password {
 7678:     my ($cnum,$cdom,$authparam,$udom) = @_;
 7679:     my ($homeserver,$response);
 7680:     my $create_passwd = 0;
 7681:     my $authchk = '';
 7682:     if ($udom =~ /^$match_domain$/) {
 7683:         $homeserver = &domain($udom,'primary');
 7684:     }
 7685:     if ($homeserver eq '') {
 7686:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7687:             $homeserver = &homeserver($cnum,$cdom);
 7688:         }
 7689:     }
 7690:     if ($homeserver eq '') {
 7691:         $authchk = 'nodomain';
 7692:     } else {
 7693:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 7694:         if ($response eq 'refused') {
 7695:             $authchk = 'refused';
 7696:         } else {
 7697:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 7698:         }
 7699:     }
 7700:     return ($authparam,$create_passwd,$authchk);
 7701: }
 7702: 
 7703: sub auto_photo_permission {
 7704:     my ($cnum,$cdom,$students) = @_;
 7705:     my $homeserver = &homeserver($cnum,$cdom);
 7706:     my ($outcome,$perm_reqd,$conditions) = 
 7707: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 7708:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7709: 	return (undef,undef);
 7710:     }
 7711:     return ($outcome,$perm_reqd,$conditions);
 7712: }
 7713: 
 7714: sub auto_checkphotos {
 7715:     my ($uname,$udom,$pid) = @_;
 7716:     my $homeserver = &homeserver($uname,$udom);
 7717:     my ($result,$resulttype);
 7718:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 7719: 				   &escape($uname).':'.&escape($pid),
 7720: 				   $homeserver));
 7721:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7722: 	return (undef,undef);
 7723:     }
 7724:     if ($outcome) {
 7725:         ($result,$resulttype) = split(/:/,$outcome);
 7726:     } 
 7727:     return ($result,$resulttype);
 7728: }
 7729: 
 7730: sub auto_photochoice {
 7731:     my ($cnum,$cdom) = @_;
 7732:     my $homeserver = &homeserver($cnum,$cdom);
 7733:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 7734: 						       &escape($cdom),
 7735: 						       $homeserver)));
 7736:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7737: 	return (undef,undef);
 7738:     }
 7739:     return ($update,$comment);
 7740: }
 7741: 
 7742: sub auto_photoupdate {
 7743:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 7744:     my $homeserver = &homeserver($cnum,$dom);
 7745:     my $host=&hostname($homeserver);
 7746:     my $cmd = '';
 7747:     my $maxtries = 1;
 7748:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7749:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7750:     }
 7751:     $cmd =~ s/%%$//;
 7752:     $cmd = &escape($cmd);
 7753:     my $query = 'institutionalphotos';
 7754:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 7755:     unless ($queryid=~/^\Q$host\E\_/) {
 7756:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 7757:         return 'error: '.$queryid;
 7758:     }
 7759:     my $reply = &get_query_reply($queryid);
 7760:     my $tries = 1;
 7761:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7762:         $reply = &get_query_reply($queryid);
 7763:         $tries ++;
 7764:     }
 7765:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7766:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7767:     } else {
 7768:         my @responses = split(/:/,$reply);
 7769:         my $outcome = shift(@responses); 
 7770:         foreach my $item (@responses) {
 7771:             my ($key,$value) = split(/=/,$item);
 7772:             $$photo{$key} = $value;
 7773:         }
 7774:         return $outcome;
 7775:     }
 7776:     return 'error';
 7777: }
 7778: 
 7779: sub auto_instcode_format {
 7780:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 7781: 	$cat_order) = @_;
 7782:     my $courses = '';
 7783:     my @homeservers;
 7784:     if ($caller eq 'global') {
 7785: 	my %servers = &get_servers($codedom,'library');
 7786: 	foreach my $tryserver (keys(%servers)) {
 7787: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7788: 		push(@homeservers,$tryserver);
 7789: 	    }
 7790:         }
 7791:     } elsif ($caller eq 'requests') {
 7792:         if ($codedom =~ /^$match_domain$/) {
 7793:             my $chome = &domain($codedom,'primary');
 7794:             unless ($chome eq 'no_host') {
 7795:                 push(@homeservers,$chome);
 7796:             }
 7797:         }
 7798:     } else {
 7799:         push(@homeservers,&homeserver($caller,$codedom));
 7800:     }
 7801:     foreach my $code (keys(%{$instcodes})) {
 7802:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 7803:     }
 7804:     chop($courses);
 7805:     my $ok_response = 0;
 7806:     my $response;
 7807:     while (@homeservers > 0 && $ok_response == 0) {
 7808:         my $server = shift(@homeservers); 
 7809:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 7810:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 7811:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 7812: 		split(/:/,$response);
 7813:             %{$codes} = (%{$codes},&str2hash($codes_str));
 7814:             push(@{$codetitles},&str2array($codetitles_str));
 7815:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 7816:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 7817:             $ok_response = 1;
 7818:         }
 7819:     }
 7820:     if ($ok_response) {
 7821:         return 'ok';
 7822:     } else {
 7823:         return $response;
 7824:     }
 7825: }
 7826: 
 7827: sub auto_instcode_defaults {
 7828:     my ($domain,$returnhash,$code_order) = @_;
 7829:     my @homeservers;
 7830: 
 7831:     my %servers = &get_servers($domain,'library');
 7832:     foreach my $tryserver (keys(%servers)) {
 7833: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7834: 	    push(@homeservers,$tryserver);
 7835: 	}
 7836:     }
 7837: 
 7838:     my $response;
 7839:     foreach my $server (@homeservers) {
 7840:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 7841:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7842: 	
 7843: 	foreach my $pair (split(/\&/,$response)) {
 7844: 	    my ($name,$value)=split(/\=/,$pair);
 7845: 	    if ($name eq 'code_order') {
 7846: 		@{$code_order} = split(/\&/,&unescape($value));
 7847: 	    } else {
 7848: 		$returnhash->{&unescape($name)}=&unescape($value);
 7849: 	    }
 7850: 	}
 7851: 	return 'ok';
 7852:     }
 7853: 
 7854:     return $response;
 7855: }
 7856: 
 7857: sub auto_possible_instcodes {
 7858:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 7859:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 7860:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 7861:         return;
 7862:     }
 7863:     my (@homeservers,$uhome);
 7864:     if (defined(&domain($domain,'primary'))) {
 7865:         $uhome=&domain($domain,'primary');
 7866:         push(@homeservers,&domain($domain,'primary'));
 7867:     } else {
 7868:         my %servers = &get_servers($domain,'library');
 7869:         foreach my $tryserver (keys(%servers)) {
 7870:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7871:                 push(@homeservers,$tryserver);
 7872:             }
 7873:         }
 7874:     }
 7875:     my $response;
 7876:     foreach my $server (@homeservers) {
 7877:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 7878:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7879:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 7880:             split(':',$response);
 7881:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 7882:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 7883:         foreach my $item (split('&',$cat_title)) {   
 7884:             my ($name,$value)=split('=',$item);
 7885:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 7886:         }
 7887:         foreach my $item (split('&',$cat_order)) {
 7888:             my ($name,$value)=split('=',$item);
 7889:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 7890:         }
 7891:         return 'ok';
 7892:     }
 7893:     return $response;
 7894: }
 7895: 
 7896: sub auto_courserequest_checks {
 7897:     my ($dom) = @_;
 7898:     my ($homeserver,%validations);
 7899:     if ($dom =~ /^$match_domain$/) {
 7900:         $homeserver = &domain($dom,'primary');
 7901:     }
 7902:     unless ($homeserver eq 'no_host') {
 7903:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 7904:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 7905:             my @items = split(/&/,$response);
 7906:             foreach my $item (@items) {
 7907:                 my ($key,$value) = split('=',$item);
 7908:                 $validations{&unescape($key)} = &thaw_unescape($value);
 7909:             }
 7910:         }
 7911:     }
 7912:     return %validations; 
 7913: }
 7914: 
 7915: sub auto_courserequest_validation {
 7916:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
 7917:     my ($homeserver,$response);
 7918:     if ($dom =~ /^$match_domain$/) {
 7919:         $homeserver = &domain($dom,'primary');
 7920:     }
 7921:     unless ($homeserver eq 'no_host') {
 7922:         my $customdata;
 7923:         if (ref($custominfo) eq 'HASH') {
 7924:             $customdata = &freeze_escape($custominfo);
 7925:         }
 7926:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 7927:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 7928:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
 7929:                                     $customdata,$homeserver));
 7930:     }
 7931:     return $response;
 7932: }
 7933: 
 7934: sub auto_validate_class_sec {
 7935:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 7936:     my $homeserver = &homeserver($cnum,$cdom);
 7937:     my $ownerlist;
 7938:     if (ref($owners) eq 'ARRAY') {
 7939:         $ownerlist = join(',',@{$owners});
 7940:     } else {
 7941:         $ownerlist = $owners;
 7942:     }
 7943:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 7944:                         &escape($ownerlist).':'.$cdom,$homeserver);
 7945:     return $response;
 7946: }
 7947: 
 7948: sub auto_crsreq_update {
 7949:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
 7950:         $code,$accessstart,$accessend,$inbound) = @_;
 7951:     my ($homeserver,%crsreqresponse);
 7952:     if ($cdom =~ /^$match_domain$/) {
 7953:         $homeserver = &domain($cdom,'primary');
 7954:     }
 7955:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 7956:         my $info;
 7957:         if (ref($inbound) eq 'HASH') {
 7958:             $info = &freeze_escape($inbound);
 7959:         }
 7960:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
 7961:                             ':'.&escape($action).':'.&escape($ownername).':'.
 7962:                             &escape($ownerdomain).':'.&escape($fullname).':'.
 7963:                             &escape($title).':'.&escape($code).':'.
 7964:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
 7965:                             $homeserver);
 7966:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 7967:             my @items = split(/&/,$response);
 7968:             foreach my $item (@items) {
 7969:                 my ($key,$value) = split('=',$item);
 7970:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
 7971:             }
 7972:         }
 7973:     }
 7974:     return \%crsreqresponse;
 7975: }
 7976: 
 7977: # ------------------------------------------------------- Course Group routines
 7978: 
 7979: sub get_coursegroups {
 7980:     my ($cdom,$cnum,$group,$namespace) = @_;
 7981:     return(&dump($namespace,$cdom,$cnum,$group));
 7982: }
 7983: 
 7984: sub modify_coursegroup {
 7985:     my ($cdom,$cnum,$groupsettings) = @_;
 7986:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 7987: }
 7988: 
 7989: sub toggle_coursegroup_status {
 7990:     my ($cdom,$cnum,$group,$action) = @_;
 7991:     my ($from_namespace,$to_namespace);
 7992:     if ($action eq 'delete') {
 7993:         $from_namespace = 'coursegroups';
 7994:         $to_namespace = 'deleted_groups';
 7995:     } else {
 7996:         $from_namespace = 'deleted_groups';
 7997:         $to_namespace = 'coursegroups';
 7998:     }
 7999:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 8000:     if (my $tmp = &error(%curr_group)) {
 8001:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 8002:         return ('read error',$tmp);
 8003:     } else {
 8004:         my %savedsettings = %curr_group; 
 8005:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 8006:         my $deloutcome;
 8007:         if ($result eq 'ok') {
 8008:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 8009:         } else {
 8010:             return ('write error',$result);
 8011:         }
 8012:         if ($deloutcome eq 'ok') {
 8013:             return 'ok';
 8014:         } else {
 8015:             return ('delete error',$deloutcome);
 8016:         }
 8017:     }
 8018: }
 8019: 
 8020: sub modify_group_roles {
 8021:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 8022:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 8023:     my $role = 'gr/'.&escape($userprivs);
 8024:     my ($uname,$udom) = split(/:/,$user);
 8025:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 8026:     if ($result eq 'ok') {
 8027:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 8028:     }
 8029:     return $result;
 8030: }
 8031: 
 8032: sub modify_coursegroup_membership {
 8033:     my ($cdom,$cnum,$membership) = @_;
 8034:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 8035:     return $result;
 8036: }
 8037: 
 8038: sub get_active_groups {
 8039:     my ($udom,$uname,$cdom,$cnum) = @_;
 8040:     my $now = time;
 8041:     my %groups = ();
 8042:     foreach my $key (keys(%env)) {
 8043:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 8044:             my ($start,$end) = split(/\./,$env{$key});
 8045:             if (($end!=0) && ($end<$now)) { next; }
 8046:             if (($start!=0) && ($start>$now)) { next; }
 8047:             if ($1 eq $cdom && $2 eq $cnum) {
 8048:                 $groups{$3} = $env{$key} ;
 8049:             }
 8050:         }
 8051:     }
 8052:     return %groups;
 8053: }
 8054: 
 8055: sub get_group_membership {
 8056:     my ($cdom,$cnum,$group) = @_;
 8057:     return(&dump('groupmembership',$cdom,$cnum,$group));
 8058: }
 8059: 
 8060: sub get_users_groups {
 8061:     my ($udom,$uname,$courseid) = @_;
 8062:     my @usersgroups;
 8063:     my $cachetime=1800;
 8064: 
 8065:     my $hashid="$udom:$uname:$courseid";
 8066:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 8067:     if (defined($cached)) {
 8068:         @usersgroups = split(/:/,$grouplist);
 8069:     } else {  
 8070:         $grouplist = '';
 8071:         my $courseurl = &courseid_to_courseurl($courseid);
 8072:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 8073:         my $access_end = $env{'course.'.$courseid.
 8074:                               '.default_enrollment_end_date'};
 8075:         my $now = time;
 8076:         foreach my $key (keys(%roleshash)) {
 8077:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 8078:                 my $group = $1;
 8079:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 8080:                     my $start = $2;
 8081:                     my $end = $1;
 8082:                     if ($start == -1) { next; } # deleted from group
 8083:                     if (($start!=0) && ($start>$now)) { next; }
 8084:                     if (($end!=0) && ($end<$now)) {
 8085:                         if ($access_end && $access_end < $now) {
 8086:                             if ($access_end - $end < 86400) {
 8087:                                 push(@usersgroups,$group);
 8088:                             }
 8089:                         }
 8090:                         next;
 8091:                     }
 8092:                     push(@usersgroups,$group);
 8093:                 }
 8094:             }
 8095:         }
 8096:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 8097:         $grouplist = join(':',@usersgroups);
 8098:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 8099:     }
 8100:     return @usersgroups;
 8101: }
 8102: 
 8103: sub devalidate_getgroups_cache {
 8104:     my ($udom,$uname,$cdom,$cnum)=@_;
 8105:     my $courseid = $cdom.'_'.$cnum;
 8106: 
 8107:     my $hashid="$udom:$uname:$courseid";
 8108:     &devalidate_cache_new('getgroups',$hashid);
 8109: }
 8110: 
 8111: # ------------------------------------------------------------------ Plain Text
 8112: 
 8113: sub plaintext {
 8114:     my ($short,$type,$cid,$forcedefault) = @_;
 8115:     if ($short =~ m{^cr/}) {
 8116: 	return (split('/',$short))[-1];
 8117:     }
 8118:     if (!defined($cid)) {
 8119:         $cid = $env{'request.course.id'};
 8120:     }
 8121:     my %rolenames = (
 8122:                       Course    => 'std',
 8123:                       Community => 'alt1',
 8124:                     );
 8125:     if ($cid ne '') {
 8126:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 8127:             unless ($forcedefault) {
 8128:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 8129:                 &Apache::lonlocal::mt_escape(\$roletext);
 8130:                 return &Apache::lonlocal::mt($roletext);
 8131:             }
 8132:         }
 8133:     }
 8134:     if ((defined($type)) && (defined($rolenames{$type})) &&
 8135:         (defined($rolenames{$type})) && 
 8136:         (defined($prp{$short}{$rolenames{$type}}))) {
 8137:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 8138:     } elsif ($cid ne '') {
 8139:         my $crstype = $env{'course.'.$cid.'.type'};
 8140:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 8141:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 8142:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 8143:         }
 8144:     }
 8145:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 8146: }
 8147: 
 8148: # ----------------------------------------------------------------- Assign Role
 8149: 
 8150: sub assignrole {
 8151:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 8152:         $context)=@_;
 8153:     my $mrole;
 8154:     if ($role =~ /^cr\//) {
 8155:         my $cwosec=$url;
 8156:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 8157: 	unless (&allowed('ccr',$cwosec)) {
 8158:            my $refused = 1;
 8159:            if ($context eq 'requestcourses') {
 8160:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 8161:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 8162:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 8163:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 8164:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8165:                            if ($crsenv{'internal.courseowner'} eq
 8166:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 8167:                                $refused = '';
 8168:                            }
 8169:                        }
 8170:                    }
 8171:                }
 8172:            }
 8173:            if ($refused) {
 8174:                &logthis('Refused custom assignrole: '.
 8175:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 8176:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 8177:                return 'refused';
 8178:            }
 8179:         }
 8180:         $mrole='cr';
 8181:     } elsif ($role =~ /^gr\//) {
 8182:         my $cwogrp=$url;
 8183:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 8184:         unless (&allowed('mdg',$cwogrp)) {
 8185:             &logthis('Refused group assignrole: '.
 8186:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 8187:                     $env{'user.name'}.' at '.$env{'user.domain'});
 8188:             return 'refused';
 8189:         }
 8190:         $mrole='gr';
 8191:     } else {
 8192:         my $cwosec=$url;
 8193:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 8194:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 8195:             my $refused;
 8196:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 8197:                 if (!(&allowed('c'.$role,$url))) {
 8198:                     $refused = 1;
 8199:                 }
 8200:             } else {
 8201:                 $refused = 1;
 8202:             }
 8203:             if ($refused) {
 8204:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 8205:                 if (!$selfenroll && $context eq 'course') {
 8206:                     my %crsenv;
 8207:                     if ($role eq 'cc' || $role eq 'co') {
 8208:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8209:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 8210:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 8211:                                 if ($crsenv{'internal.courseowner'} eq 
 8212:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 8213:                                     $refused = '';
 8214:                                 }
 8215:                             }
 8216:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 8217:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 8218:                                 if ($crsenv{'internal.courseowner'} eq 
 8219:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 8220:                                     $refused = '';
 8221:                                 }
 8222:                             }
 8223:                         }
 8224:                     }
 8225:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 8226:                     $refused = '';
 8227:                 } elsif ($context eq 'requestcourses') {
 8228:                     my @possroles = ('st','ta','ep','in','cc','co');
 8229:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 8230:                         my $wrongcc;
 8231:                         if ($cnum =~ /^$match_community$/) {
 8232:                             $wrongcc = 1 if ($role eq 'cc');
 8233:                         } else {
 8234:                             $wrongcc = 1 if ($role eq 'co');
 8235:                         }
 8236:                         unless ($wrongcc) {
 8237:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8238:                             if ($crsenv{'internal.courseowner'} eq 
 8239:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 8240:                                 $refused = '';
 8241:                             }
 8242:                         }
 8243:                     }
 8244:                 } elsif ($context eq 'requestauthor') {
 8245:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
 8246:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 8247:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 8248:                             $refused = '';
 8249:                         } else {
 8250:                             my %domdefaults = &get_domain_defaults($udom);
 8251:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 8252:                                 my $checkbystatus;
 8253:                                 if ($env{'user.adv'}) { 
 8254:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 8255:                                     if ($disposition eq 'automatic') {
 8256:                                         $refused = '';
 8257:                                     } elsif ($disposition eq '') {
 8258:                                         $checkbystatus = 1;
 8259:                                     } 
 8260:                                 } else {
 8261:                                     $checkbystatus = 1;
 8262:                                 }
 8263:                                 if ($checkbystatus) {
 8264:                                     if ($env{'environment.inststatus'}) {
 8265:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 8266:                                         foreach my $type (@inststatuses) {
 8267:                                             if (($type ne '') &&
 8268:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 8269:                                                 $refused = '';
 8270:                                             }
 8271:                                         }
 8272:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 8273:                                         $refused = '';
 8274:                                     }
 8275:                                 }
 8276:                             }
 8277:                         }
 8278:                     }
 8279:                 }
 8280:                 if ($refused) {
 8281:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 8282:                              ' '.$role.' '.$end.' '.$start.' by '.
 8283: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 8284:                     return 'refused';
 8285:                 }
 8286:             }
 8287:         } elsif ($role eq 'au') {
 8288:             if ($url ne '/'.$udom.'/') {
 8289:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 8290:                          ' to assign author role for '.$uname.':'.$udom.
 8291:                          ' in domain: '.$url.' refused (wrong domain).');
 8292:                 return 'refused';
 8293:             }
 8294:         }
 8295:         $mrole=$role;
 8296:     }
 8297:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 8298:                 "$udom:$uname:$url".'_'."$mrole=$role";
 8299:     if ($end) { $command.='_'.$end; }
 8300:     if ($start) {
 8301: 	if ($end) { 
 8302:            $command.='_'.$start; 
 8303:         } else {
 8304:            $command.='_0_'.$start;
 8305:         }
 8306:     }
 8307:     my $origstart = $start;
 8308:     my $origend = $end;
 8309:     my $delflag;
 8310: # actually delete
 8311:     if ($deleteflag) {
 8312: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 8313: # modify command to delete the role
 8314:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 8315:                 "$udom:$uname:$url".'_'."$mrole";
 8316: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 8317: # set start and finish to negative values for userrolelog
 8318:            $start=-1;
 8319:            $end=-1;
 8320:            $delflag = 1;
 8321:         }
 8322:     }
 8323: # send command
 8324:     my $answer=&reply($command,&homeserver($uname,$udom));
 8325: # log new user role if status is ok
 8326:     if ($answer eq 'ok') {
 8327: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 8328:         if (($role eq 'cc') || ($role eq 'in') ||
 8329:             ($role eq 'ep') || ($role eq 'ad') ||
 8330:             ($role eq 'ta') || ($role eq 'st') ||
 8331:             ($role=~/^cr/) || ($role eq 'gr') ||
 8332:             ($role eq 'co')) {
 8333: # for course roles, perform group memberships changes triggered by role change.
 8334:             unless ($role =~ /^gr/) {
 8335:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 8336:                                                  $origstart,$selfenroll,$context);
 8337:             }
 8338:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8339:                            $selfenroll,$context);
 8340:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
 8341:                  ($role eq 'au') || ($role eq 'dc')) {
 8342:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8343:                            $context);
 8344:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
 8345:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8346:                              $context); 
 8347:         }
 8348:         if ($role eq 'cc') {
 8349:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 8350:         }
 8351:     }
 8352:     return $answer;
 8353: }
 8354: 
 8355: sub autoupdate_coowners {
 8356:     my ($url,$end,$start,$uname,$udom) = @_;
 8357:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 8358:     if (($cdom ne '') && ($cnum ne '')) {
 8359:         my $now = time;
 8360:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 8361:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 8362:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 8363:             my $instcode = $coursehash{'internal.coursecode'};
 8364:             if ($instcode ne '') {
 8365:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 8366:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 8367:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 8368:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 8369:                         if ($result eq 'valid') {
 8370:                             if ($coursehash{'internal.co-owners'}) {
 8371:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 8372:                                     push(@newcoowners,$coowner);
 8373:                                 }
 8374:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 8375:                                     push(@newcoowners,$uname.':'.$udom);
 8376:                                 }
 8377:                                 @newcoowners = sort(@newcoowners);
 8378:                             } else {
 8379:                                 push(@newcoowners,$uname.':'.$udom);
 8380:                             }
 8381:                         } else {
 8382:                             if ($coursehash{'internal.co-owners'}) {
 8383:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 8384:                                     unless ($coowner eq $uname.':'.$udom) {
 8385:                                         push(@newcoowners,$coowner);
 8386:                                     }
 8387:                                 }
 8388:                                 unless (@newcoowners > 0) {
 8389:                                     $delcoowners = 1;
 8390:                                     $coowners = '';
 8391:                                 }
 8392:                             }
 8393:                         }
 8394:                         if (@newcoowners || $delcoowners) {
 8395:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 8396:                                             $delcoowners,@newcoowners);
 8397:                         }
 8398:                     }
 8399:                 }
 8400:             }
 8401:         }
 8402:     }
 8403: }
 8404: 
 8405: sub store_coowners {
 8406:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 8407:     my $cid = $cdom.'_'.$cnum;
 8408:     my ($coowners,$delresult,$putresult);
 8409:     if (@newcoowners) {
 8410:         $coowners = join(',',@newcoowners);
 8411:         my %coownershash = (
 8412:                             'internal.co-owners' => $coowners,
 8413:                            );
 8414:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 8415:         if ($putresult eq 'ok') {
 8416:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 8417:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 8418:             }
 8419:         }
 8420:     }
 8421:     if ($delcoowners) {
 8422:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 8423:         if ($delresult eq 'ok') {
 8424:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 8425:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 8426:             }
 8427:         }
 8428:     }
 8429:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 8430:         my %crsinfo =
 8431:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 8432:         if (ref($crsinfo{$cid}) eq 'HASH') {
 8433:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 8434:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 8435:         }
 8436:     }
 8437: }
 8438: 
 8439: # -------------------------------------------------- Modify user authentication
 8440: # Overrides without validation
 8441: 
 8442: sub modifyuserauth {
 8443:     my ($udom,$uname,$umode,$upass)=@_;
 8444:     my $uhome=&homeserver($uname,$udom);
 8445:     unless (&allowed('mau',$udom)) { return 'refused'; }
 8446:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 8447:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 8448:              ' in domain '.$env{'request.role.domain'});  
 8449:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 8450: 		     &escape($upass),$uhome);
 8451:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 8452:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 8453:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 8454:     &log($udom,,$uname,$uhome,
 8455:         'Authentication changed by '.$env{'user.domain'}.', '.
 8456:                                      $env{'user.name'}.', '.$umode.
 8457:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 8458:     unless ($reply eq 'ok') {
 8459:         &logthis('Authentication mode error: '.$reply);
 8460: 	return 'error: '.$reply;
 8461:     }   
 8462:     return 'ok';
 8463: }
 8464: 
 8465: # --------------------------------------------------------------- Modify a user
 8466: 
 8467: sub modifyuser {
 8468:     my ($udom,    $uname, $uid,
 8469:         $umode,   $upass, $first,
 8470:         $middle,  $last,  $gene,
 8471:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 8472:     $udom= &LONCAPA::clean_domain($udom);
 8473:     $uname=&LONCAPA::clean_username($uname);
 8474:     my $showcandelete = 'none';
 8475:     if (ref($candelete) eq 'ARRAY') {
 8476:         if (@{$candelete} > 0) {
 8477:             $showcandelete = join(', ',@{$candelete});
 8478:         }
 8479:     }
 8480:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 8481:              $umode.', '.$first.', '.$middle.', '.
 8482: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 8483:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 8484:                                      ' desiredhome not specified'). 
 8485:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 8486:              ' in domain '.$env{'request.role.domain'});
 8487:     my $uhome=&homeserver($uname,$udom,'true');
 8488:     my $newuser;
 8489:     if ($uhome eq 'no_host') {
 8490:         $newuser = 1;
 8491:     }
 8492: # ----------------------------------------------------------------- Create User
 8493:     if (($uhome eq 'no_host') && 
 8494: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 8495:         my $unhome='';
 8496:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 8497:             $unhome = $desiredhome;
 8498: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 8499: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 8500:         } else { # load balancing routine for determining $unhome
 8501:             my $loadm=10000000;
 8502: 	    my %servers = &get_servers($udom,'library');
 8503: 	    foreach my $tryserver (keys(%servers)) {
 8504: 		my $answer=reply('load',$tryserver);
 8505: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 8506: 		    $loadm=$answer;
 8507: 		    $unhome=$tryserver;
 8508: 		}
 8509: 	    }
 8510:         }
 8511:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 8512: 	    return 'error: unable to find a home server for '.$uname.
 8513:                    ' in domain '.$udom;
 8514:         }
 8515:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 8516:                          &escape($upass),$unhome);
 8517: 	unless ($reply eq 'ok') {
 8518:             return 'error: '.$reply;
 8519:         }   
 8520:         $uhome=&homeserver($uname,$udom,'true');
 8521:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 8522: 	    return 'error: unable verify users home machine.';
 8523:         }
 8524:     }   # End of creation of new user
 8525: # ---------------------------------------------------------------------- Add ID
 8526:     if ($uid) {
 8527:        $uid=~tr/A-Z/a-z/;
 8528:        my %uidhash=&idrget($udom,$uname);
 8529:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 8530:          && (!$forceid)) {
 8531: 	  unless ($uid eq $uidhash{$uname}) {
 8532: 	      return 'error: user id "'.$uid.'" does not match '.
 8533:                   'current user id "'.$uidhash{$uname}.'".';
 8534:           }
 8535:        } else {
 8536: 	  &idput($udom,($uname => $uid));
 8537:        }
 8538:     }
 8539: # -------------------------------------------------------------- Add names, etc
 8540:     my @tmp=&get('environment',
 8541: 		   ['firstname','middlename','lastname','generation','id',
 8542:                     'permanentemail','inststatus'],
 8543: 		   $udom,$uname);
 8544:     my (%names,%oldnames);
 8545:     if ($tmp[0] =~ m/^error:.*/) { 
 8546:         %names=(); 
 8547:     } else {
 8548:         %names = @tmp;
 8549:         %oldnames = %names;
 8550:     }
 8551: #
 8552: # If name, email and/or uid are blank (e.g., because an uploaded file
 8553: # of users did not contain them), do not overwrite existing values
 8554: # unless field is in $candelete array ref.  
 8555: #
 8556: 
 8557:     my @fields = ('firstname','middlename','lastname','generation',
 8558:                   'permanentemail','id');
 8559:     my %newvalues;
 8560:     if (ref($candelete) eq 'ARRAY') {
 8561:         foreach my $field (@fields) {
 8562:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 8563:                 if ($field eq 'firstname') {
 8564:                     $names{$field} = $first;
 8565:                 } elsif ($field eq 'middlename') {
 8566:                     $names{$field} = $middle;
 8567:                 } elsif ($field eq 'lastname') {
 8568:                     $names{$field} = $last;
 8569:                 } elsif ($field eq 'generation') { 
 8570:                     $names{$field} = $gene;
 8571:                 } elsif ($field eq 'permanentemail') {
 8572:                     $names{$field} = $email;
 8573:                 } elsif ($field eq 'id') {
 8574:                     $names{$field}  = $uid;
 8575:                 }
 8576:             }
 8577:         }
 8578:     }
 8579:     if ($first)  { $names{'firstname'}  = $first; }
 8580:     if (defined($middle)) { $names{'middlename'} = $middle; }
 8581:     if ($last)   { $names{'lastname'}   = $last; }
 8582:     if (defined($gene))   { $names{'generation'} = $gene; }
 8583:     if ($email) {
 8584:        $email=~s/[^\w\@\.\-\,]//gs;
 8585:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 8586:     }
 8587:     if ($uid) { $names{'id'}  = $uid; }
 8588:     if (defined($inststatus)) {
 8589:         $names{'inststatus'} = '';
 8590:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 8591:         if (ref($usertypes) eq 'HASH') {
 8592:             my @okstatuses; 
 8593:             foreach my $item (split(/:/,$inststatus)) {
 8594:                 if (defined($usertypes->{$item})) {
 8595:                     push(@okstatuses,$item);  
 8596:                 }
 8597:             }
 8598:             if (@okstatuses) {
 8599:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 8600:             }
 8601:         }
 8602:     }
 8603:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 8604:                  $umode.', '.$first.', '.$middle.', '.
 8605:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 8606:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 8607:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 8608:     } else {
 8609:         $logmsg .= ' during self creation';
 8610:     }
 8611:     my $changed;
 8612:     if ($newuser) {
 8613:         $changed = 1;
 8614:     } else {
 8615:         foreach my $field (@fields) {
 8616:             if ($names{$field} ne $oldnames{$field}) {
 8617:                 $changed = 1;
 8618:                 last;
 8619:             }
 8620:         }
 8621:     }
 8622:     unless ($changed) {
 8623:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 8624:         &logthis($logmsg);
 8625:         return 'ok';
 8626:     }
 8627:     my $reply = &put('environment', \%names, $udom,$uname);
 8628:     if ($reply ne 'ok') { 
 8629:         return 'error: '.$reply;
 8630:     }
 8631:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
 8632:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
 8633:     }
 8634:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 8635:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 8636:     $logmsg = 'Success modifying user '.$logmsg;
 8637:     &logthis($logmsg);
 8638:     return 'ok';
 8639: }
 8640: 
 8641: # -------------------------------------------------------------- Modify student
 8642: 
 8643: sub modifystudent {
 8644:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 8645:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 8646:         $selfenroll,$context,$inststatus,$credits)=@_;
 8647:     if (!$cid) {
 8648: 	unless ($cid=$env{'request.course.id'}) {
 8649: 	    return 'not_in_class';
 8650: 	}
 8651:     }
 8652: # --------------------------------------------------------------- Make the user
 8653:     my $reply=&modifyuser
 8654: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 8655:          $desiredhome,$email,$inststatus);
 8656:     unless ($reply eq 'ok') { return $reply; }
 8657:     # This will cause &modify_student_enrollment to get the uid from the
 8658:     # student's environment
 8659:     $uid = undef if (!$forceid);
 8660:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 8661:                                         $gene,$usec,$end,$start,$type,$locktype,
 8662:                                         $cid,$selfenroll,$context,$credits);
 8663:     return $reply;
 8664: }
 8665: 
 8666: sub modify_student_enrollment {
 8667:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
 8668:         $locktype,$cid,$selfenroll,$context,$credits) = @_;
 8669:     my ($cdom,$cnum,$chome);
 8670:     if (!$cid) {
 8671: 	unless ($cid=$env{'request.course.id'}) {
 8672: 	    return 'not_in_class';
 8673: 	}
 8674: 	$cdom=$env{'course.'.$cid.'.domain'};
 8675: 	$cnum=$env{'course.'.$cid.'.num'};
 8676:     } else {
 8677: 	($cdom,$cnum)=split(/_/,$cid);
 8678:     }
 8679:     $chome=$env{'course.'.$cid.'.home'};
 8680:     if (!$chome) {
 8681: 	$chome=&homeserver($cnum,$cdom);
 8682:     }
 8683:     if (!$chome) { return 'unknown_course'; }
 8684:     # Make sure the user exists
 8685:     my $uhome=&homeserver($uname,$udom);
 8686:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8687: 	return 'error: no such user';
 8688:     }
 8689:     # Get student data if we were not given enough information
 8690:     if (!defined($first)  || $first  eq '' || 
 8691:         !defined($last)   || $last   eq '' || 
 8692:         !defined($uid)    || $uid    eq '' || 
 8693:         !defined($middle) || $middle eq '' || 
 8694:         !defined($gene)   || $gene   eq '') {
 8695:         # They did not supply us with enough data to enroll the student, so
 8696:         # we need to pick up more information.
 8697:         my %tmp = &get('environment',
 8698:                        ['firstname','middlename','lastname', 'generation','id']
 8699:                        ,$udom,$uname);
 8700: 
 8701:         #foreach my $key (keys(%tmp)) {
 8702:         #    &logthis("key $key = ".$tmp{$key});
 8703:         #}
 8704:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 8705:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 8706:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 8707:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 8708:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 8709:     }
 8710:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 8711:     my $user = "$uname:$udom";
 8712:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
 8713:     my $reply=cput('classlist',
 8714: 		   {$user => 
 8715: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
 8716: 		   $cdom,$cnum);
 8717:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
 8718:         &devalidate_getsection_cache($udom,$uname,$cid);
 8719:     } else { 
 8720: 	return 'error: '.$reply;
 8721:     }
 8722:     # Add student role to user
 8723:     my $uurl='/'.$cid;
 8724:     $uurl=~s/\_/\//g;
 8725:     if ($usec) {
 8726: 	$uurl.='/'.$usec;
 8727:     }
 8728:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
 8729:                              $selfenroll,$context);
 8730:     if ($result ne 'ok') {
 8731:         if ($old_entry{$user} ne '') {
 8732:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
 8733:         } else {
 8734:             $reply = &del('classlist',[$user],$cdom,$cnum);
 8735:         }
 8736:     }
 8737:     return $result; 
 8738: }
 8739: 
 8740: sub format_name {
 8741:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 8742:     my $name;
 8743:     if ($first ne 'lastname') {
 8744: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 8745:     } else {
 8746: 	if ($lastname=~/\S/) {
 8747: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 8748: 	    $name=~s/\s+,/,/;
 8749: 	} else {
 8750: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 8751: 	}
 8752:     }
 8753:     $name=~s/^\s+//;
 8754:     $name=~s/\s+$//;
 8755:     $name=~s/\s+/ /g;
 8756:     return $name;
 8757: }
 8758: 
 8759: # ------------------------------------------------- Write to course preferences
 8760: 
 8761: sub writecoursepref {
 8762:     my ($courseid,%prefs)=@_;
 8763:     $courseid=~s/^\///;
 8764:     $courseid=~s/\_/\//g;
 8765:     my ($cdomain,$cnum)=split(/\//,$courseid);
 8766:     my $chome=homeserver($cnum,$cdomain);
 8767:     if (($chome eq '') || ($chome eq 'no_host')) { 
 8768: 	return 'error: no such course';
 8769:     }
 8770:     my $cstring='';
 8771:     foreach my $pref (keys(%prefs)) {
 8772: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 8773:     }
 8774:     $cstring=~s/\&$//;
 8775:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 8776: }
 8777: 
 8778: # ---------------------------------------------------------- Make/modify course
 8779: 
 8780: sub createcourse {
 8781:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 8782:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 8783:     $url=&declutter($url);
 8784:     my $cid='';
 8785:     if ($context eq 'requestcourses') {
 8786:         my $can_create = 0;
 8787:         my ($ownername,$ownerdom) = split(':',$course_owner);
 8788:         if ($udom eq $ownerdom) {
 8789:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 8790:                                   $context)) {
 8791:                 $can_create = 1;
 8792:             }
 8793:         } else {
 8794:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 8795:                                            $category);
 8796:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 8797:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 8798:                 if (@curr > 0) {
 8799:                     my @options = qw(approval validate autolimit);
 8800:                     my $optregex = join('|',@options);
 8801:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 8802:                         $can_create = 1;
 8803:                     }
 8804:                 }
 8805:             }
 8806:         }
 8807:         if ($can_create) {
 8808:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 8809:                 unless (&allowed('ccc',$udom)) {
 8810:                     return 'refused'; 
 8811:                 }
 8812:             }
 8813:         } else {
 8814:             return 'refused';
 8815:         }
 8816:     } elsif (!&allowed('ccc',$udom)) {
 8817:         return 'refused';
 8818:     }
 8819: # --------------------------------------------------------------- Get Unique ID
 8820:     my $uname;
 8821:     if ($cnum =~ /^$match_courseid$/) {
 8822:         my $chome=&homeserver($cnum,$udom,'true');
 8823:         if (($chome eq '') || ($chome eq 'no_host')) {
 8824:             $uname = $cnum;
 8825:         } else {
 8826:             $uname = &generate_coursenum($udom,$crstype);
 8827:         }
 8828:     } else {
 8829:         $uname = &generate_coursenum($udom,$crstype);
 8830:     }
 8831:     return $uname if ($uname =~ /^error/);
 8832: # -------------------------------------------------- Check supplied server name
 8833:     if (!defined($course_server)) {
 8834:         if (defined(&domain($udom,'primary'))) {
 8835:             $course_server = &domain($udom,'primary');
 8836:         } else {
 8837:             $course_server = $env{'user.home'}; 
 8838:         }
 8839:     }
 8840:     my %host_servers =
 8841:         &Apache::lonnet::get_servers($udom,'library');
 8842:     unless ($host_servers{$course_server}) {
 8843:         return 'error: invalid home server for course: '.$course_server;
 8844:     }
 8845: # ------------------------------------------------------------- Make the course
 8846:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 8847:                       $course_server);
 8848:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 8849:     my $uhome=&homeserver($uname,$udom,'true');
 8850:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8851: 	return 'error: no such course';
 8852:     }
 8853: # ----------------------------------------------------------------- Course made
 8854: # log existence
 8855:     my $now = time;
 8856:     my $newcourse = {
 8857:                     $udom.'_'.$uname => {
 8858:                                      description => $description,
 8859:                                      inst_code   => $inst_code,
 8860:                                      owner       => $course_owner,
 8861:                                      type        => $crstype,
 8862:                                      creator     => $env{'user.name'}.':'.
 8863:                                                     $env{'user.domain'},
 8864:                                      created     => $now,
 8865:                                      context     => $context,
 8866:                                                 },
 8867:                     };
 8868:     &courseidput($udom,$newcourse,$uhome,'notime');
 8869: # set toplevel url
 8870:     my $topurl=$url;
 8871:     unless ($nonstandard) {
 8872: # ------------------------------------------ For standard courses, make top url
 8873:         my $mapurl=&clutter($url);
 8874:         if ($mapurl eq '/res/') { $mapurl=''; }
 8875:         $env{'form.initmap'}=(<<ENDINITMAP);
 8876: <map>
 8877: <resource id="1" type="start"></resource>
 8878: <resource id="2" src="$mapurl"></resource>
 8879: <resource id="3" type="finish"></resource>
 8880: <link index="1" from="1" to="2"></link>
 8881: <link index="2" from="2" to="3"></link>
 8882: </map>
 8883: ENDINITMAP
 8884:         $topurl=&declutter(
 8885:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 8886:                           );
 8887:     }
 8888: # ----------------------------------------------------------- Write preferences
 8889:     &writecoursepref($udom.'_'.$uname,
 8890:                      ('description'              => $description,
 8891:                       'url'                      => $topurl,
 8892:                       'internal.creator'         => $env{'user.name'}.':'.
 8893:                                                     $env{'user.domain'},
 8894:                       'internal.created'         => $now,
 8895:                       'internal.creationcontext' => $context)
 8896:                     );
 8897:     return '/'.$udom.'/'.$uname;
 8898: }
 8899: 
 8900: # ------------------------------------------------------------------- Create ID
 8901: sub generate_coursenum {
 8902:     my ($udom,$crstype) = @_;
 8903:     my $domdesc = &domain($udom);
 8904:     return 'error: invalid domain' if ($domdesc eq '');
 8905:     my $first;
 8906:     if ($crstype eq 'Community') {
 8907:         $first = '0';
 8908:     } else {
 8909:         $first = int(1+rand(9)); 
 8910:     } 
 8911:     my $uname=$first.
 8912:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8913:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8914:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8915: # ----------------------------------------------- Make sure that does not exist
 8916:     my $uhome=&homeserver($uname,$udom,'true');
 8917:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8918:         if ($crstype eq 'Community') {
 8919:             $first = '0';
 8920:         } else {
 8921:             $first = int(1+rand(9));
 8922:         }
 8923:         $uname=$first.
 8924:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8925:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8926:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8927:         $uhome=&homeserver($uname,$udom,'true');
 8928:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8929:             return 'error: unable to generate unique course-ID';
 8930:         }
 8931:     }
 8932:     return $uname;
 8933: }
 8934: 
 8935: sub is_course {
 8936:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
 8937:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
 8938: 
 8939:     return unless $cdom and $cnum;
 8940: 
 8941:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
 8942:         '.');
 8943: 
 8944:     return unless(exists($courses{$cdom.'_'.$cnum}));
 8945:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
 8946: }
 8947: 
 8948: sub store_userdata {
 8949:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
 8950:     my $result;
 8951:     if ($datakey ne '') {
 8952:         if (ref($storehash) eq 'HASH') {
 8953:             if ($udom eq '' || $uname eq '') {
 8954:                 $udom = $env{'user.domain'};
 8955:                 $uname = $env{'user.name'};
 8956:             }
 8957:             my $uhome=&homeserver($uname,$udom);
 8958:             if (($uhome eq '') || ($uhome eq 'no_host')) {
 8959:                 $result = 'error: no_host';
 8960:             } else {
 8961:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
 8962:                 $storehash->{'host'} = $perlvar{'lonHostID'};
 8963: 
 8964:                 my $namevalue='';
 8965:                 foreach my $key (keys(%{$storehash})) {
 8966:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 8967:                 }
 8968:                 $namevalue=~s/\&$//;
 8969:                 unless ($namespace eq 'courserequests') {
 8970:                     $datakey = &escape($datakey);
 8971:                 }
 8972:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
 8973:                                   $namevalue,$uhome);
 8974:             }
 8975:         } else {
 8976:             $result = 'error: data to store was not a hash reference'; 
 8977:         }
 8978:     } else {
 8979:         $result= 'error: invalid requestkey'; 
 8980:     }
 8981:     return $result;
 8982: }
 8983: 
 8984: # ---------------------------------------------------------- Assign Custom Role
 8985: 
 8986: sub assigncustomrole {
 8987:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 8988:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 8989:                        $end,$start,$deleteflag,$selfenroll,$context);
 8990: }
 8991: 
 8992: # ----------------------------------------------------------------- Revoke Role
 8993: 
 8994: sub revokerole {
 8995:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 8996:     my $now=time;
 8997:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 8998: }
 8999: 
 9000: # ---------------------------------------------------------- Revoke Custom Role
 9001: 
 9002: sub revokecustomrole {
 9003:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 9004:     my $now=time;
 9005:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 9006:            $deleteflag,$selfenroll,$context);
 9007: }
 9008: 
 9009: # ------------------------------------------------------------ Disk usage
 9010: sub diskusage {
 9011:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 9012:     $directorypath =~ s/\/$//;
 9013:     my $listing=&reply('du2:'.&escape($directorypath).':'
 9014:                        .&escape($getpropath).':'.&escape($uname).':'
 9015:                        .&escape($udom),homeserver($uname,$udom));
 9016:     if ($listing eq 'unknown_cmd') {
 9017:         if ($getpropath) {
 9018:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 9019:         }
 9020:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 9021:     }
 9022:     return $listing;
 9023: }
 9024: 
 9025: sub is_locked {
 9026:     my ($file_name, $domain, $user, $which) = @_;
 9027:     my @check;
 9028:     my $is_locked;
 9029:     push (@check,$file_name);
 9030:     my %locked = &get('file_permissions',\@check,
 9031: 		      $env{'user.domain'},$env{'user.name'});
 9032:     my ($tmp)=keys(%locked);
 9033:     if ($tmp=~/^error:/) { undef(%locked); }
 9034:     
 9035:     if (ref($locked{$file_name}) eq 'ARRAY') {
 9036:         $is_locked = 'false';
 9037:         foreach my $entry (@{$locked{$file_name}}) {
 9038:            if (ref($entry) eq 'ARRAY') {
 9039:                $is_locked = 'true';
 9040:                if (ref($which) eq 'ARRAY') {
 9041:                    push(@{$which},$entry);
 9042:                } else {
 9043:                    last;
 9044:                }
 9045:            }
 9046:        }
 9047:     } else {
 9048:         $is_locked = 'false';
 9049:     }
 9050:     return $is_locked;
 9051: }
 9052: 
 9053: sub declutter_portfile {
 9054:     my ($file) = @_;
 9055:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 9056:     return $file;
 9057: }
 9058: 
 9059: # ------------------------------------------------------------- Mark as Read Only
 9060: 
 9061: sub mark_as_readonly {
 9062:     my ($domain,$user,$files,$what) = @_;
 9063:     my %current_permissions = &dump('file_permissions',$domain,$user);
 9064:     my ($tmp)=keys(%current_permissions);
 9065:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9066:     foreach my $file (@{$files}) {
 9067: 	$file = &declutter_portfile($file);
 9068:         push(@{$current_permissions{$file}},$what);
 9069:     }
 9070:     &put('file_permissions',\%current_permissions,$domain,$user);
 9071:     return;
 9072: }
 9073: 
 9074: # ------------------------------------------------------------Save Selected Files
 9075: 
 9076: sub save_selected_files {
 9077:     my ($user, $path, @files) = @_;
 9078:     my $filename = $user."savedfiles";
 9079:     my @other_files = &files_not_in_path($user, $path);
 9080:     open (OUT, '>'.$tmpdir.$filename);
 9081:     foreach my $file (@files) {
 9082:         print (OUT $env{'form.currentpath'}.$file."\n");
 9083:     }
 9084:     foreach my $file (@other_files) {
 9085:         print (OUT $file."\n");
 9086:     }
 9087:     close (OUT);
 9088:     return 'ok';
 9089: }
 9090: 
 9091: sub clear_selected_files {
 9092:     my ($user) = @_;
 9093:     my $filename = $user."savedfiles";
 9094:     open (OUT, '>'.LONCAPA::tempdir().$filename);
 9095:     print (OUT undef);
 9096:     close (OUT);
 9097:     return ("ok");    
 9098: }
 9099: 
 9100: sub files_in_path {
 9101:     my ($user, $path) = @_;
 9102:     my $filename = $user."savedfiles";
 9103:     my %return_files;
 9104:     open (IN, '<'.LONCAPA::tempdir().$filename);
 9105:     while (my $line_in = <IN>) {
 9106:         chomp ($line_in);
 9107:         my @paths_and_file = split (m!/!, $line_in);
 9108:         my $file_part = pop (@paths_and_file);
 9109:         my $path_part = join ('/', @paths_and_file);
 9110:         $path_part.='/';
 9111:         my $path_and_file = $path_part.$file_part;
 9112:         if ($path_part eq $path) {
 9113:             $return_files{$file_part}= 'selected';
 9114:         }
 9115:     }
 9116:     close (IN);
 9117:     return (\%return_files);
 9118: }
 9119: 
 9120: # called in portfolio select mode, to show files selected NOT in current directory
 9121: sub files_not_in_path {
 9122:     my ($user, $path) = @_;
 9123:     my $filename = $user."savedfiles";
 9124:     my @return_files;
 9125:     my $path_part;
 9126:     open(IN, '<'.LONCAPA::.$filename);
 9127:     while (my $line = <IN>) {
 9128:         #ok, I know it's clunky, but I want it to work
 9129:         my @paths_and_file = split(m|/|, $line);
 9130:         my $file_part = pop(@paths_and_file);
 9131:         chomp($file_part);
 9132:         my $path_part = join('/', @paths_and_file);
 9133:         $path_part .= '/';
 9134:         my $path_and_file = $path_part.$file_part;
 9135:         if ($path_part ne $path) {
 9136:             push(@return_files, ($path_and_file));
 9137:         }
 9138:     }
 9139:     close(OUT);
 9140:     return (@return_files);
 9141: }
 9142: 
 9143: #----------------------------------------------Get portfolio file permissions
 9144: 
 9145: sub get_portfile_permissions {
 9146:     my ($domain,$user) = @_;
 9147:     my %current_permissions = &dump('file_permissions',$domain,$user);
 9148:     my ($tmp)=keys(%current_permissions);
 9149:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9150:     return \%current_permissions;
 9151: }
 9152: 
 9153: #---------------------------------------------Get portfolio file access controls
 9154: 
 9155: sub get_access_controls {
 9156:     my ($current_permissions,$group,$file) = @_;
 9157:     my %access;
 9158:     my $real_file = $file;
 9159:     $file =~ s/\.meta$//;
 9160:     if (defined($file)) {
 9161:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 9162:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 9163:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 9164:             }
 9165:         }
 9166:     } else {
 9167:         foreach my $key (keys(%{$current_permissions})) {
 9168:             if ($key =~ /\0accesscontrol$/) {
 9169:                 if (defined($group)) {
 9170:                     if ($key !~ m-^\Q$group\E/-) {
 9171:                         next;
 9172:                     }
 9173:                 }
 9174:                 my ($fullpath) = split(/\0/,$key);
 9175:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 9176:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 9177:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 9178:                     }
 9179:                 }
 9180:             }
 9181:         }
 9182:     }
 9183:     return %access;
 9184: }
 9185: 
 9186: sub modify_access_controls {
 9187:     my ($file_name,$changes,$domain,$user)=@_;
 9188:     my ($outcome,$deloutcome);
 9189:     my %store_permissions;
 9190:     my %new_values;
 9191:     my %new_control;
 9192:     my %translation;
 9193:     my @deletions = ();
 9194:     my $now = time;
 9195:     if (exists($$changes{'activate'})) {
 9196:         if (ref($$changes{'activate'}) eq 'HASH') {
 9197:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 9198:             my $numnew = scalar(@newitems);
 9199:             for (my $i=0; $i<$numnew; $i++) {
 9200:                 my $newkey = $newitems[$i];
 9201:                 my $newid = &Apache::loncommon::get_cgi_id();
 9202:                 if ($newkey =~ /^\d+:/) { 
 9203:                     $newkey =~ s/^(\d+)/$newid/;
 9204:                     $translation{$1} = $newid;
 9205:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 9206:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 9207:                     $translation{$1} = $newid;
 9208:                 }
 9209:                 $new_values{$file_name."\0".$newkey} = 
 9210:                                           $$changes{'activate'}{$newitems[$i]};
 9211:                 $new_control{$newkey} = $now;
 9212:             }
 9213:         }
 9214:     }
 9215:     my %todelete;
 9216:     my %changed_items;
 9217:     foreach my $action ('delete','update') {
 9218:         if (exists($$changes{$action})) {
 9219:             if (ref($$changes{$action}) eq 'HASH') {
 9220:                 foreach my $key (keys(%{$$changes{$action}})) {
 9221:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 9222:                     if ($action eq 'delete') { 
 9223:                         $todelete{$itemnum} = 1;
 9224:                     } else {
 9225:                         $changed_items{$itemnum} = $key;
 9226:                     }
 9227:                 }
 9228:             }
 9229:         }
 9230:     }
 9231:     # get lock on access controls for file.
 9232:     my $lockhash = {
 9233:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 9234:                                                        ':'.$env{'user.domain'},
 9235:                    }; 
 9236:     my $tries = 0;
 9237:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 9238:    
 9239:     while (($gotlock ne 'ok') && $tries <3) {
 9240:         $tries ++;
 9241:         sleep 1;
 9242:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 9243:     }
 9244:     if ($gotlock eq 'ok') {
 9245:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 9246:         my ($tmp)=keys(%curr_permissions);
 9247:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 9248:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 9249:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 9250:             if (ref($curr_controls) eq 'HASH') {
 9251:                 foreach my $control_item (keys(%{$curr_controls})) {
 9252:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 9253:                     if (defined($todelete{$itemnum})) {
 9254:                         push(@deletions,$file_name."\0".$control_item);
 9255:                     } else {
 9256:                         if (defined($changed_items{$itemnum})) {
 9257:                             $new_control{$changed_items{$itemnum}} = $now;
 9258:                             push(@deletions,$file_name."\0".$control_item);
 9259:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 9260:                         } else {
 9261:                             $new_control{$control_item} = $$curr_controls{$control_item};
 9262:                         }
 9263:                     }
 9264:                 }
 9265:             }
 9266:         }
 9267:         my ($group);
 9268:         if (&is_course($domain,$user)) {
 9269:             ($group,my $file) = split(/\//,$file_name,2);
 9270:         }
 9271:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 9272:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 9273:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 9274:         #  remove lock
 9275:         my @del_lock = ($file_name."\0".'locked_access_records');
 9276:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 9277:         my $sqlresult =
 9278:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 9279:                                     $group);
 9280:     } else {
 9281:         $outcome = "error: could not obtain lockfile\n";  
 9282:     }
 9283:     return ($outcome,$deloutcome,\%new_values,\%translation);
 9284: }
 9285: 
 9286: sub make_public_indefinitely {
 9287:     my ($requrl) = @_;
 9288:     my $now = time;
 9289:     my $action = 'activate';
 9290:     my $aclnum = 0;
 9291:     if (&is_portfolio_url($requrl)) {
 9292:         my (undef,$udom,$unum,$file_name,$group) =
 9293:             &parse_portfolio_url($requrl);
 9294:         my $current_perms = &get_portfile_permissions($udom,$unum);
 9295:         my %access_controls = &get_access_controls($current_perms,
 9296:                                                    $group,$file_name);
 9297:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 9298:             my ($num,$scope,$end,$start) = 
 9299:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 9300:             if ($scope eq 'public') {
 9301:                 if ($start <= $now && $end == 0) {
 9302:                     $action = 'none';
 9303:                 } else {
 9304:                     $action = 'update';
 9305:                     $aclnum = $num;
 9306:                 }
 9307:                 last;
 9308:             }
 9309:         }
 9310:         if ($action eq 'none') {
 9311:              return 'ok';
 9312:         } else {
 9313:             my %changes;
 9314:             my $newend = 0;
 9315:             my $newstart = $now;
 9316:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 9317:             $changes{$action}{$newkey} = {
 9318:                 type => 'public',
 9319:                 time => {
 9320:                     start => $newstart,
 9321:                     end   => $newend,
 9322:                 },
 9323:             };
 9324:             my ($outcome,$deloutcome,$new_values,$translation) =
 9325:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 9326:             return $outcome;
 9327:         }
 9328:     } else {
 9329:         return 'invalid';
 9330:     }
 9331: }
 9332: 
 9333: #------------------------------------------------------Get Marked as Read Only
 9334: 
 9335: sub get_marked_as_readonly {
 9336:     my ($domain,$user,$what,$group) = @_;
 9337:     my $current_permissions = &get_portfile_permissions($domain,$user);
 9338:     my @readonly_files;
 9339:     my $cmp1=$what;
 9340:     if (ref($what)) { $cmp1=join('',@{$what}) };
 9341:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 9342:         if (defined($group)) {
 9343:             if ($file_name !~ m-^\Q$group\E/-) {
 9344:                 next;
 9345:             }
 9346:         }
 9347:         if (ref($value) eq "ARRAY"){
 9348:             foreach my $stored_what (@{$value}) {
 9349:                 my $cmp2=$stored_what;
 9350:                 if (ref($stored_what) eq 'ARRAY') {
 9351:                     $cmp2=join('',@{$stored_what});
 9352:                 }
 9353:                 if ($cmp1 eq $cmp2) {
 9354:                     push(@readonly_files, $file_name);
 9355:                     last;
 9356:                 } elsif (!defined($what)) {
 9357:                     push(@readonly_files, $file_name);
 9358:                     last;
 9359:                 }
 9360:             }
 9361:         }
 9362:     }
 9363:     return @readonly_files;
 9364: }
 9365: #-----------------------------------------------------------Get Marked as Read Only Hash
 9366: 
 9367: sub get_marked_as_readonly_hash {
 9368:     my ($current_permissions,$group,$what) = @_;
 9369:     my %readonly_files;
 9370:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 9371:         if (defined($group)) {
 9372:             if ($file_name !~ m-^\Q$group\E/-) {
 9373:                 next;
 9374:             }
 9375:         }
 9376:         if (ref($value) eq "ARRAY"){
 9377:             foreach my $stored_what (@{$value}) {
 9378:                 if (ref($stored_what) eq 'ARRAY') {
 9379:                     foreach my $lock_descriptor(@{$stored_what}) {
 9380:                         if ($lock_descriptor eq 'graded') {
 9381:                             $readonly_files{$file_name} = 'graded';
 9382:                         } elsif ($lock_descriptor eq 'handback') {
 9383:                             $readonly_files{$file_name} = 'handback';
 9384:                         } else {
 9385:                             if (!exists($readonly_files{$file_name})) {
 9386:                                 $readonly_files{$file_name} = 'locked';
 9387:                             }
 9388:                         }
 9389:                     }
 9390:                 } 
 9391:             }
 9392:         } 
 9393:     }
 9394:     return %readonly_files;
 9395: }
 9396: # ------------------------------------------------------------ Unmark as Read Only
 9397: 
 9398: sub unmark_as_readonly {
 9399:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 9400:     # for portfolio submissions, $what contains [$symb,$crsid] 
 9401:     my ($domain,$user,$what,$file_name,$group) = @_;
 9402:     $file_name = &declutter_portfile($file_name);
 9403:     my $symb_crs = $what;
 9404:     if (ref($what)) { $symb_crs=join('',@$what); }
 9405:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 9406:     my ($tmp)=keys(%current_permissions);
 9407:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9408:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 9409:     foreach my $file (@readonly_files) {
 9410: 	my $clean_file = &declutter_portfile($file);
 9411: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 9412: 	my $current_locks = $current_permissions{$file};
 9413:         my @new_locks;
 9414:         my @del_keys;
 9415:         if (ref($current_locks) eq "ARRAY"){
 9416:             foreach my $locker (@{$current_locks}) {
 9417:                 my $compare=$locker;
 9418:                 if (ref($locker) eq 'ARRAY') {
 9419:                     $compare=join('',@{$locker});
 9420:                     if ($compare ne $symb_crs) {
 9421:                         push(@new_locks, $locker);
 9422:                     }
 9423:                 }
 9424:             }
 9425:             if (scalar(@new_locks) > 0) {
 9426:                 $current_permissions{$file} = \@new_locks;
 9427:             } else {
 9428:                 push(@del_keys, $file);
 9429:                 &del('file_permissions',\@del_keys, $domain, $user);
 9430:                 delete($current_permissions{$file});
 9431:             }
 9432:         }
 9433:     }
 9434:     &put('file_permissions',\%current_permissions,$domain,$user);
 9435:     return;
 9436: }
 9437: 
 9438: # ------------------------------------------------------------ Directory lister
 9439: 
 9440: sub dirlist {
 9441:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 9442:     $uri=~s/^\///;
 9443:     $uri=~s/\/$//;
 9444:     my ($udom, $uname);
 9445:     if ($getuserdir) {
 9446:         $udom = $userdomain;
 9447:         $uname = $username;
 9448:     } else {
 9449:         (undef,$udom,$uname)=split(/\//,$uri);
 9450:         if(defined($userdomain)) {
 9451:             $udom = $userdomain;
 9452:         }
 9453:         if(defined($username)) {
 9454:             $uname = $username;
 9455:         }
 9456:     }
 9457:     my ($dirRoot,$listing,@listing_results);
 9458: 
 9459:     $dirRoot = $perlvar{'lonDocRoot'};
 9460:     if (defined($getpropath)) {
 9461:         $dirRoot = &propath($udom,$uname);
 9462:         $dirRoot =~ s/\/$//;
 9463:     } elsif (defined($getuserdir)) {
 9464:         my $subdir=$uname.'__';
 9465:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 9466:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 9467:                    ."/$udom/$subdir/$uname";
 9468:     } elsif (defined($alternateRoot)) {
 9469:         $dirRoot = $alternateRoot;
 9470:     }
 9471: 
 9472:     if($udom) {
 9473:         if($uname) {
 9474:             my $uhome = &homeserver($uname,$udom);
 9475:             if ($uhome eq 'no_host') {
 9476:                 return ([],'no_host');
 9477:             }
 9478:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 9479:                               .$getuserdir.':'.&escape($dirRoot)
 9480:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
 9481:             if ($listing eq 'unknown_cmd') {
 9482:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
 9483:             } else {
 9484:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 9485:             }
 9486:             if ($listing eq 'unknown_cmd') {
 9487:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
 9488:                 @listing_results = split(/:/,$listing);
 9489:             } else {
 9490:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 9491:             }
 9492:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
 9493:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
 9494:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 9495:                 return ([],$listing);
 9496:             } else {
 9497:                 return (\@listing_results);
 9498:             }
 9499:         } elsif(!$alternateRoot) {
 9500:             my (%allusers,%listerror);
 9501: 	    my %servers = &get_servers($udom,'library');
 9502:  	    foreach my $tryserver (keys(%servers)) {
 9503:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 9504:                                   &escape($udom),$tryserver);
 9505:                 if ($listing eq 'unknown_cmd') {
 9506: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 9507: 				      $udom, $tryserver);
 9508:                 } else {
 9509:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 9510:                 }
 9511: 		if ($listing eq 'unknown_cmd') {
 9512: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 9513: 				      $udom, $tryserver);
 9514: 		    @listing_results = split(/:/,$listing);
 9515: 		} else {
 9516: 		    @listing_results =
 9517: 			map { &unescape($_); } split(/:/,$listing);
 9518: 		}
 9519:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
 9520:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
 9521:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 9522:                     $listerror{$tryserver} = $listing;
 9523:                 } else {
 9524: 		    foreach my $line (@listing_results) {
 9525: 			my ($entry) = split(/&/,$line,2);
 9526: 			$allusers{$entry} = 1;
 9527: 		    }
 9528: 		}
 9529:             }
 9530:             my @alluserslist=();
 9531:             foreach my $user (sort(keys(%allusers))) {
 9532:                 push(@alluserslist,$user.'&user');
 9533:             }
 9534:             return (\@alluserslist);
 9535:         } else {
 9536:             return ([],'missing username');
 9537:         }
 9538:     } elsif(!defined($getpropath)) {
 9539:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
 9540:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
 9541:         return (\@all_domains);
 9542:     } else {
 9543:         return ([],'missing domain');
 9544:     }
 9545: }
 9546: 
 9547: # --------------------------------------------- GetFileTimestamp
 9548: # This function utilizes dirlist and returns the date stamp for
 9549: # when it was last modified.  It will also return an error of -1
 9550: # if an error occurs
 9551: 
 9552: sub GetFileTimestamp {
 9553:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 9554:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 9555:     $studentName   = &LONCAPA::clean_username($studentName);
 9556:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
 9557:                                     undef,$getuserdir);
 9558:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 9559:         return -1;
 9560:     }
 9561:     if (ref($fileref) eq 'ARRAY') {
 9562:         my @stats = split('&',$fileref->[0]);
 9563:         # @stats contains first the filename, then the stat output
 9564:         return $stats[10]; # so this is 10 instead of 9.
 9565:     } else {
 9566:         return -1;
 9567:     }
 9568: }
 9569: 
 9570: sub stat_file {
 9571:     my ($uri) = @_;
 9572:     $uri = &clutter_with_no_wrapper($uri);
 9573: 
 9574:     my ($udom,$uname,$file);
 9575:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 9576: 	($udom,$uname,$file) =
 9577: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 9578: 	$file = 'userfiles/'.$file;
 9579:     }
 9580:     if ($uri =~ m-^/res/-) {
 9581: 	($udom,$uname) = 
 9582: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 9583: 	$file = $uri;
 9584:     }
 9585: 
 9586:     if (!$udom || !$uname || !$file) {
 9587: 	# unable to handle the uri
 9588: 	return ();
 9589:     }
 9590:     my $getpropath;
 9591:     if ($file =~ /^userfiles\//) {
 9592:         $getpropath = 1;
 9593:     }
 9594:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
 9595:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 9596:         return ();
 9597:     } else {
 9598:         if (ref($listref) eq 'ARRAY') {
 9599:             my @stats = split('&',$listref->[0]);
 9600: 	    shift(@stats); #filename is first
 9601: 	    return @stats;
 9602:         }
 9603:     }
 9604:     return ();
 9605: }
 9606: 
 9607: # -------------------------------------------------------- Value of a Condition
 9608: 
 9609: # gets the value of a specific preevaluated condition
 9610: #    stored in the string  $env{user.state.<cid>}
 9611: # or looks up a condition reference in the bighash and if if hasn't
 9612: # already been evaluated recurses into docondval to get the value of
 9613: # the condition, then memoizing it to 
 9614: #   $env{user.state.<cid>.<condition>}
 9615: sub directcondval {
 9616:     my $number=shift;
 9617:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 9618: 	&Apache::lonuserstate::evalstate();
 9619:     }
 9620:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 9621: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 9622:     } elsif ($number =~ /^_/) {
 9623: 	my $sub_condition;
 9624: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9625: 		&GDBM_READER(),0640)) {
 9626: 	    $sub_condition=$bighash{'conditions'.$number};
 9627: 	    untie(%bighash);
 9628: 	}
 9629: 	my $value = &docondval($sub_condition);
 9630: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 9631: 	return $value;
 9632:     }
 9633:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 9634:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 9635:     } else {
 9636:        return 2;
 9637:     }
 9638: }
 9639: 
 9640: # get the collection of conditions for this resource
 9641: sub condval {
 9642:     my $condidx=shift;
 9643:     my $allpathcond='';
 9644:     foreach my $cond (split(/\|/,$condidx)) {
 9645: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 9646: 	    $allpathcond.=
 9647: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 9648: 	}
 9649:     }
 9650:     $allpathcond=~s/\|$//;
 9651:     return &docondval($allpathcond);
 9652: }
 9653: 
 9654: #evaluates an expression of conditions
 9655: sub docondval {
 9656:     my ($allpathcond) = @_;
 9657:     my $result=0;
 9658:     if ($env{'request.course.id'}
 9659: 	&& defined($allpathcond)) {
 9660: 	my $operand='|';
 9661: 	my @stack;
 9662: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 9663: 	    if ($chunk eq '(') {
 9664: 		push @stack,($operand,$result);
 9665: 	    } elsif ($chunk eq ')') {
 9666: 		my $before=pop @stack;
 9667: 		if (pop @stack eq '&') {
 9668: 		    $result=$result>$before?$before:$result;
 9669: 		} else {
 9670: 		    $result=$result>$before?$result:$before;
 9671: 		}
 9672: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 9673: 		$operand=$chunk;
 9674: 	    } else {
 9675: 		my $new=directcondval($chunk);
 9676: 		if ($operand eq '&') {
 9677: 		    $result=$result>$new?$new:$result;
 9678: 		} else {
 9679: 		    $result=$result>$new?$result:$new;
 9680: 		}
 9681: 	    }
 9682: 	}
 9683:     }
 9684:     return $result;
 9685: }
 9686: 
 9687: # ---------------------------------------------------- Devalidate courseresdata
 9688: 
 9689: sub devalidatecourseresdata {
 9690:     my ($coursenum,$coursedomain)=@_;
 9691:     my $hashid=$coursenum.':'.$coursedomain;
 9692:     &devalidate_cache_new('courseres',$hashid);
 9693: }
 9694: 
 9695: 
 9696: # --------------------------------------------------- Course Resourcedata Query
 9697: #
 9698: #  Parameters:
 9699: #      $coursenum    - Number of the course.
 9700: #      $coursedomain - Domain at which the course was created.
 9701: #  Returns:
 9702: #     A hash of the course parameters along (I think) with timestamps
 9703: #     and version info.
 9704: 
 9705: sub get_courseresdata {
 9706:     my ($coursenum,$coursedomain)=@_;
 9707:     my $coursehom=&homeserver($coursenum,$coursedomain);
 9708:     my $hashid=$coursenum.':'.$coursedomain;
 9709:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 9710:     my %dumpreply;
 9711:     unless (defined($cached)) {
 9712: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 9713: 	$result=\%dumpreply;
 9714: 	my ($tmp) = keys(%dumpreply);
 9715: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9716: 	    &do_cache_new('courseres',$hashid,$result,600);
 9717: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 9718: 	    return $tmp;
 9719: 	} elsif ($tmp =~ /^(error)/) {
 9720: 	    $result=undef;
 9721: 	    &do_cache_new('courseres',$hashid,$result,600);
 9722: 	}
 9723:     }
 9724:     return $result;
 9725: }
 9726: 
 9727: sub devalidateuserresdata {
 9728:     my ($uname,$udom)=@_;
 9729:     my $hashid="$udom:$uname";
 9730:     &devalidate_cache_new('userres',$hashid);
 9731: }
 9732: 
 9733: sub get_userresdata {
 9734:     my ($uname,$udom)=@_;
 9735:     #most student don\'t have any data set, check if there is some data
 9736:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 9737: 
 9738:     my $hashid="$udom:$uname";
 9739:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 9740:     if (!defined($cached)) {
 9741: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 9742: 	$result=\%resourcedata;
 9743: 	&do_cache_new('userres',$hashid,$result,600);
 9744:     }
 9745:     my ($tmp)=keys(%$result);
 9746:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 9747: 	return $result;
 9748:     }
 9749:     #error 2 occurs when the .db doesn't exist
 9750:     if ($tmp!~/error: 2 /) {
 9751: 	&logthis("<font color=\"blue\">WARNING:".
 9752: 		 " Trying to get resource data for ".
 9753: 		 $uname." at ".$udom.": ".
 9754: 		 $tmp."</font>");
 9755:     } elsif ($tmp=~/error: 2 /) {
 9756: 	#&EXT_cache_set($udom,$uname);
 9757: 	&do_cache_new('userres',$hashid,undef,600);
 9758: 	undef($tmp); # not really an error so don't send it back
 9759:     }
 9760:     return $tmp;
 9761: }
 9762: #----------------------------------------------- resdata - return resource data
 9763: #  Purpose:
 9764: #    Return resource data for either users or for a course.
 9765: #  Parameters:
 9766: #     $name      - Course/user name.
 9767: #     $domain    - Name of the domain the user/course is registered on.
 9768: #     $type      - Type of thing $name is (must be 'course' or 'user'
 9769: #     @which     - Array of names of resources desired.
 9770: #  Returns:
 9771: #     The value of the first reasource in @which that is found in the
 9772: #     resource hash.
 9773: #  Exceptional Conditions:
 9774: #     If the $type passed in is not valid (not the string 'course' or 
 9775: #     'user', an undefined  reference is returned.
 9776: #     If none of the resources are found, an undef is returned
 9777: sub resdata {
 9778:     my ($name,$domain,$type,@which)=@_;
 9779:     my $result;
 9780:     if ($type eq 'course') {
 9781: 	$result=&get_courseresdata($name,$domain);
 9782:     } elsif ($type eq 'user') {
 9783: 	$result=&get_userresdata($name,$domain);
 9784:     }
 9785:     if (!ref($result)) { return $result; }    
 9786:     foreach my $item (@which) {
 9787: 	if (defined($result->{$item->[0]})) {
 9788: 	    return [$result->{$item->[0]},$item->[1]];
 9789: 	}
 9790:     }
 9791:     return undef;
 9792: }
 9793: 
 9794: sub get_numsuppfiles {
 9795:     my ($cnum,$cdom,$ignorecache)=@_;
 9796:     my $hashid=$cnum.':'.$cdom;
 9797:     my ($suppcount,$cached);
 9798:     unless ($ignorecache) {
 9799:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
 9800:     }
 9801:     unless (defined($cached)) {
 9802:         my $chome=&homeserver($cnum,$cdom);
 9803:         unless ($chome eq 'no_host') {
 9804:             ($suppcount,my $errors) = (0,0);
 9805:             my $suppmap = 'supplemental.sequence';
 9806:             ($suppcount,$errors) = 
 9807:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
 9808:         }
 9809:         &do_cache_new('suppcount',$hashid,$suppcount,600);
 9810:     }
 9811:     return $suppcount;
 9812: }
 9813: 
 9814: #
 9815: # EXT resource caching routines
 9816: #
 9817: 
 9818: sub clear_EXT_cache_status {
 9819:     &delenv('cache.EXT.');
 9820: }
 9821: 
 9822: sub EXT_cache_status {
 9823:     my ($target_domain,$target_user) = @_;
 9824:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 9825:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 9826:         # We know already the user has no data
 9827:         return 1;
 9828:     } else {
 9829:         return 0;
 9830:     }
 9831: }
 9832: 
 9833: sub EXT_cache_set {
 9834:     my ($target_domain,$target_user) = @_;
 9835:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 9836:     #&appenv({$cachename => time});
 9837: }
 9838: 
 9839: # --------------------------------------------------------- Value of a Variable
 9840: sub EXT {
 9841: 
 9842:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
 9843:     unless ($varname) { return ''; }
 9844:     #get real user name/domain, courseid and symb
 9845:     my $courseid;
 9846:     my $publicuser;
 9847:     if ($symbparm) {
 9848: 	$symbparm=&get_symb_from_alias($symbparm);
 9849:     }
 9850:     if (!($uname && $udom)) {
 9851:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 9852:       if (!$symbparm) {	$symbparm=$cursymb; }
 9853:     } else {
 9854: 	$courseid=$env{'request.course.id'};
 9855:     }
 9856:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 9857:     my $rest;
 9858:     if (defined($therest[0])) {
 9859:        $rest=join('.',@therest);
 9860:     } else {
 9861:        $rest='';
 9862:     }
 9863: 
 9864:     my $qualifierrest=$qualifier;
 9865:     if ($rest) { $qualifierrest.='.'.$rest; }
 9866:     my $spacequalifierrest=$space;
 9867:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 9868:     if ($realm eq 'user') {
 9869: # --------------------------------------------------------------- user.resource
 9870: 	if ($space eq 'resource') {
 9871: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 9872: 		  || defined($Apache::lonhomework::parsing_a_task))
 9873: 		 &&
 9874: 		 ($symbparm eq &symbread()) ) {	
 9875: 		# if we are in the middle of processing the resource the
 9876: 		# get the value we are planning on committing
 9877:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 9878:                     return $Apache::lonhomework::results{$qualifierrest};
 9879:                 } else {
 9880:                     return $Apache::lonhomework::history{$qualifierrest};
 9881:                 }
 9882: 	    } else {
 9883: 		my %restored;
 9884: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 9885: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 9886: 		} else {
 9887: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 9888: 		}
 9889: 		return $restored{$qualifierrest};
 9890: 	    }
 9891: # ----------------------------------------------------------------- user.access
 9892:         } elsif ($space eq 'access') {
 9893: 	    # FIXME - not supporting calls for a specific user
 9894:             return &allowed($qualifier,$rest);
 9895: # ------------------------------------------ user.preferences, user.environment
 9896:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 9897: 	    if (($uname eq $env{'user.name'}) &&
 9898: 		($udom eq $env{'user.domain'})) {
 9899: 		return $env{join('.',('environment',$qualifierrest))};
 9900: 	    } else {
 9901: 		my %returnhash;
 9902: 		if (!$publicuser) {
 9903: 		    %returnhash=&userenvironment($udom,$uname,
 9904: 						 $qualifierrest);
 9905: 		}
 9906: 		return $returnhash{$qualifierrest};
 9907: 	    }
 9908: # ----------------------------------------------------------------- user.course
 9909:         } elsif ($space eq 'course') {
 9910: 	    # FIXME - not supporting calls for a specific user
 9911:             return $env{join('.',('request.course',$qualifier))};
 9912: # ------------------------------------------------------------------- user.role
 9913:         } elsif ($space eq 'role') {
 9914: 	    # FIXME - not supporting calls for a specific user
 9915:             my ($role,$where)=split(/\./,$env{'request.role'});
 9916:             if ($qualifier eq 'value') {
 9917: 		return $role;
 9918:             } elsif ($qualifier eq 'extent') {
 9919:                 return $where;
 9920:             }
 9921: # ----------------------------------------------------------------- user.domain
 9922:         } elsif ($space eq 'domain') {
 9923:             return $udom;
 9924: # ------------------------------------------------------------------- user.name
 9925:         } elsif ($space eq 'name') {
 9926:             return $uname;
 9927: # ---------------------------------------------------- Any other user namespace
 9928:         } else {
 9929: 	    my %reply;
 9930: 	    if (!$publicuser) {
 9931: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 9932: 	    }
 9933: 	    return $reply{$qualifierrest};
 9934:         }
 9935:     } elsif ($realm eq 'query') {
 9936: # ---------------------------------------------- pull stuff out of query string
 9937:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 9938: 						[$spacequalifierrest]);
 9939: 	return $env{'form.'.$spacequalifierrest}; 
 9940:    } elsif ($realm eq 'request') {
 9941: # ------------------------------------------------------------- request.browser
 9942:         if ($space eq 'browser') {
 9943:             return $env{'browser.'.$qualifier};
 9944: # ------------------------------------------------------------ request.filename
 9945:         } else {
 9946:             return $env{'request.'.$spacequalifierrest};
 9947:         }
 9948:     } elsif ($realm eq 'course') {
 9949: # ---------------------------------------------------------- course.description
 9950:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 9951:     } elsif ($realm eq 'resource') {
 9952: 
 9953: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 9954: 	    if (!$symbparm) { $symbparm=&symbread(); }
 9955: 	}
 9956: 
 9957:         if ($qualifier eq '') {
 9958: 	    if ($space eq 'title') {
 9959: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 9960: 	        return &gettitle($symbparm);
 9961: 	    }
 9962: 	
 9963: 	    if ($space eq 'map') {
 9964: 	        my ($map) = &decode_symb($symbparm);
 9965: 	        return &symbread($map);
 9966: 	    }
 9967:             if ($space eq 'maptitle') {
 9968:                 my ($map) = &decode_symb($symbparm);
 9969:                 return &gettitle($map);
 9970:             }
 9971: 	    if ($space eq 'filename') {
 9972: 	        if ($symbparm) {
 9973: 		    return &clutter((&decode_symb($symbparm))[2]);
 9974: 	        }
 9975: 	        return &hreflocation('',$env{'request.filename'});
 9976: 	    }
 9977: 
 9978:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
 9979:                 if ($space eq 'visibleparts') {
 9980:                     my $navmap = Apache::lonnavmaps::navmap->new();
 9981:                     my $item;
 9982:                     if (ref($navmap)) {
 9983:                         my $res = $navmap->getBySymb($symbparm);
 9984:                         my $parts = $res->parts();
 9985:                         if (ref($parts) eq 'ARRAY') {
 9986:                             $item = join(',',@{$parts});
 9987:                         }
 9988:                         undef($navmap);
 9989:                     }
 9990:                     return $item;
 9991:                 }
 9992:             }
 9993:         }
 9994: 
 9995: 	my ($section, $group, @groups);
 9996: 	my ($courselevelm,$courselevel);
 9997:         if (($courseid eq '') && ($cid)) {
 9998:             $courseid = $cid;
 9999:         }
10000: 	if (($symbparm && $courseid) && 
10001: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
10002: 
10003: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
10004: 
10005: # ----------------------------------------------------- Cascading lookup scheme
10006: 	    my $symbp=$symbparm;
10007: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
10008: 
10009: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
10010: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
10011: 
10012: 	    if (($env{'user.name'} eq $uname) &&
10013: 		($env{'user.domain'} eq $udom)) {
10014: 		$section=$env{'request.course.sec'};
10015:                 @groups = split(/:/,$env{'request.course.groups'});  
10016:                 @groups=&sort_course_groups($courseid,@groups); 
10017: 	    } else {
10018: 		if (! defined($usection)) {
10019: 		    $section=&getsection($udom,$uname,$courseid);
10020: 		} else {
10021: 		    $section = $usection;
10022: 		}
10023:                 @groups = &get_users_groups($udom,$uname,$courseid);
10024: 	    }
10025: 
10026: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
10027: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
10028: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
10029: 
10030: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
10031: 	    my $courselevelr=$courseid.'.'.$symbparm;
10032: 	    $courselevelm=$courseid.'.'.$mapparm;
10033: 
10034: # ----------------------------------------------------------- first, check user
10035: 
10036: 	    my $userreply=&resdata($uname,$udom,'user',
10037: 				       ([$courselevelr,'resource'],
10038: 					[$courselevelm,'map'     ],
10039: 					[$courselevel, 'course'  ]));
10040: 	    if (defined($userreply)) { return &get_reply($userreply); }
10041: 
10042: # ------------------------------------------------ second, check some of course
10043:             my $coursereply;
10044:             if (@groups > 0) {
10045:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
10046:                                        $mapparm,$spacequalifierrest);
10047:                 if (defined($coursereply)) { return &get_reply($coursereply); }
10048:             }
10049: 
10050: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10051: 				  $env{'course.'.$courseid.'.domain'},
10052: 				  'course',
10053: 				  ([$seclevelr,   'resource'],
10054: 				   [$seclevelm,   'map'     ],
10055: 				   [$seclevel,    'course'  ],
10056: 				   [$courselevelr,'resource']));
10057: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
10058: 
10059: # ------------------------------------------------------ third, check map parms
10060: 	    my %parmhash=();
10061: 	    my $thisparm='';
10062: 	    if (tie(%parmhash,'GDBM_File',
10063: 		    $env{'request.course.fn'}.'_parms.db',
10064: 		    &GDBM_READER(),0640)) {
10065: 		$thisparm=$parmhash{$symbparm};
10066: 		untie(%parmhash);
10067: 	    }
10068: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
10069: 	}
10070: # ------------------------------------------ fourth, look in resource metadata
10071: 
10072: 	$spacequalifierrest=~s/\./\_/;
10073: 	my $filename;
10074: 	if (!$symbparm) { $symbparm=&symbread(); }
10075: 	if ($symbparm) {
10076: 	    $filename=(&decode_symb($symbparm))[2];
10077: 	} else {
10078: 	    $filename=$env{'request.filename'};
10079: 	}
10080: 	my $metadata=&metadata($filename,$spacequalifierrest);
10081: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
10082: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
10083: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
10084: 
10085: # ---------------------------------------------- fourth, look in rest of course
10086: 	if ($symbparm && defined($courseid) && 
10087: 	    $courseid eq $env{'request.course.id'}) {
10088: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10089: 				     $env{'course.'.$courseid.'.domain'},
10090: 				     'course',
10091: 				     ([$courselevelm,'map'   ],
10092: 				      [$courselevel, 'course']));
10093: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
10094: 	}
10095: # ------------------------------------------------------------------ Cascade up
10096: 	unless ($space eq '0') {
10097: 	    my @parts=split(/_/,$space);
10098: 	    my $id=pop(@parts);
10099: 	    my $part=join('_',@parts);
10100: 	    if ($part eq '') { $part='0'; }
10101: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
10102: 				 $symbparm,$udom,$uname,$section,1);
10103: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
10104: 	}
10105: 	if ($recurse) { return undef; }
10106: 	my $pack_def=&packages_tab_default($filename,$varname);
10107: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
10108: # ---------------------------------------------------- Any other user namespace
10109:     } elsif ($realm eq 'environment') {
10110: # ----------------------------------------------------------------- environment
10111: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
10112: 	    return $env{'environment.'.$spacequalifierrest};
10113: 	} else {
10114: 	    if ($uname eq 'anonymous' && $udom eq '') {
10115: 		return '';
10116: 	    }
10117: 	    my %returnhash=&userenvironment($udom,$uname,
10118: 					    $spacequalifierrest);
10119: 	    return $returnhash{$spacequalifierrest};
10120: 	}
10121:     } elsif ($realm eq 'system') {
10122: # ----------------------------------------------------------------- system.time
10123: 	if ($space eq 'time') {
10124: 	    return time;
10125:         }
10126:     } elsif ($realm eq 'server') {
10127: # ----------------------------------------------------------------- system.time
10128: 	if ($space eq 'name') {
10129: 	    return $ENV{'SERVER_NAME'};
10130:         }
10131:     }
10132:     return '';
10133: }
10134: 
10135: sub get_reply {
10136:     my ($reply_value) = @_;
10137:     if (ref($reply_value) eq 'ARRAY') {
10138:         if (wantarray) {
10139: 	    return @$reply_value;
10140:         }
10141:         return $reply_value->[0];
10142:     } else {
10143:         return $reply_value;
10144:     }
10145: }
10146: 
10147: sub check_group_parms {
10148:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10149:     my @groupitems = ();
10150:     my $resultitem;
10151:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
10152:     foreach my $group (@{$groups}) {
10153:         foreach my $level (@levels) {
10154:              my $item = $courseid.'.['.$group.'].'.$level->[0];
10155:              push(@groupitems,[$item,$level->[1]]);
10156:         }
10157:     }
10158:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10159:                             $env{'course.'.$courseid.'.domain'},
10160:                                      'course',@groupitems);
10161:     return $coursereply;
10162: }
10163: 
10164: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
10165:     my ($courseid,@groups) = @_;
10166:     @groups = sort(@groups);
10167:     return @groups;
10168: }
10169: 
10170: sub packages_tab_default {
10171:     my ($uri,$varname)=@_;
10172:     my (undef,$part,$name)=split(/\./,$varname);
10173: 
10174:     my (@extension,@specifics,$do_default);
10175:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
10176: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
10177: 	if ($pack_type eq 'default') {
10178: 	    $do_default=1;
10179: 	} elsif ($pack_type eq 'extension') {
10180: 	    push(@extension,[$package,$pack_type,$pack_part]);
10181: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
10182: 	    # only look at packages defaults for packages that this id is
10183: 	    push(@specifics,[$package,$pack_type,$pack_part]);
10184: 	}
10185:     }
10186:     # first look for a package that matches the requested part id
10187:     foreach my $package (@specifics) {
10188: 	my (undef,$pack_type,$pack_part)=@{$package};
10189: 	next if ($pack_part ne $part);
10190: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10191: 	    return $packagetab{"$pack_type&$name&default"};
10192: 	}
10193:     }
10194:     # look for any possible matching non extension_ package
10195:     foreach my $package (@specifics) {
10196: 	my (undef,$pack_type,$pack_part)=@{$package};
10197: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10198: 	    return $packagetab{"$pack_type&$name&default"};
10199: 	}
10200: 	if ($pack_type eq 'part') { $pack_part='0'; }
10201: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10202: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
10203: 	}
10204:     }
10205:     # look for any posible extension_ match
10206:     foreach my $package (@extension) {
10207: 	my ($package,$pack_type)=@{$package};
10208: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10209: 	    return $packagetab{"$pack_type&$name&default"};
10210: 	}
10211: 	if (defined($packagetab{$package."&$name&default"})) {
10212: 	    return $packagetab{$package."&$name&default"};
10213: 	}
10214:     }
10215:     # look for a global default setting
10216:     if ($do_default && defined($packagetab{"default&$name&default"})) {
10217: 	return $packagetab{"default&$name&default"};
10218:     }
10219:     return undef;
10220: }
10221: 
10222: sub add_prefix_and_part {
10223:     my ($prefix,$part)=@_;
10224:     my $keyroot;
10225:     if (defined($prefix) && $prefix !~ /^__/) {
10226: 	# prefix that has a part already
10227: 	$keyroot=$prefix;
10228:     } elsif (defined($prefix)) {
10229: 	# prefix that is missing a part
10230: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10231:     } else {
10232: 	# no prefix at all
10233: 	if (defined($part)) { $keyroot='_'.$part; }
10234:     }
10235:     return $keyroot;
10236: }
10237: 
10238: # ---------------------------------------------------------------- Get metadata
10239: 
10240: my %metaentry;
10241: my %importedpartids;
10242: sub metadata {
10243:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
10244:     $uri=&declutter($uri);
10245:     # if it is a non metadata possible uri return quickly
10246:     if (($uri eq '') || 
10247: 	(($uri =~ m|^/*adm/|) && 
10248: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
10249:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
10250: 	return undef;
10251:     }
10252:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
10253: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
10254: 	return undef;
10255:     }
10256:     my $filename=$uri;
10257:     $uri=~s/\.meta$//;
10258: #
10259: # Is the metadata already cached?
10260: # Look at timestamp of caching
10261: # Everything is cached by the main uri, libraries are never directly cached
10262: #
10263:     if (!defined($liburi)) {
10264: 	my ($result,$cached)=&is_cached_new('meta',$uri);
10265: 	if (defined($cached)) { return $result->{':'.$what}; }
10266:     }
10267:     {
10268: # Imported parts would go here
10269:         my %importedids=();
10270:         my @origfileimportpartids=();
10271:         my $importedparts=0;
10272: #
10273: # Is this a recursive call for a library?
10274: #
10275: #	if (! exists($metacache{$uri})) {
10276: #	    $metacache{$uri}={};
10277: #	}
10278: 	my $cachetime = 60*60;
10279:         if ($liburi) {
10280: 	    $liburi=&declutter($liburi);
10281:             $filename=$liburi;
10282:         } else {
10283: 	    &devalidate_cache_new('meta',$uri);
10284: 	    undef(%metaentry);
10285: 	}
10286:         my %metathesekeys=();
10287:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
10288: 	my $metastring;
10289: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
10290: 	    my $which = &hreflocation('','/'.($liburi || $uri));
10291: 	    $metastring = 
10292: 		&Apache::lonnet::ssi_body($which,
10293: 					  ('grade_target' => 'meta'));
10294: 	    $cachetime = 1; # only want this cached in the child not long term
10295: 	} elsif (($uri !~ m -^(editupload)/-) && 
10296:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
10297: 	    my $file=&filelocation('',&clutter($filename));
10298: 	    #push(@{$metaentry{$uri.'.file'}},$file);
10299: 	    $metastring=&getfile($file);
10300: 	}
10301:         my $parser=HTML::LCParser->new(\$metastring);
10302:         my $token;
10303:         undef %metathesekeys;
10304:         while ($token=$parser->get_token) {
10305: 	    if ($token->[0] eq 'S') {
10306: 		if (defined($token->[2]->{'package'})) {
10307: #
10308: # This is a package - get package info
10309: #
10310: 		    my $package=$token->[2]->{'package'};
10311: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10312: 		    if (defined($token->[2]->{'id'})) { 
10313: 			$keyroot.='_'.$token->[2]->{'id'}; 
10314: 		    }
10315: 		    if ($metaentry{':packages'}) {
10316: 			$metaentry{':packages'}.=','.$package.$keyroot;
10317: 		    } else {
10318: 			$metaentry{':packages'}=$package.$keyroot;
10319: 		    }
10320: 		    foreach my $pack_entry (keys(%packagetab)) {
10321: 			my $part=$keyroot;
10322: 			$part=~s/^\_//;
10323: 			if ($pack_entry=~/^\Q$package\E\&/ || 
10324: 			    $pack_entry=~/^\Q$package\E_0\&/) {
10325: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
10326: 			    # ignore package.tab specified default values
10327:                             # here &package_tab_default() will fetch those
10328: 			    if ($subp eq 'default') { next; }
10329: 			    my $value=$packagetab{$pack_entry};
10330: 			    my $unikey;
10331: 			    if ($pack =~ /_0$/) {
10332: 				$unikey='parameter_0_'.$name;
10333: 				$part=0;
10334: 			    } else {
10335: 				$unikey='parameter'.$keyroot.'_'.$name;
10336: 			    }
10337: 			    if ($subp eq 'display') {
10338: 				$value.=' [Part: '.$part.']';
10339: 			    }
10340: 			    $metaentry{':'.$unikey.'.part'}=$part;
10341: 			    $metathesekeys{$unikey}=1;
10342: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10343: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
10344: 			    }
10345: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
10346: 				$metaentry{':'.$unikey}=
10347: 				    $metaentry{':'.$unikey.'.default'};
10348: 			    }
10349: 			}
10350: 		    }
10351: 		} else {
10352: #
10353: # This is not a package - some other kind of start tag
10354: #
10355: 		    my $entry=$token->[1];
10356: 		    my $unikey='';
10357: 
10358: 		    if ($entry eq 'import') {
10359: #
10360: # Importing a library here
10361: #
10362:                         my $location=$parser->get_text('/import');
10363:                         my $dir=$filename;
10364:                         $dir=~s|[^/]*$||;
10365:                         $location=&filelocation($dir,$location);
10366:                        
10367:                         my $importmode=$token->[2]->{'importmode'};
10368:                         if ($importmode eq 'problem') {
10369: # Import as problem/response
10370:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10371:                         } elsif ($importmode eq 'part') {
10372: # Import as part(s)
10373:                            $importedparts=1;
10374: # We need to get the original file and the imported file to get the part order correct
10375: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10376: # Load and inspect original file
10377:                            if ($#origfileimportpartids<0) {
10378:                               undef(%importedpartids);
10379:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10380:                               my $origfile=&getfile($origfilelocation);
10381:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10382:                            }
10383: 
10384: # Load and inspect imported file
10385:                            my $impfile=&getfile($location);
10386:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10387:                            if ($#impfilepartids>=0) {
10388: # This problem had parts
10389:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
10390:                            } else {
10391: # Importing by turning a single problem into a problem part
10392: # It gets the import-tags ID as part-ID
10393:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
10394:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
10395:                            }
10396:                         } else {
10397: # Normal import
10398:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10399:                            if (defined($token->[2]->{'id'})) {
10400:                               $unikey.='_'.$token->[2]->{'id'};
10401:                            }
10402:                         }
10403: 
10404: 			if ($depthcount<20) {
10405: 			    my $metadata = 
10406: 				&metadata($uri,'keys', $location,$unikey,
10407: 					  $depthcount+1);
10408: 			    foreach my $meta (split(',',$metadata)) {
10409: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
10410: 				$metathesekeys{$meta}=1;
10411: 			    }
10412: 			
10413:                         }
10414: 		    } else {
10415: #
10416: # Not importing, some other kind of non-package, non-library start tag
10417: # 
10418:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10419:                         if (defined($token->[2]->{'id'})) {
10420:                             $unikey.='_'.$token->[2]->{'id'};
10421:                         }
10422: 			if (defined($token->[2]->{'name'})) { 
10423: 			    $unikey.='_'.$token->[2]->{'name'}; 
10424: 			}
10425: 			$metathesekeys{$unikey}=1;
10426: 			foreach my $param (@{$token->[3]}) {
10427: 			    $metaentry{':'.$unikey.'.'.$param} =
10428: 				$token->[2]->{$param};
10429: 			}
10430: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
10431: 			my $default=$metaentry{':'.$unikey.'.default'};
10432: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10433: 		 # only ws inside the tag, and not in default, so use default
10434: 		 # as value
10435: 			    $metaentry{':'.$unikey}=$default;
10436: 			} elsif ( $internaltext =~ /\S/ ) {
10437: 		  # something interesting inside the tag
10438: 			    $metaentry{':'.$unikey}=$internaltext;
10439: 			} else {
10440: 		  # no interesting values, don't set a default
10441: 			}
10442: # end of not-a-package not-a-library import
10443: 		    }
10444: # end of not-a-package start tag
10445: 		}
10446: # the next is the end of "start tag"
10447: 	    }
10448: 	}
10449: 	my ($extension) = ($uri =~ /\.(\w+)$/);
10450: 	$extension = lc($extension);
10451: 	if ($extension eq 'htm') { $extension='html'; }
10452: 
10453: 	foreach my $key (keys(%packagetab)) {
10454: 	    #no specific packages #how's our extension
10455: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
10456: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
10457: 					 \%metathesekeys);
10458: 	}
10459: 
10460: 	if (!exists($metaentry{':packages'})
10461: 	    || $packagetab{"import_defaults&extension_$extension"}) {
10462: 	    foreach my $key (keys(%packagetab)) {
10463: 		#no specific packages well let's get default then
10464: 		if ($key!~/^default&/) { next; }
10465: 		&metadata_create_package_def($uri,$key,'default',
10466: 					     \%metathesekeys);
10467: 	    }
10468: 	}
10469: # are there custom rights to evaluate
10470: 	if ($metaentry{':copyright'} eq 'custom') {
10471: 
10472:     #
10473:     # Importing a rights file here
10474:     #
10475: 	    unless ($depthcount) {
10476: 		my $location=$metaentry{':customdistributionfile'};
10477: 		my $dir=$filename;
10478: 		$dir=~s|[^/]*$||;
10479: 		$location=&filelocation($dir,$location);
10480: 		my $rights_metadata =
10481: 		    &metadata($uri,'keys',$location,'_rights',
10482: 			      $depthcount+1);
10483: 		foreach my $rights (split(',',$rights_metadata)) {
10484: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10485: 		    $metathesekeys{$rights}=1;
10486: 		}
10487: 	    }
10488: 	}
10489: 	# uniqifiy package listing
10490: 	my %seen;
10491: 	my @uniq_packages =
10492: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10493: 	$metaentry{':packages'} = join(',',@uniq_packages);
10494: 
10495:         if ($importedparts) {
10496: # We had imported parts and need to rebuild partorder
10497:            $metaentry{':partorder'}='';
10498:            $metathesekeys{'partorder'}=1;
10499:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10500:                if ($origfileimportpartids[$index] eq 'part') {
10501: # original part, part of the problem
10502:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10503:                } else {
10504: # we have imported parts at this position
10505:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10506:                }
10507:            }
10508:            $metaentry{':partorder'}=~s/^\,//;
10509:         }
10510: 
10511: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
10512: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
10513: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
10514: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
10515: # this is the end of "was not already recently cached
10516:     }
10517:     return $metaentry{':'.$what};
10518: }
10519: 
10520: sub metadata_create_package_def {
10521:     my ($uri,$key,$package,$metathesekeys)=@_;
10522:     my ($pack,$name,$subp)=split(/\&/,$key);
10523:     if ($subp eq 'default') { next; }
10524:     
10525:     if (defined($metaentry{':packages'})) {
10526: 	$metaentry{':packages'}.=','.$package;
10527:     } else {
10528: 	$metaentry{':packages'}=$package;
10529:     }
10530:     my $value=$packagetab{$key};
10531:     my $unikey;
10532:     $unikey='parameter_0_'.$name;
10533:     $metaentry{':'.$unikey.'.part'}=0;
10534:     $$metathesekeys{$unikey}=1;
10535:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10536: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
10537:     }
10538:     if (defined($metaentry{':'.$unikey.'.default'})) {
10539: 	$metaentry{':'.$unikey}=
10540: 	    $metaentry{':'.$unikey.'.default'};
10541:     }
10542: }
10543: 
10544: sub metadata_generate_part0 {
10545:     my ($metadata,$metacache,$uri) = @_;
10546:     my %allnames;
10547:     foreach my $metakey (keys(%$metadata)) {
10548: 	if ($metakey=~/^parameter\_(.*)/) {
10549: 	  my $part=$$metacache{':'.$metakey.'.part'};
10550: 	  my $name=$$metacache{':'.$metakey.'.name'};
10551: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
10552: 	    $allnames{$name}=$part;
10553: 	  }
10554: 	}
10555:     }
10556:     foreach my $name (keys(%allnames)) {
10557:       $$metadata{"parameter_0_$name"}=1;
10558:       my $key=":parameter_0_$name";
10559:       $$metacache{"$key.part"}='0';
10560:       $$metacache{"$key.name"}=$name;
10561:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
10562: 					   $allnames{$name}.'_'.$name.
10563: 					   '.type'};
10564:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
10565: 			     '.display'};
10566:       my $expr='[Part: '.$allnames{$name}.']';
10567:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
10568:       $$metacache{"$key.display"}=$olddis;
10569:     }
10570: }
10571: 
10572: # ------------------------------------------------------ Devalidate title cache
10573: 
10574: sub devalidate_title_cache {
10575:     my ($url)=@_;
10576:     if (!$env{'request.course.id'}) { return; }
10577:     my $symb=&symbread($url);
10578:     if (!$symb) { return; }
10579:     my $key=$env{'request.course.id'}."\0".$symb;
10580:     &devalidate_cache_new('title',$key);
10581: }
10582: 
10583: # ------------------------------------------------- Get the title of a course
10584: 
10585: sub current_course_title {
10586:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10587: }
10588: # ------------------------------------------------- Get the title of a resource
10589: 
10590: sub gettitle {
10591:     my $urlsymb=shift;
10592:     my $symb=&symbread($urlsymb);
10593:     if ($symb) {
10594: 	my $key=$env{'request.course.id'}."\0".$symb;
10595: 	my ($result,$cached)=&is_cached_new('title',$key);
10596: 	if (defined($cached)) { 
10597: 	    return $result;
10598: 	}
10599: 	my ($map,$resid,$url)=&decode_symb($symb);
10600: 	my $title='';
10601: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10602: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10603: 	} else {
10604: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10605: 		    &GDBM_READER(),0640)) {
10606: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
10607: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
10608: 		untie(%bighash);
10609: 	    }
10610: 	}
10611: 	$title=~s/\&colon\;/\:/gs;
10612: 	if ($title) {
10613: # Remember both $symb and $title for dynamic metadata
10614:             $accesshash{$symb.'___crstitle'}=$title;
10615:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
10616: # Cache this title and then return it
10617: 	    return &do_cache_new('title',$key,$title,600);
10618: 	}
10619: 	$urlsymb=$url;
10620:     }
10621:     my $title=&metadata($urlsymb,'title');
10622:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
10623:     return $title;
10624: }
10625: 
10626: sub get_slot {
10627:     my ($which,$cnum,$cdom)=@_;
10628:     if (!$cnum || !$cdom) {
10629: 	(undef,my $courseid)=&whichuser();
10630: 	$cdom=$env{'course.'.$courseid.'.domain'};
10631: 	$cnum=$env{'course.'.$courseid.'.num'};
10632:     }
10633:     my $key=join("\0",'slots',$cdom,$cnum,$which);
10634:     my %slotinfo;
10635:     if (exists($remembered{$key})) {
10636: 	$slotinfo{$which} = $remembered{$key};
10637:     } else {
10638: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
10639: 	&Apache::lonhomework::showhash(%slotinfo);
10640: 	my ($tmp)=keys(%slotinfo);
10641: 	if ($tmp=~/^error:/) { return (); }
10642: 	$remembered{$key} = $slotinfo{$which};
10643:     }
10644:     if (ref($slotinfo{$which}) eq 'HASH') {
10645: 	return %{$slotinfo{$which}};
10646:     }
10647:     return $slotinfo{$which};
10648: }
10649: 
10650: sub get_reservable_slots {
10651:     my ($cnum,$cdom,$uname,$udom) = @_;
10652:     my $now = time;
10653:     my $reservable_info;
10654:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10655:     if (exists($remembered{$key})) {
10656:         $reservable_info = $remembered{$key};
10657:     } else {
10658:         my %resv;
10659:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10660:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10661:         $reservable_info = \%resv;
10662:         $remembered{$key} = $reservable_info;
10663:     }
10664:     return $reservable_info;
10665: }
10666: 
10667: sub get_course_slots {
10668:     my ($cnum,$cdom) = @_;
10669:     my $hashid=$cnum.':'.$cdom;
10670:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10671:     if (defined($cached)) {
10672:         if (ref($result) eq 'HASH') {
10673:             return %{$result};
10674:         }
10675:     } else {
10676:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10677:         my ($tmp) = keys(%slots);
10678:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10679:             &do_cache_new('allslots',$hashid,\%slots,600);
10680:             return %slots;
10681:         }
10682:     }
10683:     return;
10684: }
10685: 
10686: sub devalidate_slots_cache {
10687:     my ($cnum,$cdom)=@_;
10688:     my $hashid=$cnum.':'.$cdom;
10689:     &devalidate_cache_new('allslots',$hashid);
10690: }
10691: 
10692: sub get_coursechange {
10693:     my ($cdom,$cnum) = @_;
10694:     if ($cdom eq '' || $cnum eq '') {
10695:         return unless ($env{'request.course.id'});
10696:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10697:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10698:     }
10699:     my $hashid=$cdom.'_'.$cnum;
10700:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
10701:     if ((defined($cached)) && ($change ne '')) {
10702:         return $change;
10703:     } else {
10704:         my %crshash;
10705:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10706:         if ($crshash{'internal.contentchange'} eq '') {
10707:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
10708:             if ($change eq '') {
10709:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
10710:                 $change = $crshash{'internal.created'};
10711:             }
10712:         } else {
10713:             $change = $crshash{'internal.contentchange'};
10714:         }
10715:         my $cachetime = 600;
10716:         &do_cache_new('crschange',$hashid,$change,$cachetime);
10717:     }
10718:     return $change;
10719: }
10720: 
10721: sub devalidate_coursechange_cache {
10722:     my ($cnum,$cdom)=@_;
10723:     my $hashid=$cnum.':'.$cdom;
10724:     &devalidate_cache_new('crschange',$hashid);
10725: }
10726: 
10727: # ------------------------------------------------- Update symbolic store links
10728: 
10729: sub symblist {
10730:     my ($mapname,%newhash)=@_;
10731:     $mapname=&deversion(&declutter($mapname));
10732:     my %hash;
10733:     if (($env{'request.course.fn'}) && (%newhash)) {
10734:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10735:                       &GDBM_WRCREAT(),0640)) {
10736: 	    foreach my $url (keys(%newhash)) {
10737: 		next if ($url eq 'last_known'
10738: 			 && $env{'form.no_update_last_known'});
10739: 		$hash{declutter($url)}=&encode_symb($mapname,
10740: 						    $newhash{$url}->[1],
10741: 						    $newhash{$url}->[0]);
10742:             }
10743:             if (untie(%hash)) {
10744: 		return 'ok';
10745:             }
10746:         }
10747:     }
10748:     return 'error';
10749: }
10750: 
10751: # --------------------------------------------------------------- Verify a symb
10752: 
10753: sub symbverify {
10754:     my ($symb,$thisurl,$encstate)=@_;
10755:     my $thisfn=$thisurl;
10756:     $thisfn=&declutter($thisfn);
10757: # direct jump to resource in page or to a sequence - will construct own symbs
10758:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10759: # check URL part
10760:     my ($map,$resid,$url)=&decode_symb($symb);
10761: 
10762:     unless ($url eq $thisfn) { return 0; }
10763: 
10764:     $symb=&symbclean($symb);
10765:     $thisurl=&deversion($thisurl);
10766:     $thisfn=&deversion($thisfn);
10767: 
10768:     my %bighash;
10769:     my $okay=0;
10770: 
10771:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10772:                             &GDBM_READER(),0640)) {
10773:         my $noclutter;
10774:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10775:             $thisurl =~ s/\?.+$//;
10776:             if ($map =~ m{^uploaded/.+\.page$}) {
10777:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
10778:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
10779:                 $noclutter = 1;
10780:             }
10781:         }
10782:         my $ids;
10783:         if ($noclutter) {
10784:             $ids=$bighash{'ids_'.$thisurl};
10785:         } else {
10786:             $ids=$bighash{'ids_'.&clutter($thisurl)};
10787:         }
10788:         unless ($ids) {
10789:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
10790:             $ids=$bighash{$idkey};
10791:         }
10792:         if ($ids) {
10793: # ------------------------------------------------------------------- Has ID(s)
10794:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
10795:                 $symb =~ s/\?.+$//;
10796:             }
10797: 	    foreach my $id (split(/\,/,$ids)) {
10798: 	       my ($mapid,$resid)=split(/\./,$id);
10799:                if (
10800:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
10801:    eq $symb) {
10802:                    if (ref($encstate)) {
10803:                        $$encstate = $bighash{'encrypted_'.$id};
10804:                    }
10805: 		   if (($env{'request.role.adv'}) ||
10806: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
10807:                        ($thisurl eq '/adm/navmaps')) {
10808: 		       $okay=1;
10809:                        last;
10810: 		   }
10811: 	       }
10812: 	   }
10813:         }
10814: 	untie(%bighash);
10815:     }
10816:     return $okay;
10817: }
10818: 
10819: # --------------------------------------------------------------- Clean-up symb
10820: 
10821: sub symbclean {
10822:     my $symb=shift;
10823:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10824: # remove version from map
10825:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
10826: 
10827: # remove version from URL
10828:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
10829: 
10830: # remove wrapper
10831: 
10832:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
10833:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
10834:     return $symb;
10835: }
10836: 
10837: # ---------------------------------------------- Split symb to find map and url
10838: 
10839: sub encode_symb {
10840:     my ($map,$resid,$url)=@_;
10841:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
10842: }
10843: 
10844: sub decode_symb {
10845:     my $symb=shift;
10846:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10847:     my ($map,$resid,$url)=split(/___/,$symb);
10848:     return (&fixversion($map),$resid,&fixversion($url));
10849: }
10850: 
10851: sub fixversion {
10852:     my $fn=shift;
10853:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
10854:     my %bighash;
10855:     my $uri=&clutter($fn);
10856:     my $key=$env{'request.course.id'}.'_'.$uri;
10857: # is this cached?
10858:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
10859:     if (defined($cached)) { return $result; }
10860: # unfortunately not cached, or expired
10861:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10862: 	    &GDBM_READER(),0640)) {
10863:  	if ($bighash{'version_'.$uri}) {
10864:  	    my $version=$bighash{'version_'.$uri};
10865:  	    unless (($version eq 'mostrecent') || 
10866: 		    ($version==&getversion($uri))) {
10867:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
10868:  	    }
10869:  	}
10870:  	untie %bighash;
10871:     }
10872:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
10873: }
10874: 
10875: sub deversion {
10876:     my $url=shift;
10877:     $url=~s/\.\d+\.(\w+)$/\.$1/;
10878:     return $url;
10879: }
10880: 
10881: # ------------------------------------------------------ Return symb list entry
10882: 
10883: sub symbread {
10884:     my ($thisfn,$donotrecurse)=@_;
10885:     my $cache_str='request.symbread.cached.'.$thisfn;
10886:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
10887: # no filename provided? try from environment
10888:     unless ($thisfn) {
10889:         if ($env{'request.symb'}) {
10890: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
10891: 	}
10892: 	$thisfn=$env{'request.filename'};
10893:     }
10894:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
10895: # is that filename actually a symb? Verify, clean, and return
10896:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
10897: 	if (&symbverify($thisfn,$1)) {
10898: 	    return $env{$cache_str}=&symbclean($thisfn);
10899: 	}
10900:     }
10901:     $thisfn=declutter($thisfn);
10902:     my %hash;
10903:     my %bighash;
10904:     my $syval='';
10905:     if (($env{'request.course.fn'}) && ($thisfn)) {
10906:         my $targetfn = $thisfn;
10907:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
10908:             $targetfn = 'adm/wrapper/'.$thisfn;
10909:         }
10910: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
10911: 	    $targetfn=$1;
10912: 	}
10913:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10914:                       &GDBM_READER(),0640)) {
10915: 	    $syval=$hash{$targetfn};
10916:             untie(%hash);
10917:         }
10918: # ---------------------------------------------------------- There was an entry
10919:         if ($syval) {
10920: 	    #unless ($syval=~/\_\d+$/) {
10921: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
10922: 		    #&appenv({'request.ambiguous' => $thisfn});
10923: 		    #return $env{$cache_str}='';
10924: 		#}    
10925: 		#$syval.=$1;
10926: 	    #}
10927:         } else {
10928: # ------------------------------------------------------- Was not in symb table
10929:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10930:                             &GDBM_READER(),0640)) {
10931: # ---------------------------------------------- Get ID(s) for current resource
10932:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
10933:               unless ($ids) { 
10934:                  $ids=$bighash{'ids_/'.$thisfn};
10935:               }
10936:               unless ($ids) {
10937: # alias?
10938: 		  $ids=$bighash{'mapalias_'.$thisfn};
10939:               }
10940:               if ($ids) {
10941: # ------------------------------------------------------------------- Has ID(s)
10942:                  my @possibilities=split(/\,/,$ids);
10943:                  if ($#possibilities==0) {
10944: # ----------------------------------------------- There is only one possibility
10945: 		     my ($mapid,$resid)=split(/\./,$ids);
10946: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
10947: 						    $resid,$thisfn);
10948:                  } elsif (!$donotrecurse) {
10949: # ------------------------------------------ There is more than one possibility
10950:                      my $realpossible=0;
10951:                      foreach my $id (@possibilities) {
10952: 			 my $file=$bighash{'src_'.$id};
10953:                          if (&allowed('bre',$file)) {
10954:          		    my ($mapid,$resid)=split(/\./,$id);
10955:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
10956: 				$realpossible++;
10957:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
10958: 						    $resid,$thisfn);
10959:                             }
10960: 			 }
10961:                      }
10962: 		     if ($realpossible!=1) { $syval=''; }
10963:                  } else {
10964:                      $syval='';
10965:                  }
10966: 	      }
10967:               untie(%bighash)
10968:            }
10969:         }
10970:         if ($syval) {
10971: 	    return $env{$cache_str}=$syval;
10972:         }
10973:     }
10974:     &appenv({'request.ambiguous' => $thisfn});
10975:     return $env{$cache_str}='';
10976: }
10977: 
10978: # ---------------------------------------------------------- Return random seed
10979: 
10980: sub numval {
10981:     my $txt=shift;
10982:     $txt=~tr/A-J/0-9/;
10983:     $txt=~tr/a-j/0-9/;
10984:     $txt=~tr/K-T/0-9/;
10985:     $txt=~tr/k-t/0-9/;
10986:     $txt=~tr/U-Z/0-5/;
10987:     $txt=~tr/u-z/0-5/;
10988:     $txt=~s/\D//g;
10989:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
10990:     return int($txt);
10991: }
10992: 
10993: sub numval2 {
10994:     my $txt=shift;
10995:     $txt=~tr/A-J/0-9/;
10996:     $txt=~tr/a-j/0-9/;
10997:     $txt=~tr/K-T/0-9/;
10998:     $txt=~tr/k-t/0-9/;
10999:     $txt=~tr/U-Z/0-5/;
11000:     $txt=~tr/u-z/0-5/;
11001:     $txt=~s/\D//g;
11002:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11003:     my $total;
11004:     foreach my $val (@txts) { $total+=$val; }
11005:     if ($_64bit) { if ($total > 2**32) { return -1; } }
11006:     return int($total);
11007: }
11008: 
11009: sub numval3 {
11010:     use integer;
11011:     my $txt=shift;
11012:     $txt=~tr/A-J/0-9/;
11013:     $txt=~tr/a-j/0-9/;
11014:     $txt=~tr/K-T/0-9/;
11015:     $txt=~tr/k-t/0-9/;
11016:     $txt=~tr/U-Z/0-5/;
11017:     $txt=~tr/u-z/0-5/;
11018:     $txt=~s/\D//g;
11019:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11020:     my $total;
11021:     foreach my $val (@txts) { $total+=$val; }
11022:     if ($_64bit) { $total=(($total<<32)>>32); }
11023:     return $total;
11024: }
11025: 
11026: sub digest {
11027:     my ($data)=@_;
11028:     my $digest=&Digest::MD5::md5($data);
11029:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
11030:     my ($e,$f);
11031:     {
11032:         use integer;
11033:         $e=($a+$b);
11034:         $f=($c+$d);
11035:         if ($_64bit) {
11036:             $e=(($e<<32)>>32);
11037:             $f=(($f<<32)>>32);
11038:         }
11039:     }
11040:     if (wantarray) {
11041: 	return ($e,$f);
11042:     } else {
11043: 	my $g;
11044: 	{
11045: 	    use integer;
11046: 	    $g=($e+$f);
11047: 	    if ($_64bit) {
11048: 		$g=(($g<<32)>>32);
11049: 	    }
11050: 	}
11051: 	return $g;
11052:     }
11053: }
11054: 
11055: sub latest_rnd_algorithm_id {
11056:     return '64bit5';
11057: }
11058: 
11059: sub get_rand_alg {
11060:     my ($courseid)=@_;
11061:     if (!$courseid) { $courseid=(&whichuser())[1]; }
11062:     if ($courseid) {
11063: 	return $env{"course.$courseid.rndseed"};
11064:     }
11065:     return &latest_rnd_algorithm_id();
11066: }
11067: 
11068: sub validCODE {
11069:     my ($CODE)=@_;
11070:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
11071:     return 0;
11072: }
11073: 
11074: sub getCODE {
11075:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
11076:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
11077: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
11078: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
11079: 	return $Apache::lonhomework::history{'resource.CODE'};
11080:     }
11081:     return undef;
11082: }
11083: #
11084: #  Determines the random seed for a specific context:
11085: #
11086: # parameters:
11087: #   symb      - in course context the symb for the seed.
11088: #   course_id - The course id of the form domain_coursenum.
11089: #   domain    - Domain for the user.
11090: #   course    - Course for the user.
11091: #   cenv      - environment of the course.
11092: #
11093: # NOTE:
11094: #   All parameters are picked out of the environment if missing
11095: #   or not defined.
11096: #   If a symb cannot be determined the current time is used instead.
11097: #
11098: #  For a given well defined symb, courside, domain, username,
11099: #  and course environment, the seed is reproducible.
11100: #
11101: sub rndseed {
11102:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
11103:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
11104:     if (!defined($symb)) {
11105: 	unless ($symb=$wsymb) { return time; }
11106:     }
11107:     if (!defined $courseid) { 
11108: 	$courseid=$wcourseid; 
11109:     }
11110:     if (!defined $domain) { $domain=$wdomain; }
11111:     if (!defined $username) { $username=$wusername }
11112: 
11113:     my $which;
11114:     if (defined($cenv->{'rndseed'})) {
11115: 	$which = $cenv->{'rndseed'};
11116:     } else {
11117: 	$which =&get_rand_alg($courseid);
11118:     }
11119:     if (defined(&getCODE())) {
11120: 
11121: 	if ($which eq '64bit5') {
11122: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
11123: 	} elsif ($which eq '64bit4') {
11124: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
11125: 	} else {
11126: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
11127: 	}
11128:     } elsif ($which eq '64bit5') {
11129: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
11130:     } elsif ($which eq '64bit4') {
11131: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
11132:     } elsif ($which eq '64bit3') {
11133: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
11134:     } elsif ($which eq '64bit2') {
11135: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
11136:     } elsif ($which eq '64bit') {
11137: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
11138:     }
11139:     return &rndseed_32bit($symb,$courseid,$domain,$username);
11140: }
11141: 
11142: sub rndseed_32bit {
11143:     my ($symb,$courseid,$domain,$username)=@_;
11144:     {
11145: 	use integer;
11146: 	my $symbchck=unpack("%32C*",$symb) << 27;
11147: 	my $symbseed=numval($symb) << 22;
11148: 	my $namechck=unpack("%32C*",$username) << 17;
11149: 	my $nameseed=numval($username) << 12;
11150: 	my $domainseed=unpack("%32C*",$domain) << 7;
11151: 	my $courseseed=unpack("%32C*",$courseid);
11152: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
11153: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11154: 	#&logthis("rndseed :$num:$symb");
11155: 	if ($_64bit) { $num=(($num<<32)>>32); }
11156: 	return $num;
11157:     }
11158: }
11159: 
11160: sub rndseed_64bit {
11161:     my ($symb,$courseid,$domain,$username)=@_;
11162:     {
11163: 	use integer;
11164: 	my $symbchck=unpack("%32S*",$symb) << 21;
11165: 	my $symbseed=numval($symb) << 10;
11166: 	my $namechck=unpack("%32S*",$username);
11167: 	
11168: 	my $nameseed=numval($username) << 21;
11169: 	my $domainseed=unpack("%32S*",$domain) << 10;
11170: 	my $courseseed=unpack("%32S*",$courseid);
11171: 	
11172: 	my $num1=$symbchck+$symbseed+$namechck;
11173: 	my $num2=$nameseed+$domainseed+$courseseed;
11174: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11175: 	#&logthis("rndseed :$num:$symb");
11176: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11177: 	return "$num1,$num2";
11178:     }
11179: }
11180: 
11181: sub rndseed_64bit2 {
11182:     my ($symb,$courseid,$domain,$username)=@_;
11183:     {
11184: 	use integer;
11185: 	# strings need to be an even # of cahracters long, it it is odd the
11186:         # last characters gets thrown away
11187: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11188: 	my $symbseed=numval($symb) << 10;
11189: 	my $namechck=unpack("%32S*",$username.' ');
11190: 	
11191: 	my $nameseed=numval($username) << 21;
11192: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11193: 	my $courseseed=unpack("%32S*",$courseid.' ');
11194: 	
11195: 	my $num1=$symbchck+$symbseed+$namechck;
11196: 	my $num2=$nameseed+$domainseed+$courseseed;
11197: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11198: 	#&logthis("rndseed :$num:$symb");
11199: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11200: 	return "$num1,$num2";
11201:     }
11202: }
11203: 
11204: sub rndseed_64bit3 {
11205:     my ($symb,$courseid,$domain,$username)=@_;
11206:     {
11207: 	use integer;
11208: 	# strings need to be an even # of cahracters long, it it is odd the
11209:         # last characters gets thrown away
11210: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11211: 	my $symbseed=numval2($symb) << 10;
11212: 	my $namechck=unpack("%32S*",$username.' ');
11213: 	
11214: 	my $nameseed=numval2($username) << 21;
11215: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11216: 	my $courseseed=unpack("%32S*",$courseid.' ');
11217: 	
11218: 	my $num1=$symbchck+$symbseed+$namechck;
11219: 	my $num2=$nameseed+$domainseed+$courseseed;
11220: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11221: 	#&logthis("rndseed :$num1:$num2:$_64bit");
11222: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11223: 	
11224: 	return "$num1:$num2";
11225:     }
11226: }
11227: 
11228: sub rndseed_64bit4 {
11229:     my ($symb,$courseid,$domain,$username)=@_;
11230:     {
11231: 	use integer;
11232: 	# strings need to be an even # of cahracters long, it it is odd the
11233:         # last characters gets thrown away
11234: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11235: 	my $symbseed=numval3($symb) << 10;
11236: 	my $namechck=unpack("%32S*",$username.' ');
11237: 	
11238: 	my $nameseed=numval3($username) << 21;
11239: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11240: 	my $courseseed=unpack("%32S*",$courseid.' ');
11241: 	
11242: 	my $num1=$symbchck+$symbseed+$namechck;
11243: 	my $num2=$nameseed+$domainseed+$courseseed;
11244: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11245: 	#&logthis("rndseed :$num1:$num2:$_64bit");
11246: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11247: 	
11248: 	return "$num1:$num2";
11249:     }
11250: }
11251: 
11252: sub rndseed_64bit5 {
11253:     my ($symb,$courseid,$domain,$username)=@_;
11254:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11255:     return "$num1:$num2";
11256: }
11257: 
11258: sub rndseed_CODE_64bit {
11259:     my ($symb,$courseid,$domain,$username)=@_;
11260:     {
11261: 	use integer;
11262: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
11263: 	my $symbseed=numval2($symb);
11264: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11265: 	my $CODEseed=numval(&getCODE());
11266: 	my $courseseed=unpack("%32S*",$courseid.' ');
11267: 	my $num1=$symbseed+$CODEchck;
11268: 	my $num2=$CODEseed+$courseseed+$symbchck;
11269: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11270: 	#&logthis("rndseed :$num1:$num2:$symb");
11271: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
11272: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
11273: 	return "$num1:$num2";
11274:     }
11275: }
11276: 
11277: sub rndseed_CODE_64bit4 {
11278:     my ($symb,$courseid,$domain,$username)=@_;
11279:     {
11280: 	use integer;
11281: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
11282: 	my $symbseed=numval3($symb);
11283: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11284: 	my $CODEseed=numval3(&getCODE());
11285: 	my $courseseed=unpack("%32S*",$courseid.' ');
11286: 	my $num1=$symbseed+$CODEchck;
11287: 	my $num2=$CODEseed+$courseseed+$symbchck;
11288: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11289: 	#&logthis("rndseed :$num1:$num2:$symb");
11290: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
11291: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
11292: 	return "$num1:$num2";
11293:     }
11294: }
11295: 
11296: sub rndseed_CODE_64bit5 {
11297:     my ($symb,$courseid,$domain,$username)=@_;
11298:     my $code = &getCODE();
11299:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
11300:     return "$num1:$num2";
11301: }
11302: 
11303: sub setup_random_from_rndseed {
11304:     my ($rndseed)=@_;
11305:     if ($rndseed =~/([,:])/) {
11306:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
11307:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
11308:             &Math::Random::random_set_seed_from_phrase($rndseed);
11309:         } else {
11310:             &Math::Random::random_set_seed($num1,$num2);
11311:         }
11312:     } else {
11313: 	&Math::Random::random_set_seed_from_phrase($rndseed);
11314:     }
11315: }
11316: 
11317: sub latest_receipt_algorithm_id {
11318:     return 'receipt3';
11319: }
11320: 
11321: sub recunique {
11322:     my $fucourseid=shift;
11323:     my $unique;
11324:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11325: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11326: 	$unique=$env{"course.$fucourseid.internal.encseed"};
11327:     } else {
11328: 	$unique=$perlvar{'lonReceipt'};
11329:     }
11330:     return unpack("%32C*",$unique);
11331: }
11332: 
11333: sub recprefix {
11334:     my $fucourseid=shift;
11335:     my $prefix;
11336:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11337: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11338: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
11339:     } else {
11340: 	$prefix=$perlvar{'lonHostID'};
11341:     }
11342:     return unpack("%32C*",$prefix);
11343: }
11344: 
11345: sub ireceipt {
11346:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
11347: 
11348:     my $return =&recprefix($fucourseid).'-';
11349: 
11350:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11351: 	$env{'request.state'} eq 'construct') {
11352: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11353: 	return $return;
11354:     }
11355: 
11356:     my $cuname=unpack("%32C*",$funame);
11357:     my $cudom=unpack("%32C*",$fudom);
11358:     my $cucourseid=unpack("%32C*",$fucourseid);
11359:     my $cusymb=unpack("%32C*",$fusymb);
11360:     my $cunique=&recunique($fucourseid);
11361:     my $cpart=unpack("%32S*",$part);
11362:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11363: 
11364: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
11365: 			       
11366: 	$return.= ($cunique%$cuname+
11367: 		   $cunique%$cudom+
11368: 		   $cusymb%$cuname+
11369: 		   $cusymb%$cudom+
11370: 		   $cucourseid%$cuname+
11371: 		   $cucourseid%$cudom+
11372: 		   $cpart%$cuname+
11373: 		   $cpart%$cudom);
11374:     } else {
11375: 	$return.= ($cunique%$cuname+
11376: 		   $cunique%$cudom+
11377: 		   $cusymb%$cuname+
11378: 		   $cusymb%$cudom+
11379: 		   $cucourseid%$cuname+
11380: 		   $cucourseid%$cudom);
11381:     }
11382:     return $return;
11383: }
11384: 
11385: sub receipt {
11386:     my ($part)=@_;
11387:     my ($symb,$courseid,$domain,$name) = &whichuser();
11388:     return &ireceipt($name,$domain,$courseid,$symb,$part);
11389: }
11390: 
11391: sub whichuser {
11392:     my ($passedsymb)=@_;
11393:     my ($symb,$courseid,$domain,$name,$publicuser);
11394:     if (defined($env{'form.grade_symb'})) {
11395: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11396: 	my $allowed=&allowed('vgr',$tmp_courseid);
11397: 	if (!$allowed &&
11398: 	    exists($env{'request.course.sec'}) &&
11399: 	    $env{'request.course.sec'} !~ /^\s*$/) {
11400: 	    $allowed=&allowed('vgr',$tmp_courseid.
11401: 			      '/'.$env{'request.course.sec'});
11402: 	}
11403: 	if ($allowed) {
11404: 	    ($symb)=&get_env_multiple('form.grade_symb');
11405: 	    $courseid=$tmp_courseid;
11406: 	    ($domain)=&get_env_multiple('form.grade_domain');
11407: 	    ($name)=&get_env_multiple('form.grade_username');
11408: 	    return ($symb,$courseid,$domain,$name,$publicuser);
11409: 	}
11410:     }
11411:     if (!$passedsymb) {
11412: 	$symb=&symbread();
11413:     } else {
11414: 	$symb=$passedsymb;
11415:     }
11416:     $courseid=$env{'request.course.id'};
11417:     $domain=$env{'user.domain'};
11418:     $name=$env{'user.name'};
11419:     if ($name eq 'public' && $domain eq 'public') {
11420: 	if (!defined($env{'form.username'})) {
11421: 	    $env{'form.username'}.=time.rand(10000000);
11422: 	}
11423: 	$name.=$env{'form.username'};
11424:     }
11425:     return ($symb,$courseid,$domain,$name,$publicuser);
11426: 
11427: }
11428: 
11429: # ------------------------------------------------------------ Serves up a file
11430: # returns either the contents of the file or 
11431: # -1 if the file doesn't exist
11432: #
11433: # if the target is a file that was uploaded via DOCS, 
11434: # a check will be made to see if a current copy exists on the local server,
11435: # if it does this will be served, otherwise a copy will be retrieved from
11436: # the home server for the course and stored in /home/httpd/html/userfiles on
11437: # the local server.   
11438: 
11439: sub getfile {
11440:     my ($file) = @_;
11441:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
11442:     &repcopy($file);
11443:     return &readfile($file);
11444: }
11445: 
11446: sub repcopy_userfile {
11447:     my ($file)=@_;
11448:     my $londocroot = $perlvar{'lonDocRoot'};
11449:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
11450:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
11451:     my ($cdom,$cnum,$filename) = 
11452: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
11453:     my $uri="/uploaded/$cdom/$cnum/$filename";
11454:     if (-e "$file") {
11455: # we already have a local copy, check it out
11456: 	my @fileinfo = stat($file);
11457: 	my $rtncode;
11458: 	my $info;
11459: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
11460: 	if ($lwpresp ne 'ok') {
11461: # there is no such file anymore, even though we had a local copy
11462: 	    if ($rtncode eq '404') {
11463: 		unlink($file);
11464: 	    }
11465: 	    return -1;
11466: 	}
11467: 	if ($info < $fileinfo[9]) {
11468: # nice, the file we have is up-to-date, just say okay
11469: 	    return 'ok';
11470: 	} else {
11471: # the file is outdated, get rid of it
11472: 	    unlink($file);
11473: 	}
11474:     }
11475: # one way or the other, at this point, we don't have the file
11476: # construct the correct path for the file
11477:     my @parts = ($cdom,$cnum); 
11478:     if ($filename =~ m|^(.+)/[^/]+$|) {
11479: 	push @parts, split(/\//,$1);
11480:     }
11481:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11482:     foreach my $part (@parts) {
11483: 	$path .= '/'.$part;
11484: 	if (!-e $path) {
11485: 	    mkdir($path,0770);
11486: 	}
11487:     }
11488: # now the path exists for sure
11489: # get a user agent
11490:     my $ua=new LWP::UserAgent;
11491:     my $transferfile=$file.'.in.transfer';
11492: # FIXME: this should flock
11493:     if (-e $transferfile) { return 'ok'; }
11494:     my $request;
11495:     $uri=~s/^\///;
11496:     my $homeserver = &homeserver($cnum,$cdom);
11497:     my $protocol = $protocol{$homeserver};
11498:     $protocol = 'http' if ($protocol ne 'https');
11499:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
11500:     my $response=$ua->request($request,$transferfile);
11501: # did it work?
11502:     if ($response->is_error()) {
11503: 	unlink($transferfile);
11504: 	&logthis("Userfile repcopy failed for $uri");
11505: 	return -1;
11506:     }
11507: # worked, rename the transfer file
11508:     rename($transferfile,$file);
11509:     return 'ok';
11510: }
11511: 
11512: sub tokenwrapper {
11513:     my $uri=shift;
11514:     $uri=~s|^https?\://([^/]+)||;
11515:     $uri=~s|^/||;
11516:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
11517:     my $token=$1;
11518:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
11519:     if ($udom && $uname && $file) {
11520: 	$file=~s|(\?\.*)*$||;
11521:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
11522:         my $homeserver = &homeserver($uname,$udom);
11523:         my $protocol = $protocol{$homeserver};
11524:         $protocol = 'http' if ($protocol ne 'https');
11525:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
11526:                (($uri=~/\?/)?'&':'?').'token='.$token.
11527:                                '&tokenissued='.$perlvar{'lonHostID'};
11528:     } else {
11529:         return '/adm/notfound.html';
11530:     }
11531: }
11532: 
11533: # call with reqtype HEAD: get last modification time
11534: # call with reqtype GET: get the file contents
11535: # Do not call this with reqtype GET for large files! It loads everything into memory
11536: #
11537: sub getuploaded {
11538:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11539:     $uri=~s/^\///;
11540:     my $homeserver = &homeserver($cnum,$cdom);
11541:     my $protocol = $protocol{$homeserver};
11542:     $protocol = 'http' if ($protocol ne 'https');
11543:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
11544:     my $ua=new LWP::UserAgent;
11545:     my $request=new HTTP::Request($reqtype,$uri);
11546:     my $response=$ua->request($request);
11547:     $$rtncode = $response->code;
11548:     if (! $response->is_success()) {
11549: 	return 'failed';
11550:     }      
11551:     if ($reqtype eq 'HEAD') {
11552: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
11553:     } elsif ($reqtype eq 'GET') {
11554: 	$$info = $response->content;
11555:     }
11556:     return 'ok';
11557: }
11558: 
11559: sub readfile {
11560:     my $file = shift;
11561:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
11562:     my $fh;
11563:     open($fh,"<$file");
11564:     my $a='';
11565:     while (my $line = <$fh>) { $a .= $line; }
11566:     return $a;
11567: }
11568: 
11569: sub filelocation {
11570:     my ($dir,$file) = @_;
11571:     my $location;
11572:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
11573: 
11574:     if ($file =~ m-^/adm/-) {
11575: 	$file=~s-^/adm/wrapper/-/-;
11576: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
11577:     }
11578: 
11579:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
11580:         $location = $file;
11581:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
11582:         my ($udom,$uname,$filename)=
11583:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
11584:         my $home=&homeserver($uname,$udom);
11585:         my $is_me=0;
11586:         my @ids=&current_machine_ids();
11587:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11588:         if ($is_me) {
11589:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
11590:         } else {
11591:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11592:   	      $udom.'/'.$uname.'/'.$filename;
11593:         }
11594:     } elsif ($file =~ m-^/adm/-) {
11595: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
11596:     } else {
11597:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
11598:         $file=~s:^/(res|priv)/:/:;
11599:         my $space=$1;
11600:         if ( !( $file =~ m:^/:) ) {
11601:             $location = $dir. '/'.$file;
11602:         } else {
11603:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
11604:         }
11605:     }
11606:     $location=~s://+:/:g; # remove duplicate /
11607:     while ($location=~m{/\.\./}) {
11608: 	if ($location =~ m{/[^/]+/\.\./}) {
11609: 	    $location=~ s{/[^/]+/\.\./}{/}g;
11610: 	} else {
11611: 	    $location=~ s{/\.\./}{/}g;
11612: 	}
11613:     } #remove dir/..
11614:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11615:     return $location;
11616: }
11617: 
11618: sub hreflocation {
11619:     my ($dir,$file)=@_;
11620:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
11621: 	$file=filelocation($dir,$file);
11622:     } elsif ($file=~m-^/adm/-) {
11623: 	$file=~s-^/adm/wrapper/-/-;
11624: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
11625:     }
11626:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11627: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11628:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
11629: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11630: 	        {/uploaded/$1/$2/}x;
11631:     }
11632:     if ($file=~ m{^/userfiles/}) {
11633: 	$file =~ s{^/userfiles/}{/uploaded/};
11634:     }
11635:     return $file;
11636: }
11637: 
11638: 
11639: 
11640: 
11641: 
11642: sub current_machine_domains {
11643:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
11644: }
11645: 
11646: sub machine_domains {
11647:     my ($hostname) = @_;
11648:     my @domains;
11649:     my %hostname = &all_hostnames();
11650:     while( my($id, $name) = each(%hostname)) {
11651: #	&logthis("-$id-$name-$hostname-");
11652: 	if ($hostname eq $name) {
11653: 	    push(@domains,&host_domain($id));
11654: 	}
11655:     }
11656:     return @domains;
11657: }
11658: 
11659: sub current_machine_ids {
11660:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
11661: }
11662: 
11663: sub machine_ids {
11664:     my ($hostname) = @_;
11665:     $hostname ||= &hostname($perlvar{'lonHostID'});
11666:     my @ids;
11667:     my %name_to_host = &all_names();
11668:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11669: 	return @{ $name_to_host{$hostname} };
11670:     }
11671:     return;
11672: }
11673: 
11674: sub additional_machine_domains {
11675:     my @domains;
11676:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
11677:     while( my $line = <$fh>) {
11678:         $line =~ s/\s//g;
11679:         push(@domains,$line);
11680:     }
11681:     return @domains;
11682: }
11683: 
11684: sub default_login_domain {
11685:     my $domain = $perlvar{'lonDefDomain'};
11686:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
11687:     foreach my $posdom (&current_machine_domains(),
11688:                         &additional_machine_domains()) {
11689:         if (lc($posdom) eq lc($testdomain)) {
11690:             $domain=$posdom;
11691:             last;
11692:         }
11693:     }
11694:     return $domain;
11695: }
11696: 
11697: # ------------------------------------------------------------- Declutters URLs
11698: 
11699: sub declutter {
11700:     my $thisfn=shift;
11701:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
11702:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
11703:         $thisfn=~s{^/home/httpd/html}{};
11704:     }
11705:     $thisfn=~s/^\///;
11706:     $thisfn=~s|^adm/wrapper/||;
11707:     $thisfn=~s|^adm/coursedocs/showdoc/||;
11708:     $thisfn=~s/^res\///;
11709:     $thisfn=~s/^priv\///;
11710:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
11711:         $thisfn=~s/\?.+$//;
11712:     }
11713:     return $thisfn;
11714: }
11715: 
11716: # ------------------------------------------------------------- Clutter up URLs
11717: 
11718: sub clutter {
11719:     my $thisfn='/'.&declutter(shift);
11720:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
11721: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
11722:        $thisfn='/res'.$thisfn; 
11723:     }
11724:     if ($thisfn !~m|^/adm|) {
11725: 	if ($thisfn =~ m|^/ext/|) {
11726: 	    $thisfn='/adm/wrapper'.$thisfn;
11727: 	} else {
11728: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
11729: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
11730: 	    if ($embstyle eq 'ssi'
11731: 		|| ($embstyle eq 'hdn')
11732: 		|| ($embstyle eq 'rat')
11733: 		|| ($embstyle eq 'prv')
11734: 		|| ($embstyle eq 'ign')) {
11735: 		#do nothing with these
11736: 	    } elsif (($embstyle eq 'img') 
11737: 		|| ($embstyle eq 'emb')
11738: 		|| ($embstyle eq 'wrp')) {
11739: 		$thisfn='/adm/wrapper'.$thisfn;
11740: 	    } elsif ($embstyle eq 'unk'
11741: 		     && $thisfn!~/\.(sequence|page)$/) {
11742: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
11743: 	    } else {
11744: #		&logthis("Got a blank emb style");
11745: 	    }
11746: 	}
11747:     }
11748:     return $thisfn;
11749: }
11750: 
11751: sub clutter_with_no_wrapper {
11752:     my $uri = &clutter(shift);
11753:     if ($uri =~ m-^/adm/-) {
11754: 	$uri =~ s-^/adm/wrapper/-/-;
11755: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
11756:     }
11757:     return $uri;
11758: }
11759: 
11760: sub freeze_escape {
11761:     my ($value)=@_;
11762:     if (ref($value)) {
11763: 	$value=&nfreeze($value);
11764: 	return '__FROZEN__'.&escape($value);
11765:     }
11766:     return &escape($value);
11767: }
11768: 
11769: 
11770: sub thaw_unescape {
11771:     my ($value)=@_;
11772:     if ($value =~ /^__FROZEN__/) {
11773: 	substr($value,0,10,undef);
11774: 	$value=&unescape($value);
11775: 	return &thaw($value);
11776:     }
11777:     return &unescape($value);
11778: }
11779: 
11780: sub correct_line_ends {
11781:     my ($result)=@_;
11782:     $$result =~s/\r\n/\n/mg;
11783:     $$result =~s/\r/\n/mg;
11784: }
11785: # ================================================================ Main Program
11786: 
11787: sub goodbye {
11788:    &logthis("Starting Shut down");
11789: #not converted to using infrastruture and probably shouldn't be
11790:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
11791: #converted
11792: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
11793:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
11794: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
11795: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
11796: #1.1 only
11797: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
11798: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
11799: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
11800: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
11801:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
11802:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
11803:    &logthis(sprintf("%-20s is %s",'hits',$hits));
11804:    &flushcourselogs();
11805:    &logthis("Shutting down");
11806: }
11807: 
11808: sub get_dns {
11809:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
11810:     if (!$ignore_cache) {
11811: 	my ($content,$cached)=
11812: 	    &Apache::lonnet::is_cached_new('dns',$url);
11813: 	if ($cached) {
11814: 	    &$func($content,$hashref);
11815: 	    return;
11816: 	}
11817:     }
11818: 
11819:     my %alldns;
11820:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11821:     foreach my $dns (<$config>) {
11822: 	next if ($dns !~ /^\^(\S*)/x);
11823:         my $line = $1;
11824:         my ($host,$protocol) = split(/:/,$line);
11825:         if ($protocol ne 'https') {
11826:             $protocol = 'http';
11827:         }
11828: 	$alldns{$host} = $protocol;
11829:     }
11830:     while (%alldns) {
11831: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
11832: 	my $ua=new LWP::UserAgent;
11833:         $ua->timeout(30);
11834: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
11835: 	my $response=$ua->request($request);
11836:         delete($alldns{$dns});
11837: 	next if ($response->is_error());
11838: 	my @content = split("\n",$response->content);
11839: 	unless ($nocache) {
11840: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
11841: 	}
11842: 	&$func(\@content,$hashref);
11843: 	return;
11844:     }
11845:     close($config);
11846:     my $which = (split('/',$url))[3];
11847:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
11848:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
11849:     my @content = <$config>;
11850:     &$func(\@content,$hashref);
11851:     return;
11852: }
11853: 
11854: # ------------------------------------------------------Get DNS checksums file
11855: sub parse_dns_checksums_tab {
11856:     my ($lines,$hashref) = @_;
11857:     my $lonhost = $perlvar{'lonHostID'};
11858:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
11859:     my $loncaparev = &get_server_loncaparev($machine_dom);
11860:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
11861:     my $webconfdir = '/etc/httpd/conf';
11862:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
11863:         $webconfdir = '/etc/apache2';
11864:     } elsif ($distro =~ /^sles(\d+)$/) {
11865:         if ($1 >= 10) {
11866:             $webconfdir = '/etc/apache2';
11867:         }
11868:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
11869:         if ($1 >= 10.0) {
11870:             $webconfdir = '/etc/apache2';
11871:         }
11872:     }
11873:     my ($release,$timestamp) = split(/\-/,$loncaparev);
11874:     my (%chksum,%revnum);
11875:     if (ref($lines) eq 'ARRAY') {
11876:         chomp(@{$lines});
11877:         my $version = shift(@{$lines});
11878:         if ($version eq $release) {  
11879:             foreach my $line (@{$lines}) {
11880:                 my ($file,$version,$shasum) = split(/,/,$line);
11881:                 if ($file =~ m{^/etc/httpd/conf}) {
11882:                     if ($webconfdir eq '/etc/apache2') {
11883:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
11884:                     }
11885:                 }
11886:                 $chksum{$file} = $shasum;
11887:                 $revnum{$file} = $version;
11888:             }
11889:             if (ref($hashref) eq 'HASH') {
11890:                 %{$hashref} = (
11891:                                 sums     => \%chksum,
11892:                                 versions => \%revnum,
11893:                               );
11894:             }
11895:         }
11896:     }
11897:     return;
11898: }
11899: 
11900: sub fetch_dns_checksums {
11901:     my %checksums;
11902:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11903:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
11904:     my ($release,$timestamp) = split(/\-/,$loncaparev);
11905:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
11906:              \%checksums);
11907:     return \%checksums;
11908: }
11909: 
11910: # ------------------------------------------------------------ Read domain file
11911: {
11912:     my $loaded;
11913:     my %domain;
11914: 
11915:     sub parse_domain_tab {
11916: 	my ($lines) = @_;
11917: 	foreach my $line (@$lines) {
11918: 	    next if ($line =~ /^(\#|\s*$ )/x);
11919: 
11920: 	    chomp($line);
11921: 	    my ($name,@elements) = split(/:/,$line,9);
11922: 	    my %this_domain;
11923: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
11924: 			       'lang_def', 'city', 'longi', 'lati',
11925: 			       'primary') {
11926: 		$this_domain{$field} = shift(@elements);
11927: 	    }
11928: 	    $domain{$name} = \%this_domain;
11929: 	}
11930:     }
11931: 
11932:     sub reset_domain_info {
11933: 	undef($loaded);
11934: 	undef(%domain);
11935:     }
11936: 
11937:     sub load_domain_tab {
11938: 	my ($ignore_cache) = @_;
11939: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
11940: 	my $fh;
11941: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
11942: 	    my @lines = <$fh>;
11943: 	    &parse_domain_tab(\@lines);
11944: 	}
11945: 	close($fh);
11946: 	$loaded = 1;
11947:     }
11948: 
11949:     sub domain {
11950: 	&load_domain_tab() if (!$loaded);
11951: 
11952: 	my ($name,$what) = @_;
11953: 	return if ( !exists($domain{$name}) );
11954: 
11955: 	if (!$what) {
11956: 	    return $domain{$name}{'description'};
11957: 	}
11958: 	return $domain{$name}{$what};
11959:     }
11960: 
11961:     sub domain_info {
11962:         &load_domain_tab() if (!$loaded);
11963:         return %domain;
11964:     }
11965: 
11966: }
11967: 
11968: 
11969: # ------------------------------------------------------------- Read hosts file
11970: {
11971:     my %hostname;
11972:     my %hostdom;
11973:     my %libserv;
11974:     my $loaded;
11975:     my %name_to_host;
11976:     my %internetdom;
11977:     my %LC_dns_serv;
11978: 
11979:     sub parse_hosts_tab {
11980: 	my ($file) = @_;
11981: 	foreach my $configline (@$file) {
11982: 	    next if ($configline =~ /^(\#|\s*$ )/x);
11983:             chomp($configline);
11984: 	    if ($configline =~ /^\^/) {
11985:                 if ($configline =~ /^\^([\w.\-]+)/) {
11986:                     $LC_dns_serv{$1} = 1;
11987:                 }
11988:                 next;
11989:             }
11990: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
11991: 	    $name=~s/\s//g;
11992: 	    if ($id && $domain && $role && $name) {
11993: 		$hostname{$id}=$name;
11994: 		push(@{$name_to_host{$name}}, $id);
11995: 		$hostdom{$id}=$domain;
11996: 		if ($role eq 'library') { $libserv{$id}=$name; }
11997:                 if (defined($protocol)) {
11998:                     if ($protocol eq 'https') {
11999:                         $protocol{$id} = $protocol;
12000:                     } else {
12001:                         $protocol{$id} = 'http'; 
12002:                     }
12003:                 } else {
12004:                     $protocol{$id} = 'http';
12005:                 }
12006:                 if (defined($intdom)) {
12007:                     $internetdom{$id} = $intdom;
12008:                 }
12009: 	    }
12010: 	}
12011:     }
12012:     
12013:     sub reset_hosts_info {
12014: 	&purge_remembered();
12015: 	&reset_domain_info();
12016: 	&reset_hosts_ip_info();
12017: 	undef(%name_to_host);
12018: 	undef(%hostname);
12019: 	undef(%hostdom);
12020: 	undef(%libserv);
12021: 	undef($loaded);
12022:     }
12023: 
12024:     sub load_hosts_tab {
12025: 	my ($ignore_cache) = @_;
12026: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
12027: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12028: 	my @config = <$config>;
12029: 	&parse_hosts_tab(\@config);
12030: 	close($config);
12031: 	$loaded=1;
12032:     }
12033: 
12034:     sub hostname {
12035: 	&load_hosts_tab() if (!$loaded);
12036: 
12037: 	my ($lonid) = @_;
12038: 	return $hostname{$lonid};
12039:     }
12040: 
12041:     sub all_hostnames {
12042: 	&load_hosts_tab() if (!$loaded);
12043: 
12044: 	return %hostname;
12045:     }
12046: 
12047:     sub all_names {
12048: 	&load_hosts_tab() if (!$loaded);
12049: 
12050: 	return %name_to_host;
12051:     }
12052: 
12053:     sub all_host_domain {
12054:         &load_hosts_tab() if (!$loaded);
12055:         return %hostdom;
12056:     }
12057: 
12058:     sub is_library {
12059: 	&load_hosts_tab() if (!$loaded);
12060: 
12061: 	return exists($libserv{$_[0]});
12062:     }
12063: 
12064:     sub all_library {
12065: 	&load_hosts_tab() if (!$loaded);
12066: 
12067: 	return %libserv;
12068:     }
12069: 
12070:     sub unique_library {
12071: 	#2x reverse removes all hostnames that appear more than once
12072:         my %unique = reverse &all_library();
12073:         return reverse %unique;
12074:     }
12075: 
12076:     sub get_servers {
12077: 	&load_hosts_tab() if (!$loaded);
12078: 
12079: 	my ($domain,$type) = @_;
12080: 	my %possible_hosts = ($type eq 'library') ? %libserv
12081: 	                                          : %hostname;
12082: 	my %result;
12083: 	if (ref($domain) eq 'ARRAY') {
12084: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
12085: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
12086: 		    $result{$host} = $hostname;
12087: 		}
12088: 	    }
12089: 	} else {
12090: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
12091: 		if ($hostdom{$host} eq $domain) {
12092: 		    $result{$host} = $hostname;
12093: 		}
12094: 	    }
12095: 	}
12096: 	return %result;
12097:     }
12098: 
12099:     sub get_unique_servers {
12100:         my %unique = reverse &get_servers(@_);
12101: 	return reverse %unique;
12102:     }
12103: 
12104:     sub host_domain {
12105: 	&load_hosts_tab() if (!$loaded);
12106: 
12107: 	my ($lonid) = @_;
12108: 	return $hostdom{$lonid};
12109:     }
12110: 
12111:     sub all_domains {
12112: 	&load_hosts_tab() if (!$loaded);
12113: 
12114: 	my %seen;
12115: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
12116: 	return @uniq;
12117:     }
12118: 
12119:     sub internet_dom {
12120:         &load_hosts_tab() if (!$loaded);
12121: 
12122:         my ($lonid) = @_;
12123:         return $internetdom{$lonid};
12124:     }
12125: 
12126:     sub is_LC_dns {
12127:         &load_hosts_tab() if (!$loaded);
12128: 
12129:         my ($hostname) = @_;
12130:         return exists($LC_dns_serv{$hostname});
12131:     }
12132: 
12133: }
12134: 
12135: { 
12136:     my %iphost;
12137:     my %name_to_ip;
12138:     my %lonid_to_ip;
12139: 
12140:     sub get_hosts_from_ip {
12141: 	my ($ip) = @_;
12142: 	my %iphosts = &get_iphost();
12143: 	if (ref($iphosts{$ip})) {
12144: 	    return @{$iphosts{$ip}};
12145: 	}
12146: 	return;
12147:     }
12148:     
12149:     sub reset_hosts_ip_info {
12150: 	undef(%iphost);
12151: 	undef(%name_to_ip);
12152: 	undef(%lonid_to_ip);
12153:     }
12154: 
12155:     sub get_host_ip {
12156: 	my ($lonid) = @_;
12157: 	if (exists($lonid_to_ip{$lonid})) {
12158: 	    return $lonid_to_ip{$lonid};
12159: 	}
12160: 	my $name=&hostname($lonid);
12161:    	my $ip = gethostbyname($name);
12162: 	return if (!$ip || length($ip) ne 4);
12163: 	$ip=inet_ntoa($ip);
12164: 	$name_to_ip{$name}   = $ip;
12165: 	$lonid_to_ip{$lonid} = $ip;
12166: 	return $ip;
12167:     }
12168:     
12169:     sub get_iphost {
12170: 	my ($ignore_cache) = @_;
12171: 
12172: 	if (!$ignore_cache) {
12173: 	    if (%iphost) {
12174: 		return %iphost;
12175: 	    }
12176: 	    my ($ip_info,$cached)=
12177: 		&Apache::lonnet::is_cached_new('iphost','iphost');
12178: 	    if ($cached) {
12179: 		%iphost      = %{$ip_info->[0]};
12180: 		%name_to_ip  = %{$ip_info->[1]};
12181: 		%lonid_to_ip = %{$ip_info->[2]};
12182: 		return %iphost;
12183: 	    }
12184: 	}
12185: 
12186: 	# get yesterday's info for fallback
12187: 	my %old_name_to_ip;
12188: 	my ($ip_info,$cached)=
12189: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
12190: 	if ($cached) {
12191: 	    %old_name_to_ip = %{$ip_info->[1]};
12192: 	}
12193: 
12194: 	my %name_to_host = &all_names();
12195: 	foreach my $name (keys(%name_to_host)) {
12196: 	    my $ip;
12197: 	    if (!exists($name_to_ip{$name})) {
12198: 		$ip = gethostbyname($name);
12199: 		if (!$ip || length($ip) ne 4) {
12200: 		    if (defined($old_name_to_ip{$name})) {
12201: 			$ip = $old_name_to_ip{$name};
12202: 			&logthis("Can't find $name defaulting to old $ip");
12203: 		    } else {
12204: 			&logthis("Name $name no IP found");
12205: 			next;
12206: 		    }
12207: 		} else {
12208: 		    $ip=inet_ntoa($ip);
12209: 		}
12210: 		$name_to_ip{$name} = $ip;
12211: 	    } else {
12212: 		$ip = $name_to_ip{$name};
12213: 	    }
12214: 	    foreach my $id (@{ $name_to_host{$name} }) {
12215: 		$lonid_to_ip{$id} = $ip;
12216: 	    }
12217: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
12218: 	}
12219: 	&do_cache_new('iphost','iphost',
12220: 		      [\%iphost,\%name_to_ip,\%lonid_to_ip],
12221: 		      48*60*60);
12222: 
12223: 	return %iphost;
12224:     }
12225: 
12226:     #
12227:     #  Given a DNS returns the loncapa host name for that DNS 
12228:     # 
12229:     sub host_from_dns {
12230:         my ($dns) = @_;
12231:         my @hosts;
12232:         my $ip;
12233: 
12234:         if (exists($name_to_ip{$dns})) {
12235:             $ip = $name_to_ip{$dns};
12236:         }
12237:         if (!$ip) {
12238:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12239:             if (length($ip) == 4) { 
12240: 	        $ip   = &IO::Socket::inet_ntoa($ip);
12241:             }
12242:         }
12243:         if ($ip) {
12244: 	    @hosts = get_hosts_from_ip($ip);
12245: 	    return $hosts[0];
12246:         }
12247:         return undef;
12248:     }
12249: 
12250:     sub get_internet_names {
12251:         my ($lonid) = @_;
12252:         return if ($lonid eq '');
12253:         my ($idnref,$cached)=
12254:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
12255:         if ($cached) {
12256:             return $idnref;
12257:         }
12258:         my $ip = &get_host_ip($lonid);
12259:         my @hosts = &get_hosts_from_ip($ip);
12260:         my %iphost = &get_iphost();
12261:         my (@idns,%seen);
12262:         foreach my $id (@hosts) {
12263:             my $dom = &host_domain($id);
12264:             my $prim_id = &domain($dom,'primary');
12265:             my $prim_ip = &get_host_ip($prim_id);
12266:             next if ($seen{$prim_ip});
12267:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12268:                 foreach my $id (@{$iphost{$prim_ip}}) {
12269:                     my $intdom = &internet_dom($id);
12270:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
12271:                         push(@idns,$intdom);
12272:                     }
12273:                 }
12274:             }
12275:             $seen{$prim_ip} = 1;
12276:         }
12277:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
12278:     }
12279: 
12280: }
12281: 
12282: sub all_loncaparevs {
12283:     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);
12284: }
12285: 
12286: # ---------------------------------------------------------- Read loncaparev table
12287: {
12288:     sub load_loncaparevs { 
12289:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12290:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12291:                 while (my $configline=<$config>) {
12292:                     chomp($configline);
12293:                     my ($hostid,$loncaparev)=split(/:/,$configline);
12294:                     $loncaparevs{$hostid}=$loncaparev;
12295:                 }
12296:                 close($config);
12297:             }
12298:         }
12299:     }
12300: }
12301: 
12302: # ---------------------------------------------------------- Read serverhostID table
12303: {
12304:     sub load_serverhomeIDs {
12305:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12306:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12307:                 while (my $configline=<$config>) {
12308:                     chomp($configline);
12309:                     my ($name,$id)=split(/:/,$configline);
12310:                     $serverhomeIDs{$name}=$id;
12311:                 }
12312:                 close($config);
12313:             }
12314:         }
12315:     }
12316: }
12317: 
12318: 
12319: BEGIN {
12320: 
12321: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12322:     unless ($readit) {
12323: {
12324:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12325:     %perlvar = (%perlvar,%{$configvars});
12326: }
12327: 
12328: 
12329: # ------------------------------------------------------ Read spare server file
12330: {
12331:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
12332: 
12333:     while (my $configline=<$config>) {
12334:        chomp($configline);
12335:        if ($configline) {
12336: 	   my ($host,$type) = split(':',$configline,2);
12337: 	   if (!defined($type) || $type eq '') { $type = 'default' };
12338: 	   push(@{ $spareid{$type} }, $host);
12339:        }
12340:     }
12341:     close($config);
12342: }
12343: # ------------------------------------------------------------ Read permissions
12344: {
12345:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
12346: 
12347:     while (my $configline=<$config>) {
12348: 	chomp($configline);
12349: 	if ($configline) {
12350: 	    my ($role,$perm)=split(/ /,$configline);
12351: 	    if ($perm ne '') { $pr{$role}=$perm; }
12352: 	}
12353:     }
12354:     close($config);
12355: }
12356: 
12357: # -------------------------------------------- Read plain texts for permissions
12358: {
12359:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
12360: 
12361:     while (my $configline=<$config>) {
12362: 	chomp($configline);
12363: 	if ($configline) {
12364: 	    my ($short,@plain)=split(/:/,$configline);
12365:             %{$prp{$short}} = ();
12366: 	    if (@plain > 0) {
12367:                 $prp{$short}{'std'} = $plain[0];
12368:                 for (my $i=1; $i<@plain; $i++) {
12369:                     $prp{$short}{'alt'.$i} = $plain[$i];  
12370:                 }
12371:             }
12372: 	}
12373:     }
12374:     close($config);
12375: }
12376: 
12377: # ---------------------------------------------------------- Read package table
12378: {
12379:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
12380: 
12381:     while (my $configline=<$config>) {
12382: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
12383: 	chomp($configline);
12384: 	my ($short,$plain)=split(/:/,$configline);
12385: 	my ($pack,$name)=split(/\&/,$short);
12386: 	if ($plain ne '') {
12387: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
12388: 	    $packagetab{$short}=$plain; 
12389: 	}
12390:     }
12391:     close($config);
12392: }
12393: 
12394: # ---------------------------------------------------------- Read loncaparev table
12395: 
12396: &load_loncaparevs();
12397: 
12398: # ---------------------------------------------------------- Read serverhostID table
12399: 
12400: &load_serverhomeIDs();
12401: 
12402: # ---------------------------------------------------------- Read releaseslist XML
12403: {
12404:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12405:     if (-e $file) {
12406:         my $parser = HTML::LCParser->new($file);
12407:         while (my $token = $parser->get_token()) {
12408:             if ($token->[0] eq 'S') {
12409:                 my $item = $token->[1];
12410:                 my $name = $token->[2]{'name'};
12411:                 my $value = $token->[2]{'value'};
12412:                 if ($item ne '' && $name ne '' && $value ne '') {
12413:                     my $release = $parser->get_text();
12414:                     $release =~ s/(^\s*|\s*$ )//gx;
12415:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
12416:                 }
12417:             }
12418:         }
12419:     }
12420: }
12421: 
12422: # ---------------------------------------------------------- Read managers table
12423: {
12424:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12425:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12426:             while (my $configline=<$config>) {
12427:                 chomp($configline);
12428:                 next if ($configline =~ /^\#/);
12429:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12430:                     $managerstab{$configline} = 1;
12431:                 }
12432:             }
12433:             close($config);
12434:         }
12435:     }
12436: }
12437: 
12438: # ------------- set up temporary directory
12439: {
12440:     $tmpdir = LONCAPA::tempdir();
12441: 
12442: }
12443: 
12444: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
12445: 				'compress_threshold'=> 20_000,
12446:  			        });
12447: 
12448: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
12449: $dumpcount=0;
12450: $locknum=0;
12451: 
12452: &logtouch();
12453: &logthis('<font color="yellow">INFO: Read configuration</font>');
12454: $readit=1;
12455:     {
12456: 	use integer;
12457: 	my $test=(2**32)+1;
12458: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
12459: 	&logthis(" Detected 64bit platform ($_64bit)");
12460:     }
12461: }
12462: }
12463: 
12464: 1;
12465: __END__
12466: 
12467: =pod
12468: 
12469: =head1 NAME
12470: 
12471: Apache::lonnet - Subroutines to ask questions about things in the network.
12472: 
12473: =head1 SYNOPSIS
12474: 
12475: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
12476: 
12477:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12478: 
12479: Common parameters:
12480: 
12481: =over 4
12482: 
12483: =item *
12484: 
12485: $uname : an internal username (if $cname expecting a course Id specifically)
12486: 
12487: =item *
12488: 
12489: $udom : a domain (if $cdom expecting a course's domain specifically)
12490: 
12491: =item *
12492: 
12493: $symb : a resource instance identifier
12494: 
12495: =item *
12496: 
12497: $namespace : the name of a .db file that contains the data needed or
12498: being set.
12499: 
12500: =back
12501: 
12502: =head1 OVERVIEW
12503: 
12504: lonnet provides subroutines which interact with the
12505: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12506: about classes, users, and resources.
12507: 
12508: For many of these objects you can also use this to store data about
12509: them or modify them in various ways.
12510: 
12511: =head2 Symbs
12512: 
12513: To identify a specific instance of a resource, LON-CAPA uses symbols
12514: or "symbs"X<symb>. These identifiers are built from the URL of the
12515: map, the resource number of the resource in the map, and the URL of
12516: the resource itself. The latter is somewhat redundant, but might help
12517: if maps change.
12518: 
12519: An example is
12520: 
12521:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12522: 
12523: The respective map entry is
12524: 
12525:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
12526:   title="Problem 2">
12527:  </resource>
12528: 
12529: Symbs are used by the random number generator, as well as to store and
12530: restore data specific to a certain instance of for example a problem.
12531: 
12532: =head2 Storing And Retrieving Data
12533: 
12534: X<store()>X<cstore()>X<restore()>Three of the most important functions
12535: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12536: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12537: is is the non-critical message twin of cstore. These functions are for
12538: handlers to store a perl hash to a user's permanent data space in an
12539: easy manner, and to retrieve it again on another call. It is expected
12540: that a handler would use this once at the beginning to retrieve data,
12541: and then again once at the end to send only the new data back.
12542: 
12543: The data is stored in the user's data directory on the user's
12544: homeserver under the ID of the course.
12545: 
12546: The hash that is returned by restore will have all of the previous
12547: value for all of the elements of the hash.
12548: 
12549: Example:
12550: 
12551:  #creating a hash
12552:  my %hash;
12553:  $hash{'foo'}='bar';
12554: 
12555:  #storing it
12556:  &Apache::lonnet::cstore(\%hash);
12557: 
12558:  #changing a value
12559:  $hash{'foo'}='notbar';
12560: 
12561:  #adding a new value
12562:  $hash{'bar'}='foo';
12563:  &Apache::lonnet::cstore(\%hash);
12564: 
12565:  #retrieving the hash
12566:  my %history=&Apache::lonnet::restore();
12567: 
12568:  #print the hash
12569:  foreach my $key (sort(keys(%history))) {
12570:    print("\%history{$key} = $history{$key}");
12571:  }
12572: 
12573: Will print out:
12574: 
12575:  %history{1:foo} = bar
12576:  %history{1:keys} = foo:timestamp
12577:  %history{1:timestamp} = 990455579
12578:  %history{2:bar} = foo
12579:  %history{2:foo} = notbar
12580:  %history{2:keys} = foo:bar:timestamp
12581:  %history{2:timestamp} = 990455580
12582:  %history{bar} = foo
12583:  %history{foo} = notbar
12584:  %history{timestamp} = 990455580
12585:  %history{version} = 2
12586: 
12587: Note that the special hash entries C<keys>, C<version> and
12588: C<timestamp> were added to the hash. C<version> will be equal to the
12589: total number of versions of the data that have been stored. The
12590: C<timestamp> attribute will be the UNIX time the hash was
12591: stored. C<keys> is available in every historical section to list which
12592: keys were added or changed at a specific historical revision of a
12593: hash.
12594: 
12595: B<Warning>: do not store the hash that restore returns directly. This
12596: will cause a mess since it will restore the historical keys as if the
12597: were new keys. I.E. 1:foo will become 1:1:foo etc.
12598: 
12599: Calling convention:
12600: 
12601:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
12602:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
12603: 
12604: For more detailed information, see lonnet specific documentation.
12605: 
12606: =head1 RETURN MESSAGES
12607: 
12608: =over 4
12609: 
12610: =item * B<con_lost>: unable to contact remote host
12611: 
12612: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12613: when the connection is brought back up
12614: 
12615: =item * B<con_failed>: unable to contact remote host and unable to save message
12616: for later delivery
12617: 
12618: =item * B<error:>: an error a occurred, a description of the error follows the :
12619: 
12620: =item * B<no_such_host>: unable to fund a host associated with the user/domain
12621: that was requested
12622: 
12623: =back
12624: 
12625: =head1 PUBLIC SUBROUTINES
12626: 
12627: =head2 Session Environment Functions
12628: 
12629: =over 4
12630: 
12631: =item * 
12632: X<appenv()>
12633: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
12634: the user envirnoment file, and will be restored for each access this
12635: user makes during this session, also modifies the %env for the current
12636: process. Optional rolesarrayref - if defined contains a reference to an array
12637: of roles which are exempt from the restriction on modifying user.role entries 
12638: in the user's environment.db and in %env.    
12639: 
12640: =item *
12641: X<delenv()>
12642: B<delenv($delthis,$regexp)>: removes all items from the session
12643: environment file that begin with $delthis. If the 
12644: optional second arg - $regexp - is true, $delthis is treated as a 
12645: regular expression, otherwise \Q$delthis\E is used. 
12646: The values are also deleted from the current processes %env.
12647: 
12648: =item * get_env_multiple($name) 
12649: 
12650: gets $name from the %env hash, it seemlessly handles the cases where multiple
12651: values may be defined and end up as an array ref.
12652: 
12653: returns an array of values
12654: 
12655: =back
12656: 
12657: =head2 User Information
12658: 
12659: =over 4
12660: 
12661: =item *
12662: X<queryauthenticate()>
12663: B<queryauthenticate($uname,$udom)>: try to determine user's current 
12664: authentication scheme
12665: 
12666: =item *
12667: X<authenticate()>
12668: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
12669: authenticate user from domain's lib servers (first use the current
12670: one). C<$upass> should be the users password.
12671: $checkdefauth is optional (value is 1 if a check should be made to
12672:    authenticate user using default authentication method, and allow
12673:    account creation if username does not have account in the domain).
12674: $clientcancheckhost is optional (value is 1 if checking whether the
12675:    server can host will occur on the client side in lonauth.pm).   
12676: 
12677: =item *
12678: X<homeserver()>
12679: B<homeserver($uname,$udom)>: find the server which has
12680: the user's directory and files (there must be only one), this caches
12681: the answer, and also caches if there is a borken connection.
12682: 
12683: =item *
12684: X<idget()>
12685: B<idget($udom,@ids)>: find the usernames behind a list of IDs
12686: (IDs are a unique resource in a domain, there must be only 1 ID per
12687: username, and only 1 username per ID in a specific domain) (returns
12688: hash: id=>name,id=>name)
12689: 
12690: =item *
12691: X<idrget()>
12692: B<idrget($udom,@unames)>: find the IDs behind a list of
12693: usernames (returns hash: name=>id,name=>id)
12694: 
12695: =item *
12696: X<idput()>
12697: B<idput($udom,%ids)>: store away a list of names and associated IDs
12698: 
12699: =item *
12700: X<rolesinit()>
12701: B<rolesinit($udom,$username)>: get user privileges.
12702: returns user role, first access and timer interval hashes
12703: 
12704: =item *
12705: X<privileged()>
12706: B<privileged($username,$domain)>: returns a true if user has a
12707: privileged and active role (i.e. su or dc), false otherwise.
12708: 
12709: =item *
12710: X<getsection()>
12711: B<getsection($udom,$uname,$cname)>: finds the section of student in the
12712: course $cname, return section name/number or '' for "not in course"
12713: and '-1' for "no section"
12714: 
12715: =item *
12716: X<userenvironment()>
12717: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
12718: passed in @what from the requested user's environment, returns a hash
12719: 
12720: =item * 
12721: X<userlog_query()>
12722: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
12723: activity.log file. %filters defines filters applied when parsing the
12724: log file. These can be start or end timestamps, or the type of action
12725: - log to look for Login or Logout events, check for Checkin or
12726: Checkout, role for role selection. The response is in the form
12727: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
12728: escaped strings of the action recorded in the activity.log file.
12729: 
12730: =back
12731: 
12732: =head2 User Roles
12733: 
12734: =over 4
12735: 
12736: =item *
12737: 
12738: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
12739:  F: full access
12740:  U,I,K: authentication modes (cxx only)
12741:  '': forbidden
12742:  1: user needs to choose course
12743:  2: browse allowed
12744:  A: passphrase authentication needed
12745: 
12746: =item *
12747: 
12748: constructaccess($url,$setpriv) : check for access to construction space URL
12749: 
12750: See if the owner domain and name in the URL match those in the
12751: expected environment.  If so, return three element list
12752: ($ownername,$ownerdomain,$ownerhome).
12753: 
12754: Otherwise return the null string.
12755: 
12756: If second argument 'setpriv' is true, it assigns the privileges,
12757: and returns the same three element list, unless the owner has
12758: blocked "ad hoc" Domain Coordinator access to the Author Space,
12759: in which case the null string is returned.
12760: 
12761: =item *
12762: 
12763: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
12764: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
12765: and course level
12766: 
12767: =item *
12768: 
12769: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
12770: (rolesplain.tab); plain text explanation of a user role term.
12771: $type is Course (default) or Community.
12772: If $forcedefault evaluates to true, text returned will be default 
12773: text for $type. Otherwise, if this is a course, the text returned 
12774: will be a custom name for the role (if defined in the course's 
12775: environment).  If no custom name is defined the default is returned.
12776:    
12777: =item *
12778: 
12779: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
12780: All arguments are optional. Returns a hash of a roles, either for
12781: co-author/assistant author roles for a user's Construction Space
12782: (default), or if $context is 'userroles', roles for the user himself,
12783: In the hash, keys are set to colon-separated $uname,$udom,$role, and
12784: (optionally) if $withsec is true, a fourth colon-separated item - $section.
12785: For each key, value is set to colon-separated start and end times for
12786: the role.  If no username and domain are specified, will default to
12787: current user/domain. Types, roles, and roledoms are references to arrays
12788: of role statuses (active, future or previous), roles 
12789: (e.g., cc,in, st etc.) and domains of the roles which can be used
12790: to restrict the list of roles reported. If no array ref is 
12791: provided for types, will default to return only active roles.
12792: 
12793: =item *
12794: 
12795: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
12796: user: $uname:$udom has a role in the course: $cdom_$cnum. 
12797: 
12798: Additional optional arguments are: $type (if role checking is to be restricted 
12799: to certain user status types -- previous (expired roles), active (currently
12800: available roles) or future (roles available in the future), and
12801: $hideprivileged -- if true will not report course roles for users who
12802: have active Domain Coordinator role in course's domain or in additional
12803: domains (specified in 'Domains to check for privileged users' in course
12804: environment -- set via:  Course Settings -> Classlists and staff listing).
12805: 
12806: =item *
12807: 
12808: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
12809: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
12810: $possdomains and $possroles are optional array refs -- to domains to check and
12811: roles to check.  If $possdomains is not specified, a dump will be done of the
12812: users' roles.db to check for a dc or su role in any domain. This can be
12813: time consuming if &privileged is called repeatedly (e.g., when displaying a
12814: classlist), so in such cases, supplying a $possdomains array is preferred, as
12815: this then allows &privileged_by_domain() to be used, which caches the identity
12816: of privileged users, eliminating the need for repeated calls to &dump().
12817: 
12818: =item *
12819: 
12820: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
12821: where the outer hash keys are domains specified in the $possdomains array ref,
12822: next inner hash keys are privileged roles specified in the $roles array ref,
12823: and the innermost hash contains key = value pairs for username:domain = end:start
12824: for active or future "privileged" users with that role in that domain. To avoid
12825: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
12826: innerhash are cached using priv_$role and $dom as the identifiers.
12827: 
12828: =back
12829: 
12830: =head2 User Modification
12831: 
12832: =over 4
12833: 
12834: =item *
12835: 
12836: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
12837: user for the level given by URL.  Optional start and end dates (leave empty
12838: string or zero for "no date")
12839: 
12840: =item *
12841: 
12842: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
12843: change a users, password, possible return values are: ok,
12844: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
12845: refused
12846: 
12847: =item *
12848: 
12849: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
12850: 
12851: =item *
12852: 
12853: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
12854:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
12855: 
12856: will update user information (firstname,middlename,lastname,generation,
12857: permanentemail), and if forceid is true, student/employee ID also.
12858: A user's institutional affiliation(s) can also be updated.
12859: User information fields will not be overwritten with empty entries 
12860: unless the field is included in the $candelete array reference.
12861: This array is included when a single user is modified via "Manage Users",
12862: or when Autoupdate.pl is run by cron in a domain.
12863: 
12864: =item *
12865: 
12866: modifystudent
12867: 
12868: modify a student's enrollment and identification information.
12869: The course id is resolved based on the current user's environment.  
12870: This means the invoking user must be a course coordinator or otherwise
12871: associated with a course.
12872: 
12873: This call is essentially a wrapper for lonnet::modifyuser and
12874: lonnet::modify_student_enrollment
12875: 
12876: Inputs: 
12877: 
12878: =over 4
12879: 
12880: =item B<$udom> Student's loncapa domain
12881: 
12882: =item B<$uname> Student's loncapa login name
12883: 
12884: =item B<$uid> Student/Employee ID
12885: 
12886: =item B<$umode> Student's authentication mode
12887: 
12888: =item B<$upass> Student's password
12889: 
12890: =item B<$first> Student's first name
12891: 
12892: =item B<$middle> Student's middle name
12893: 
12894: =item B<$last> Student's last name
12895: 
12896: =item B<$gene> Student's generation
12897: 
12898: =item B<$usec> Student's section in course
12899: 
12900: =item B<$end> Unix time of the roles expiration
12901: 
12902: =item B<$start> Unix time of the roles start date
12903: 
12904: =item B<$forceid> If defined, allow $uid to be changed
12905: 
12906: =item B<$desiredhome> server to use as home server for student
12907: 
12908: =item B<$email> Student's permanent e-mail address
12909: 
12910: =item B<$type> Type of enrollment (auto or manual)
12911: 
12912: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
12913: 
12914: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
12915: 
12916: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
12917: 
12918: =item B<$context> role change context (shown in User Management Logs display in a course)
12919: 
12920: =item B<$inststatus> institutional status of user - : separated string of escaped status types
12921: 
12922: =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.
12923: 
12924: =back
12925: 
12926: =item *
12927: 
12928: modify_student_enrollment
12929: 
12930: Change a student's enrollment status in a class.  The environment variable
12931: 'role.request.course' must be defined for this function to proceed.
12932: 
12933: Inputs:
12934: 
12935: =over 4
12936: 
12937: =item $udom, student's domain
12938: 
12939: =item $uname, student's name
12940: 
12941: =item $uid, student's user id
12942: 
12943: =item $first, student's first name
12944: 
12945: =item $middle
12946: 
12947: =item $last
12948: 
12949: =item $gene
12950: 
12951: =item $usec
12952: 
12953: =item $end
12954: 
12955: =item $start
12956: 
12957: =item $type
12958: 
12959: =item $locktype
12960: 
12961: =item $cid
12962: 
12963: =item $selfenroll
12964: 
12965: =item $context
12966: 
12967: =item $credits, number of credits student will earn from this class
12968: 
12969: =back
12970: 
12971: 
12972: =item *
12973: 
12974: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
12975: custom role; give a custom role to a user for the level given by URL.  Specify
12976: name and domain of role author, and role name
12977: 
12978: =item *
12979: 
12980: revokerole($udom,$uname,$url,$role) : revoke a role for url
12981: 
12982: =item *
12983: 
12984: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
12985: 
12986: =back
12987: 
12988: =head2 Course Infomation
12989: 
12990: =over 4
12991: 
12992: =item *
12993: 
12994: coursedescription($courseid,$options) : returns a hash of information about the
12995: specified course id, including all environment settings for the
12996: course, the description of the course will be in the hash under the
12997: key 'description'
12998: 
12999: $options is an optional parameter that if supplied is a hash reference that controls
13000: what how this function works.  It has the following key/values:
13001: 
13002: =over 4
13003: 
13004: =item freshen_cache
13005: 
13006: If defined, and the environment cache for the course is valid, it is 
13007: returned in the returned hash.
13008: 
13009: =item one_time
13010: 
13011: If defined, the last cache time is set to _now_
13012: 
13013: =item user
13014: 
13015: If defined, the supplied username is used instead of the current user.
13016: 
13017: 
13018: =back
13019: 
13020: =item *
13021: 
13022: resdata($name,$domain,$type,@which) : request for current parameter
13023: setting for a specific $type, where $type is either 'course' or 'user',
13024: @what should be a list of parameters to ask about. This routine caches
13025: answers for 10 minutes.
13026: 
13027: =item *
13028: 
13029: get_courseresdata($courseid, $domain) : dump the entire course resource
13030: data base, returning a hash that is keyed by the resource name and has
13031: values that are the resource value.  I believe that the timestamps and
13032: versions are also returned.
13033: 
13034: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
13035: supplemental content area. This routine caches the number of files for 
13036: 10 minutes.
13037: 
13038: =back
13039: 
13040: =head2 Course Modification
13041: 
13042: =over 4
13043: 
13044: =item *
13045: 
13046: writecoursepref($courseid,%prefs) : write preferences (environment
13047: database) for a course
13048: 
13049: =item *
13050: 
13051: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
13052: 
13053: =item *
13054: 
13055: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
13056: 
13057: =item *
13058: 
13059: is_course($courseid), is_course($cdom, $cnum)
13060: 
13061: Accepts either a combined $courseid (in the form of domain_courseid) or the
13062: two component version $cdom, $cnum. It checks if the specified course exists.
13063: 
13064: Returns:
13065:     undef if the course doesn't exist, otherwise
13066:     in scalar context the combined courseid.
13067:     in list context the two components of the course identifier, domain and 
13068:     courseid.    
13069: 
13070: =back
13071: 
13072: =head2 Resource Subroutines
13073: 
13074: =over 4
13075: 
13076: =item *
13077: 
13078: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
13079: 
13080: =item *
13081: 
13082: repcopy($filename) : subscribes to the requested file, and attempts to
13083: replicate from the owning library server, Might return
13084: 'unavailable', 'not_found', 'forbidden', 'ok', or
13085: 'bad_request', also attempts to grab the metadata for the
13086: resource. Expects the local filesystem pathname
13087: (/home/httpd/html/res/....)
13088: 
13089: =back
13090: 
13091: =head2 Resource Information
13092: 
13093: =over 4
13094: 
13095: =item *
13096: 
13097: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
13098: and returns the value of a variety of different possible values,
13099: $varname should be a request string, and the other parameters can be
13100: used to specify who and what one is asking about. Ordinarily, $cid 
13101: does not need to be specified, as it is retrived from 
13102: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
13103: within lonuserstate::loadmap() when initializing a course, before
13104: $env{'request.course.id'} has been set, so it needs to be provided
13105: in that one case.
13106: 
13107: Possible values for $varname are environment.lastname (or other item
13108: from the envirnment hash), user.name (or someother aspect about the
13109: user), resource.0.maxtries (or some other part and parameter of a
13110: resource)
13111: 
13112: =item *
13113: 
13114: directcondval($number) : get current value of a condition; reads from a state
13115: string
13116: 
13117: =item *
13118: 
13119: condval($condidx) : value of condition index based on state
13120: 
13121: =item *
13122: 
13123: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
13124: resource's metadata, $what should be either a specific key, or either
13125: 'keys' (to get a list of possible keys) or 'packages' to get a list of
13126: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
13127: 
13128: this function automatically caches all requests
13129: 
13130: =item *
13131: 
13132: metadata_query($query,$custom,$customshow) : make a metadata query against the
13133: network of library servers; returns file handle of where SQL and regex results
13134: will be stored for query
13135: 
13136: =item *
13137: 
13138: symbread($filename) : return symbolic list entry (filename argument optional);
13139: returns the data handle
13140: 
13141: =item *
13142: 
13143: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
13144: and is a possible symb for the URL in $thisfn, and if is an encrypted
13145: resource that the user accessed using /enc/ returns a 1 on success, 0
13146: on failure, user must be in a course, as it assumes the existence of
13147: the course initial hash, and uses $env('request.course.id'}.  The third
13148: arg is an optional reference to a scalar.  If this arg is passed in the 
13149: call to symbverify, it will be set to 1 if the symb has been set to be 
13150: encrypted; otherwise it will be null.  
13151: 
13152: =item *
13153: 
13154: symbclean($symb) : removes versions numbers from a symb, returns the
13155: cleaned symb
13156: 
13157: =item *
13158: 
13159: is_on_map($uri) : checks if the $uri is somewhere on the current
13160: course map, user must be in a course for it to work.
13161: 
13162: =item *
13163: 
13164: numval($salt) : return random seed value (addend for rndseed)
13165: 
13166: =item *
13167: 
13168: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13169: a random seed, all arguments are optional, if they aren't sent it uses the
13170: environment to derive them. Note: if symb isn't sent and it can't get one
13171: from &symbread it will use the current time as its return value
13172: 
13173: =item *
13174: 
13175: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13176: unfakeable, receipt
13177: 
13178: =item *
13179: 
13180: receipt() : API to ireceipt working off of env values; given out to users
13181: 
13182: =item *
13183: 
13184: countacc($url) : count the number of accesses to a given URL
13185: 
13186: =item *
13187: 
13188: 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
13189: 
13190: =item *
13191: 
13192: 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)
13193: 
13194: =item *
13195: 
13196: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
13197: 
13198: =item *
13199: 
13200: devalidate($symb) : devalidate temporary spreadsheet calculations,
13201: forcing spreadsheet to reevaluate the resource scores next time.
13202: 
13203: =item * 
13204: 
13205: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13206: when viewing in course context.
13207: 
13208:  input: six args -- filename (decluttered), course number, course domain,
13209:                     url, symb (if registered) and group (if this is a 
13210:                     group item -- e.g., bulletin board, group page etc.).
13211: 
13212:  output: array of five scalars --
13213:          $cfile -- url for file editing if editable on current server
13214:          $home -- homeserver of resource (i.e., for author if published,
13215:                                           or course if uploaded.).
13216:          $switchserver --  1 if server switch will be needed.
13217:          $forceedit -- 1 if icon/link should be to go to edit mode 
13218:          $forceview -- 1 if icon/link should be to go to view mode
13219: 
13220: =item *
13221: 
13222: is_course_upload($file,$cnum,$cdom)
13223: 
13224: Used in course context to determine if current file was uploaded to 
13225: the course (i.e., would be found in /userfiles/docs on the course's 
13226: homeserver.
13227: 
13228:   input: 3 args -- filename (decluttered), course number and course domain.
13229:   output: boolean -- 1 if file was uploaded.
13230: 
13231: =back
13232: 
13233: =head2 Storing/Retreiving Data
13234: 
13235: =over 4
13236: 
13237: =item *
13238: 
13239: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
13240: permanently for this url; hashref needs to be given and should be a \%hashname;
13241: the remaining args aren't required and if they aren't passed or are '' they will
13242: be derived from the env (with the exception of $laststore, which is an 
13243: optional arg used when a user's submission is stored in grading).
13244: $laststore is $version=$timestamp, where $version is the most recent version
13245: number retrieved for the corresponding $symb in the $namespace db file, and
13246: $timestamp is the timestamp for that transaction (UNIX time).
13247: $laststore is currently only passed when cstore() is called by 
13248: structuretags::finalize_storage().
13249: 
13250: =item *
13251: 
13252: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
13253: but uses critical subroutine
13254: 
13255: =item *
13256: 
13257: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13258: all args are optional
13259: 
13260: =item *
13261: 
13262: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
13263: dumps the complete (or key matching regexp) namespace into a hash
13264: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13265: normally &store()ed into
13266: 
13267: $range should be either an integer '100' (give me the first 100
13268:                                            matching records)
13269:               or be  two integers sperated by a - with no spaces
13270:                  '30-50' (give me the 30th through the 50th matching
13271:                           records)
13272: 
13273: 
13274: =item *
13275: 
13276: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
13277: replaces a &store() version of data with a replacement set of data
13278: for a particular resource in a namespace passed in the $storehash hash 
13279: reference. If $tolog is true, the transaction is logged in the courselog
13280: with an action=PUTSTORE.
13281: 
13282: =item *
13283: 
13284: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13285: works very similar to store/cstore, but all data is stored in a
13286: temporary location and can be reset using tmpreset, $storehash should
13287: be a hash reference, returns nothing on success
13288: 
13289: =item *
13290: 
13291: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13292: similar to restore, but all data is stored in a temporary location and
13293: can be reset using tmpreset. Returns a hash of values on success,
13294: error string otherwise.
13295: 
13296: =item *
13297: 
13298: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13299: deltes all keys for $symb form the temporary storage hash.
13300: 
13301: =item *
13302: 
13303: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13304: reference filled in from namesp ($udom and $uname are optional)
13305: 
13306: =item *
13307: 
13308: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13309: namesp ($udom and $uname are optional)
13310: 
13311: =item *
13312: 
13313: dump($namespace,$udom,$uname,$regexp,$range) : 
13314: dumps the complete (or key matching regexp) namespace into a hash
13315: ($udom, $uname, $regexp, $range are optional)
13316: 
13317: $range should be either an integer '100' (give me the first 100
13318:                                            matching records)
13319:               or be  two integers sperated by a - with no spaces
13320:                  '30-50' (give me the 30th through the 50th matching
13321:                           records)
13322: =item *
13323: 
13324: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13325: $store can be a scalar, an array reference, or if the amount to be 
13326: incremented is > 1, a hash reference.
13327: 
13328: ($udom and $uname are optional)
13329: 
13330: =item *
13331: 
13332: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13333: ($udom and $uname are optional)
13334: 
13335: =item *
13336: 
13337: cput($namespace,$storehash,$udom,$uname) : critical put
13338: ($udom and $uname are optional)
13339: 
13340: =item *
13341: 
13342: newput($namespace,$storehash,$udom,$uname) :
13343: 
13344: Attempts to store the items in the $storehash, but only if they don't
13345: currently exist, if this succeeds you can be certain that you have 
13346: successfully created a new key value pair in the $namespace db.
13347: 
13348: 
13349: Args:
13350:  $namespace: name of database to store values to
13351:  $storehash: hashref to store to the db
13352:  $udom: (optional) domain of user containing the db
13353:  $uname: (optional) name of user caontaining the db
13354: 
13355: Returns:
13356:  'ok' -> succeeded in storing all keys of $storehash
13357:  'key_exists: <key>' -> failed to anything out of $storehash, as at
13358:                         least <key> already existed in the db (other
13359:                         requested keys may also already exist)
13360:  'error: <msg>' -> unable to tie the DB or other error occurred
13361:  'con_lost' -> unable to contact request server
13362:  'refused' -> action was not allowed by remote machine
13363: 
13364: 
13365: =item *
13366: 
13367: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13368: reference filled in from namesp (encrypts the return communication)
13369: ($udom and $uname are optional)
13370: 
13371: =item *
13372: 
13373: log($udom,$name,$home,$message) : write to permanent log for user; use
13374: critical subroutine
13375: 
13376: =item *
13377: 
13378: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13379: array reference filled in from namespace found in domain level on either
13380: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
13381: 
13382: =item *
13383: 
13384: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
13385: domain level either on specified domain server ($uhome) or primary domain 
13386: server ($udom and $uhome are optional)
13387: 
13388: =item * 
13389: 
13390: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
13391: for: authentication, language, quotas, timezone, date locale, and portal URL in
13392: the target domain.
13393: 
13394: May also include additional key => value pairs for the following groups:
13395: 
13396: =over
13397: 
13398: =item
13399: disk quotas (MB allocated by default to portfolios and authoring spaces).
13400: 
13401: =over
13402: 
13403: =item defaultquota, authorquota
13404: 
13405: =back
13406: 
13407: =item
13408: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
13409: portfolio for users).
13410: 
13411: =over
13412: 
13413: =item
13414: aboutme, blog, webdav, portfolio
13415: 
13416: =back
13417: 
13418: =item
13419: requestcourses: ability to request courses, and how requests are processed.
13420: 
13421: =over
13422: 
13423: =item
13424: official, unofficial, community, textbook
13425: 
13426: =back
13427: 
13428: =item
13429: inststatus: types of institutional affiliation, and order in which they are displayed.
13430: 
13431: =over
13432: 
13433: =item
13434: inststatustypes, inststatusorder, inststatusguest
13435: 
13436: =back
13437: 
13438: =item
13439: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
13440: for course's uploaded content.
13441: 
13442: =over
13443: 
13444: =item
13445: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
13446: communityquota, textbookquota
13447: 
13448: =back
13449: 
13450: =item
13451: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
13452: on your servers.
13453: 
13454: =over
13455: 
13456: =item 
13457: remotesessions, hostedsessions
13458: 
13459: =back
13460: 
13461: =back
13462: 
13463: In cases where a domain coordinator has never used the "Set Domain Configuration"
13464: utility to create a configuration.db file on a domain's primary library server 
13465: only the following domain defaults: auth_def, auth_arg_def, lang_def
13466: -- corresponding values are authentication type (internal, krb4, krb5,
13467: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
13468: will be available. Values are retrieved from cache (if current), unless the
13469: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
13470: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
13471: 
13472: Typical usage:
13473: 
13474: %domdefaults = &get_domain_defaults($target_domain);
13475: 
13476: =back
13477: 
13478: =head2 Network Status Functions
13479: 
13480: =over 4
13481: 
13482: =item *
13483: 
13484: dirlist() : return directory list based on URI (first arg).
13485: 
13486: Inputs: 1 required, 5 optional.
13487: 
13488: =over
13489: 
13490: =item 
13491: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13492: 
13493: =item
13494: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
13495: 
13496: =item
13497: $username -  username of user/course to be listed. Extracted from $uri if absent. 
13498: 
13499: =item
13500: $getpropath - boolean: 1 if prepend path using &propath(). 
13501: 
13502: =item
13503: $getuserdir - boolean: 1 if prepend path for "userfiles".
13504: 
13505: =item 
13506: $alternateRoot - path to prepend in place of path from $uri.
13507: 
13508: =back
13509: 
13510: Returns: Array of up to two items.
13511: 
13512: =over
13513: 
13514: a reference to an array of files/subdirectories
13515: 
13516: =over
13517: 
13518: Each element in the array of files/subdirectories is a & separated list of
13519: item name and the result of running stat on the item.  If dirlist was requested
13520: for a file instead of a directory, the item name will be ''. For a directory 
13521: listing, if the item is a metadata file, the element will end &N&M 
13522: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13523: default copyright set (1).  
13524: 
13525: =back
13526: 
13527: a scalar containing error condition (if encountered).
13528: 
13529: =over
13530: 
13531: =item 
13532: no_host (no homeserver identified for $username:$domain).
13533: 
13534: =item 
13535: no_such_host (server contacted for listing not identified as valid host).
13536: 
13537: =item 
13538: con_lost (connection to remote server failed).
13539: 
13540: =item 
13541: refused (invalid $username:$domain received on lond side).
13542: 
13543: =item 
13544: no_such_dir (directory at specified path on lond side does not exist). 
13545: 
13546: =item 
13547: empty (directory at specified path on lond side is empty).
13548: 
13549: =over
13550: 
13551: This is currently not encountered because the &ls3, &ls2, 
13552: &ls (_handler) routines on the lond side do not filter out
13553: . and .. from a directory listing. 
13554: 
13555: =back
13556: 
13557: =back
13558: 
13559: =back
13560: 
13561: =item *
13562: 
13563: spareserver() : find server with least workload from spare.tab
13564: 
13565: 
13566: =item *
13567: 
13568: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13569: if there is no corresponding loncapa host.
13570: 
13571: =back
13572: 
13573: 
13574: =head2 Apache Request
13575: 
13576: =over 4
13577: 
13578: =item *
13579: 
13580: ssi($url,%hash) : server side include, does a complete request cycle on url to
13581: localhost, posts hash
13582: 
13583: =back
13584: 
13585: =head2 Data to String to Data
13586: 
13587: =over 4
13588: 
13589: =item *
13590: 
13591: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13592: and '&' separators, supports elements that are arrayrefs and hashrefs
13593: 
13594: =item *
13595: 
13596: hashref2str($hashref) : convert a hashref into a string complete with
13597: escaping and '=' and '&' separators, supports elements that are
13598: arrayrefs and hashrefs
13599: 
13600: =item *
13601: 
13602: arrayref2str($arrayref) : convert an arrayref into a string complete
13603: with escaping and '&' separators, supports elements that are arrayrefs
13604: and hashrefs
13605: 
13606: =item *
13607: 
13608: str2hash($string) : convert string to hash using unescaping and
13609: splitting on '=' and '&', supports elements that are arrayrefs and
13610: hashrefs
13611: 
13612: =item *
13613: 
13614: str2array($string) : convert string to hash using unescaping and
13615: splitting on '&', supports elements that are arrayrefs and hashrefs
13616: 
13617: =back
13618: 
13619: =head2 Logging Routines
13620: 
13621: 
13622: These routines allow one to make log messages in the lonnet.log and
13623: lonnet.perm logfiles.
13624: 
13625: =over 4
13626: 
13627: =item *
13628: 
13629: logtouch() : make sure the logfile, lonnet.log, exists
13630: 
13631: =item *
13632: 
13633: logthis() : append message to the normal lonnet.log file, it gets
13634: preiodically rolled over and deleted.
13635: 
13636: =item *
13637: 
13638: logperm() : append a permanent message to lonnet.perm.log, this log
13639: file never gets deleted by any automated portion of the system, only
13640: messages of critical importance should go in here.
13641: 
13642: 
13643: =back
13644: 
13645: =head2 General File Helper Routines
13646: 
13647: =over 4
13648: 
13649: =item *
13650: 
13651: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
13652: (a) files in /uploaded
13653:   (i) If a local copy of the file exists - 
13654:       compares modification date of local copy with last-modified date for 
13655:       definitive version stored on home server for course. If local copy is 
13656:       stale, requests a new version from the home server and stores it. 
13657:       If the original has been removed from the home server, then local copy 
13658:       is unlinked.
13659:   (ii) If local copy does not exist -
13660:       requests the file from the home server and stores it. 
13661:   
13662:   If $caller is 'uploadrep':  
13663:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
13664:     for request for files originally uploaded via DOCS. 
13665:      - returns 'ok' if fresh local copy now available, -1 otherwise.
13666:   
13667:   Otherwise:
13668:      This indicates a call from the content generation phase of the request.
13669:      -  returns the entire contents of the file or -1.
13670:      
13671: (b) files in /res
13672:    - returns the entire contents of a file or -1; 
13673:    it properly subscribes to and replicates the file if neccessary.
13674: 
13675: 
13676: =item *
13677: 
13678: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
13679:                   reference
13680: 
13681: returns either a stat() list of data about the file or an empty list
13682: if the file doesn't exist or couldn't find out about it (connection
13683: problems or user unknown)
13684: 
13685: =item *
13686: 
13687: filelocation($dir,$file) : returns file system location of a file
13688: based on URI; meant to be "fairly clean" absolute reference, $dir is a
13689: directory that relative $file lookups are to looked in ($dir of /a/dir
13690: and a file of ../bob will become /a/bob)
13691: 
13692: =item *
13693: 
13694: hreflocation($dir,$file) : returns file system location or a URL; same as
13695: filelocation except for hrefs
13696: 
13697: =item *
13698: 
13699: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
13700: also removes beginning /home/httpd/html unless /priv/ follows it.
13701: 
13702: =back
13703: 
13704: =head2 Usererfile file routines (/uploaded*)
13705: 
13706: =over 4
13707: 
13708: =item *
13709: 
13710: userfileupload(): main rotine for putting a file in a user or course's
13711:                   filespace, arguments are,
13712: 
13713:  formname - required - this is the name of the element in $env where the
13714:            filename, and the contents of the file to create/modifed exist
13715:            the filename is in $env{'form.'.$formname.'.filename'} and the
13716:            contents of the file is located in $env{'form.'.$formname}
13717:  context - if coursedoc, store the file in the course of the active role
13718:              of the current user; 
13719:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
13720:            if 'canceloverwrite': delete file in tmp/overwrites directory
13721:  subdir - required - subdirectory to put the file in under ../userfiles/
13722:          if undefined, it will be placed in "unknown"
13723: 
13724:  (This routine calls clean_filename() to remove any dangerous
13725:  characters from the filename, and then calls finuserfileupload() to
13726:  complete the transaction)
13727: 
13728:  returns either the url of the uploaded file (/uploaded/....) if successful
13729:  and /adm/notfound.html if unsuccessful
13730: 
13731: =item *
13732: 
13733: clean_filename(): routine for cleaing a filename up for storage in
13734:                  userfile space, argument is:
13735: 
13736:  filename - proposed filename
13737: 
13738: returns: the new clean filename
13739: 
13740: =item *
13741: 
13742: finishuserfileupload(): routine that creates and sends the file to
13743: userspace, probably shouldn't be called directly
13744: 
13745:   docuname: username or courseid of destination for the file
13746:   docudom: domain of user/course of destination for the file
13747:   formname: same as for userfileupload()
13748:   fname: filename (including subdirectories) for the file
13749:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
13750:   allfiles: reference to hash used to store objects found by parser
13751:   codebase: reference to hash used for codebases of java objects found by parser
13752:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
13753:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
13754:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
13755:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
13756:   context: if 'overwrite', will move the uploaded file from its temporary location to
13757:             userfiles to facilitate overwriting a previously uploaded file with same name.
13758:   mimetype: reference to scalar to accommodate mime type determined
13759:             from File::MMagic if $parser = parse.
13760: 
13761:  returns either the url of the uploaded file (/uploaded/....) if successful
13762:  and /adm/notfound.html if unsuccessful (or an error message if context 
13763:  was 'overwrite').
13764:  
13765: 
13766: =item *
13767: 
13768: renameuserfile(): renames an existing userfile to a new name
13769: 
13770:   Args:
13771:    docuname: username or courseid of destination for the file
13772:    docudom: domain of user/course of destination for the file
13773:    old: current file name (including any subdirs under userfiles)
13774:    new: desired file name (including any subdirs under userfiles)
13775: 
13776: =item *
13777: 
13778: mkdiruserfile(): creates a directory is a userfiles dir
13779: 
13780:   Args:
13781:    docuname: username or courseid of destination for the file
13782:    docudom: domain of user/course of destination for the file
13783:    dir: dir to create (including any subdirs under userfiles)
13784: 
13785: =item *
13786: 
13787: removeuserfile(): removes a file that exists in userfiles
13788: 
13789:   Args:
13790:    docuname: username or courseid of destination for the file
13791:    docudom: domain of user/course of destination for the file
13792:    fname: filname to delete (including any subdirs under userfiles)
13793: 
13794: =item *
13795: 
13796: removeuploadedurl(): convience function for removeuserfile()
13797: 
13798:   Args:
13799:    url:  a full /uploaded/... url to delete
13800: 
13801: =item * 
13802: 
13803: get_portfile_permissions():
13804:   Args:
13805:     domain: domain of user or course contain the portfolio files
13806:     user: name of user or num of course contain the portfolio files
13807:   Returns:
13808:     hashref of a dump of the proper file_permissions.db
13809:    
13810: 
13811: =item * 
13812: 
13813: get_access_controls():
13814: 
13815: Args:
13816:   current_permissions: the hash ref returned from get_portfile_permissions()
13817:   group: (optional) the group you want the files associated with
13818:   file: (optional) the file you want access info on
13819: 
13820: Returns:
13821:     a hash (keys are file names) of hashes containing
13822:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
13823:         values are XML containing access control settings (see below) 
13824: 
13825: Internal notes:
13826: 
13827:  access controls are stored in file_permissions.db as key=value pairs.
13828:     key -> path to file/file_name\0uniqueID:scope_end_start
13829:         where scope -> public,guest,course,group,domains or users.
13830:               end -> UNIX time for end of access (0 -> no end date)
13831:               start -> UNIX time for start of access
13832: 
13833:     value -> XML description of access control
13834:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
13835:             <start></start>
13836:             <end></end>
13837: 
13838:             <password></password>  for scope type = guest
13839: 
13840:             <domain></domain>     for scope type = course or group
13841:             <number></number>
13842:             <roles id="">
13843:              <role></role>
13844:              <access></access>
13845:              <section></section>
13846:              <group></group>
13847:             </roles>
13848: 
13849:             <dom></dom>         for scope type = domains
13850: 
13851:             <users>             for scope type = users
13852:              <user>
13853:               <uname></uname>
13854:               <udom></udom>
13855:              </user>
13856:             </users>
13857:            </scope> 
13858:               
13859:  Access data is also aggregated for each file in an additional key=value pair:
13860:  key -> path to file/file_name\0accesscontrol 
13861:  value -> reference to hash
13862:           hash contains key = value pairs
13863:           where key = uniqueID:scope_end_start
13864:                 value = UNIX time record was last updated
13865: 
13866:           Used to improve speed of look-ups of access controls for each file.  
13867:  
13868:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
13869: 
13870: =item *
13871: 
13872: modify_access_controls():
13873: 
13874: Modifies access controls for a portfolio file
13875: Args
13876: 1. file name
13877: 2. reference to hash of required changes,
13878: 3. domain
13879: 4. username
13880:   where domain,username are the domain of the portfolio owner 
13881:   (either a user or a course) 
13882: 
13883: Returns:
13884: 1. result of additions or updates ('ok' or 'error', with error message). 
13885: 2. result of deletions ('ok' or 'error', with error message).
13886: 3. reference to hash of any new or updated access controls.
13887: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
13888:    key = integer (inbound ID)
13889:    value = uniqueID
13890: 
13891: =item *
13892: 
13893: get_timebased_id():
13894: 
13895: Attempts to get a unique timestamp-based suffix for use with items added to a 
13896: course via the Course Editor (e.g., folders, composite pages, 
13897: group bulletin boards).
13898: 
13899: Args: (first three required; six others optional)
13900: 
13901: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
13902:    docssequence, or name of group
13903: 
13904: 2. keyid (alphanumeric): name of temporary locking key in hash,
13905:    e.g., num, boardids
13906: 
13907: 3. namespace: name of gdbm file used to store suffixes already assigned;  
13908:    file will be named nohist_namespace.db
13909: 
13910: 4. cdom: domain of course; default is current course domain from %env
13911: 
13912: 5. cnum: course number; default is current course number from %env
13913: 
13914: 6. idtype: set to concat if an additional digit is to be appended to the 
13915:    unix timestamp to form the suffix, if the plain timestamp is already
13916:    in use.  Default is to not do this, but simply increment the unix 
13917:    timestamp by 1 until a unique key is obtained.
13918: 
13919: 7. who: holder of locking key; defaults to user:domain for user.
13920: 
13921: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
13922:    retrying); default is 3.
13923: 
13924: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
13925: 
13926: Returns:
13927: 
13928: 1. suffix obtained (numeric)
13929: 
13930: 2. result of deleting locking key (ok if deleted, or lock never obtained)
13931: 
13932: 3. error: contains (localized) error message if an error occurred.
13933: 
13934: 
13935: =back
13936: 
13937: =head2 HTTP Helper Routines
13938: 
13939: =over 4
13940: 
13941: =item *
13942: 
13943: escape() : unpack non-word characters into CGI-compatible hex codes
13944: 
13945: =item *
13946: 
13947: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
13948: 
13949: =back
13950: 
13951: =head1 PRIVATE SUBROUTINES
13952: 
13953: =head2 Underlying communication routines (Shouldn't call)
13954: 
13955: =over 4
13956: 
13957: =item *
13958: 
13959: subreply() : tries to pass a message to lonc, returns con_lost if incapable
13960: 
13961: =item *
13962: 
13963: reply() : uses subreply to send a message to remote machine, logs all failures
13964: 
13965: =item *
13966: 
13967: critical() : passes a critical message to another server; if cannot
13968: get through then place message in connection buffer directory and
13969: returns con_delayed, if incapable of saving message, returns
13970: con_failed
13971: 
13972: =item *
13973: 
13974: reconlonc() : tries to reconnect lonc client processes.
13975: 
13976: =back
13977: 
13978: =head2 Resource Access Logging
13979: 
13980: =over 4
13981: 
13982: =item *
13983: 
13984: flushcourselogs() : flush (save) buffer logs and access logs
13985: 
13986: =item *
13987: 
13988: courselog($what) : save message for course in hash
13989: 
13990: =item *
13991: 
13992: courseacclog($what) : save message for course using &courselog().  Perform
13993: special processing for specific resource types (problems, exams, quizzes, etc).
13994: 
13995: =item *
13996: 
13997: goodbye() : flush course logs and log shutting down; it is called in srm.conf
13998: as a PerlChildExitHandler
13999: 
14000: =back
14001: 
14002: =head2 Other
14003: 
14004: =over 4
14005: 
14006: =item *
14007: 
14008: symblist($mapname,%newhash) : update symbolic storage links
14009: 
14010: =back
14011: 
14012: =cut
14013: 

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