File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1275: download - view: text, annotated - select for diffs
Tue Dec 16 19:57:56 2014 UTC (9 years, 6 months ago) by musolffc
Branches: MAIN
CVS tags: HEAD
Fixed closing paren typo

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1275 2014/12/16 19:57:56 musolffc 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 { 
 2727:             my $name = escape($_);
 2728:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
 2729:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
 2730:             : &escape($form{$_}) );    
 2731:         } keys(%form)));
 2732:     } else {
 2733:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 2734:     }
 2735: 
 2736:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 2737:     my $response= $ua->request($request);
 2738:     my $content = $response->content;
 2739: 
 2740: 
 2741:     if (wantarray) {
 2742: 	return ($content, $response);
 2743:     } else {
 2744: 	return $content;
 2745:     }
 2746: }
 2747: 
 2748: sub externalssi {
 2749:     my ($url)=@_;
 2750:     my $ua=new LWP::UserAgent;
 2751:     my $request=new HTTP::Request('GET',$url);
 2752:     my $response=$ua->request($request);
 2753:     if (wantarray) {
 2754:         return ($response->content, $response);
 2755:     } else {
 2756:         return $response->content;
 2757:     }
 2758: }
 2759: 
 2760: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 2761: 
 2762: sub allowuploaded {
 2763:     my ($srcurl,$url)=@_;
 2764:     $url=&clutter(&declutter($url));
 2765:     my $dir=$url;
 2766:     $dir=~s/\/[^\/]+$//;
 2767:     my %httpref=();
 2768:     my $httpurl=&hreflocation('',$url);
 2769:     $httpref{'httpref.'.$httpurl}=$srcurl;
 2770:     &Apache::lonnet::appenv(\%httpref);
 2771: }
 2772: 
 2773: #
 2774: # Determine if the current user should be able to edit a particular resource,
 2775: # when viewing in course context.
 2776: # (a) When viewing resource used to determine if "Edit" item is included in 
 2777: #     Functions.
 2778: # (b) When displaying folder contents in course editor, used to determine if
 2779: #     "Edit" link will be displayed alongside resource.
 2780: #
 2781: #  input: six args -- filename (decluttered), course number, course domain,
 2782: #                   url, symb (if registered) and group (if this is a group
 2783: #                   item -- e.g., bulletin board, group page etc.).
 2784: #  output: array of five scalars -- 
 2785: #          $cfile -- url for file editing if editable on current server
 2786: #          $home -- homeserver of resource (i.e., for author if published,
 2787: #                                           or course if uploaded.).
 2788: #          $switchserver --  1 if server switch will be needed.
 2789: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 2790: #          $forceview -- 1 if icon/link should be to go to view mode
 2791: #
 2792: 
 2793: sub can_edit_resource {
 2794:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 2795:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 2796: #
 2797: # For aboutme pages user can only edit his/her own.
 2798: #
 2799:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 2800:         my ($sdom,$sname) = ($1,$2);
 2801:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 2802:             $home = $env{'user.home'};
 2803:             $cfile = $resurl;
 2804:             if ($env{'form.forceedit'}) {
 2805:                 $forceview = 1;
 2806:             } else {
 2807:                 $forceedit = 1;
 2808:             }
 2809:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 2810:         } else {
 2811:             return;
 2812:         }
 2813:     }
 2814: 
 2815:     if ($env{'request.course.id'}) {
 2816:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 2817:         if ($group ne '') {
 2818: # if this is a group homepage or group bulletin board, check group privs
 2819:             my $allowed = 0;
 2820:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 2821:                 if ((&allowed('mdg',$env{'request.course.id'}.
 2822:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 2823:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 2824:                     $allowed = 1;
 2825:                 }
 2826:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 2827:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 2828:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 2829:                     $allowed = 1;
 2830:                 }
 2831:             }
 2832:             if ($allowed) {
 2833:                 $home=&homeserver($cnum,$cdom);
 2834:                 if ($env{'form.forceedit'}) {
 2835:                     $forceview = 1;
 2836:                 } else {
 2837:                     $forceedit = 1;
 2838:                 }
 2839:                 $cfile = $resurl;
 2840:             } else {
 2841:                 return;
 2842:             }
 2843:         } else {
 2844:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 2845:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 2846:                     return;
 2847:                 }
 2848:             } elsif (!$crsedit) {
 2849: #
 2850: # No edit allowed where CC has switched to student role.
 2851: #
 2852:                 return;
 2853:             }
 2854:         }
 2855:     }
 2856: 
 2857:     if ($file ne '') {
 2858:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 2859:             if (&is_course_upload($file,$cnum,$cdom)) {
 2860:                 $uploaded = 1;
 2861:                 $incourse = 1;
 2862:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 2863:                     $cfile = &hreflocation('',$file);
 2864:                     if ($env{'form.forceedit'}) {
 2865:                         $forceview = 1;
 2866:                     } else {
 2867:                         $forceedit = 1;
 2868:                     }
 2869:                 }
 2870:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 2871:                 $incourse = 1;
 2872:                 if ($env{'form.forceedit'}) {
 2873:                     $forceview = 1;
 2874:                 } else {
 2875:                     $forceedit = 1;
 2876:                 }
 2877:                 $cfile = $resurl;
 2878:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 2879:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 2880:                     $incourse = 1;
 2881:                     if ($env{'form.forceedit'}) {
 2882:                         $forceview = 1;
 2883:                     } else {
 2884:                         $forceedit = 1;
 2885:                     }
 2886:                     $cfile = $resurl;
 2887:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 2888:                     $incourse = 1;
 2889:                     $cfile = $resurl.'/smpedit';
 2890:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 2891:                     $incourse = 1;
 2892:                     if ($env{'form.forceedit'}) {
 2893:                         $forceview = 1;
 2894:                     } else {
 2895:                         $forceedit = 1;
 2896:                     }
 2897:                     $cfile = $resurl;
 2898:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 2899:                     $incourse = 1;
 2900:                     if ($env{'form.forceedit'}) {
 2901:                         $forceview = 1;
 2902:                     } else {
 2903:                         $forceedit = 1;
 2904:                     }
 2905:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 2906:                 }
 2907:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 2908:                 my $template = '/res/lib/templates/simpleproblem.problem';
 2909:                 if (&is_on_map($template)) { 
 2910:                     $incourse = 1;
 2911:                     $forceview = 1;
 2912:                     $cfile = $template;
 2913:                 }
 2914:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 2915:                     $incourse = 1;
 2916:                     if ($env{'form.forceedit'}) {
 2917:                         $forceview = 1;
 2918:                     } else {
 2919:                         $forceedit = 1;
 2920:                     }
 2921:                     $cfile = $resurl;
 2922:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 2923:                 $incourse = 1;
 2924:                 $forceview = 1;
 2925:                 if ($symb) {
 2926:                     my ($map,$id,$res)=&decode_symb($symb);
 2927:                     $env{'request.symb'} = $symb;
 2928:                     $cfile = &clutter($res);
 2929:                 } else {
 2930:                     $cfile = $env{'form.suppurl'};
 2931:                     $cfile =~ s{^http://}{};
 2932:                     $cfile = '/adm/wrapper/ext/'.$cfile;
 2933:                 }
 2934:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 2935:                 if ($env{'form.forceedit'}) {
 2936:                     $forceview = 1;
 2937:                 } else {
 2938:                     $forceedit = 1;
 2939:                 }
 2940:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 2941:             }
 2942:         }
 2943:         if ($uploaded || $incourse) {
 2944:             $home=&homeserver($cnum,$cdom);
 2945:         } elsif ($file !~ m{/$}) {
 2946:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 2947:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 2948:             # Check that the user has permission to edit this resource
 2949:             my $setpriv = 1;
 2950:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 2951:             if (defined($cfudom)) {
 2952:                 $home=&homeserver($cfuname,$cfudom);
 2953:                 $cfile=$file;
 2954:             }
 2955:         }
 2956:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 2957:             (($home ne '') && ($home ne 'no_host'))) {
 2958:             my @ids=&current_machine_ids();
 2959:             unless (grep(/^\Q$home\E$/,@ids)) {
 2960:                 $switchserver=1;
 2961:             }
 2962:         }
 2963:     }
 2964:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 2965: }
 2966: 
 2967: sub is_course_upload {
 2968:     my ($file,$cnum,$cdom) = @_;
 2969:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 2970:     $uploadpath =~ s{^\/}{};
 2971:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 2972:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 2973:         return 1;
 2974:     }
 2975:     return;
 2976: }
 2977: 
 2978: sub in_course {
 2979:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 2980:     if ($hideprivileged) {
 2981:         my $skipuser;
 2982:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 2983:         my @possdoms = ($cdom);  
 2984:         if ($coursehash{'checkforpriv'}) { 
 2985:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 2986:         }
 2987:         if (&privileged($uname,$udom,\@possdoms)) {
 2988:             $skipuser = 1;
 2989:             if ($coursehash{'nothideprivileged'}) {
 2990:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2991:                     my $user;
 2992:                     if ($item =~ /:/) {
 2993:                         $user = $item;
 2994:                     } else {
 2995:                         $user = join(':',split(/[\@]/,$item));
 2996:                     }
 2997:                     if ($user eq $uname.':'.$udom) {
 2998:                         undef($skipuser);
 2999:                         last;
 3000:                     }
 3001:                 }
 3002:             }
 3003:             if ($skipuser) {
 3004:                 return 0;
 3005:             }
 3006:         }
 3007:     }
 3008:     $type ||= 'any';
 3009:     if (!defined($cdom) || !defined($cnum)) {
 3010:         my $cid  = $env{'request.course.id'};
 3011:         $cdom = $env{'course.'.$cid.'.domain'};
 3012:         $cnum = $env{'course.'.$cid.'.num'};
 3013:     }
 3014:     my $typesref;
 3015:     if (($type eq 'any') || ($type eq 'all')) {
 3016:         $typesref = ['active','previous','future'];
 3017:     } elsif ($type eq 'previous' || $type eq 'future') {
 3018:         $typesref = [$type];
 3019:     }
 3020:     my %roles = &get_my_roles($uname,$udom,'userroles',
 3021:                               $typesref,undef,[$cdom]);
 3022:     my ($tmp) = keys(%roles);
 3023:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 3024:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 3025:     if (@course_roles > 0) {
 3026:         return 1;
 3027:     }
 3028:     return 0;
 3029: }
 3030: 
 3031: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 3032: # input: action, courseID, current domain, intended
 3033: #        path to file, source of file, instruction to parse file for objects,
 3034: #        ref to hash for embedded objects,
 3035: #        ref to hash for codebase of java objects.
 3036: #        reference to scalar to accommodate mime type determined
 3037: #          from File::MMagic if $parser = parse.
 3038: #
 3039: # output: url to file (if action was uploaddoc), 
 3040: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 3041: #
 3042: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 3043: # course.
 3044: #
 3045: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3046: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 3047: #          course's home server.
 3048: #
 3049: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 3050: #          be copied from $source (current location) to 
 3051: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3052: #         and will then be copied to
 3053: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 3054: #         course's home server.
 3055: #
 3056: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3057: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 3058: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3059: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 3060: #         in course's home server.
 3061: #
 3062: 
 3063: sub process_coursefile {
 3064:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 3065:         $mimetype)=@_;
 3066:     my $fetchresult;
 3067:     my $home=&homeserver($docuname,$docudom);
 3068:     if ($action eq 'propagate') {
 3069:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3070: 			     $home);
 3071:     } else {
 3072:         my $fpath = '';
 3073:         my $fname = $file;
 3074:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3075:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3076:         my $filepath = &build_filepath($fpath);
 3077:         if ($action eq 'copy') {
 3078:             if ($source eq '') {
 3079:                 $fetchresult = 'no source file';
 3080:                 return $fetchresult;
 3081:             } else {
 3082:                 my $destination = $filepath.'/'.$fname;
 3083:                 rename($source,$destination);
 3084:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3085:                                  $home);
 3086:             }
 3087:         } elsif ($action eq 'uploaddoc') {
 3088:             open(my $fh,'>'.$filepath.'/'.$fname);
 3089:             print $fh $env{'form.'.$source};
 3090:             close($fh);
 3091:             if ($parser eq 'parse') {
 3092:                 my $mm = new File::MMagic;
 3093:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 3094:                 if ($type eq 'text/html') {
 3095:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 3096:                     unless ($parse_result eq 'ok') {
 3097:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 3098:                     }
 3099:                 }
 3100:                 if (ref($mimetype)) {
 3101:                     $$mimetype = $type;
 3102:                 } 
 3103:             }
 3104:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3105:                                  $home);
 3106:             if ($fetchresult eq 'ok') {
 3107:                 return '/uploaded/'.$fpath.'/'.$fname;
 3108:             } else {
 3109:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3110:                         ' to host '.$home.': '.$fetchresult);
 3111:                 return '/adm/notfound.html';
 3112:             }
 3113:         }
 3114:     }
 3115:     unless ( $fetchresult eq 'ok') {
 3116:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3117:              ' to host '.$home.': '.$fetchresult);
 3118:     }
 3119:     return $fetchresult;
 3120: }
 3121: 
 3122: sub build_filepath {
 3123:     my ($fpath) = @_;
 3124:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 3125:     unless ($fpath eq '') {
 3126:         my @parts=split('/',$fpath);
 3127:         foreach my $part (@parts) {
 3128:             $filepath.= '/'.$part;
 3129:             if ((-e $filepath)!=1) {
 3130:                 mkdir($filepath,0777);
 3131:             }
 3132:         }
 3133:     }
 3134:     return $filepath;
 3135: }
 3136: 
 3137: sub store_edited_file {
 3138:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 3139:     my $file = $primary_url;
 3140:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 3141:     my $fpath = '';
 3142:     my $fname = $file;
 3143:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3144:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3145:     my $filepath = &build_filepath($fpath);
 3146:     open(my $fh,'>'.$filepath.'/'.$fname);
 3147:     print $fh $content;
 3148:     close($fh);
 3149:     my $home=&homeserver($docuname,$docudom);
 3150:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3151: 			  $home);
 3152:     if ($$fetchresult eq 'ok') {
 3153:         return '/uploaded/'.$fpath.'/'.$fname;
 3154:     } else {
 3155:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3156: 		 ' to host '.$home.': '.$$fetchresult);
 3157:         return '/adm/notfound.html';
 3158:     }
 3159: }
 3160: 
 3161: sub clean_filename {
 3162:     my ($fname,$args)=@_;
 3163: # Replace Windows backslashes by forward slashes
 3164:     $fname=~s/\\/\//g;
 3165:     if (!$args->{'keep_path'}) {
 3166:         # Get rid of everything but the actual filename
 3167: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 3168:     }
 3169: # Replace spaces by underscores
 3170:     $fname=~s/\s+/\_/g;
 3171: # Replace all other weird characters by nothing
 3172:     $fname=~s{[^/\w\.\-]}{}g;
 3173: # Replace all .\d. sequences with _\d. so they no longer look like version
 3174: # numbers
 3175:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 3176:     return $fname;
 3177: }
 3178: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 3179: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 3180: # image with the same aspect ratio as the original, but with dimensions which do 
 3181: # not exceed $resizewidth and $resizeheight.
 3182:  
 3183: sub resizeImage {
 3184:     my ($img_path,$resizewidth,$resizeheight) = @_;
 3185:     my $ima = Image::Magick->new;
 3186:     my $resized;
 3187:     if (-e $img_path) {
 3188:         $ima->Read($img_path);
 3189:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 3190:             my $width = $ima->Get('width');
 3191:             my $height = $ima->Get('height');
 3192:             if ($width > $resizewidth) {
 3193: 	        my $factor = $width/$resizewidth;
 3194:                 my $newheight = $height/$factor;
 3195:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 3196:                 $resized = 1;
 3197:             }
 3198:         }
 3199:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 3200:             my $width = $ima->Get('width');
 3201:             my $height = $ima->Get('height');
 3202:             if ($height > $resizeheight) {
 3203:                 my $factor = $height/$resizeheight;
 3204:                 my $newwidth = $width/$factor;
 3205:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 3206:                 $resized = 1;
 3207:             }
 3208:         }
 3209:         if ($resized) {
 3210:             $ima->Write($img_path);
 3211:         }
 3212:     }
 3213:     return;
 3214: }
 3215: 
 3216: # --------------- Take an uploaded file and put it into the userfiles directory
 3217: # input: $formname - the contents of the file are in $env{"form.$formname"}
 3218: #                    the desired filename is in $env{"form.$formname.filename"}
 3219: #        $context - possible values: coursedoc, existingfile, overwrite, 
 3220: #                                    canceloverwrite, or ''. 
 3221: #                   if 'coursedoc': upload to the current course
 3222: #                   if 'existingfile': write file to tmp/overwrites directory 
 3223: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 3224: #                   $context is passed as argument to &finishuserfileupload
 3225: #        $subdir - directory in userfile to store the file into
 3226: #        $parser - instruction to parse file for objects ($parser = parse)    
 3227: #        $allfiles - reference to hash for embedded objects
 3228: #        $codebase - reference to hash for codebase of java objects
 3229: #        $desuname - username for permanent storage of uploaded file
 3230: #        $dsetudom - domain for permanaent storage of uploaded file
 3231: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 3232: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 3233: #        $resizewidth - width (pixels) to which to resize uploaded image
 3234: #        $resizeheight - height (pixels) to which to resize uploaded image
 3235: #        $mimetype - reference to scalar to accommodate mime type determined
 3236: #                    from File::MMagic.
 3237: # 
 3238: # output: url of file in userspace, or error: <message> 
 3239: #             or /adm/notfound.html if failure to upload occurse
 3240: 
 3241: sub userfileupload {
 3242:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 3243:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 3244:     if (!defined($subdir)) { $subdir='unknown'; }
 3245:     my $fname=$env{'form.'.$formname.'.filename'};
 3246:     $fname=&clean_filename($fname);
 3247:     # See if there is anything left
 3248:     unless ($fname) { return 'error: no uploaded file'; }
 3249:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 3250:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 3251:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 3252:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3253:         my $now = time;
 3254:         my $filepath;
 3255:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 3256:              $filepath = 'tmp/helprequests/'.$now;
 3257:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 3258:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 3259:                          '_'.$env{'user.domain'}.'/pending';
 3260:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3261:             my ($docuname,$docudom);
 3262:             if ($destudom) {
 3263:                 $docudom = $destudom;
 3264:             } else {
 3265:                 $docudom = $env{'user.domain'};
 3266:             }
 3267:             if ($destuname) {
 3268:                 $docuname = $destuname;
 3269:             } else {
 3270:                 $docuname = $env{'user.name'};
 3271:             }
 3272:             if (exists($env{'form.group'})) {
 3273:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3274:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3275:             }
 3276:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 3277:             if ($context eq 'canceloverwrite') {
 3278:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 3279:                 if (-e  $tempfile) {
 3280:                     my @info = stat($tempfile);
 3281:                     if ($info[9] eq $env{'form.timestamp'}) {
 3282:                         unlink($tempfile);
 3283:                     }
 3284:                 }
 3285:                 return;
 3286:             }
 3287:         }
 3288:         # Create the directory if not present
 3289:         my @parts=split(/\//,$filepath);
 3290:         my $fullpath = $perlvar{'lonDaemons'};
 3291:         for (my $i=0;$i<@parts;$i++) {
 3292:             $fullpath .= '/'.$parts[$i];
 3293:             if ((-e $fullpath)!=1) {
 3294:                 mkdir($fullpath,0777);
 3295:             }
 3296:         }
 3297:         open(my $fh,'>'.$fullpath.'/'.$fname);
 3298:         print $fh $env{'form.'.$formname};
 3299:         close($fh);
 3300:         if ($context eq 'existingfile') {
 3301:             my @info = stat($fullpath.'/'.$fname);
 3302:             return ($fullpath.'/'.$fname,$info[9]);
 3303:         } else {
 3304:             return $fullpath.'/'.$fname;
 3305:         }
 3306:     }
 3307:     if ($subdir eq 'scantron') {
 3308:         $fname = 'scantron_orig_'.$fname;
 3309:     } else {
 3310:         $fname="$subdir/$fname";
 3311:     }
 3312:     if ($context eq 'coursedoc') {
 3313: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3314: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3315:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 3316:             return &finishuserfileupload($docuname,$docudom,
 3317: 					 $formname,$fname,$parser,$allfiles,
 3318: 					 $codebase,$thumbwidth,$thumbheight,
 3319:                                          $resizewidth,$resizeheight,$context,$mimetype);
 3320:         } else {
 3321:             if ($env{'form.folder'}) {
 3322:                 $fname=$env{'form.folder'}.'/'.$fname;
 3323:             }
 3324:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 3325: 				       $fname,$formname,$parser,
 3326: 				       $allfiles,$codebase,$mimetype);
 3327:         }
 3328:     } elsif (defined($destuname)) {
 3329:         my $docuname=$destuname;
 3330:         my $docudom=$destudom;
 3331: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3332: 				     $parser,$allfiles,$codebase,
 3333:                                      $thumbwidth,$thumbheight,
 3334:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3335:     } else {
 3336:         my $docuname=$env{'user.name'};
 3337:         my $docudom=$env{'user.domain'};
 3338:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 3339:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3340:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3341:         }
 3342: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3343: 				     $parser,$allfiles,$codebase,
 3344:                                      $thumbwidth,$thumbheight,
 3345:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3346:     }
 3347: }
 3348: 
 3349: sub finishuserfileupload {
 3350:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 3351:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 3352:     my $path=$docudom.'/'.$docuname.'/';
 3353:     my $filepath=$perlvar{'lonDocRoot'};
 3354:   
 3355:     my ($fnamepath,$file,$fetchthumb);
 3356:     $file=$fname;
 3357:     if ($fname=~m|/|) {
 3358:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 3359: 	$path.=$fnamepath.'/';
 3360:     }
 3361:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 3362:     my $count;
 3363:     for ($count=4;$count<=$#parts;$count++) {
 3364:         $filepath.="/$parts[$count]";
 3365:         if ((-e $filepath)!=1) {
 3366: 	    mkdir($filepath,0777);
 3367:         }
 3368:     }
 3369: 
 3370: # Save the file
 3371:     {
 3372: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 3373: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 3374: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 3375: 	    return '/adm/notfound.html';
 3376: 	}
 3377:         if ($context eq 'overwrite') {
 3378:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 3379:             my $target = $filepath.'/'.$file;
 3380:             if (-e $source) {
 3381:                 my @info = stat($source);
 3382:                 if ($info[9] eq $env{'form.timestamp'}) {   
 3383:                     unless (&File::Copy::move($source,$target)) {
 3384:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 3385:                         return "Moving from $source failed";
 3386:                     }
 3387:                 } else {
 3388:                     return "Temporary file: $source had unexpected date/time for last modification";
 3389:                 }
 3390:             } else {
 3391:                 return "Temporary file: $source missing";
 3392:             }
 3393:         } elsif (!print FH ($env{'form.'.$formname})) {
 3394: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 3395: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 3396: 	    return '/adm/notfound.html';
 3397: 	}
 3398: 	close(FH);
 3399:         if ($resizewidth && $resizeheight) {
 3400:             my $mm = new File::MMagic;
 3401:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 3402:             if ($mime_type =~ m{^image/}) {
 3403: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 3404:             }  
 3405: 	}
 3406:     }
 3407:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 3408:         if (ref($mimetype)) {
 3409:             if ($$mimetype eq '') {
 3410:                 my $mm = new File::MMagic;
 3411:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 3412:                 $$mimetype = $type;
 3413:             }
 3414:         }
 3415:     }
 3416:     if ($parser eq 'parse') {
 3417:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 3418:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 3419:                                                        $allfiles,$codebase);
 3420:             unless ($parse_result eq 'ok') {
 3421:                 &logthis('Failed to parse '.$filepath.$file.
 3422: 	   	         ' for embedded media: '.$parse_result); 
 3423:             }
 3424:         }
 3425:     }
 3426:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 3427:         my $input = $filepath.'/'.$file;
 3428:         my $output = $filepath.'/'.'tn-'.$file;
 3429:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 3430:         system("convert -sample $thumbsize $input $output");
 3431:         if (-e $filepath.'/'.'tn-'.$file) {
 3432:             $fetchthumb  = 1; 
 3433:         }
 3434:     }
 3435:  
 3436: # Notify homeserver to grep it
 3437: #
 3438:     my $docuhome=&homeserver($docuname,$docudom);	
 3439:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 3440:     if ($fetchresult eq 'ok') {
 3441:         if ($fetchthumb) {
 3442:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 3443:             if ($thumbresult ne 'ok') {
 3444:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 3445:                          $docuhome.': '.$thumbresult);
 3446:             }
 3447:         }
 3448: #
 3449: # Return the URL to it
 3450:         return '/uploaded/'.$path.$file;
 3451:     } else {
 3452:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 3453: 		 ': '.$fetchresult);
 3454:         return '/adm/notfound.html';
 3455:     }
 3456: }
 3457: 
 3458: sub extract_embedded_items {
 3459:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 3460:     my @state = ();
 3461:     my (%lastids,%related,%shockwave,%flashvars);
 3462:     my %javafiles = (
 3463:                       codebase => '',
 3464:                       code => '',
 3465:                       archive => ''
 3466:                     );
 3467:     my %mediafiles = (
 3468:                       src => '',
 3469:                       movie => '',
 3470:                      );
 3471:     my $p;
 3472:     if ($content) {
 3473:         $p = HTML::LCParser->new($content);
 3474:     } else {
 3475:         $p = HTML::LCParser->new($fullpath);
 3476:     }
 3477:     while (my $t=$p->get_token()) {
 3478: 	if ($t->[0] eq 'S') {
 3479: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 3480: 	    push(@state, $tagname);
 3481:             if (lc($tagname) eq 'allow') {
 3482:                 &add_filetype($allfiles,$attr->{'src'},'src');
 3483:             }
 3484: 	    if (lc($tagname) eq 'img') {
 3485: 		&add_filetype($allfiles,$attr->{'src'},'src');
 3486: 	    }
 3487: 	    if (lc($tagname) eq 'a') {
 3488:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 3489:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3490:                 }
 3491: 	    }
 3492:             if (lc($tagname) eq 'script') {
 3493:                 my $src;
 3494:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 3495:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 3496:                 } else {
 3497:                     if ($attr->{'src'} ne '') {
 3498:                         $src = $attr->{'src'};
 3499:                         &add_filetype($allfiles,$src,'src');
 3500:                     }
 3501:                 }
 3502:                 my $text = $p->get_trimmed_text();
 3503:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 3504:                     my @swfargs = split(/,/,$1);
 3505:                     foreach my $item (@swfargs) {
 3506:                         $item =~ s/["']//g;
 3507:                         $item =~ s/^\s+//;
 3508:                         $item =~ s/\s+$//;
 3509:                     }
 3510:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 3511:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 3512:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 3513:                         } else {
 3514:                             $related{$swfargs[0]} = [$swfargs[2]];
 3515:                         }
 3516:                     }
 3517:                 }
 3518:             }
 3519:             if (lc($tagname) eq 'link') {
 3520:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 3521:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3522:                 }
 3523:             }
 3524: 	    if (lc($tagname) eq 'object' ||
 3525: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 3526: 		foreach my $item (keys(%javafiles)) {
 3527: 		    $javafiles{$item} = '';
 3528: 		}
 3529:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 3530:                     $lastids{lc($tagname)} = $attr->{'id'};
 3531:                 }
 3532: 	    }
 3533: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 3534: 		my $name = lc($attr->{'name'});
 3535: 		foreach my $item (keys(%javafiles)) {
 3536: 		    if ($name eq $item) {
 3537: 			$javafiles{$item} = $attr->{'value'};
 3538: 			last;
 3539: 		    }
 3540: 		}
 3541:                 my $pathfrom;
 3542: 		foreach my $item (keys(%mediafiles)) {
 3543: 		    if ($name eq $item) {
 3544:                         $pathfrom = $attr->{'value'};
 3545:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 3546: 			&add_filetype($allfiles,$pathfrom,$name);
 3547: 			last;
 3548: 		    }
 3549: 		}
 3550:                 if ($name eq 'flashvars') {
 3551:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 3552:                 }
 3553:                 if ($pathfrom ne '') {
 3554:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 3555:                                          $pathfrom);
 3556:                 }
 3557: 	    }
 3558: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 3559: 		foreach my $item (keys(%javafiles)) {
 3560: 		    if ($attr->{$item}) {
 3561: 			$javafiles{$item} = $attr->{$item};
 3562: 			last;
 3563: 		    }
 3564: 		}
 3565: 		foreach my $item (keys(%mediafiles)) {
 3566: 		    if ($attr->{$item}) {
 3567: 			&add_filetype($allfiles,$attr->{$item},$item);
 3568: 			last;
 3569: 		    }
 3570: 		}
 3571:                 if (lc($tagname) eq 'embed') {
 3572:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 3573:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 3574:                                              $attr->{'src'});
 3575:                     }
 3576:                 }
 3577: 	    }
 3578:             if (lc($tagname) eq 'iframe') {
 3579:                 my $src = $attr->{'src'} ;
 3580:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 3581:                     &add_filetype($allfiles,$src,'src');
 3582:                 } elsif ($src =~ m{^/}) {
 3583:                     if ($env{'request.course.id'}) {
 3584:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3585:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3586:                         my $url = &hreflocation('',$fullpath);
 3587:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 3588:                             my $relpath = $1;
 3589:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 3590:                                 &add_filetype($allfiles,$1,'src');
 3591:                             }
 3592:                         }
 3593:                     }
 3594:                 }
 3595:             }
 3596:             if ($t->[4] =~ m{/>$}) {
 3597:                 pop(@state);
 3598:             }
 3599: 	} elsif ($t->[0] eq 'E') {
 3600: 	    my ($tagname) = ($t->[1]);
 3601: 	    if ($javafiles{'codebase'} ne '') {
 3602: 		$javafiles{'codebase'} .= '/';
 3603: 	    }  
 3604: 	    if (lc($tagname) eq 'applet' ||
 3605: 		lc($tagname) eq 'object' ||
 3606: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 3607: 		) {
 3608: 		foreach my $item (keys(%javafiles)) {
 3609: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 3610: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 3611: 			&add_filetype($allfiles,$file,$item);
 3612: 		    }
 3613: 		}
 3614: 	    } 
 3615: 	    pop @state;
 3616: 	}
 3617:     }
 3618:     foreach my $id (sort(keys(%flashvars))) {
 3619:         if ($shockwave{$id} ne '') {
 3620:             my @pairs = split(/\&/,$flashvars{$id});
 3621:             foreach my $pair (@pairs) {
 3622:                 my ($key,$value) = split(/\=/,$pair);
 3623:                 if ($key eq 'thumb') {
 3624:                     &add_filetype($allfiles,$value,$key);
 3625:                 } elsif ($key eq 'content') {
 3626:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 3627:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 3628:                     if ($ext ne '') {
 3629:                         &add_filetype($allfiles,$path.$value,$ext);
 3630:                     }
 3631:                 }
 3632:             }
 3633:         }
 3634:     }
 3635:     return 'ok';
 3636: }
 3637: 
 3638: sub add_filetype {
 3639:     my ($allfiles,$file,$type)=@_;
 3640:     if (exists($allfiles->{$file})) {
 3641: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 3642: 	    push(@{$allfiles->{$file}}, &escape($type));
 3643: 	}
 3644:     } else {
 3645: 	@{$allfiles->{$file}} = (&escape($type));
 3646:     }
 3647: }
 3648: 
 3649: sub embedded_dependency {
 3650:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 3651:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 3652:         if (($identifier ne '') &&
 3653:             (ref($related->{$identifier}) eq 'ARRAY') &&
 3654:             ($pathfrom ne '')) {
 3655:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 3656:             foreach my $dep (@{$related->{$identifier}}) {
 3657:                 &add_filetype($allfiles,$path.$dep,'object');
 3658:             }
 3659:         }
 3660:     }
 3661:     return;
 3662: }
 3663: 
 3664: sub removeuploadedurl {
 3665:     my ($url)=@_;	
 3666:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 3667:     return &removeuserfile($uname,$udom,$fname);
 3668: }
 3669: 
 3670: sub removeuserfile {
 3671:     my ($docuname,$docudom,$fname)=@_;
 3672:     my $home=&homeserver($docuname,$docudom);    
 3673:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 3674:     if ($result eq 'ok') {	
 3675:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 3676:             my $metafile = $fname.'.meta';
 3677:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 3678: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 3679:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 3680:             my $sqlresult = 
 3681:                 &update_portfolio_table($docuname,$docudom,$file,
 3682:                                         'portfolio_metadata',$group,
 3683:                                         'delete');
 3684:         }
 3685:     }
 3686:     return $result;
 3687: }
 3688: 
 3689: sub mkdiruserfile {
 3690:     my ($docuname,$docudom,$dir)=@_;
 3691:     my $home=&homeserver($docuname,$docudom);
 3692:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 3693: }
 3694: 
 3695: sub renameuserfile {
 3696:     my ($docuname,$docudom,$old,$new)=@_;
 3697:     my $home=&homeserver($docuname,$docudom);
 3698:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 3699:                         &escape("$old").':'.&escape("$new"),$home);
 3700:     if ($result eq 'ok') {
 3701:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 3702:             my $oldmeta = $old.'.meta';
 3703:             my $newmeta = $new.'.meta';
 3704:             my $metaresult = 
 3705:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 3706: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 3707:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 3708:             my $sqlresult = 
 3709:                 &update_portfolio_table($docuname,$docudom,$file,
 3710:                                         'portfolio_metadata',$group,
 3711:                                         'delete');
 3712:         }
 3713:     }
 3714:     return $result;
 3715: }
 3716: 
 3717: # ------------------------------------------------------------------------- Log
 3718: 
 3719: sub log {
 3720:     my ($dom,$nam,$hom,$what)=@_;
 3721:     return critical("log:$dom:$nam:$what",$hom);
 3722: }
 3723: 
 3724: # ------------------------------------------------------------------ Course Log
 3725: #
 3726: # This routine flushes several buffers of non-mission-critical nature
 3727: #
 3728: 
 3729: sub flushcourselogs {
 3730:     &logthis('Flushing log buffers');
 3731: #
 3732: # course logs
 3733: # This is a log of all transactions in a course, which can be used
 3734: # for data mining purposes
 3735: #
 3736: # It also collects the courseid database, which lists last transaction
 3737: # times and course titles for all courseids
 3738: #
 3739:     my %courseidbuffer=();
 3740:     foreach my $crsid (keys(%courselogs)) {
 3741:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 3742: 		          &escape($courselogs{$crsid}),
 3743: 		          $coursehombuf{$crsid}) eq 'ok') {
 3744: 	    delete $courselogs{$crsid};
 3745:         } else {
 3746:             &logthis('Failed to flush log buffer for '.$crsid);
 3747:             if (length($courselogs{$crsid})>40000) {
 3748:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 3749:                         " exceeded maximum size, deleting.</font>");
 3750:                delete $courselogs{$crsid};
 3751:             }
 3752:         }
 3753:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 3754:             'description' => $coursedescrbuf{$crsid},
 3755:             'inst_code'    => $courseinstcodebuf{$crsid},
 3756:             'type'        => $coursetypebuf{$crsid},
 3757:             'owner'       => $courseownerbuf{$crsid},
 3758:         };
 3759:     }
 3760: #
 3761: # Write course id database (reverse lookup) to homeserver of courses 
 3762: # Is used in pickcourse
 3763: #
 3764:     foreach my $crs_home (keys(%courseidbuffer)) {
 3765:         my $response = &courseidput(&host_domain($crs_home),
 3766:                                     $courseidbuffer{$crs_home},
 3767:                                     $crs_home,'timeonly');
 3768:     }
 3769: #
 3770: # File accesses
 3771: # Writes to the dynamic metadata of resources to get hit counts, etc.
 3772: #
 3773:     foreach my $entry (keys(%accesshash)) {
 3774:         if ($entry =~ /___count$/) {
 3775:             my ($dom,$name);
 3776:             ($dom,$name,undef)=
 3777: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 3778:             if (! defined($dom) || $dom eq '' || 
 3779:                 ! defined($name) || $name eq '') {
 3780:                 my $cid = $env{'request.course.id'};
 3781:                 $dom  = $env{'request.'.$cid.'.domain'};
 3782:                 $name = $env{'request.'.$cid.'.num'};
 3783:             }
 3784:             my $value = $accesshash{$entry};
 3785:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 3786:             my %temphash=($url => $value);
 3787:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 3788:             if ($result eq 'ok') {
 3789:                 delete $accesshash{$entry};
 3790:             }
 3791:         } else {
 3792:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 3793:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 3794:             my %temphash=($entry => $accesshash{$entry});
 3795:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 3796:                 delete $accesshash{$entry};
 3797:             }
 3798:         }
 3799:     }
 3800: #
 3801: # Roles
 3802: # Reverse lookup of user roles for course faculty/staff and co-authorship
 3803: #
 3804:     foreach my $entry (keys(%userrolehash)) {
 3805:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 3806: 	    split(/\:/,$entry);
 3807:         if (&Apache::lonnet::put('nohist_userroles',
 3808:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 3809:                 $rudom,$runame) eq 'ok') {
 3810: 	    delete $userrolehash{$entry};
 3811:         }
 3812:     }
 3813: #
 3814: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 3815: #
 3816:     my %domrolebuffer = ();
 3817:     foreach my $entry (keys(%domainrolehash)) {
 3818:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 3819:         if ($domrolebuffer{$rudom}) {
 3820:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 3821:                       '='.&escape($domainrolehash{$entry});
 3822:         } else {
 3823:             $domrolebuffer{$rudom}.=&escape($entry).
 3824:                       '='.&escape($domainrolehash{$entry});
 3825:         }
 3826:         delete $domainrolehash{$entry};
 3827:     }
 3828:     foreach my $dom (keys(%domrolebuffer)) {
 3829: 	my %servers = &get_servers($dom,'library');
 3830: 	foreach my $tryserver (keys(%servers)) {
 3831: 	    unless (&reply('domroleput:'.$dom.':'.
 3832: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 3833: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 3834: 	    }
 3835:         }
 3836:     }
 3837:     $dumpcount++;
 3838: }
 3839: 
 3840: sub courselog {
 3841:     my $what=shift;
 3842:     $what=time.':'.$what;
 3843:     unless ($env{'request.course.id'}) { return ''; }
 3844:     $coursedombuf{$env{'request.course.id'}}=
 3845:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 3846:     $coursenumbuf{$env{'request.course.id'}}=
 3847:        $env{'course.'.$env{'request.course.id'}.'.num'};
 3848:     $coursehombuf{$env{'request.course.id'}}=
 3849:        $env{'course.'.$env{'request.course.id'}.'.home'};
 3850:     $coursedescrbuf{$env{'request.course.id'}}=
 3851:        $env{'course.'.$env{'request.course.id'}.'.description'};
 3852:     $courseinstcodebuf{$env{'request.course.id'}}=
 3853:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 3854:     $courseownerbuf{$env{'request.course.id'}}=
 3855:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 3856:     $coursetypebuf{$env{'request.course.id'}}=
 3857:        $env{'course.'.$env{'request.course.id'}.'.type'};
 3858:     if (defined $courselogs{$env{'request.course.id'}}) {
 3859: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 3860:     } else {
 3861: 	$courselogs{$env{'request.course.id'}}.=$what;
 3862:     }
 3863:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 3864: 	&flushcourselogs();
 3865:     }
 3866: }
 3867: 
 3868: sub courseacclog {
 3869:     my $fnsymb=shift;
 3870:     unless ($env{'request.course.id'}) { return ''; }
 3871:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 3872:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 3873:         $what.=':POST';
 3874:         # FIXME: Probably ought to escape things....
 3875: 	foreach my $key (keys(%env)) {
 3876:             if ($key=~/^form\.(.*)/) {
 3877:                 my $formitem = $1;
 3878:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 3879:                     $what.=':'.$formitem.'='.$env{$key};
 3880:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 3881:                     $what.=':'.$formitem.'='.$env{$key};
 3882:                 }
 3883:             }
 3884:         }
 3885:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 3886:         # FIXME: We should not be depending on a form parameter that someone
 3887:         # editing lonsearchcat.pm might change in the future.
 3888:         if ($env{'form.phase'} eq 'course_search') {
 3889:             $what.= ':POST';
 3890:             # FIXME: Probably ought to escape things....
 3891:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 3892:                                  'crsdiscuss') {
 3893:                 $what.=':'.$element.'='.$env{'form.'.$element};
 3894:             }
 3895:         }
 3896:     }
 3897:     &courselog($what);
 3898: }
 3899: 
 3900: sub countacc {
 3901:     my $url=&declutter(shift);
 3902:     return if (! defined($url) || $url eq '');
 3903:     unless ($env{'request.course.id'}) { return ''; }
 3904: #
 3905: # Mark that this url was used in this course
 3906: #
 3907:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 3908: #
 3909: # Increase the access count for this resource in this child process
 3910: #
 3911:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 3912:     $accesshash{$key}++;
 3913: }
 3914: 
 3915: sub linklog {
 3916:     my ($from,$to)=@_;
 3917:     $from=&declutter($from);
 3918:     $to=&declutter($to);
 3919:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 3920:     $accesshash{$to.'___'.$from.'___goto'}=1;
 3921: }
 3922: 
 3923: sub statslog {
 3924:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 3925:     if ($users<2) { return; }
 3926:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 3927:             'course'       => $env{'request.course.id'},
 3928:             'sections'     => '"all"',
 3929:             'num_students' => $users,
 3930:             'part'         => $part,
 3931:             'symb'         => $symb,
 3932:             'mean_tries'   => $av_attempts,
 3933:             'deg_of_diff'  => $degdiff});
 3934:     foreach my $key (keys(%dynstore)) {
 3935:         $accesshash{$key}=$dynstore{$key};
 3936:     }
 3937: }
 3938:   
 3939: sub userrolelog {
 3940:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 3941:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 3942:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3943:        $userrolehash
 3944:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3945:                     =$tend.':'.$tstart;
 3946:     }
 3947:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 3948:        $userrolehash
 3949:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 3950:                     =$tend.':'.$tstart;
 3951:     }
 3952:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
 3953:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3954:        $domainrolehash
 3955:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3956:                     = $tend.':'.$tstart;
 3957:     }
 3958: }
 3959: 
 3960: sub courserolelog {
 3961:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 3962:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 3963:         my $cdom = $1;
 3964:         my $cnum = $2;
 3965:         my $sec = $3;
 3966:         my $namespace = 'rolelog';
 3967:         my %storehash = (
 3968:                            role    => $trole,
 3969:                            start   => $tstart,
 3970:                            end     => $tend,
 3971:                            selfenroll => $selfenroll,
 3972:                            context    => $context,
 3973:                         );
 3974:         if ($trole eq 'gr') {
 3975:             $namespace = 'groupslog';
 3976:             $storehash{'group'} = $sec;
 3977:         } else {
 3978:             $storehash{'section'} = $sec;
 3979:         }
 3980:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 3981:                    $domain,$cnum,$cdom);
 3982:         if (($trole ne 'st') || ($sec ne '')) {
 3983:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 3984:         }
 3985:     }
 3986:     return;
 3987: }
 3988: 
 3989: sub domainrolelog {
 3990:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 3991:     if ($area =~ m{^/($match_domain)/$}) {
 3992:         my $cdom = $1;
 3993:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 3994:         my $namespace = 'rolelog';
 3995:         my %storehash = (
 3996:                            role    => $trole,
 3997:                            start   => $tstart,
 3998:                            end     => $tend,
 3999:                            context => $context,
 4000:                         );
 4001:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 4002:                    $domain,$domconfiguser,$cdom);
 4003:     }
 4004:     return;
 4005: 
 4006: }
 4007: 
 4008: sub coauthorrolelog {
 4009:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4010:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 4011:         my $audom = $1;
 4012:         my $auname = $2;
 4013:         my $namespace = 'rolelog';
 4014:         my %storehash = (
 4015:                            role    => $trole,
 4016:                            start   => $tstart,
 4017:                            end     => $tend,
 4018:                            context => $context,
 4019:                         );
 4020:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 4021:                    $domain,$auname,$audom);
 4022:     }
 4023:     return;
 4024: }
 4025: 
 4026: sub get_course_adv_roles {
 4027:     my ($cid,$codes) = @_;
 4028:     $cid=$env{'request.course.id'} unless (defined($cid));
 4029:     my %coursehash=&coursedescription($cid);
 4030:     my $crstype = &Apache::loncommon::course_type($cid);
 4031:     my %nothide=();
 4032:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4033:         if ($user !~ /:/) {
 4034: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 4035:         } else {
 4036:             $nothide{$user}=1;
 4037:         }
 4038:     }
 4039:     my @possdoms = ($coursehash{'domain'});
 4040:     if ($coursehash{'checkforpriv'}) {
 4041:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 4042:     }
 4043:     my %returnhash=();
 4044:     my %dumphash=
 4045:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 4046:     my $now=time;
 4047:     my %privileged;
 4048:     foreach my $entry (keys(%dumphash)) {
 4049: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4050:         if (($tstart) && ($tstart<0)) { next; }
 4051:         if (($tend) && ($tend<$now)) { next; }
 4052:         if (($tstart) && ($now<$tstart)) { next; }
 4053:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 4054: 	if ($username eq '' || $domain eq '') { next; }
 4055:         if ((&privileged($username,$domain,\@possdoms)) &&
 4056:             (!$nothide{$username.':'.$domain})) { next; }
 4057: 	if ($role eq 'cr') { next; }
 4058:         if ($codes) {
 4059:             if ($section) { $role .= ':'.$section; }
 4060:             if ($returnhash{$role}) {
 4061:                 $returnhash{$role}.=','.$username.':'.$domain;
 4062:             } else {
 4063:                 $returnhash{$role}=$username.':'.$domain;
 4064:             }
 4065:         } else {
 4066:             my $key=&plaintext($role,$crstype);
 4067:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 4068:             if ($returnhash{$key}) {
 4069: 	        $returnhash{$key}.=','.$username.':'.$domain;
 4070:             } else {
 4071:                 $returnhash{$key}=$username.':'.$domain;
 4072:             }
 4073:         }
 4074:     }
 4075:     return %returnhash;
 4076: }
 4077: 
 4078: sub get_my_roles {
 4079:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 4080:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 4081:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 4082:     my (%dumphash,%nothide);
 4083:     if ($context eq 'userroles') {
 4084:         %dumphash = &dump('roles',$udom,$uname);
 4085:     } else {
 4086:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 4087:         if ($hidepriv) {
 4088:             my %coursehash=&coursedescription($udom.'_'.$uname);
 4089:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4090:                 if ($user !~ /:/) {
 4091:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 4092:                 } else {
 4093:                     $nothide{$user} = 1;
 4094:                 }
 4095:             }
 4096:         }
 4097:     }
 4098:     my %returnhash=();
 4099:     my $now=time;
 4100:     my %privileged;
 4101:     foreach my $entry (keys(%dumphash)) {
 4102:         my ($role,$tend,$tstart);
 4103:         if ($context eq 'userroles') {
 4104:             next if ($entry =~ /^rolesdef/);
 4105: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 4106:         } else {
 4107:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4108:         }
 4109:         if (($tstart) && ($tstart<0)) { next; }
 4110:         my $status = 'active';
 4111:         if (($tend) && ($tend<=$now)) {
 4112:             $status = 'previous';
 4113:         } 
 4114:         if (($tstart) && ($now<$tstart)) {
 4115:             $status = 'future';
 4116:         }
 4117:         if (ref($types) eq 'ARRAY') {
 4118:             if (!grep(/^\Q$status\E$/,@{$types})) {
 4119:                 next;
 4120:             } 
 4121:         } else {
 4122:             if ($status ne 'active') {
 4123:                 next;
 4124:             }
 4125:         }
 4126:         my ($rolecode,$username,$domain,$section,$area);
 4127:         if ($context eq 'userroles') {
 4128:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 4129:             (undef,$domain,$username,$section) = split(/\//,$area);
 4130:         } else {
 4131:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 4132:         }
 4133:         if (ref($roledoms) eq 'ARRAY') {
 4134:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 4135:                 next;
 4136:             }
 4137:         }
 4138:         if (ref($roles) eq 'ARRAY') {
 4139:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 4140:                 if ($role =~ /^cr\//) {
 4141:                     if (!grep(/^cr$/,@{$roles})) {
 4142:                         next;
 4143:                     }
 4144:                 } elsif ($role =~ /^gr\//) {
 4145:                     if (!grep(/^gr$/,@{$roles})) {
 4146:                         next;
 4147:                     }
 4148:                 } else {
 4149:                     next;
 4150:                 }
 4151:             }
 4152:         }
 4153:         if ($hidepriv) {
 4154:             my @privroles = ('dc','su');
 4155:             if ($context eq 'userroles') {
 4156:                 next if (grep(/^\Q$role\E$/,@privroles));
 4157:             } else {
 4158:                 my $possdoms = [$domain];
 4159:                 if (ref($roledoms) eq 'ARRAY') {
 4160:                    push(@{$possdoms},@{$roledoms}); 
 4161:                 }
 4162:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 4163:                     if (!$nothide{$username.':'.$domain}) {
 4164:                         next;
 4165:                     }
 4166:                 }
 4167:             }
 4168:         }
 4169:         if ($withsec) {
 4170:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 4171:                 $tstart.':'.$tend;
 4172:         } else {
 4173:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 4174:         }
 4175:     }
 4176:     return %returnhash;
 4177: }
 4178: 
 4179: # ----------------------------------------------------- Frontpage Announcements
 4180: #
 4181: #
 4182: 
 4183: sub postannounce {
 4184:     my ($server,$text)=@_;
 4185:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 4186:     unless ($text=~/\w/) { $text=''; }
 4187:     return &reply('setannounce:'.&escape($text),$server);
 4188: }
 4189: 
 4190: sub getannounce {
 4191: 
 4192:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 4193: 	my $announcement='';
 4194: 	while (my $line = <$fh>) { $announcement .= $line; }
 4195: 	close($fh);
 4196: 	if ($announcement=~/\w/) { 
 4197: 	    return 
 4198:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 4199:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 4200: 	} else {
 4201: 	    return '';
 4202: 	}
 4203:     } else {
 4204: 	return '';
 4205:     }
 4206: }
 4207: 
 4208: # ---------------------------------------------------------- Course ID routines
 4209: # Deal with domain's nohist_courseid.db files
 4210: #
 4211: 
 4212: sub courseidput {
 4213:     my ($domain,$storehash,$coursehome,$caller) = @_;
 4214:     return unless (ref($storehash) eq 'HASH');
 4215:     my $outcome;
 4216:     if ($caller eq 'timeonly') {
 4217:         my $cids = '';
 4218:         foreach my $item (keys(%$storehash)) {
 4219:             $cids.=&escape($item).'&';
 4220:         }
 4221:         $cids=~s/\&$//;
 4222:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 4223:                           $coursehome);       
 4224:     } else {
 4225:         my $items = '';
 4226:         foreach my $item (keys(%$storehash)) {
 4227:             $items.= &escape($item).'='.
 4228:                      &freeze_escape($$storehash{$item}).'&';
 4229:         }
 4230:         $items=~s/\&$//;
 4231:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 4232:                           $coursehome);
 4233:     }
 4234:     if ($outcome eq 'unknown_cmd') {
 4235:         my $what;
 4236:         foreach my $cid (keys(%$storehash)) {
 4237:             $what .= &escape($cid).'=';
 4238:             foreach my $item ('description','inst_code','owner','type') {
 4239:                 $what .= &escape($storehash->{$cid}{$item}).':';
 4240:             }
 4241:             $what =~ s/\:$/&/;
 4242:         }
 4243:         $what =~ s/\&$//;  
 4244:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 4245:     } else {
 4246:         return $outcome;
 4247:     }
 4248: }
 4249: 
 4250: sub courseiddump {
 4251:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 4252:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 4253:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 4254:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 4255:         $hasuniquecode)=@_;
 4256:     my $as_hash = 1;
 4257:     my %returnhash;
 4258:     if (!$domfilter) { $domfilter=''; }
 4259:     my %libserv = &all_library();
 4260:     foreach my $tryserver (keys(%libserv)) {
 4261:         if ( (  $hostidflag == 1 
 4262: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 4263: 	     || (!defined($hostidflag)) ) {
 4264: 
 4265: 	    if (($domfilter eq '') ||
 4266: 		(&host_domain($tryserver) eq $domfilter)) {
 4267:                 my $rep;
 4268:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 4269:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 4270:                         join(":", (&host_domain($tryserver), $sincefilter, 
 4271:                                 &escape($descfilter), &escape($instcodefilter), 
 4272:                                 &escape($ownerfilter), &escape($coursefilter),
 4273:                                 &escape($typefilter), &escape($regexp_ok), 
 4274:                                 $as_hash, &escape($selfenrollonly), 
 4275:                                 &escape($catfilter), $showhidden, $caller, 
 4276:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 4277:                                 &escape($createdbefore), &escape($createdafter), 
 4278:                                 &escape($creationcontext), $domcloner, $hasuniquecode)));
 4279:                 } else {
 4280:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 4281:                              $sincefilter.':'.&escape($descfilter).':'.
 4282:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 4283:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 4284:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 4285:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 4286:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 4287:                              &escape($cc_clone).':'.$cloneonly.':'.
 4288:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 4289:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode,
 4290:                              $tryserver);
 4291:                 }
 4292:                      
 4293:                 my @pairs=split(/\&/,$rep);
 4294:                 foreach my $item (@pairs) {
 4295:                     my ($key,$value)=split(/\=/,$item,2);
 4296:                     $key = &unescape($key);
 4297:                     next if ($key =~ /^error: 2 /);
 4298:                     my $result = &thaw_unescape($value);
 4299:                     if (ref($result) eq 'HASH') {
 4300:                         $returnhash{$key}=$result;
 4301:                     } else {
 4302:                         my @responses = split(/:/,$value);
 4303:                         my @items = ('description','inst_code','owner','type');
 4304:                         for (my $i=0; $i<@responses; $i++) {
 4305:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 4306:                         }
 4307:                     }
 4308:                 }
 4309:             }
 4310:         }
 4311:     }
 4312:     return %returnhash;
 4313: }
 4314: 
 4315: sub courselastaccess {
 4316:     my ($cdom,$cnum,$hostidref) = @_;
 4317:     my %returnhash;
 4318:     if ($cdom && $cnum) {
 4319:         my $chome = &homeserver($cnum,$cdom);
 4320:         if ($chome ne 'no_host') {
 4321:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 4322:             &extract_lastaccess(\%returnhash,$rep);
 4323:         }
 4324:     } else {
 4325:         if (!$cdom) { $cdom=''; }
 4326:         my %libserv = &all_library();
 4327:         foreach my $tryserver (keys(%libserv)) {
 4328:             if (ref($hostidref) eq 'ARRAY') {
 4329:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 4330:             } 
 4331:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 4332:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 4333:                 &extract_lastaccess(\%returnhash,$rep);
 4334:             }
 4335:         }
 4336:     }
 4337:     return %returnhash;
 4338: }
 4339: 
 4340: sub extract_lastaccess {
 4341:     my ($returnhash,$rep) = @_;
 4342:     if (ref($returnhash) eq 'HASH') {
 4343:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 4344:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 4345:                  $rep eq '') {
 4346:             my @pairs=split(/\&/,$rep);
 4347:             foreach my $item (@pairs) {
 4348:                 my ($key,$value)=split(/\=/,$item,2);
 4349:                 $key = &unescape($key);
 4350:                 next if ($key =~ /^error: 2 /);
 4351:                 $returnhash->{$key} = &thaw_unescape($value);
 4352:             }
 4353:         }
 4354:     }
 4355:     return;
 4356: }
 4357: 
 4358: # ---------------------------------------------------------- DC e-mail
 4359: 
 4360: sub dcmailput {
 4361:     my ($domain,$msgid,$message,$server)=@_;
 4362:     my $status = &Apache::lonnet::critical(
 4363:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 4364:        &escape($message),$server);
 4365:     return $status;
 4366: }
 4367: 
 4368: sub dcmaildump {
 4369:     my ($dom,$startdate,$enddate,$senders) = @_;
 4370:     my %returnhash=();
 4371: 
 4372:     if (defined(&domain($dom,'primary'))) {
 4373:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 4374:                                                          &escape($enddate).':';
 4375: 	my @esc_senders=map { &escape($_)} @$senders;
 4376: 	$cmd.=&escape(join('&',@esc_senders));
 4377: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 4378:             my ($key,$value) = split(/\=/,$line,2);
 4379:             if (($key) && ($value)) {
 4380:                 $returnhash{&unescape($key)} = &unescape($value);
 4381:             }
 4382:         }
 4383:     }
 4384:     return %returnhash;
 4385: }
 4386: # ---------------------------------------------------------- Domain roles
 4387: 
 4388: sub get_domain_roles {
 4389:     my ($dom,$roles,$startdate,$enddate)=@_;
 4390:     if ((!defined($startdate)) || ($startdate eq '')) {
 4391:         $startdate = '.';
 4392:     }
 4393:     if ((!defined($enddate)) || ($enddate eq '')) {
 4394:         $enddate = '.';
 4395:     }
 4396:     my $rolelist;
 4397:     if (ref($roles) eq 'ARRAY') {
 4398:         $rolelist = join('&',@{$roles});
 4399:     }
 4400:     my %personnel = ();
 4401: 
 4402:     my %servers = &get_servers($dom,'library');
 4403:     foreach my $tryserver (keys(%servers)) {
 4404: 	%{$personnel{$tryserver}}=();
 4405: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 4406: 					    &escape($startdate).':'.
 4407: 					    &escape($enddate).':'.
 4408: 					    &escape($rolelist), $tryserver))) {
 4409: 	    my ($key,$value) = split(/\=/,$line,2);
 4410: 	    if (($key) && ($value)) {
 4411: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 4412: 	    }
 4413: 	}
 4414:     }
 4415:     return %personnel;
 4416: }
 4417: 
 4418: # ----------------------------------------------------------- Interval timing 
 4419: 
 4420: {
 4421: # Caches needed for speedup of navmaps
 4422: # We don't want to cache this for very long at all (5 seconds at most)
 4423: # 
 4424: # The user for whom we cache
 4425: my $cachedkey='';
 4426: # The cached times for this user
 4427: my %cachedtimes=();
 4428: # When this was last done
 4429: my $cachedtime=();
 4430: 
 4431: sub load_all_first_access {
 4432:     my ($uname,$udom)=@_;
 4433:     if (($cachedkey eq $uname.':'.$udom) &&
 4434:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
 4435:         return;
 4436:     }
 4437:     $cachedtime=time;
 4438:     $cachedkey=$uname.':'.$udom;
 4439:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 4440: }
 4441: 
 4442: sub get_first_access {
 4443:     my ($type,$argsymb,$argmap)=@_;
 4444:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4445:     if ($argsymb) { $symb=$argsymb; }
 4446:     my ($map,$id,$res)=&decode_symb($symb);
 4447:     if ($argmap) { $map = $argmap; }
 4448:     if ($type eq 'course') {
 4449: 	$res='course';
 4450:     } elsif ($type eq 'map') {
 4451: 	$res=&symbread($map);
 4452:     } else {
 4453: 	$res=$symb;
 4454:     }
 4455:     &load_all_first_access($uname,$udom);
 4456:     return $cachedtimes{"$courseid\0$res"};
 4457: }
 4458: 
 4459: sub set_first_access {
 4460:     my ($type,$interval)=@_;
 4461:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4462:     my ($map,$id,$res)=&decode_symb($symb);
 4463:     if ($type eq 'course') {
 4464: 	$res='course';
 4465:     } elsif ($type eq 'map') {
 4466: 	$res=&symbread($map);
 4467:     } else {
 4468: 	$res=$symb;
 4469:     }
 4470:     $cachedkey='';
 4471:     my $firstaccess=&get_first_access($type,$symb,$map);
 4472:     if (!$firstaccess) {
 4473:         my $start = time;
 4474: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 4475:                           $udom,$uname);
 4476:         if ($putres eq 'ok') {
 4477:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 4478:                  $udom,$uname); 
 4479:             &appenv(
 4480:                      {
 4481:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 4482:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 4483:                      }
 4484:                   );
 4485:         }
 4486:         return $putres;
 4487:     }
 4488:     return 'already_set';
 4489: }
 4490: }
 4491: # --------------------------------------------- Set Expire Date for Spreadsheet
 4492: 
 4493: sub expirespread {
 4494:     my ($uname,$udom,$stype,$usymb)=@_;
 4495:     my $cid=$env{'request.course.id'}; 
 4496:     if ($cid) {
 4497:        my $now=time;
 4498:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 4499:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 4500:                             $env{'course.'.$cid.'.num'}.
 4501: 	        	    ':nohist_expirationdates:'.
 4502:                             &escape($key).'='.$now,
 4503:                             $env{'course.'.$cid.'.home'})
 4504:     }
 4505:     return 'ok';
 4506: }
 4507: 
 4508: # ----------------------------------------------------- Devalidate Spreadsheets
 4509: 
 4510: sub devalidate {
 4511:     my ($symb,$uname,$udom)=@_;
 4512:     my $cid=$env{'request.course.id'}; 
 4513:     if ($cid) {
 4514:         # delete the stored spreadsheets for
 4515:         # - the student level sheet of this user in course's homespace
 4516:         # - the assessment level sheet for this resource 
 4517:         #   for this user in user's homespace
 4518: 	# - current conditional state info
 4519: 	my $key=$uname.':'.$udom.':';
 4520:         my $status=
 4521: 	    &del('nohist_calculatedsheets',
 4522: 		 [$key.'studentcalc:'],
 4523: 		 $env{'course.'.$cid.'.domain'},
 4524: 		 $env{'course.'.$cid.'.num'})
 4525: 		.' '.
 4526: 	    &del('nohist_calculatedsheets_'.$cid,
 4527: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 4528:         unless ($status eq 'ok ok') {
 4529:            &logthis('Could not devalidate spreadsheet '.
 4530:                     $uname.' at '.$udom.' for '.
 4531: 		    $symb.': '.$status);
 4532:         }
 4533: 	&delenv('user.state.'.$cid);
 4534:     }
 4535: }
 4536: 
 4537: sub get_scalar {
 4538:     my ($string,$end) = @_;
 4539:     my $value;
 4540:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 4541: 	$value = $1;
 4542:     } elsif ($$string =~ s/^([^&]*?)&//) {
 4543: 	$value = $1;
 4544:     }
 4545:     return &unescape($value);
 4546: }
 4547: 
 4548: sub array2str {
 4549:   my (@array) = @_;
 4550:   my $result=&arrayref2str(\@array);
 4551:   $result=~s/^__ARRAY_REF__//;
 4552:   $result=~s/__END_ARRAY_REF__$//;
 4553:   return $result;
 4554: }
 4555: 
 4556: sub arrayref2str {
 4557:   my ($arrayref) = @_;
 4558:   my $result='__ARRAY_REF__';
 4559:   foreach my $elem (@$arrayref) {
 4560:     if(ref($elem) eq 'ARRAY') {
 4561:       $result.=&arrayref2str($elem).'&';
 4562:     } elsif(ref($elem) eq 'HASH') {
 4563:       $result.=&hashref2str($elem).'&';
 4564:     } elsif(ref($elem)) {
 4565:       #print("Got a ref of ".(ref($elem))." skipping.");
 4566:     } else {
 4567:       $result.=&escape($elem).'&';
 4568:     }
 4569:   }
 4570:   $result=~s/\&$//;
 4571:   $result .= '__END_ARRAY_REF__';
 4572:   return $result;
 4573: }
 4574: 
 4575: sub hash2str {
 4576:   my (%hash) = @_;
 4577:   my $result=&hashref2str(\%hash);
 4578:   $result=~s/^__HASH_REF__//;
 4579:   $result=~s/__END_HASH_REF__$//;
 4580:   return $result;
 4581: }
 4582: 
 4583: sub hashref2str {
 4584:   my ($hashref)=@_;
 4585:   my $result='__HASH_REF__';
 4586:   foreach my $key (sort(keys(%$hashref))) {
 4587:     if (ref($key) eq 'ARRAY') {
 4588:       $result.=&arrayref2str($key).'=';
 4589:     } elsif (ref($key) eq 'HASH') {
 4590:       $result.=&hashref2str($key).'=';
 4591:     } elsif (ref($key)) {
 4592:       $result.='=';
 4593:       #print("Got a ref of ".(ref($key))." skipping.");
 4594:     } else {
 4595: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 4596:     }
 4597: 
 4598:     if(ref($hashref->{$key}) eq 'ARRAY') {
 4599:       $result.=&arrayref2str($hashref->{$key}).'&';
 4600:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 4601:       $result.=&hashref2str($hashref->{$key}).'&';
 4602:     } elsif(ref($hashref->{$key})) {
 4603:        $result.='&';
 4604:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 4605:     } else {
 4606:       $result.=&escape($hashref->{$key}).'&';
 4607:     }
 4608:   }
 4609:   $result=~s/\&$//;
 4610:   $result .= '__END_HASH_REF__';
 4611:   return $result;
 4612: }
 4613: 
 4614: sub str2hash {
 4615:     my ($string)=@_;
 4616:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 4617:     return %$hash;
 4618: }
 4619: 
 4620: sub str2hashref {
 4621:   my ($string) = @_;
 4622: 
 4623:   my %hash;
 4624: 
 4625:   if($string !~ /^__HASH_REF__/) {
 4626:       if (! ($string eq '' || !defined($string))) {
 4627: 	  $hash{'error'}='Not hash reference';
 4628:       }
 4629:       return (\%hash, $string);
 4630:   }
 4631: 
 4632:   $string =~ s/^__HASH_REF__//;
 4633: 
 4634:   while($string !~ /^__END_HASH_REF__/) {
 4635:       #key
 4636:       my $key='';
 4637:       if($string =~ /^__HASH_REF__/) {
 4638:           ($key, $string)=&str2hashref($string);
 4639:           if(defined($key->{'error'})) {
 4640:               $hash{'error'}='Bad data';
 4641:               return (\%hash, $string);
 4642:           }
 4643:       } elsif($string =~ /^__ARRAY_REF__/) {
 4644:           ($key, $string)=&str2arrayref($string);
 4645:           if($key->[0] eq 'Array reference error') {
 4646:               $hash{'error'}='Bad data';
 4647:               return (\%hash, $string);
 4648:           }
 4649:       } else {
 4650:           $string =~ s/^(.*?)=//;
 4651: 	  $key=&unescape($1);
 4652:       }
 4653:       $string =~ s/^=//;
 4654: 
 4655:       #value
 4656:       my $value='';
 4657:       if($string =~ /^__HASH_REF__/) {
 4658:           ($value, $string)=&str2hashref($string);
 4659:           if(defined($value->{'error'})) {
 4660:               $hash{'error'}='Bad data';
 4661:               return (\%hash, $string);
 4662:           }
 4663:       } elsif($string =~ /^__ARRAY_REF__/) {
 4664:           ($value, $string)=&str2arrayref($string);
 4665:           if($value->[0] eq 'Array reference error') {
 4666:               $hash{'error'}='Bad data';
 4667:               return (\%hash, $string);
 4668:           }
 4669:       } else {
 4670: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 4671:       }
 4672:       $string =~ s/^&//;
 4673: 
 4674:       $hash{$key}=$value;
 4675:   }
 4676: 
 4677:   $string =~ s/^__END_HASH_REF__//;
 4678: 
 4679:   return (\%hash, $string);
 4680: }
 4681: 
 4682: sub str2array {
 4683:     my ($string)=@_;
 4684:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 4685:     return @$array;
 4686: }
 4687: 
 4688: sub str2arrayref {
 4689:   my ($string) = @_;
 4690:   my @array;
 4691: 
 4692:   if($string !~ /^__ARRAY_REF__/) {
 4693:       if (! ($string eq '' || !defined($string))) {
 4694: 	  $array[0]='Array reference error';
 4695:       }
 4696:       return (\@array, $string);
 4697:   }
 4698: 
 4699:   $string =~ s/^__ARRAY_REF__//;
 4700: 
 4701:   while($string !~ /^__END_ARRAY_REF__/) {
 4702:       my $value='';
 4703:       if($string =~ /^__HASH_REF__/) {
 4704:           ($value, $string)=&str2hashref($string);
 4705:           if(defined($value->{'error'})) {
 4706:               $array[0] ='Array reference error';
 4707:               return (\@array, $string);
 4708:           }
 4709:       } elsif($string =~ /^__ARRAY_REF__/) {
 4710:           ($value, $string)=&str2arrayref($string);
 4711:           if($value->[0] eq 'Array reference error') {
 4712:               $array[0] ='Array reference error';
 4713:               return (\@array, $string);
 4714:           }
 4715:       } else {
 4716: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 4717:       }
 4718:       $string =~ s/^&//;
 4719: 
 4720:       push(@array, $value);
 4721:   }
 4722: 
 4723:   $string =~ s/^__END_ARRAY_REF__//;
 4724: 
 4725:   return (\@array, $string);
 4726: }
 4727: 
 4728: # -------------------------------------------------------------------Temp Store
 4729: 
 4730: sub tmpreset {
 4731:   my ($symb,$namespace,$domain,$stuname) = @_;
 4732:   if (!$symb) {
 4733:     $symb=&symbread();
 4734:     if (!$symb) { $symb= $env{'request.url'}; }
 4735:   }
 4736:   $symb=escape($symb);
 4737: 
 4738:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4739:   $namespace=~s/\//\_/g;
 4740:   $namespace=~s/\W//g;
 4741: 
 4742:   if (!$domain) { $domain=$env{'user.domain'}; }
 4743:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4744:   if ($domain eq 'public' && $stuname eq 'public') {
 4745:       $stuname=$ENV{'REMOTE_ADDR'};
 4746:   }
 4747:   my $path=LONCAPA::tempdir();
 4748:   my %hash;
 4749:   if (tie(%hash,'GDBM_File',
 4750: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4751: 	  &GDBM_WRCREAT(),0640)) {
 4752:     foreach my $key (keys(%hash)) {
 4753:       if ($key=~ /:$symb/) {
 4754: 	delete($hash{$key});
 4755:       }
 4756:     }
 4757:   }
 4758: }
 4759: 
 4760: sub tmpstore {
 4761:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4762: 
 4763:   if (!$symb) {
 4764:     $symb=&symbread();
 4765:     if (!$symb) { $symb= $env{'request.url'}; }
 4766:   }
 4767:   $symb=escape($symb);
 4768: 
 4769:   if (!$namespace) {
 4770:     # I don't think we would ever want to store this for a course.
 4771:     # it seems this will only be used if we don't have a course.
 4772:     #$namespace=$env{'request.course.id'};
 4773:     #if (!$namespace) {
 4774:       $namespace=$env{'request.state'};
 4775:     #}
 4776:   }
 4777:   $namespace=~s/\//\_/g;
 4778:   $namespace=~s/\W//g;
 4779:   if (!$domain) { $domain=$env{'user.domain'}; }
 4780:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4781:   if ($domain eq 'public' && $stuname eq 'public') {
 4782:       $stuname=$ENV{'REMOTE_ADDR'};
 4783:   }
 4784:   my $now=time;
 4785:   my %hash;
 4786:   my $path=LONCAPA::tempdir();
 4787:   if (tie(%hash,'GDBM_File',
 4788: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4789: 	  &GDBM_WRCREAT(),0640)) {
 4790:     $hash{"version:$symb"}++;
 4791:     my $version=$hash{"version:$symb"};
 4792:     my $allkeys=''; 
 4793:     foreach my $key (keys(%$storehash)) {
 4794:       $allkeys.=$key.':';
 4795:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 4796:     }
 4797:     $hash{"$version:$symb:timestamp"}=$now;
 4798:     $allkeys.='timestamp';
 4799:     $hash{"$version:keys:$symb"}=$allkeys;
 4800:     if (untie(%hash)) {
 4801:       return 'ok';
 4802:     } else {
 4803:       return "error:$!";
 4804:     }
 4805:   } else {
 4806:     return "error:$!";
 4807:   }
 4808: }
 4809: 
 4810: # -----------------------------------------------------------------Temp Restore
 4811: 
 4812: sub tmprestore {
 4813:   my ($symb,$namespace,$domain,$stuname) = @_;
 4814: 
 4815:   if (!$symb) {
 4816:     $symb=&symbread();
 4817:     if (!$symb) { $symb= $env{'request.url'}; }
 4818:   }
 4819:   $symb=escape($symb);
 4820: 
 4821:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4822: 
 4823:   if (!$domain) { $domain=$env{'user.domain'}; }
 4824:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4825:   if ($domain eq 'public' && $stuname eq 'public') {
 4826:       $stuname=$ENV{'REMOTE_ADDR'};
 4827:   }
 4828:   my %returnhash;
 4829:   $namespace=~s/\//\_/g;
 4830:   $namespace=~s/\W//g;
 4831:   my %hash;
 4832:   my $path=LONCAPA::tempdir();
 4833:   if (tie(%hash,'GDBM_File',
 4834: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4835: 	  &GDBM_READER(),0640)) {
 4836:     my $version=$hash{"version:$symb"};
 4837:     $returnhash{'version'}=$version;
 4838:     my $scope;
 4839:     for ($scope=1;$scope<=$version;$scope++) {
 4840:       my $vkeys=$hash{"$scope:keys:$symb"};
 4841:       my @keys=split(/:/,$vkeys);
 4842:       my $key;
 4843:       $returnhash{"$scope:keys"}=$vkeys;
 4844:       foreach $key (@keys) {
 4845: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4846: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4847:       }
 4848:     }
 4849:     if (!(untie(%hash))) {
 4850:       return "error:$!";
 4851:     }
 4852:   } else {
 4853:     return "error:$!";
 4854:   }
 4855:   return %returnhash;
 4856: }
 4857: 
 4858: # ----------------------------------------------------------------------- Store
 4859: 
 4860: sub store {
 4861:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 4862:     my $home='';
 4863: 
 4864:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4865: 
 4866:     $symb=&symbclean($symb);
 4867:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4868: 
 4869:     if (!$domain) { $domain=$env{'user.domain'}; }
 4870:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4871: 
 4872:     &devalidate($symb,$stuname,$domain);
 4873: 
 4874:     $symb=escape($symb);
 4875:     if (!$namespace) { 
 4876:        unless ($namespace=$env{'request.course.id'}) { 
 4877:           return ''; 
 4878:        } 
 4879:     }
 4880:     if (!$home) { $home=$env{'user.home'}; }
 4881: 
 4882:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4883:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4884: 
 4885:     my $namevalue='';
 4886:     foreach my $key (keys(%$storehash)) {
 4887:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4888:     }
 4889:     $namevalue=~s/\&$//;
 4890:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 4891:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 4892: }
 4893: 
 4894: # -------------------------------------------------------------- Critical Store
 4895: 
 4896: sub cstore {
 4897:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 4898:     my $home='';
 4899: 
 4900:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4901: 
 4902:     $symb=&symbclean($symb);
 4903:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4904: 
 4905:     if (!$domain) { $domain=$env{'user.domain'}; }
 4906:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4907: 
 4908:     &devalidate($symb,$stuname,$domain);
 4909: 
 4910:     $symb=escape($symb);
 4911:     if (!$namespace) { 
 4912:        unless ($namespace=$env{'request.course.id'}) { 
 4913:           return ''; 
 4914:        } 
 4915:     }
 4916:     if (!$home) { $home=$env{'user.home'}; }
 4917: 
 4918:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4919:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4920: 
 4921:     my $namevalue='';
 4922:     foreach my $key (keys(%$storehash)) {
 4923:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4924:     }
 4925:     $namevalue=~s/\&$//;
 4926:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 4927:     return critical
 4928:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 4929: }
 4930: 
 4931: # --------------------------------------------------------------------- Restore
 4932: 
 4933: sub restore {
 4934:     my ($symb,$namespace,$domain,$stuname) = @_;
 4935:     my $home='';
 4936: 
 4937:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4938: 
 4939:     if (!$symb) {
 4940:         return if ($namespace eq 'courserequests');
 4941:         unless ($symb=escape(&symbread())) { return ''; }
 4942:     } else {
 4943:         unless ($namespace eq 'courserequests') {
 4944:             $symb=&escape(&symbclean($symb));
 4945:         }
 4946:     }
 4947:     if (!$namespace) { 
 4948:        unless ($namespace=$env{'request.course.id'}) { 
 4949:           return ''; 
 4950:        } 
 4951:     }
 4952:     if (!$domain) { $domain=$env{'user.domain'}; }
 4953:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4954:     if (!$home) { $home=$env{'user.home'}; }
 4955:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 4956: 
 4957:     my %returnhash=();
 4958:     foreach my $line (split(/\&/,$answer)) {
 4959: 	my ($name,$value)=split(/\=/,$line);
 4960:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 4961:     }
 4962:     my $version;
 4963:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 4964:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 4965:           $returnhash{$item}=$returnhash{$version.':'.$item};
 4966:        }
 4967:     }
 4968:     return %returnhash;
 4969: }
 4970: 
 4971: # ---------------------------------------------------------- Course Description
 4972: #
 4973: #  
 4974: 
 4975: sub coursedescription {
 4976:     my ($courseid,$args)=@_;
 4977:     $courseid=~s/^\///;
 4978:     $courseid=~s/\_/\//g;
 4979:     my ($cdomain,$cnum)=split(/\//,$courseid);
 4980:     my $chome=&homeserver($cnum,$cdomain);
 4981:     my $normalid=$cdomain.'_'.$cnum;
 4982:     # need to always cache even if we get errors otherwise we keep 
 4983:     # trying and trying and trying to get the course description.
 4984:     my %envhash=();
 4985:     my %returnhash=();
 4986:     
 4987:     my $expiretime=600;
 4988:     if ($env{'request.course.id'} eq $normalid) {
 4989: 	$expiretime=120;
 4990:     }
 4991: 
 4992:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 4993:     if (!$args->{'freshen_cache'}
 4994: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 4995: 	foreach my $key (keys(%env)) {
 4996: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 4997: 	    my ($setting) = $1;
 4998: 	    $returnhash{$setting} = $env{$key};
 4999: 	}
 5000: 	return %returnhash;
 5001:     }
 5002: 
 5003:     # get the data again
 5004: 
 5005:     if (!$args->{'one_time'}) {
 5006: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 5007:     }
 5008: 
 5009:     if ($chome ne 'no_host') {
 5010:        %returnhash=&dump('environment',$cdomain,$cnum);
 5011:        if (!exists($returnhash{'con_lost'})) {
 5012: 	   my $username = $env{'user.name'}; # Defult username
 5013: 	   if(defined $args->{'user'}) {
 5014: 	       $username = $args->{'user'};
 5015: 	   }
 5016:            $returnhash{'home'}= $chome;
 5017: 	   $returnhash{'domain'} = $cdomain;
 5018: 	   $returnhash{'num'} = $cnum;
 5019:            if (!defined($returnhash{'type'})) {
 5020:                $returnhash{'type'} = 'Course';
 5021:            }
 5022:            while (my ($name,$value) = each %returnhash) {
 5023:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 5024:            }
 5025:            $returnhash{'url'}=&clutter($returnhash{'url'});
 5026:            $returnhash{'fn'}=LONCAPA::tempdir() .
 5027: 	       $username.'_'.$cdomain.'_'.$cnum;
 5028:            $envhash{'course.'.$normalid.'.home'}=$chome;
 5029:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 5030:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 5031:        }
 5032:     }
 5033:     if (!$args->{'one_time'}) {
 5034: 	&appenv(\%envhash);
 5035:     }
 5036:     return %returnhash;
 5037: }
 5038: 
 5039: sub update_released_required {
 5040:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 5041:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 5042:         $cid = $env{'request.course.id'};
 5043:         $cdom = $env{'course.'.$cid.'.domain'};
 5044:         $cnum = $env{'course.'.$cid.'.num'};
 5045:         $chome = $env{'course.'.$cid.'.home'};
 5046:     }
 5047:     if ($needsrelease) {
 5048:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 5049:         my $needsupdate;
 5050:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 5051:             $needsupdate = 1;
 5052:         } else {
 5053:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 5054:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 5055:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 5056:                 $needsupdate = 1;
 5057:             }
 5058:         }
 5059:         if ($needsupdate) {
 5060:             my %needshash = (
 5061:                              'internal.releaserequired' => $needsrelease,
 5062:                             );
 5063:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 5064:             if ($putresult eq 'ok') {
 5065:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 5066:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 5067:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 5068:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 5069:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 5070:                 }
 5071:             }
 5072:         }
 5073:     }
 5074:     return;
 5075: }
 5076: 
 5077: # -------------------------------------------------See if a user is privileged
 5078: 
 5079: sub privileged {
 5080:     my ($username,$domain,$possdomains,$possroles)=@_;
 5081:     my $now = time;
 5082:     my $roles;
 5083:     if (ref($possroles) eq 'ARRAY') {
 5084:         $roles = $possroles; 
 5085:     } else {
 5086:         $roles = ['dc','su'];
 5087:     }
 5088:     if (ref($possdomains) eq 'ARRAY') {
 5089:         my %privileged = &privileged_by_domain($possdomains,$roles);
 5090:         foreach my $dom (@{$possdomains}) {
 5091:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 5092:                 (ref($privileged{$dom}) eq 'HASH')) {
 5093:                 foreach my $role (@{$roles}) {
 5094:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5095:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 5096:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 5097:                             return 1 unless (($end && $end < $now) ||
 5098:                                              ($start && $start > $now));
 5099:                         }
 5100:                     }
 5101:                 }
 5102:             }
 5103:         }
 5104:     } else {
 5105:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 5106:         my $now = time;
 5107: 
 5108:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
 5109:             my ($trole, $tend, $tstart) = split(/_/, $role);
 5110:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 5111:                 return 1 unless ($tend && $tend < $now) 
 5112:                         or ($tstart && $tstart > $now);
 5113:             }
 5114:         }
 5115:     }
 5116:     return 0;
 5117: }
 5118: 
 5119: sub privileged_by_domain {
 5120:     my ($domains,$roles) = @_;
 5121:     my %privileged = ();
 5122:     my $cachetime = 60*60*24;
 5123:     my $now = time;
 5124:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 5125:         return %privileged;
 5126:     }
 5127:     foreach my $dom (@{$domains}) {
 5128:         next if (ref($privileged{$dom}) eq 'HASH');
 5129:         my $needroles;
 5130:         foreach my $role (@{$roles}) {
 5131:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 5132:             if (defined($cached)) {
 5133:                 if (ref($result) eq 'HASH') {
 5134:                     $privileged{$dom}{$role} = $result;
 5135:                 }
 5136:             } else {
 5137:                 $needroles = 1;
 5138:             }
 5139:         }
 5140:         if ($needroles) {
 5141:             my %dompersonnel = &get_domain_roles($dom,$roles);
 5142:             $privileged{$dom} = {};
 5143:             foreach my $server (keys(%dompersonnel)) {
 5144:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 5145:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 5146:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 5147:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 5148:                         next if ($end && $end < $now);
 5149:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 5150:                             $dompersonnel{$server}{$item};
 5151:                     }
 5152:                 }
 5153:             }
 5154:             if (ref($privileged{$dom}) eq 'HASH') {
 5155:                 foreach my $role (@{$roles}) {
 5156:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5157:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 5158:                     } else {
 5159:                         my %hash = ();
 5160:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 5161:                     }
 5162:                 }
 5163:             }
 5164:         }
 5165:     }
 5166:     return %privileged;
 5167: }
 5168: 
 5169: # -------------------------------------------------------- Get user privileges
 5170: 
 5171: sub rolesinit {
 5172:     my ($domain, $username) = @_;
 5173:     my %userroles = ('user.login.time' => time);
 5174:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 5175: 
 5176:     # firstaccess and timerinterval are related to timed maps/resources. 
 5177:     # also, blocking can be triggered by an activating timer
 5178:     # it's saved in the user's %env.
 5179:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 5180:     my %timerinterval = &dump('timerinterval', $domain, $username);
 5181:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 5182:         %timerintchk, %timerintenv);
 5183: 
 5184:     foreach my $key (keys(%firstaccess)) {
 5185:         my ($cid, $rest) = split(/\0/, $key);
 5186:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 5187:     }
 5188: 
 5189:     foreach my $key (keys(%timerinterval)) {
 5190:         my ($cid,$rest) = split(/\0/,$key);
 5191:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 5192:     }
 5193: 
 5194:     my %allroles=();
 5195:     my %allgroups=();
 5196: 
 5197:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
 5198:         my $role = $rolesdump{$area};
 5199:         $area =~ s/\_\w\w$//;
 5200: 
 5201:         my ($trole, $tend, $tstart, $group_privs);
 5202: 
 5203:         if ($role =~ /^cr/) {
 5204:         # Custom role, defined by a user 
 5205:         # e.g., user.role.cr/msu/smith/mynewrole
 5206:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 5207:                 $trole = $1;
 5208:                 ($tend, $tstart) = split('_', $2);
 5209:             } else {
 5210:                 $trole = $role;
 5211:             }
 5212:         } elsif ($role =~ m|^gr/|) {
 5213:         # Role of member in a group, defined within a course/community
 5214:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 5215:             ($trole, $tend, $tstart) = split(/_/, $role);
 5216:             next if $tstart eq '-1';
 5217:             ($trole, $group_privs) = split(/\//, $trole);
 5218:             $group_privs = &unescape($group_privs);
 5219:         } else {
 5220:         # Just a normal role, defined in roles.tab
 5221:             ($trole, $tend, $tstart) = split(/_/,$role);
 5222:         }
 5223: 
 5224:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 5225:                  $username);
 5226:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 5227: 
 5228:         # role expired or not available yet?
 5229:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 5230:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 5231: 
 5232:         next if $area eq '' or $trole eq '';
 5233: 
 5234:         my $spec = "$trole.$area";
 5235:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 5236: 
 5237:         if ($trole =~ /^cr\//) {
 5238:         # Custom role, defined by a user
 5239:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 5240:         } elsif ($trole eq 'gr') {
 5241:         # Role of a member in a group, defined within a course/community
 5242:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 5243:             next;
 5244:         } else {
 5245:         # Normal role, defined in roles.tab
 5246:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 5247:         }
 5248: 
 5249:         my $cid = $tdomain.'_'.$trest;
 5250:         unless ($firstaccchk{$cid}) {
 5251:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 5252:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 5253:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 5254:                         $coursetimerstarts{$cid}{$item}; 
 5255:                 }
 5256:             }
 5257:             $firstaccchk{$cid} = 1;
 5258:         }
 5259:         unless ($timerintchk{$cid}) {
 5260:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 5261:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 5262:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 5263:                        $coursetimerintervals{$cid}{$item};
 5264:                 }
 5265:             }
 5266:             $timerintchk{$cid} = 1;
 5267:         }
 5268:     }
 5269: 
 5270:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
 5271:         \%allroles, \%allgroups);
 5272:     $env{'user.adv'} = $userroles{'user.adv'};
 5273: 
 5274:     return (\%userroles,\%firstaccenv,\%timerintenv);
 5275: }
 5276: 
 5277: sub set_arearole {
 5278:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 5279:     unless ($nolog) {
 5280: # log the associated role with the area
 5281:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 5282:     }
 5283:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 5284: }
 5285: 
 5286: sub custom_roleprivs {
 5287:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 5288:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 5289:     my $homsvr = &homeserver($rauthor,$rdomain);
 5290:     if (&hostname($homsvr) ne '') {
 5291:         my ($rdummy,$roledef)=
 5292:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 5293:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 5294:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 5295:             if (defined($syspriv)) {
 5296:                 if ($trest =~ /^$match_community$/) {
 5297:                     $syspriv =~ s/bre\&S//; 
 5298:                 }
 5299:                 $$allroles{'cm./'}.=':'.$syspriv;
 5300:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 5301:             }
 5302:             if ($tdomain ne '') {
 5303:                 if (defined($dompriv)) {
 5304:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 5305:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 5306:                 }
 5307:                 if (($trest ne '') && (defined($coursepriv))) {
 5308:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 5309:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 5310:                 }
 5311:             }
 5312:         }
 5313:     }
 5314: }
 5315: 
 5316: sub group_roleprivs {
 5317:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 5318:     my $access = 1;
 5319:     my $now = time;
 5320:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 5321:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 5322:     if ($access) {
 5323:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 5324:         $$allgroups{$course}{$group} .=':'.$group_privs;
 5325:     }
 5326: }
 5327: 
 5328: sub standard_roleprivs {
 5329:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 5330:     if (defined($pr{$trole.':s'})) {
 5331:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 5332:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 5333:     }
 5334:     if ($tdomain ne '') {
 5335:         if (defined($pr{$trole.':d'})) {
 5336:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 5337:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 5338:         }
 5339:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 5340:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 5341:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 5342:         }
 5343:     }
 5344: }
 5345: 
 5346: sub set_userprivs {
 5347:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 5348:     my $author=0;
 5349:     my $adv=0;
 5350:     my %grouproles = ();
 5351:     if (keys(%{$allgroups}) > 0) {
 5352:         my @groupkeys; 
 5353:         foreach my $role (keys(%{$allroles})) {
 5354:             push(@groupkeys,$role);
 5355:         }
 5356:         if (ref($groups_roles) eq 'HASH') {
 5357:             foreach my $key (keys(%{$groups_roles})) {
 5358:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 5359:                     push(@groupkeys,$key);
 5360:                 }
 5361:             }
 5362:         }
 5363:         if (@groupkeys > 0) {
 5364:             foreach my $role (@groupkeys) {
 5365:                 my ($trole,$area,$sec,$extendedarea);
 5366:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 5367:                     $trole = $1;
 5368:                     $area = $2;
 5369:                     $sec = $3;
 5370:                     $extendedarea = $area.$sec;
 5371:                     if (exists($$allgroups{$area})) {
 5372:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 5373:                             my $spec = $trole.'.'.$extendedarea;
 5374:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 5375:                                                 $$allgroups{$area}{$group};
 5376:                         }
 5377:                     }
 5378:                 }
 5379:             }
 5380:         }
 5381:     }
 5382:     foreach my $group (keys(%grouproles)) {
 5383:         $$allroles{$group} = $grouproles{$group};
 5384:     }
 5385:     foreach my $role (keys(%{$allroles})) {
 5386:         my %thesepriv;
 5387:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 5388:         foreach my $item (split(/:/,$$allroles{$role})) {
 5389:             if ($item ne '') {
 5390:                 my ($privilege,$restrictions)=split(/&/,$item);
 5391:                 if ($restrictions eq '') {
 5392:                     $thesepriv{$privilege}='F';
 5393:                 } elsif ($thesepriv{$privilege} ne 'F') {
 5394:                     $thesepriv{$privilege}.=$restrictions;
 5395:                 }
 5396:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 5397:             }
 5398:         }
 5399:         my $thesestr='';
 5400:         foreach my $priv (sort(keys(%thesepriv))) {
 5401: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 5402: 	}
 5403:         $userroles->{'user.priv.'.$role} = $thesestr;
 5404:     }
 5405:     return ($author,$adv);
 5406: }
 5407: 
 5408: sub role_status {
 5409:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 5410:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 5411:         my ($one,$two) = split(m{\./},$rolekey,2);
 5412:         (undef,undef,$$role) = split(/\./,$one,3);
 5413:         unless (!defined($$role) || $$role eq '') {
 5414:             $$where = '/'.$two;
 5415:             $$trolecode=$$role.'.'.$$where;
 5416:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 5417:             $$tstatus='is';
 5418:             if ($$tstart && $$tstart>$update) {
 5419:                 $$tstatus='future';
 5420:                 if ($$tstart<$now) {
 5421:                     if ($$tstart && $$tstart>$refresh) {
 5422:                         if (($$where ne '') && ($$role ne '')) {
 5423:                             my (%allroles,%allgroups,$group_privs,
 5424:                                 %groups_roles,@rolecodes);
 5425:                             my %userroles = (
 5426:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 5427:                             );
 5428:                             @rolecodes = ('cm'); 
 5429:                             my $spec=$$role.'.'.$$where;
 5430:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 5431:                             if ($$role =~ /^cr\//) {
 5432:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 5433:                                 push(@rolecodes,'cr');
 5434:                             } elsif ($$role eq 'gr') {
 5435:                                 push(@rolecodes,$$role);
 5436:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 5437:                                                     $env{'user.name'});
 5438:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 5439:                                 (undef,my $group_privs) = split(/\//,$trole);
 5440:                                 $group_privs = &unescape($group_privs);
 5441:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 5442:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 5443:                                 &get_groups_roles($tdomain,$trest,
 5444:                                                   \%course_roles,\@rolecodes,
 5445:                                                   \%groups_roles);
 5446:                             } else {
 5447:                                 push(@rolecodes,$$role);
 5448:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 5449:                             }
 5450:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
 5451:                             &appenv(\%userroles,\@rolecodes);
 5452:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5453:                         }
 5454:                     }
 5455:                     $$tstatus = 'is';
 5456:                 }
 5457:             }
 5458:             if ($$tend) {
 5459:                 if ($$tend<$update) {
 5460:                     $$tstatus='expired';
 5461:                 } elsif ($$tend<$now) {
 5462:                     $$tstatus='will_not';
 5463:                 }
 5464:             }
 5465:         }
 5466:     }
 5467: }
 5468: 
 5469: sub get_groups_roles {
 5470:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 5471:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 5472:                   (ref($rolecodes) eq 'ARRAY') && 
 5473:                   (ref($groups_roles) eq 'HASH')); 
 5474:     if (keys(%{$cdom_courseroles}) > 0) {
 5475:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 5476:         if ($cdom ne '' && $cnum ne '') {
 5477:             foreach my $key (keys(%{$cdom_courseroles})) {
 5478:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 5479:                     my $crsrole = $1;
 5480:                     my $crssec = $2;
 5481:                     if ($crsrole =~ /^cr/) {
 5482:                         unless (grep(/^cr$/,@{$rolecodes})) {
 5483:                             push(@{$rolecodes},'cr');
 5484:                         }
 5485:                     } else {
 5486:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 5487:                             push(@{$rolecodes},$crsrole);
 5488:                         }
 5489:                     }
 5490:                     my $rolekey = "$crsrole./$cdom/$cnum";
 5491:                     if ($crssec ne '') {
 5492:                         $rolekey .= "/$crssec";
 5493:                     }
 5494:                     $rolekey .= './';
 5495:                     $groups_roles->{$rolekey} = $rolecodes;
 5496:                 }
 5497:             }
 5498:         }
 5499:     }
 5500:     return;
 5501: }
 5502: 
 5503: sub delete_env_groupprivs {
 5504:     my ($where,$courseroles,$possroles) = @_;
 5505:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 5506:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 5507:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 5508:         %{$courseroles->{$udom}} =
 5509:             &get_my_roles('','','userroles',['active'],
 5510:                           $possroles,[$udom],1);
 5511:     }
 5512:     if (ref($courseroles->{$udom}) eq 'HASH') {
 5513:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 5514:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 5515:             my $area = '/'.$cdom.'/'.$cnum;
 5516:             my $privkey = "user.priv.$crsrole.$area";
 5517:             if ($crssec ne '') {
 5518:                 $privkey .= '/'.$crssec;
 5519:             }
 5520:             $privkey .= ".$area/$group";
 5521:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 5522:         }
 5523:     }
 5524:     return;
 5525: }
 5526: 
 5527: sub check_adhoc_privs {
 5528:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
 5529:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 5530:     my $setprivs;
 5531:     if ($env{$cckey}) {
 5532:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 5533:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 5534:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 5535:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5536:             $setprivs = 1;
 5537:         }
 5538:     } else {
 5539:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5540:         $setprivs = 1;
 5541:     }
 5542:     return $setprivs;
 5543: }
 5544: 
 5545: sub set_adhoc_privileges {
 5546: # role can be cc or ca
 5547:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
 5548:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 5549:     my $spec = $role.'.'.$area;
 5550:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 5551:                                   $env{'user.name'},1);
 5552:     my %ccrole = ();
 5553:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
 5554:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
 5555:     &appenv(\%userroles,[$role,'cm']);
 5556:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5557:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 5558:         &appenv( {'request.role'        => $spec,
 5559:                   'request.role.domain' => $dcdom,
 5560:                   'request.course.sec'  => ''
 5561:                  }
 5562:                );
 5563:         my $tadv=0;
 5564:         if (&allowed('adv') eq 'F') { $tadv=1; }
 5565:         &appenv({'request.role.adv'    => $tadv});
 5566:     }
 5567: }
 5568: 
 5569: # --------------------------------------------------------------- get interface
 5570: 
 5571: sub get {
 5572:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5573:    my $items='';
 5574:    foreach my $item (@$storearr) {
 5575:        $items.=&escape($item).'&';
 5576:    }
 5577:    $items=~s/\&$//;
 5578:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5579:    if (!$uname) { $uname=$env{'user.name'}; }
 5580:    my $uhome=&homeserver($uname,$udomain);
 5581: 
 5582:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 5583:    my @pairs=split(/\&/,$rep);
 5584:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 5585:      return @pairs;
 5586:    }
 5587:    my %returnhash=();
 5588:    my $i=0;
 5589:    foreach my $item (@$storearr) {
 5590:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5591:       $i++;
 5592:    }
 5593:    return %returnhash;
 5594: }
 5595: 
 5596: # --------------------------------------------------------------- del interface
 5597: 
 5598: sub del {
 5599:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5600:    my $items='';
 5601:    foreach my $item (@$storearr) {
 5602:        $items.=&escape($item).'&';
 5603:    }
 5604: 
 5605:    $items=~s/\&$//;
 5606:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5607:    if (!$uname) { $uname=$env{'user.name'}; }
 5608:    my $uhome=&homeserver($uname,$udomain);
 5609:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 5610: }
 5611: 
 5612: # -------------------------------------------------------------- dump interface
 5613: 
 5614: sub unserialize {
 5615:     my ($rep, $escapedkeys) = @_;
 5616: 
 5617:     return {} if $rep =~ /^error/;
 5618: 
 5619:     my %returnhash=();
 5620: 	foreach my $item (split(/\&/,$rep)) {
 5621: 	    my ($key, $value) = split(/=/, $item, 2);
 5622: 	    $key = unescape($key) unless $escapedkeys;
 5623: 	    next if $key =~ /^error: 2 /;
 5624: 	    $returnhash{$key} = &thaw_unescape($value);
 5625: 	}
 5626:     #return %returnhash;
 5627:     return \%returnhash;
 5628: }        
 5629: 
 5630: # see Lond::dump_with_regexp
 5631: # if $escapedkeys hash keys won't get unescaped.
 5632: sub dump {
 5633:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 5634:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5635:     if (!$uname) { $uname=$env{'user.name'}; }
 5636:     my $uhome=&homeserver($uname,$udomain);
 5637: 
 5638:     if ($regexp) {
 5639:         $regexp=&escape($regexp);
 5640:     } else {
 5641:         $regexp='.';
 5642:     }
 5643:     if (grep { $_ eq $uhome } current_machine_ids()) {
 5644:         # user is hosted on this machine
 5645:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 5646:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 5647:         return %{unserialize($reply, $escapedkeys)};
 5648:     }
 5649:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 5650:     my @pairs=split(/\&/,$rep);
 5651:     my %returnhash=();
 5652:     if (!($rep =~ /^error/ )) {
 5653: 	foreach my $item (@pairs) {
 5654: 	    my ($key,$value)=split(/=/,$item,2);
 5655:         $key = unescape($key) unless $escapedkeys;
 5656:         #$key = &unescape($key);
 5657: 	    next if ($key =~ /^error: 2 /);
 5658: 	    $returnhash{$key}=&thaw_unescape($value);
 5659: 	}
 5660:     }
 5661:     return %returnhash;
 5662: }
 5663: 
 5664: 
 5665: # --------------------------------------------------------- dumpstore interface
 5666: 
 5667: sub dumpstore {
 5668:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 5669:    # same as dump but keys must be escaped. They may contain colon separated
 5670:    # lists of values that may themself contain colons (e.g. symbs).
 5671:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 5672: }
 5673: 
 5674: # -------------------------------------------------------------- keys interface
 5675: 
 5676: sub getkeys {
 5677:    my ($namespace,$udomain,$uname)=@_;
 5678:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5679:    if (!$uname) { $uname=$env{'user.name'}; }
 5680:    my $uhome=&homeserver($uname,$udomain);
 5681:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 5682:    my @keyarray=();
 5683:    foreach my $key (split(/\&/,$rep)) {
 5684:       next if ($key =~ /^error: 2 /);
 5685:       push(@keyarray,&unescape($key));
 5686:    }
 5687:    return @keyarray;
 5688: }
 5689: 
 5690: # --------------------------------------------------------------- currentdump
 5691: sub currentdump {
 5692:    my ($courseid,$sdom,$sname)=@_;
 5693:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 5694:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 5695:    $sname    = $env{'user.name'}         if (! defined($sname));
 5696:    my $uhome = &homeserver($sname,$sdom);
 5697:    my $rep;
 5698: 
 5699:    if (grep { $_ eq $uhome } current_machine_ids()) {
 5700:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 5701:                    $courseid)));
 5702:    } else {
 5703:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 5704:    }
 5705: 
 5706:    return if ($rep =~ /^(error:|no_such_host)/);
 5707:    #
 5708:    my %returnhash=();
 5709:    #
 5710:    if ($rep eq "unknown_cmd") { 
 5711:        # an old lond will not know currentdump
 5712:        # Do a dump and make it look like a currentdump
 5713:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 5714:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 5715:        my %hash = @tmp;
 5716:        @tmp=();
 5717:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 5718:    } else {
 5719:        my @pairs=split(/\&/,$rep);
 5720:        foreach my $pair (@pairs) {
 5721:            my ($key,$value)=split(/=/,$pair,2);
 5722:            my ($symb,$param) = split(/:/,$key);
 5723:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 5724:                                                         &thaw_unescape($value);
 5725:        }
 5726:    }
 5727:    return %returnhash;
 5728: }
 5729: 
 5730: sub convert_dump_to_currentdump{
 5731:     my %hash = %{shift()};
 5732:     my %returnhash;
 5733:     # Code ripped from lond, essentially.  The only difference
 5734:     # here is the unescaping done by lonnet::dump().  Conceivably
 5735:     # we might run in to problems with parameter names =~ /^v\./
 5736:     while (my ($key,$value) = each(%hash)) {
 5737:         my ($v,$symb,$param) = split(/:/,$key);
 5738: 	$symb  = &unescape($symb);
 5739: 	$param = &unescape($param);
 5740:         next if ($v eq 'version' || $symb eq 'keys');
 5741:         next if (exists($returnhash{$symb}) &&
 5742:                  exists($returnhash{$symb}->{$param}) &&
 5743:                  $returnhash{$symb}->{'v.'.$param} > $v);
 5744:         $returnhash{$symb}->{$param}=$value;
 5745:         $returnhash{$symb}->{'v.'.$param}=$v;
 5746:     }
 5747:     #
 5748:     # Remove all of the keys in the hashes which keep track of
 5749:     # the version of the parameter.
 5750:     while (my ($symb,$param_hash) = each(%returnhash)) {
 5751:         # use a foreach because we are going to delete from the hash.
 5752:         foreach my $key (keys(%$param_hash)) {
 5753:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 5754:         }
 5755:     }
 5756:     return \%returnhash;
 5757: }
 5758: 
 5759: # ------------------------------------------------------ critical inc interface
 5760: 
 5761: sub cinc {
 5762:     return &inc(@_,'critical');
 5763: }
 5764: 
 5765: # --------------------------------------------------------------- inc interface
 5766: 
 5767: sub inc {
 5768:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 5769:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5770:     if (!$uname) { $uname=$env{'user.name'}; }
 5771:     my $uhome=&homeserver($uname,$udomain);
 5772:     my $items='';
 5773:     if (! ref($store)) {
 5774:         # got a single value, so use that instead
 5775:         $items = &escape($store).'=&';
 5776:     } elsif (ref($store) eq 'SCALAR') {
 5777:         $items = &escape($$store).'=&';        
 5778:     } elsif (ref($store) eq 'ARRAY') {
 5779:         $items = join('=&',map {&escape($_);} @{$store});
 5780:     } elsif (ref($store) eq 'HASH') {
 5781:         while (my($key,$value) = each(%{$store})) {
 5782:             $items.= &escape($key).'='.&escape($value).'&';
 5783:         }
 5784:     }
 5785:     $items=~s/\&$//;
 5786:     if ($critical) {
 5787: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 5788:     } else {
 5789: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 5790:     }
 5791: }
 5792: 
 5793: # --------------------------------------------------------------- put interface
 5794: 
 5795: sub put {
 5796:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5797:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5798:    if (!$uname) { $uname=$env{'user.name'}; }
 5799:    my $uhome=&homeserver($uname,$udomain);
 5800:    my $items='';
 5801:    foreach my $item (keys(%$storehash)) {
 5802:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5803:    }
 5804:    $items=~s/\&$//;
 5805:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5806: }
 5807: 
 5808: # ------------------------------------------------------------ newput interface
 5809: 
 5810: sub newput {
 5811:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5812:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5813:    if (!$uname) { $uname=$env{'user.name'}; }
 5814:    my $uhome=&homeserver($uname,$udomain);
 5815:    my $items='';
 5816:    foreach my $key (keys(%$storehash)) {
 5817:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5818:    }
 5819:    $items=~s/\&$//;
 5820:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 5821: }
 5822: 
 5823: # ---------------------------------------------------------  putstore interface
 5824: 
 5825: sub putstore {
 5826:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
 5827:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5828:    if (!$uname) { $uname=$env{'user.name'}; }
 5829:    my $uhome=&homeserver($uname,$udomain);
 5830:    my $items='';
 5831:    foreach my $key (keys(%$storehash)) {
 5832:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 5833:    }
 5834:    $items=~s/\&$//;
 5835:    my $esc_symb=&escape($symb);
 5836:    my $esc_v=&escape($version);
 5837:    my $reply =
 5838:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 5839: 	      $uhome);
 5840:    if (($tolog) && ($reply eq 'ok')) {
 5841:        my $namevalue='';
 5842:        foreach my $key (keys(%{$storehash})) {
 5843:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 5844:        }
 5845:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
 5846:                      '&host='.&escape($perlvar{'lonHostID'}).
 5847:                      '&version='.$esc_v.
 5848:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
 5849:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
 5850:    }
 5851:    if ($reply eq 'unknown_cmd') {
 5852:        # gfall back to way things use to be done
 5853:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 5854: 			    $uname);
 5855:    }
 5856:    return $reply;
 5857: }
 5858: 
 5859: sub old_putstore {
 5860:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5861:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5862:     if (!$uname) { $uname=$env{'user.name'}; }
 5863:     my $uhome=&homeserver($uname,$udomain);
 5864:     my %newstorehash;
 5865:     foreach my $item (keys(%$storehash)) {
 5866: 	my $key = $version.':'.&escape($symb).':'.$item;
 5867: 	$newstorehash{$key} = $storehash->{$item};
 5868:     }
 5869:     my $items='';
 5870:     my %allitems = ();
 5871:     foreach my $item (keys(%newstorehash)) {
 5872: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 5873: 	    my $key = $1.':keys:'.$2;
 5874: 	    $allitems{$key} .= $3.':';
 5875: 	}
 5876: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 5877:     }
 5878:     foreach my $item (keys(%allitems)) {
 5879: 	$allitems{$item} =~ s/\:$//;
 5880: 	$items.= $item.'='.$allitems{$item}.'&';
 5881:     }
 5882:     $items=~s/\&$//;
 5883:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5884: }
 5885: 
 5886: # ------------------------------------------------------ critical put interface
 5887: 
 5888: sub cput {
 5889:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5890:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5891:    if (!$uname) { $uname=$env{'user.name'}; }
 5892:    my $uhome=&homeserver($uname,$udomain);
 5893:    my $items='';
 5894:    foreach my $item (keys(%$storehash)) {
 5895:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5896:    }
 5897:    $items=~s/\&$//;
 5898:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 5899: }
 5900: 
 5901: # -------------------------------------------------------------- eget interface
 5902: 
 5903: sub eget {
 5904:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5905:    my $items='';
 5906:    foreach my $item (@$storearr) {
 5907:        $items.=&escape($item).'&';
 5908:    }
 5909:    $items=~s/\&$//;
 5910:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5911:    if (!$uname) { $uname=$env{'user.name'}; }
 5912:    my $uhome=&homeserver($uname,$udomain);
 5913:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 5914:    my @pairs=split(/\&/,$rep);
 5915:    my %returnhash=();
 5916:    my $i=0;
 5917:    foreach my $item (@$storearr) {
 5918:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5919:       $i++;
 5920:    }
 5921:    return %returnhash;
 5922: }
 5923: 
 5924: # ------------------------------------------------------------ tmpput interface
 5925: sub tmpput {
 5926:     my ($storehash,$server,$context)=@_;
 5927:     my $items='';
 5928:     foreach my $item (keys(%$storehash)) {
 5929: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5930:     }
 5931:     $items=~s/\&$//;
 5932:     if (defined($context)) {
 5933:         $items .= ':'.&escape($context);
 5934:     }
 5935:     return &reply("tmpput:$items",$server);
 5936: }
 5937: 
 5938: # ------------------------------------------------------------ tmpget interface
 5939: sub tmpget {
 5940:     my ($token,$server)=@_;
 5941:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5942:     my $rep=&reply("tmpget:$token",$server);
 5943:     my %returnhash;
 5944:     foreach my $item (split(/\&/,$rep)) {
 5945: 	my ($key,$value)=split(/=/,$item);
 5946:         next if ($key =~ /^error: 2 /);
 5947: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 5948:     }
 5949:     return %returnhash;
 5950: }
 5951: 
 5952: # ------------------------------------------------------------ tmpdel interface
 5953: sub tmpdel {
 5954:     my ($token,$server)=@_;
 5955:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5956:     return &reply("tmpdel:$token",$server);
 5957: }
 5958: 
 5959: # ------------------------------------------------------------ get_timebased_id 
 5960: 
 5961: sub get_timebased_id {
 5962:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 5963:         $maxtries) = @_;
 5964:     my ($newid,$error,$dellock);
 5965:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 5966:         return ('','ok','invalid call to get suffix');
 5967:     }
 5968: 
 5969: # set defaults for any optional args for which values were not supplied
 5970:     if ($who eq '') {
 5971:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 5972:     }
 5973:     if (!$locktries) {
 5974:         $locktries = 3;
 5975:     }
 5976:     if (!$maxtries) {
 5977:         $maxtries = 10;
 5978:     }
 5979:     
 5980:     if (($cdom eq '') || ($cnum eq '')) {
 5981:         if ($env{'request.course.id'}) {
 5982:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5983:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5984:         }
 5985:         if (($cdom eq '') || ($cnum eq '')) {
 5986:             return ('','ok','call to get suffix not in course context');
 5987:         }
 5988:     }
 5989: 
 5990: # construct locking item
 5991:     my $lockhash = {
 5992:                       $prefix."\0".'locked_'.$keyid => $who,
 5993:                    };
 5994:     my $tries = 0;
 5995: 
 5996: # attempt to get lock on nohist_$namespace file
 5997:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 5998:     while (($gotlock ne 'ok') && $tries <$locktries) {
 5999:         $tries ++;
 6000:         sleep 1;
 6001:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 6002:     }
 6003: 
 6004: # attempt to get unique identifier, based on current timestamp
 6005:     if ($gotlock eq 'ok') {
 6006:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 6007:         my $id = time;
 6008:         $newid = $id;
 6009:         if ($idtype eq 'addcode') {
 6010:             $newid .= &sixnum_code();
 6011:         }
 6012:         my $idtries = 0;
 6013:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 6014:             if ($idtype eq 'concat') {
 6015:                 $newid = $id.$idtries;
 6016:             } elsif ($idtype eq 'addcode') {
 6017:                 $newid = $newid.&sixnum_code();
 6018:             } else {
 6019:                 $newid ++;
 6020:             }
 6021:             $idtries ++;
 6022:         }
 6023:         if (!exists($inuse{$prefix."\0".$newid})) {
 6024:             my %new_item =  (
 6025:                               $prefix."\0".$newid => $who,
 6026:                             );
 6027:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 6028:                                                  $cdom,$cnum);
 6029:             if ($putresult ne 'ok') {
 6030:                 undef($newid);
 6031:                 $error = 'error saving new item: '.$putresult;
 6032:             }
 6033:         } else {
 6034:              undef($newid);
 6035:              $error = ('error: no unique suffix available for the new item ');
 6036:         }
 6037: #  remove lock
 6038:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 6039:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 6040:     } else {
 6041:         $error = "error: could not obtain lockfile\n";
 6042:         $dellock = 'ok';
 6043:     }
 6044:     return ($newid,$dellock,$error);
 6045: }
 6046: 
 6047: sub sixnum_code {
 6048:     my $code;
 6049:     for (0..6) {
 6050:         $code .= int( rand(9) );
 6051:     }
 6052:     return $code;
 6053: }
 6054: 
 6055: # -------------------------------------------------- portfolio access checking
 6056: 
 6057: sub portfolio_access {
 6058:     my ($requrl,$clientip) = @_;
 6059:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 6060:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
 6061:     if ($result) {
 6062:         my %setters;
 6063:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 6064:             my ($startblock,$endblock) =
 6065:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 6066:             if ($startblock && $endblock) {
 6067:                 return 'B';
 6068:             }
 6069:         } else {
 6070:             my ($startblock,$endblock) =
 6071:                 &Apache::loncommon::blockcheck(\%setters,'port');
 6072:             if ($startblock && $endblock) {
 6073:                 return 'B';
 6074:             }
 6075:         }
 6076:     }
 6077:     if ($result eq 'ok') {
 6078:        return 'F';
 6079:     } elsif ($result =~ /^[^:]+:guest_/) {
 6080:        return 'A';
 6081:     }
 6082:     return '';
 6083: }
 6084: 
 6085: sub get_portfolio_access {
 6086:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
 6087: 
 6088:     if (!ref($access_hash)) {
 6089: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 6090: 	my %access_controls = &get_access_controls($current_perms,$group,
 6091: 						   $file_name);
 6092: 	$access_hash = $access_controls{$file_name};
 6093:     }
 6094: 
 6095:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
 6096:     my $now = time;
 6097:     if (ref($access_hash) eq 'HASH') {
 6098:         foreach my $key (keys(%{$access_hash})) {
 6099:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 6100:             if ($start > $now) {
 6101:                 next;
 6102:             }
 6103:             if ($end && $end<$now) {
 6104:                 next;
 6105:             }
 6106:             if ($scope eq 'public') {
 6107:                 $public = $key;
 6108:                 last;
 6109:             } elsif ($scope eq 'guest') {
 6110:                 $guest = $key;
 6111:             } elsif ($scope eq 'domains') {
 6112:                 push(@domains,$key);
 6113:             } elsif ($scope eq 'users') {
 6114:                 push(@users,$key);
 6115:             } elsif ($scope eq 'course') {
 6116:                 push(@courses,$key);
 6117:             } elsif ($scope eq 'group') {
 6118:                 push(@groups,$key);
 6119:             } elsif ($scope eq 'ip') {
 6120:                 push(@ips,$key);
 6121:             }
 6122:         }
 6123:         if ($public) {
 6124:             return 'ok';
 6125:         } elsif (@ips > 0) {
 6126:             my $allowed;
 6127:             foreach my $ipkey (@ips) {
 6128:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
 6129:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
 6130:                         $allowed = 1;
 6131:                         last; 
 6132:                     }
 6133:                 }
 6134:             }
 6135:             if ($allowed) {
 6136:                 return 'ok';
 6137:             }
 6138:         }
 6139:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 6140:             if ($guest) {
 6141:                 return $guest;
 6142:             }
 6143:         } else {
 6144:             if (@domains > 0) {
 6145:                 foreach my $domkey (@domains) {
 6146:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 6147:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 6148:                             return 'ok';
 6149:                         }
 6150:                     }
 6151:                 }
 6152:             }
 6153:             if (@users > 0) {
 6154:                 foreach my $userkey (@users) {
 6155:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 6156:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 6157:                             if (ref($item) eq 'HASH') {
 6158:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 6159:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 6160:                                     return 'ok';
 6161:                                 }
 6162:                             }
 6163:                         }
 6164:                     } 
 6165:                 }
 6166:             }
 6167:             my %roleshash;
 6168:             my @courses_and_groups = @courses;
 6169:             push(@courses_and_groups,@groups); 
 6170:             if (@courses_and_groups > 0) {
 6171:                 my (%allgroups,%allroles); 
 6172:                 my ($start,$end,$role,$sec,$group);
 6173:                 foreach my $envkey (%env) {
 6174:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 6175:                         my $cid = $2.'_'.$3; 
 6176:                         if ($1 eq 'gr') {
 6177:                             $group = $4;
 6178:                             $allgroups{$cid}{$group} = $env{$envkey};
 6179:                         } else {
 6180:                             if ($4 eq '') {
 6181:                                 $sec = 'none';
 6182:                             } else {
 6183:                                 $sec = $4;
 6184:                             }
 6185:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 6186:                         }
 6187:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 6188:                         my $cid = $2.'_'.$3;
 6189:                         if ($4 eq '') {
 6190:                             $sec = 'none';
 6191:                         } else {
 6192:                             $sec = $4;
 6193:                         }
 6194:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 6195:                     }
 6196:                 }
 6197:                 if (keys(%allroles) == 0) {
 6198:                     return;
 6199:                 }
 6200:                 foreach my $key (@courses_and_groups) {
 6201:                     my %content = %{$$access_hash{$key}};
 6202:                     my $cnum = $content{'number'};
 6203:                     my $cdom = $content{'domain'};
 6204:                     my $cid = $cdom.'_'.$cnum;
 6205:                     if (!exists($allroles{$cid})) {
 6206:                         next;
 6207:                     }    
 6208:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 6209:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 6210:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 6211:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 6212:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 6213:                         foreach my $role (keys(%{$allroles{$cid}})) {
 6214:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 6215:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 6216:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 6217:                                         if (grep/^all$/,@sections) {
 6218:                                             return 'ok';
 6219:                                         } else {
 6220:                                             if (grep/^$sec$/,@sections) {
 6221:                                                 return 'ok';
 6222:                                             }
 6223:                                         }
 6224:                                     }
 6225:                                 }
 6226:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 6227:                                     if (grep/^none$/,@groups) {
 6228:                                         return 'ok';
 6229:                                     }
 6230:                                 } else {
 6231:                                     if (grep/^all$/,@groups) {
 6232:                                         return 'ok';
 6233:                                     } 
 6234:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 6235:                                         if (grep/^$group$/,@groups) {
 6236:                                             return 'ok';
 6237:                                         }
 6238:                                     }
 6239:                                 } 
 6240:                             }
 6241:                         }
 6242:                     }
 6243:                 }
 6244:             }
 6245:             if ($guest) {
 6246:                 return $guest;
 6247:             }
 6248:         }
 6249:     }
 6250:     return;
 6251: }
 6252: 
 6253: sub course_group_datechecker {
 6254:     my ($dates,$now,$status) = @_;
 6255:     my ($start,$end) = split(/\./,$dates);
 6256:     if (!$start && !$end) {
 6257:         return 'ok';
 6258:     }
 6259:     if (grep/^active$/,@{$status}) {
 6260:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 6261:             return 'ok';
 6262:         }
 6263:     }
 6264:     if (grep/^previous$/,@{$status}) {
 6265:         if ($end > $now ) {
 6266:             return 'ok';
 6267:         }
 6268:     }
 6269:     if (grep/^future$/,@{$status}) {
 6270:         if ($start > $now) {
 6271:             return 'ok';
 6272:         }
 6273:     }
 6274:     return; 
 6275: }
 6276: 
 6277: sub parse_portfolio_url {
 6278:     my ($url) = @_;
 6279: 
 6280:     my ($type,$udom,$unum,$group,$file_name);
 6281:     
 6282:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 6283: 	$type = 1;
 6284:         $udom = $1;
 6285:         $unum = $2;
 6286:         $file_name = $3;
 6287:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 6288: 	$type = 2;
 6289:         $udom = $1;
 6290:         $unum = $2;
 6291:         $group = $3;
 6292:         $file_name = $3.'/'.$4;
 6293:     }
 6294:     if (wantarray) {
 6295: 	return ($type,$udom,$unum,$file_name,$group);
 6296:     }
 6297:     return $type;
 6298: }
 6299: 
 6300: sub is_portfolio_url {
 6301:     my ($url) = @_;
 6302:     return scalar(&parse_portfolio_url($url));
 6303: }
 6304: 
 6305: sub is_portfolio_file {
 6306:     my ($file) = @_;
 6307:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 6308:         return 1;
 6309:     }
 6310:     return;
 6311: }
 6312: 
 6313: sub usertools_access {
 6314:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 6315:     my ($access,%tools);
 6316:     if ($context eq '') {
 6317:         $context = 'tools';
 6318:     }
 6319:     if ($context eq 'requestcourses') {
 6320:         %tools = (
 6321:                       official   => 1,
 6322:                       unofficial => 1,
 6323:                       community  => 1,
 6324:                       textbook   => 1,
 6325:                  );
 6326:     } elsif ($context eq 'requestauthor') {
 6327:         %tools = (
 6328:                       requestauthor => 1,
 6329:                  );
 6330:     } else {
 6331:         %tools = (
 6332:                       aboutme   => 1,
 6333:                       blog      => 1,
 6334:                       webdav    => 1,
 6335:                       portfolio => 1,
 6336:                  );
 6337:     }
 6338:     return if (!defined($tools{$tool}));
 6339: 
 6340:     if (($udom eq '') || ($uname eq '')) {
 6341:         $udom = $env{'user.domain'};
 6342:         $uname = $env{'user.name'};
 6343:     }
 6344: 
 6345:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6346:         if ($action ne 'reload') {
 6347:             if ($context eq 'requestcourses') {
 6348:                 return $env{'environment.canrequest.'.$tool};
 6349:             } elsif ($context eq 'requestauthor') {
 6350:                 return $env{'environment.canrequest.author'};
 6351:             } else {
 6352:                 return $env{'environment.availabletools.'.$tool};
 6353:             }
 6354:         }
 6355:     }
 6356: 
 6357:     my ($toolstatus,$inststatus,$envkey);
 6358:     if ($context eq 'requestauthor') {
 6359:         $envkey = $context; 
 6360:     } else {
 6361:         $envkey = $context.'.'.$tool;
 6362:     }
 6363: 
 6364:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 6365:          ($action ne 'reload')) {
 6366:         $toolstatus = $env{'environment.'.$envkey};
 6367:         $inststatus = $env{'environment.inststatus'};
 6368:     } else {
 6369:         if (ref($userenvref) eq 'HASH') {
 6370:             $toolstatus = $userenvref->{$envkey};
 6371:             $inststatus = $userenvref->{'inststatus'};
 6372:         } else {
 6373:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 6374:             $toolstatus = $userenv{$envkey};
 6375:             $inststatus = $userenv{'inststatus'};
 6376:         }
 6377:     }
 6378: 
 6379:     if ($toolstatus ne '') {
 6380:         if ($toolstatus) {
 6381:             $access = 1;
 6382:         } else {
 6383:             $access = 0;
 6384:         }
 6385:         return $access;
 6386:     }
 6387: 
 6388:     my ($is_adv,%domdef);
 6389:     if (ref($is_advref) eq 'HASH') {
 6390:         $is_adv = $is_advref->{'is_adv'};
 6391:     } else {
 6392:         $is_adv = &is_advanced_user($udom,$uname);
 6393:     }
 6394:     if (ref($domdefref) eq 'HASH') {
 6395:         %domdef = %{$domdefref};
 6396:     } else {
 6397:         %domdef = &get_domain_defaults($udom);
 6398:     }
 6399:     if (ref($domdef{$tool}) eq 'HASH') {
 6400:         if ($is_adv) {
 6401:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 6402:                 if ($domdef{$tool}{'_LC_adv'}) { 
 6403:                     $access = 1;
 6404:                 } else {
 6405:                     $access = 0;
 6406:                 }
 6407:                 return $access;
 6408:             }
 6409:         }
 6410:         if ($inststatus ne '') {
 6411:             my ($hasaccess,$hasnoaccess);
 6412:             foreach my $affiliation (split(/:/,$inststatus)) {
 6413:                 if ($domdef{$tool}{$affiliation} ne '') { 
 6414:                     if ($domdef{$tool}{$affiliation}) {
 6415:                         $hasaccess = 1;
 6416:                     } else {
 6417:                         $hasnoaccess = 1;
 6418:                     }
 6419:                 }
 6420:             }
 6421:             if ($hasaccess || $hasnoaccess) {
 6422:                 if ($hasaccess) {
 6423:                     $access = 1;
 6424:                 } elsif ($hasnoaccess) {
 6425:                     $access = 0; 
 6426:                 }
 6427:                 return $access;
 6428:             }
 6429:         } else {
 6430:             if ($domdef{$tool}{'default'} ne '') {
 6431:                 if ($domdef{$tool}{'default'}) {
 6432:                     $access = 1;
 6433:                 } elsif ($domdef{$tool}{'default'} == 0) {
 6434:                     $access = 0;
 6435:                 }
 6436:                 return $access;
 6437:             }
 6438:         }
 6439:     } else {
 6440:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 6441:             $access = 1;
 6442:         } else {
 6443:             $access = 0;
 6444:         }
 6445:         return $access;
 6446:     }
 6447: }
 6448: 
 6449: sub is_course_owner {
 6450:     my ($cdom,$cnum,$udom,$uname) = @_;
 6451:     if (($udom eq '') || ($uname eq '')) {
 6452:         $udom = $env{'user.domain'};
 6453:         $uname = $env{'user.name'};
 6454:     }
 6455:     unless (($udom eq '') || ($uname eq '')) {
 6456:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 6457:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 6458:                 return 1;
 6459:             } else {
 6460:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 6461:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 6462:                     return 1;
 6463:                 }
 6464:             }
 6465:         }
 6466:     }
 6467:     return;
 6468: }
 6469: 
 6470: sub is_advanced_user {
 6471:     my ($udom,$uname) = @_;
 6472:     if ($udom ne '' && $uname ne '') {
 6473:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6474:             if (wantarray) {
 6475:                 return ($env{'user.adv'},$env{'user.author'});
 6476:             } else {
 6477:                 return $env{'user.adv'};
 6478:             }
 6479:         }
 6480:     }
 6481:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 6482:     my %allroles;
 6483:     my ($is_adv,$is_author);
 6484:     foreach my $role (keys(%roleshash)) {
 6485:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 6486:         my $area = '/'.$tdomain.'/'.$trest;
 6487:         if ($sec ne '') {
 6488:             $area .= '/'.$sec;
 6489:         }
 6490:         if (($area ne '') && ($trole ne '')) {
 6491:             my $spec=$trole.'.'.$area;
 6492:             if ($trole =~ /^cr\//) {
 6493:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6494:             } elsif ($trole ne 'gr') {
 6495:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6496:             }
 6497:             if ($trole eq 'au') {
 6498:                 $is_author = 1;
 6499:             }
 6500:         }
 6501:     }
 6502:     foreach my $role (keys(%allroles)) {
 6503:         last if ($is_adv);
 6504:         foreach my $item (split(/:/,$allroles{$role})) {
 6505:             if ($item ne '') {
 6506:                 my ($privilege,$restrictions)=split(/&/,$item);
 6507:                 if ($privilege eq 'adv') {
 6508:                     $is_adv = 1;
 6509:                     last;
 6510:                 }
 6511:             }
 6512:         }
 6513:     }
 6514:     if (wantarray) {
 6515:         return ($is_adv,$is_author);
 6516:     }
 6517:     return $is_adv;
 6518: }
 6519: 
 6520: sub check_can_request {
 6521:     my ($dom,$can_request,$request_domains) = @_;
 6522:     my $canreq = 0;
 6523:     my ($types,$typename) = &Apache::loncommon::course_types();
 6524:     my @options = ('approval','validate','autolimit');
 6525:     my $optregex = join('|',@options);
 6526:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 6527:         foreach my $type (@{$types}) {
 6528:             if (&usertools_access($env{'user.name'},
 6529:                                   $env{'user.domain'},
 6530:                                   $type,undef,'requestcourses')) {
 6531:                 $canreq ++;
 6532:                 if (ref($request_domains) eq 'HASH') {
 6533:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 6534:                 }
 6535:                 if ($dom eq $env{'user.domain'}) {
 6536:                     $can_request->{$type} = 1;
 6537:                 }
 6538:             }
 6539:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 6540:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 6541:                 if (@curr > 0) {
 6542:                     foreach my $item (@curr) {
 6543:                         if (ref($request_domains) eq 'HASH') {
 6544:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 6545:                             if ($otherdom ne '') {
 6546:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 6547:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 6548:                                         push(@{$request_domains->{$type}},$otherdom);
 6549:                                     }
 6550:                                 } else {
 6551:                                     push(@{$request_domains->{$type}},$otherdom);
 6552:                                 }
 6553:                             }
 6554:                         }
 6555:                     }
 6556:                     unless($dom eq $env{'user.domain'}) {
 6557:                         $canreq ++;
 6558:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 6559:                             $can_request->{$type} = 1;
 6560:                         }
 6561:                     }
 6562:                 }
 6563:             }
 6564:         }
 6565:     }
 6566:     return $canreq;
 6567: }
 6568: 
 6569: # ---------------------------------------------- Custom access rule evaluation
 6570: 
 6571: sub customaccess {
 6572:     my ($priv,$uri)=@_;
 6573:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 6574:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 6575:     $udom = &LONCAPA::clean_domain($udom);
 6576:     $ucrs = &LONCAPA::clean_username($ucrs);
 6577:     my $access=0;
 6578:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 6579: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 6580: 	if ($type eq 'user') {
 6581: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 6582: 		my ($tdom,$tuname)=split(m{/},$scope);
 6583: 		if ($tdom) {
 6584: 		    if ($tdom ne $env{'user.domain'}) { next; }
 6585: 		}
 6586: 		if ($tuname) {
 6587: 		    if ($tuname ne $env{'user.name'}) { next; }
 6588: 		}
 6589: 		$access=($effect eq 'allow');
 6590: 		last;
 6591: 	    }
 6592: 	} else {
 6593: 	    if ($role) {
 6594: 		if ($role ne $urole) { next; }
 6595: 	    }
 6596: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 6597: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 6598: 		if ($tdom) {
 6599: 		    if ($tdom ne $udom) { next; }
 6600: 		}
 6601: 		if ($tcrs) {
 6602: 		    if ($tcrs ne $ucrs) { next; }
 6603: 		}
 6604: 		if ($tsec) {
 6605: 		    if ($tsec ne $usec) { next; }
 6606: 		}
 6607: 		$access=($effect eq 'allow');
 6608: 		last;
 6609: 	    }
 6610: 	    if ($realm eq '' && $role eq '') {
 6611: 		$access=($effect eq 'allow');
 6612: 	    }
 6613: 	}
 6614:     }
 6615:     return $access;
 6616: }
 6617: 
 6618: # ------------------------------------------------- Check for a user privilege
 6619: 
 6620: sub allowed {
 6621:     my ($priv,$uri,$symb,$role,$clientip)=@_;
 6622:     my $ver_orguri=$uri;
 6623:     $uri=&deversion($uri);
 6624:     my $orguri=$uri;
 6625:     $uri=&declutter($uri);
 6626: 
 6627:     if ($priv eq 'evb') {
 6628: # Evade communication block restrictions for specified role in a course
 6629:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 6630:             return $1;
 6631:         } else {
 6632:             return;
 6633:         }
 6634:     }
 6635: 
 6636:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 6637: # Free bre access to adm and meta resources
 6638:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 6639: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 6640: 	&& ($priv eq 'bre')) {
 6641: 	return 'F';
 6642:     }
 6643: 
 6644: # Free bre access to user's own portfolio contents
 6645:     my ($space,$domain,$name,@dir)=split('/',$uri);
 6646:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 6647: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 6648:         my %setters;
 6649:         my ($startblock,$endblock) = 
 6650:             &Apache::loncommon::blockcheck(\%setters,'port');
 6651:         if ($startblock && $endblock) {
 6652:             return 'B';
 6653:         } else {
 6654:             return 'F';
 6655:         }
 6656:     }
 6657: 
 6658: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 6659:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 6660:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 6661:         if (exists($env{'request.course.id'})) {
 6662:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6663:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6664:             if (($domain eq $cdom) && ($name eq $cnum)) {
 6665:                 my $courseprivid=$env{'request.course.id'};
 6666:                 $courseprivid=~s/\_/\//;
 6667:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 6668:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 6669:                     return $1; 
 6670:                 } else {
 6671:                     if ($env{'request.course.sec'}) {
 6672:                         $courseprivid.='/'.$env{'request.course.sec'};
 6673:                     }
 6674:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 6675:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 6676:                         return $2;
 6677:                     }
 6678:                 }
 6679:             }
 6680:         }
 6681:     }
 6682: 
 6683: # Free bre to public access
 6684: 
 6685:     if ($priv eq 'bre') {
 6686:         my $copyright=&metadata($uri,'copyright');
 6687: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 6688:            return 'F'; 
 6689:         }
 6690:         if ($copyright eq 'priv') {
 6691:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6692: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 6693: 		return '';
 6694:             }
 6695:         }
 6696:         if ($copyright eq 'domain') {
 6697:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6698: 	    unless (($env{'user.domain'} eq $1) ||
 6699:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 6700: 		return '';
 6701:             }
 6702:         }
 6703:         if ($env{'request.role'}=~ /li\.\//) {
 6704:             # Library role, so allow browsing of resources in this domain.
 6705:             return 'F';
 6706:         }
 6707:         if ($copyright eq 'custom') {
 6708: 	    unless (&customaccess($priv,$uri)) { return ''; }
 6709:         }
 6710:     }
 6711:     # Domain coordinator is trying to create a course
 6712:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 6713:         # uri is the requested domain in this case.
 6714:         # comparison to 'request.role.domain' shows if the user has selected
 6715:         # a role of dc for the domain in question.
 6716:         return 'F' if ($uri eq $env{'request.role.domain'});
 6717:     }
 6718: 
 6719:     my $thisallowed='';
 6720:     my $statecond=0;
 6721:     my $courseprivid='';
 6722: 
 6723:     my $ownaccess;
 6724:     # Community Coordinator or Assistant Co-author browsing resource space.
 6725:     if (($priv eq 'bro') && ($env{'user.author'})) {
 6726:         if ($uri eq '') {
 6727:             $ownaccess = 1;
 6728:         } else {
 6729:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 6730:                 my $udom = $env{'user.domain'};
 6731:                 my $uname = $env{'user.name'};
 6732:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 6733:                     $ownaccess = 1;
 6734:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 6735:                     unless ($uri =~ m{\.\./}) {
 6736:                         $ownaccess = 1;
 6737:                     }
 6738:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 6739:                     my $now = time;
 6740:                     if ($uri =~ m{^([^/]+)/?$}) {
 6741:                         my $adom = $1;
 6742:                         foreach my $key (keys(%env)) {
 6743:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 6744:                                 my ($start,$end) = split('.',$env{$key});
 6745:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6746:                                     $ownaccess = 1;
 6747:                                     last;
 6748:                                 }
 6749:                             }
 6750:                         }
 6751:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 6752:                         my $adom = $1;
 6753:                         my $aname = $2;
 6754:                         foreach my $role ('ca','aa') { 
 6755:                             if ($env{"user.role.$role./$adom/$aname"}) {
 6756:                                 my ($start,$end) =
 6757:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 6758:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6759:                                     $ownaccess = 1;
 6760:                                     last;
 6761:                                 }
 6762:                             }
 6763:                         }
 6764:                     }
 6765:                 }
 6766:             }
 6767:         }
 6768:     }
 6769: 
 6770: # Course
 6771: 
 6772:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 6773:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6774:             $thisallowed.=$1;
 6775:         }
 6776:     }
 6777: 
 6778: # Domain
 6779: 
 6780:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 6781:        =~/\Q$priv\E\&([^\:]*)/) {
 6782:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6783:             $thisallowed.=$1;
 6784:         }
 6785:     }
 6786: 
 6787: # User who is not author or co-author might still be able to edit
 6788: # resource of an author in the domain (e.g., if Domain Coordinator).
 6789:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 6790:         (&allowed('mdc',$env{'request.course.id'}))) {
 6791:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 6792:             $thisallowed.=$1;
 6793:         }
 6794:     }
 6795: 
 6796: # Course: uri itself is a course
 6797:     my $courseuri=$uri;
 6798:     $courseuri=~s/\_(\d)/\/$1/;
 6799:     $courseuri=~s/^([^\/])/\/$1/;
 6800: 
 6801:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 6802:        =~/\Q$priv\E\&([^\:]*)/) {
 6803:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6804:             $thisallowed.=$1;
 6805:         }
 6806:     }
 6807: 
 6808: # URI is an uploaded document for this course, default permissions don't matter
 6809: # not allowing 'edit' access (editupload) to uploaded course docs
 6810:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 6811: 	$thisallowed='';
 6812:         my ($match)=&is_on_map($uri);
 6813:         if ($match) {
 6814:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 6815:                   =~/\Q$priv\E\&([^\:]*)/) {
 6816:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6817:                 if (@blockers > 0) {
 6818:                     $thisallowed = 'B';
 6819:                 } else {
 6820:                     $thisallowed.=$1;
 6821:                 }
 6822:             }
 6823:         } else {
 6824:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 6825:             if ($refuri) {
 6826:                 if ($refuri =~ m|^/adm/|) {
 6827:                     $thisallowed='F';
 6828:                 } else {
 6829:                     $refuri=&declutter($refuri);
 6830:                     my ($match) = &is_on_map($refuri);
 6831:                     if ($match) {
 6832:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6833:                         if (@blockers > 0) {
 6834:                             $thisallowed = 'B';
 6835:                         } else {
 6836:                             $thisallowed='F';
 6837:                         }
 6838:                     }
 6839:                 }
 6840:             }
 6841:         }
 6842:     }
 6843: 
 6844:     if ($priv eq 'bre'
 6845: 	&& $thisallowed ne 'F' 
 6846: 	&& $thisallowed ne '2'
 6847: 	&& &is_portfolio_url($uri)) {
 6848: 	$thisallowed = &portfolio_access($uri,$clientip);
 6849:     }
 6850: 
 6851: # Full access at system, domain or course-wide level? Exit.
 6852:     if ($thisallowed=~/F/) {
 6853: 	return 'F';
 6854:     }
 6855: 
 6856: # If this is generating or modifying users, exit with special codes
 6857: 
 6858:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 6859: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 6860: 	    my ($audom,$auname)=split('/',$uri);
 6861: # no author name given, so this just checks on the general right to make a co-author in this domain
 6862: 	    unless ($auname) { return $thisallowed; }
 6863: # an author name is given, so we are about to actually make a co-author for a certain account
 6864: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 6865: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 6866: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 6867: 	}
 6868: 	return $thisallowed;
 6869:     }
 6870: #
 6871: # Gathered so far: system, domain and course wide privileges
 6872: #
 6873: # Course: See if uri or referer is an individual resource that is part of 
 6874: # the course
 6875: 
 6876:     if ($env{'request.course.id'}) {
 6877: 
 6878:        $courseprivid=$env{'request.course.id'};
 6879:        if ($env{'request.course.sec'}) {
 6880:           $courseprivid.='/'.$env{'request.course.sec'};
 6881:        }
 6882:        $courseprivid=~s/\_/\//;
 6883:        my $checkreferer=1;
 6884:        my ($match,$cond)=&is_on_map($uri);
 6885:        if ($match) {
 6886:            $statecond=$cond;
 6887:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6888:                =~/\Q$priv\E\&([^\:]*)/) {
 6889:                my $value = $1;
 6890:                if ($priv eq 'bre') {
 6891:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6892:                    if (@blockers > 0) {
 6893:                        $thisallowed = 'B';
 6894:                    } else {
 6895:                        $thisallowed.=$value;
 6896:                    }
 6897:                } else {
 6898:                    $thisallowed.=$value;
 6899:                }
 6900:                $checkreferer=0;
 6901:            }
 6902:        }
 6903:        
 6904:        if ($checkreferer) {
 6905: 	  my $refuri=$env{'httpref.'.$orguri};
 6906:             unless ($refuri) {
 6907:                 foreach my $key (keys(%env)) {
 6908: 		    if ($key=~/^httpref\..*\*/) {
 6909: 			my $pattern=$key;
 6910:                         $pattern=~s/^httpref\.\/res\///;
 6911:                         $pattern=~s/\*/\[\^\/\]\+/g;
 6912:                         $pattern=~s/\//\\\//g;
 6913:                         if ($orguri=~/$pattern/) {
 6914: 			    $refuri=$env{$key};
 6915:                         }
 6916:                     }
 6917:                 }
 6918:             }
 6919: 
 6920:          if ($refuri) { 
 6921: 	  $refuri=&declutter($refuri);
 6922:           my ($match,$cond)=&is_on_map($refuri);
 6923:             if ($match) {
 6924:               my $refstatecond=$cond;
 6925:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6926:                   =~/\Q$priv\E\&([^\:]*)/) {
 6927:                   my $value = $1;
 6928:                   if ($priv eq 'bre') {
 6929:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6930:                       if (@blockers > 0) {
 6931:                           $thisallowed = 'B';
 6932:                       } else {
 6933:                           $thisallowed.=$value;
 6934:                       }
 6935:                   } else {
 6936:                       $thisallowed.=$value;
 6937:                   }
 6938:                   $uri=$refuri;
 6939:                   $statecond=$refstatecond;
 6940:               }
 6941:           }
 6942:         }
 6943:        }
 6944:    }
 6945: 
 6946: #
 6947: # Gathered now: all privileges that could apply, and condition number
 6948: # 
 6949: #
 6950: # Full or no access?
 6951: #
 6952: 
 6953:     if ($thisallowed=~/F/) {
 6954: 	return 'F';
 6955:     }
 6956: 
 6957:     unless ($thisallowed) {
 6958:         return '';
 6959:     }
 6960: 
 6961: # Restrictions exist, deal with them
 6962: #
 6963: #   C:according to course preferences
 6964: #   R:according to resource settings
 6965: #   L:unless locked
 6966: #   X:according to user session state
 6967: #
 6968: 
 6969: # Possibly locked functionality, check all courses
 6970: # Locks might take effect only after 10 minutes cache expiration for other
 6971: # courses, and 2 minutes for current course
 6972: 
 6973:     my $envkey;
 6974:     if ($thisallowed=~/L/) {
 6975:         foreach $envkey (keys(%env)) {
 6976:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 6977:                my $courseid=$2;
 6978:                my $roleid=$1.'.'.$2;
 6979:                $courseid=~s/^\///;
 6980:                my $expiretime=600;
 6981:                if ($env{'request.role'} eq $roleid) {
 6982: 		  $expiretime=120;
 6983:                }
 6984: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 6985:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 6986:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 6987: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 6988:                }
 6989:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6990:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 6991: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 6992:                        &log($env{'user.domain'},$env{'user.name'},
 6993:                             $env{'user.home'},
 6994:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 6995:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6996:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6997: 		       return '';
 6998:                    }
 6999:                }
 7000:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 7001:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 7002: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 7003:                        &log($env{'user.domain'},$env{'user.name'},
 7004:                             $env{'user.home'},
 7005:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 7006:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 7007:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 7008: 		       return '';
 7009:                    }
 7010:                }
 7011: 	   }
 7012:        }
 7013:     }
 7014:    
 7015: #
 7016: # Rest of the restrictions depend on selected course
 7017: #
 7018: 
 7019:     unless ($env{'request.course.id'}) {
 7020: 	if ($thisallowed eq 'A') {
 7021: 	    return 'A';
 7022:         } elsif ($thisallowed eq 'B') {
 7023:             return 'B';
 7024: 	} else {
 7025: 	    return '1';
 7026: 	}
 7027:     }
 7028: 
 7029: #
 7030: # Now user is definitely in a course
 7031: #
 7032: 
 7033: 
 7034: # Course preferences
 7035: 
 7036:    if ($thisallowed=~/C/) {
 7037:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 7038:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 7039:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 7040: 	   =~/\Q$rolecode\E/) {
 7041: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 7042: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 7043: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 7044: 			$env{'request.course.id'});
 7045: 	   }
 7046:            return '';
 7047:        }
 7048: 
 7049:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 7050: 	   =~/\Q$unamedom\E/) {
 7051: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 7052: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 7053: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 7054: 			$env{'request.course.id'});
 7055: 	   }
 7056:            return '';
 7057:        }
 7058:    }
 7059: 
 7060: # Resource preferences
 7061: 
 7062:    if ($thisallowed=~/R/) {
 7063:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 7064:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 7065: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 7066: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 7067: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 7068: 	   }
 7069: 	   return '';
 7070:        }
 7071:    }
 7072: 
 7073: # Restricted by state or randomout?
 7074: 
 7075:    if ($thisallowed=~/X/) {
 7076:       if ($env{'acc.randomout'}) {
 7077: 	 if (!$symb) { $symb=&symbread($uri,1); }
 7078:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 7079:             return ''; 
 7080:          }
 7081:       }
 7082:       if (&condval($statecond)) {
 7083: 	 return '2';
 7084:       } else {
 7085:          return '';
 7086:       }
 7087:    }
 7088: 
 7089:     if ($thisallowed eq 'A') {
 7090: 	return 'A';
 7091:     } elsif ($thisallowed eq 'B') {
 7092:         return 'B';
 7093:     }
 7094:    return 'F';
 7095: }
 7096: 
 7097: # ------------------------------------------- Check construction space access
 7098: 
 7099: sub constructaccess {
 7100:     my ($url,$setpriv)=@_;
 7101: 
 7102: # We do not allow editing of previous versions of files
 7103:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 7104: 
 7105: # Get username and domain from URL
 7106:     my ($ownername,$ownerdomain,$ownerhome);
 7107: 
 7108:     ($ownerdomain,$ownername) =
 7109:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
 7110: 
 7111: # The URL does not really point to any authorspace, forget it
 7112:     unless (($ownername) && ($ownerdomain)) { return ''; }
 7113: 
 7114: # Now we need to see if the user has access to the authorspace of
 7115: # $ownername at $ownerdomain
 7116: 
 7117:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 7118: # Real author for this?
 7119:        $ownerhome = $env{'user.home'};
 7120:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 7121:           return ($ownername,$ownerdomain,$ownerhome);
 7122:        }
 7123:     } else {
 7124: # Co-author for this?
 7125:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 7126:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 7127:             $ownerhome = &homeserver($ownername,$ownerdomain);
 7128:             return ($ownername,$ownerdomain,$ownerhome);
 7129:         }
 7130:     }
 7131: 
 7132: # We don't have any access right now. If we are not possibly going to do anything about this,
 7133: # we might as well leave
 7134:    unless ($setpriv) { return ''; }
 7135: 
 7136: # Backdoor access?
 7137:     my $allowed=&allowed('eco',$ownerdomain);
 7138: # Nope
 7139:     unless ($allowed) { return ''; }
 7140: # Looks like we may have access, but could be locked by the owner of the construction space
 7141:     if ($allowed eq 'U') {
 7142:         my %blocked=&get('environment',['domcoord.author'],
 7143:                          $ownerdomain,$ownername);
 7144: # Is blocked by owner
 7145:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 7146:     }
 7147:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 7148: # Grant temporary access
 7149:         my $then=$env{'user.login.time'};
 7150:         my $update=$env{'user.update.time'};
 7151:         if (!$update) { $update = $then; }
 7152:         my $refresh=$env{'user.refresh.time'};
 7153:         if (!$refresh) { $refresh = $update; }
 7154:         my $now = time;
 7155:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 7156:                            $now,'ca','constructaccess');
 7157:         $ownerhome = &homeserver($ownername,$ownerdomain);
 7158:         return($ownername,$ownerdomain,$ownerhome);
 7159:     }
 7160: # No business here
 7161:     return '';
 7162: }
 7163: 
 7164: sub get_comm_blocks {
 7165:     my ($cdom,$cnum) = @_;
 7166:     if ($cdom eq '' || $cnum eq '') {
 7167:         return unless ($env{'request.course.id'});
 7168:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7169:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7170:     }
 7171:     my %commblocks;
 7172:     my $hashid=$cdom.'_'.$cnum;
 7173:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 7174:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 7175:         %commblocks = %{$blocksref};
 7176:     } else {
 7177:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 7178:         my $cachetime = 600;
 7179:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 7180:     }
 7181:     return %commblocks;
 7182: }
 7183: 
 7184: sub has_comm_blocking {
 7185:     my ($priv,$symb,$uri,$blocks) = @_;
 7186:     return unless ($env{'request.course.id'});
 7187:     return unless ($priv eq 'bre');
 7188:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 7189:     my %commblocks;
 7190:     if (ref($blocks) eq 'HASH') {
 7191:         %commblocks = %{$blocks};
 7192:     } else {
 7193:         %commblocks = &get_comm_blocks();
 7194:     }
 7195:     return unless (keys(%commblocks) > 0);
 7196:     if (!$symb) { $symb=&symbread($uri,1); }
 7197:     my ($map,$resid,undef)=&decode_symb($symb);
 7198:     my %tocheck = (
 7199:                     maps      => $map,
 7200:                     resources => $symb,
 7201:                   );
 7202:     my @blockers;
 7203:     my $now = time;
 7204:     my $navmap = Apache::lonnavmaps::navmap->new();
 7205:     foreach my $block (keys(%commblocks)) {
 7206:         if ($block =~ /^(\d+)____(\d+)$/) {
 7207:             my ($start,$end) = ($1,$2);
 7208:             if ($start <= $now && $end >= $now) {
 7209:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 7210:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 7211:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 7212:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
 7213:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 7214:                                     push(@blockers,$block);
 7215:                                 }
 7216:                             }
 7217:                         }
 7218:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 7219:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
 7220:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
 7221:                                     push(@blockers,$block);
 7222:                                 }
 7223:                             }
 7224:                         }
 7225:                     }
 7226:                 }
 7227:             }
 7228:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 7229:             my $item = $1;
 7230:             my @to_test;
 7231:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 7232:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 7233:                     my $check_interval;
 7234:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
 7235:                         my @interval;
 7236:                         my $type = 'map';
 7237:                         if ($item eq 'course') {
 7238:                             $type = 'course';
 7239:                             @interval=&EXT("resource.0.interval");
 7240:                         } else {
 7241:                             if ($item =~ /___\d+___/) {
 7242:                                 $type = 'resource';
 7243:                                 @interval=&EXT("resource.0.interval",$item);
 7244:                                 if (ref($navmap)) {                        
 7245:                                     my $res = $navmap->getBySymb($item); 
 7246:                                     push(@to_test,$res);
 7247:                                 }
 7248:                             } else {
 7249:                                 my $mapsymb = &symbread($item,1);
 7250:                                 if ($mapsymb) {
 7251:                                     if (ref($navmap)) {
 7252:                                         my $mapres = $navmap->getBySymb($mapsymb);
 7253:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
 7254:                                         foreach my $res (@to_test) {
 7255:                                             my $symb = $res->symb();
 7256:                                             next if ($symb eq $mapsymb);
 7257:                                             if ($symb ne '') {
 7258:                                                 @interval=&EXT("resource.0.interval",$symb);
 7259:                                                 last;
 7260:                                             }
 7261:                                         }
 7262:                                     }
 7263:                                 }
 7264:                             }
 7265:                         }
 7266:                         if ($interval[0] =~ /\d+/) {
 7267:                             my $first_access;
 7268:                             if ($type eq 'resource') {
 7269:                                 $first_access=&get_first_access($interval[1],$item);
 7270:                             } elsif ($type eq 'map') {
 7271:                                 $first_access=&get_first_access($interval[1],undef,$item);
 7272:                             } else {
 7273:                                 $first_access=&get_first_access($interval[1]);
 7274:                             }
 7275:                             if ($first_access) {
 7276:                                 my $timesup = $first_access+$interval[0];
 7277:                                 if ($timesup > $now) {
 7278:                                     foreach my $res (@to_test) {
 7279:                                         if ($res->is_problem()) {
 7280:                                             if ($res->completable()) {
 7281:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 7282:                                                     push(@blockers,$block);
 7283:                                                 }
 7284:                                                 last;
 7285:                                             }
 7286:                                         }
 7287:                                     }
 7288:                                 }
 7289:                             }
 7290:                         }
 7291:                     }
 7292:                 }
 7293:             }
 7294:         }
 7295:     }
 7296:     return @blockers;
 7297: }
 7298: 
 7299: sub check_docs_block {
 7300:     my ($docsblock,$tocheck) =@_;
 7301:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
 7302:         return;
 7303:     }
 7304:     if (ref($docsblock->{'maps'}) eq 'HASH') {
 7305:         if ($tocheck->{'maps'}) {
 7306:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
 7307:                 return 1;
 7308:             }
 7309:         }
 7310:     }
 7311:     if (ref($docsblock->{'resources'}) eq 'HASH') {
 7312:         if ($tocheck->{'resources'}) {
 7313:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
 7314:                 return 1;
 7315:             }
 7316:         }
 7317:     }
 7318:     return;
 7319: }
 7320: 
 7321: #
 7322: #   Removes the versino from a URI and
 7323: #   splits it in to its filename and path to the filename.
 7324: #   Seems like File::Basename could have done this more clearly.
 7325: #   Parameters:
 7326: #      $uri   - input URI
 7327: #   Returns:
 7328: #     Two element list consisting of 
 7329: #     $pathname  - the URI up to and excluding the trailing /
 7330: #     $filename  - The part of the URI following the last /
 7331: #  NOTE:
 7332: #    Another realization of this is simply:
 7333: #    use File::Basename;
 7334: #    ...
 7335: #    $uri = shift;
 7336: #    $filename = basename($uri);
 7337: #    $path     = dirname($uri);
 7338: #    return ($filename, $path);
 7339: #
 7340: #     The implementation below is probably faster however.
 7341: #
 7342: sub split_uri_for_cond {
 7343:     my $uri=&deversion(&declutter(shift));
 7344:     my @uriparts=split(/\//,$uri);
 7345:     my $filename=pop(@uriparts);
 7346:     my $pathname=join('/',@uriparts);
 7347:     return ($pathname,$filename);
 7348: }
 7349: # --------------------------------------------------- Is a resource on the map?
 7350: 
 7351: sub is_on_map {
 7352:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 7353:     #Trying to find the conditional for the file
 7354:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 7355: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 7356:     if ($match) {
 7357: 	return (1,$1);
 7358:     } else {
 7359: 	return (0,0);
 7360:     }
 7361: }
 7362: 
 7363: # --------------------------------------------------------- Get symb from alias
 7364: 
 7365: sub get_symb_from_alias {
 7366:     my $symb=shift;
 7367:     my ($map,$resid,$url)=&decode_symb($symb);
 7368: # Already is a symb
 7369:     if ($url) { return $symb; }
 7370: # Must be an alias
 7371:     my $aliassymb='';
 7372:     my %bighash;
 7373:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7374:                             &GDBM_READER(),0640)) {
 7375:         my $rid=$bighash{'mapalias_'.$symb};
 7376: 	if ($rid) {
 7377: 	    my ($mapid,$resid)=split(/\./,$rid);
 7378: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 7379: 				    $resid,$bighash{'src_'.$rid});
 7380: 	}
 7381:         untie %bighash;
 7382:     }
 7383:     return $aliassymb;
 7384: }
 7385: 
 7386: # ----------------------------------------------------------------- Define Role
 7387: 
 7388: sub definerole {
 7389:   if (allowed('mcr','/')) {
 7390:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 7391:     foreach my $role (split(':',$sysrole)) {
 7392: 	my ($crole,$cqual)=split(/\&/,$role);
 7393:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 7394:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 7395: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 7396:                return "refused:s:$crole&$cqual"; 
 7397:             }
 7398:         }
 7399:     }
 7400:     foreach my $role (split(':',$domrole)) {
 7401: 	my ($crole,$cqual)=split(/\&/,$role);
 7402:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 7403:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 7404: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 7405:                return "refused:d:$crole&$cqual"; 
 7406:             }
 7407:         }
 7408:     }
 7409:     foreach my $role (split(':',$courole)) {
 7410: 	my ($crole,$cqual)=split(/\&/,$role);
 7411:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 7412:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 7413: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 7414:                return "refused:c:$crole&$cqual"; 
 7415:             }
 7416:         }
 7417:     }
 7418:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 7419:                 "$env{'user.domain'}:$env{'user.name'}:".
 7420: 	        "rolesdef_$rolename=".
 7421:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 7422:     return reply($command,$env{'user.home'});
 7423:   } else {
 7424:     return 'refused';
 7425:   }
 7426: }
 7427: 
 7428: # ---------------- Make a metadata query against the network of library servers
 7429: 
 7430: sub metadata_query {
 7431:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 7432:     my %rhash;
 7433:     my %libserv = &all_library();
 7434:     my @server_list = (defined($server_array) ? @$server_array
 7435:                                               : keys(%libserv) );
 7436:     for my $server (@server_list) {
 7437:         my $domains = ''; 
 7438:         if (ref($domains_hash) eq 'HASH') {
 7439:             $domains = $domains_hash->{$server}; 
 7440:         }
 7441: 	unless ($custom or $customshow) {
 7442: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 7443: 	    $rhash{$server}=$reply;
 7444: 	}
 7445: 	else {
 7446: 	    my $reply=&reply("querysend:".&escape($query).':'.
 7447: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 7448: 			     $server);
 7449: 	    $rhash{$server}=$reply;
 7450: 	}
 7451:     }
 7452:     return \%rhash;
 7453: }
 7454: 
 7455: # ----------------------------------------- Send log queries and wait for reply
 7456: 
 7457: sub log_query {
 7458:     my ($uname,$udom,$query,%filters)=@_;
 7459:     my $uhome=&homeserver($uname,$udom);
 7460:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 7461:     my $uhost=&hostname($uhome);
 7462:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 7463:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 7464:                        $uhome);
 7465:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 7466:     return get_query_reply($queryid);
 7467: }
 7468: 
 7469: # -------------------------- Update MySQL table for portfolio file
 7470: 
 7471: sub update_portfolio_table {
 7472:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 7473:     if ($group ne '') {
 7474:         $file_name =~s /^\Q$group\E//;
 7475:     }
 7476:     my $homeserver = &homeserver($uname,$udom);
 7477:     my $queryid=
 7478:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 7479:                ':'.&escape($file_name).':'.$action,$homeserver);
 7480:     my $reply = &get_query_reply($queryid);
 7481:     return $reply;
 7482: }
 7483: 
 7484: # -------------------------- Update MySQL allusers table
 7485: 
 7486: sub update_allusers_table {
 7487:     my ($uname,$udom,$names) = @_;
 7488:     my $homeserver = &homeserver($uname,$udom);
 7489:     my $queryid=
 7490:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 7491:                'lastname='.&escape($names->{'lastname'}).'%%'.
 7492:                'firstname='.&escape($names->{'firstname'}).'%%'.
 7493:                'middlename='.&escape($names->{'middlename'}).'%%'.
 7494:                'generation='.&escape($names->{'generation'}).'%%'.
 7495:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 7496:                'id='.&escape($names->{'id'}),$homeserver);
 7497:     return;
 7498: }
 7499: 
 7500: # ------- Request retrieval of institutional classlists for course(s)
 7501: 
 7502: sub fetch_enrollment_query {
 7503:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 7504:     my $homeserver;
 7505:     my $maxtries = 1;
 7506:     if ($context eq 'automated') {
 7507:         $homeserver = $perlvar{'lonHostID'};
 7508:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 7509:     } else {
 7510:         $homeserver = &homeserver($cnum,$dom);
 7511:     }
 7512:     my $host=&hostname($homeserver);
 7513:     my $cmd = '';
 7514:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7515:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7516:     }
 7517:     $cmd =~ s/%%$//;
 7518:     $cmd = &escape($cmd);
 7519:     my $query = 'fetchenrollment';
 7520:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 7521:     unless ($queryid=~/^\Q$host\E\_/) { 
 7522:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 7523:         return 'error: '.$queryid;
 7524:     }
 7525:     my $reply = &get_query_reply($queryid);
 7526:     my $tries = 1;
 7527:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7528:         $reply = &get_query_reply($queryid);
 7529:         $tries ++;
 7530:     }
 7531:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7532:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7533:     } else {
 7534:         my @responses = split(/:/,$reply);
 7535:         if ($homeserver eq $perlvar{'lonHostID'}) {
 7536:             foreach my $line (@responses) {
 7537:                 my ($key,$value) = split(/=/,$line,2);
 7538:                 $$replyref{$key} = $value;
 7539:             }
 7540:         } else {
 7541:             my $pathname = LONCAPA::tempdir();
 7542:             foreach my $line (@responses) {
 7543:                 my ($key,$value) = split(/=/,$line);
 7544:                 $$replyref{$key} = $value;
 7545:                 if ($value > 0) {
 7546:                     foreach my $item (@{$$affiliatesref{$key}}) {
 7547:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 7548:                         my $destname = $pathname.'/'.$filename;
 7549:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 7550:                         if ($xml_classlist =~ /^error/) {
 7551:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 7552:                         } else {
 7553:                             if ( open(FILE,">$destname") ) {
 7554:                                 print FILE &unescape($xml_classlist);
 7555:                                 close(FILE);
 7556:                             } else {
 7557:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 7558:                             }
 7559:                         }
 7560:                     }
 7561:                 }
 7562:             }
 7563:         }
 7564:         return 'ok';
 7565:     }
 7566:     return 'error';
 7567: }
 7568: 
 7569: sub get_query_reply {
 7570:     my $queryid=shift;
 7571:     my $replyfile=LONCAPA::tempdir().$queryid;
 7572:     my $reply='';
 7573:     for (1..100) {
 7574: 	sleep 2;
 7575:         if (-e $replyfile.'.end') {
 7576: 	    if (open(my $fh,$replyfile)) {
 7577: 		$reply = join('',<$fh>);
 7578: 		close($fh);
 7579: 	   } else { return 'error: reply_file_error'; }
 7580:            return &unescape($reply);
 7581: 	}
 7582:     }
 7583:     return 'timeout:'.$queryid;
 7584: }
 7585: 
 7586: sub courselog_query {
 7587: #
 7588: # possible filters:
 7589: # url: url or symb
 7590: # username
 7591: # domain
 7592: # action: view, submit, grade
 7593: # start: timestamp
 7594: # end: timestamp
 7595: #
 7596:     my (%filters)=@_;
 7597:     unless ($env{'request.course.id'}) { return 'no_course'; }
 7598:     if ($filters{'url'}) {
 7599: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 7600:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 7601:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 7602:     }
 7603:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7604:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7605:     return &log_query($cname,$cdom,'courselog',%filters);
 7606: }
 7607: 
 7608: sub userlog_query {
 7609: #
 7610: # possible filters:
 7611: # action: log check role
 7612: # start: timestamp
 7613: # end: timestamp
 7614: #
 7615:     my ($uname,$udom,%filters)=@_;
 7616:     return &log_query($uname,$udom,'userlog',%filters);
 7617: }
 7618: 
 7619: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 7620: 
 7621: sub auto_run {
 7622:     my ($cnum,$cdom) = @_;
 7623:     my $response = 0;
 7624:     my $settings;
 7625:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 7626:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 7627:         $settings = $domconfig{'autoenroll'};
 7628:         if ($settings->{'run'} eq '1') {
 7629:             $response = 1;
 7630:         }
 7631:     } else {
 7632:         my $homeserver;
 7633:         if (&is_course($cdom,$cnum)) {
 7634:             $homeserver = &homeserver($cnum,$cdom);
 7635:         } else {
 7636:             $homeserver = &domain($cdom,'primary');
 7637:         }
 7638:         if ($homeserver ne 'no_host') {
 7639:             $response = &reply('autorun:'.$cdom,$homeserver);
 7640:         }
 7641:     }
 7642:     return $response;
 7643: }
 7644: 
 7645: sub auto_get_sections {
 7646:     my ($cnum,$cdom,$inst_coursecode) = @_;
 7647:     my $homeserver;
 7648:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 7649:         $homeserver = &homeserver($cnum,$cdom);
 7650:     }
 7651:     if (!defined($homeserver)) { 
 7652:         if ($cdom =~ /^$match_domain$/) {
 7653:             $homeserver = &domain($cdom,'primary');
 7654:         }
 7655:     }
 7656:     my @secs;
 7657:     if (defined($homeserver)) {
 7658:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 7659:         unless ($response eq 'refused') {
 7660:             @secs = split(/:/,$response);
 7661:         }
 7662:     }
 7663:     return @secs;
 7664: }
 7665: 
 7666: sub auto_new_course {
 7667:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 7668:     my $homeserver = &homeserver($cnum,$cdom);
 7669:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 7670:     return $response;
 7671: }
 7672: 
 7673: sub auto_validate_courseID {
 7674:     my ($cnum,$cdom,$inst_course_id) = @_;
 7675:     my $homeserver = &homeserver($cnum,$cdom);
 7676:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 7677:     return $response;
 7678: }
 7679: 
 7680: sub auto_validate_instcode {
 7681:     my ($cnum,$cdom,$instcode,$owner) = @_;
 7682:     my ($homeserver,$response);
 7683:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7684:         $homeserver = &homeserver($cnum,$cdom);
 7685:     }
 7686:     if (!defined($homeserver)) {
 7687:         if ($cdom =~ /^$match_domain$/) {
 7688:             $homeserver = &domain($cdom,'primary');
 7689:         }
 7690:     }
 7691:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 7692:                         &escape($instcode).':'.&escape($owner),$homeserver));
 7693:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 7694:     return ($outcome,$description,$defaultcredits);
 7695: }
 7696: 
 7697: sub auto_create_password {
 7698:     my ($cnum,$cdom,$authparam,$udom) = @_;
 7699:     my ($homeserver,$response);
 7700:     my $create_passwd = 0;
 7701:     my $authchk = '';
 7702:     if ($udom =~ /^$match_domain$/) {
 7703:         $homeserver = &domain($udom,'primary');
 7704:     }
 7705:     if ($homeserver eq '') {
 7706:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7707:             $homeserver = &homeserver($cnum,$cdom);
 7708:         }
 7709:     }
 7710:     if ($homeserver eq '') {
 7711:         $authchk = 'nodomain';
 7712:     } else {
 7713:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 7714:         if ($response eq 'refused') {
 7715:             $authchk = 'refused';
 7716:         } else {
 7717:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 7718:         }
 7719:     }
 7720:     return ($authparam,$create_passwd,$authchk);
 7721: }
 7722: 
 7723: sub auto_photo_permission {
 7724:     my ($cnum,$cdom,$students) = @_;
 7725:     my $homeserver = &homeserver($cnum,$cdom);
 7726:     my ($outcome,$perm_reqd,$conditions) = 
 7727: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 7728:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7729: 	return (undef,undef);
 7730:     }
 7731:     return ($outcome,$perm_reqd,$conditions);
 7732: }
 7733: 
 7734: sub auto_checkphotos {
 7735:     my ($uname,$udom,$pid) = @_;
 7736:     my $homeserver = &homeserver($uname,$udom);
 7737:     my ($result,$resulttype);
 7738:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 7739: 				   &escape($uname).':'.&escape($pid),
 7740: 				   $homeserver));
 7741:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7742: 	return (undef,undef);
 7743:     }
 7744:     if ($outcome) {
 7745:         ($result,$resulttype) = split(/:/,$outcome);
 7746:     } 
 7747:     return ($result,$resulttype);
 7748: }
 7749: 
 7750: sub auto_photochoice {
 7751:     my ($cnum,$cdom) = @_;
 7752:     my $homeserver = &homeserver($cnum,$cdom);
 7753:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 7754: 						       &escape($cdom),
 7755: 						       $homeserver)));
 7756:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7757: 	return (undef,undef);
 7758:     }
 7759:     return ($update,$comment);
 7760: }
 7761: 
 7762: sub auto_photoupdate {
 7763:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 7764:     my $homeserver = &homeserver($cnum,$dom);
 7765:     my $host=&hostname($homeserver);
 7766:     my $cmd = '';
 7767:     my $maxtries = 1;
 7768:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7769:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7770:     }
 7771:     $cmd =~ s/%%$//;
 7772:     $cmd = &escape($cmd);
 7773:     my $query = 'institutionalphotos';
 7774:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 7775:     unless ($queryid=~/^\Q$host\E\_/) {
 7776:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 7777:         return 'error: '.$queryid;
 7778:     }
 7779:     my $reply = &get_query_reply($queryid);
 7780:     my $tries = 1;
 7781:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7782:         $reply = &get_query_reply($queryid);
 7783:         $tries ++;
 7784:     }
 7785:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7786:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7787:     } else {
 7788:         my @responses = split(/:/,$reply);
 7789:         my $outcome = shift(@responses); 
 7790:         foreach my $item (@responses) {
 7791:             my ($key,$value) = split(/=/,$item);
 7792:             $$photo{$key} = $value;
 7793:         }
 7794:         return $outcome;
 7795:     }
 7796:     return 'error';
 7797: }
 7798: 
 7799: sub auto_instcode_format {
 7800:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 7801: 	$cat_order) = @_;
 7802:     my $courses = '';
 7803:     my @homeservers;
 7804:     if ($caller eq 'global') {
 7805: 	my %servers = &get_servers($codedom,'library');
 7806: 	foreach my $tryserver (keys(%servers)) {
 7807: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7808: 		push(@homeservers,$tryserver);
 7809: 	    }
 7810:         }
 7811:     } elsif ($caller eq 'requests') {
 7812:         if ($codedom =~ /^$match_domain$/) {
 7813:             my $chome = &domain($codedom,'primary');
 7814:             unless ($chome eq 'no_host') {
 7815:                 push(@homeservers,$chome);
 7816:             }
 7817:         }
 7818:     } else {
 7819:         push(@homeservers,&homeserver($caller,$codedom));
 7820:     }
 7821:     foreach my $code (keys(%{$instcodes})) {
 7822:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 7823:     }
 7824:     chop($courses);
 7825:     my $ok_response = 0;
 7826:     my $response;
 7827:     while (@homeservers > 0 && $ok_response == 0) {
 7828:         my $server = shift(@homeservers); 
 7829:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 7830:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 7831:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 7832: 		split(/:/,$response);
 7833:             %{$codes} = (%{$codes},&str2hash($codes_str));
 7834:             push(@{$codetitles},&str2array($codetitles_str));
 7835:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 7836:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 7837:             $ok_response = 1;
 7838:         }
 7839:     }
 7840:     if ($ok_response) {
 7841:         return 'ok';
 7842:     } else {
 7843:         return $response;
 7844:     }
 7845: }
 7846: 
 7847: sub auto_instcode_defaults {
 7848:     my ($domain,$returnhash,$code_order) = @_;
 7849:     my @homeservers;
 7850: 
 7851:     my %servers = &get_servers($domain,'library');
 7852:     foreach my $tryserver (keys(%servers)) {
 7853: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7854: 	    push(@homeservers,$tryserver);
 7855: 	}
 7856:     }
 7857: 
 7858:     my $response;
 7859:     foreach my $server (@homeservers) {
 7860:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 7861:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7862: 	
 7863: 	foreach my $pair (split(/\&/,$response)) {
 7864: 	    my ($name,$value)=split(/\=/,$pair);
 7865: 	    if ($name eq 'code_order') {
 7866: 		@{$code_order} = split(/\&/,&unescape($value));
 7867: 	    } else {
 7868: 		$returnhash->{&unescape($name)}=&unescape($value);
 7869: 	    }
 7870: 	}
 7871: 	return 'ok';
 7872:     }
 7873: 
 7874:     return $response;
 7875: }
 7876: 
 7877: sub auto_possible_instcodes {
 7878:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 7879:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 7880:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 7881:         return;
 7882:     }
 7883:     my (@homeservers,$uhome);
 7884:     if (defined(&domain($domain,'primary'))) {
 7885:         $uhome=&domain($domain,'primary');
 7886:         push(@homeservers,&domain($domain,'primary'));
 7887:     } else {
 7888:         my %servers = &get_servers($domain,'library');
 7889:         foreach my $tryserver (keys(%servers)) {
 7890:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7891:                 push(@homeservers,$tryserver);
 7892:             }
 7893:         }
 7894:     }
 7895:     my $response;
 7896:     foreach my $server (@homeservers) {
 7897:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 7898:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7899:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 7900:             split(':',$response);
 7901:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 7902:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 7903:         foreach my $item (split('&',$cat_title)) {   
 7904:             my ($name,$value)=split('=',$item);
 7905:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 7906:         }
 7907:         foreach my $item (split('&',$cat_order)) {
 7908:             my ($name,$value)=split('=',$item);
 7909:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 7910:         }
 7911:         return 'ok';
 7912:     }
 7913:     return $response;
 7914: }
 7915: 
 7916: sub auto_courserequest_checks {
 7917:     my ($dom) = @_;
 7918:     my ($homeserver,%validations);
 7919:     if ($dom =~ /^$match_domain$/) {
 7920:         $homeserver = &domain($dom,'primary');
 7921:     }
 7922:     unless ($homeserver eq 'no_host') {
 7923:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 7924:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 7925:             my @items = split(/&/,$response);
 7926:             foreach my $item (@items) {
 7927:                 my ($key,$value) = split('=',$item);
 7928:                 $validations{&unescape($key)} = &thaw_unescape($value);
 7929:             }
 7930:         }
 7931:     }
 7932:     return %validations; 
 7933: }
 7934: 
 7935: sub auto_courserequest_validation {
 7936:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
 7937:     my ($homeserver,$response);
 7938:     if ($dom =~ /^$match_domain$/) {
 7939:         $homeserver = &domain($dom,'primary');
 7940:     }
 7941:     unless ($homeserver eq 'no_host') {
 7942:         my $customdata;
 7943:         if (ref($custominfo) eq 'HASH') {
 7944:             $customdata = &freeze_escape($custominfo);
 7945:         }
 7946:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 7947:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 7948:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
 7949:                                     $customdata,$homeserver));
 7950:     }
 7951:     return $response;
 7952: }
 7953: 
 7954: sub auto_validate_class_sec {
 7955:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 7956:     my $homeserver = &homeserver($cnum,$cdom);
 7957:     my $ownerlist;
 7958:     if (ref($owners) eq 'ARRAY') {
 7959:         $ownerlist = join(',',@{$owners});
 7960:     } else {
 7961:         $ownerlist = $owners;
 7962:     }
 7963:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 7964:                         &escape($ownerlist).':'.$cdom,$homeserver);
 7965:     return $response;
 7966: }
 7967: 
 7968: sub auto_crsreq_update {
 7969:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
 7970:         $code,$accessstart,$accessend,$inbound) = @_;
 7971:     my ($homeserver,%crsreqresponse);
 7972:     if ($cdom =~ /^$match_domain$/) {
 7973:         $homeserver = &domain($cdom,'primary');
 7974:     }
 7975:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 7976:         my $info;
 7977:         if (ref($inbound) eq 'HASH') {
 7978:             $info = &freeze_escape($inbound);
 7979:         }
 7980:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
 7981:                             ':'.&escape($action).':'.&escape($ownername).':'.
 7982:                             &escape($ownerdomain).':'.&escape($fullname).':'.
 7983:                             &escape($title).':'.&escape($code).':'.
 7984:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
 7985:                             $homeserver);
 7986:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 7987:             my @items = split(/&/,$response);
 7988:             foreach my $item (@items) {
 7989:                 my ($key,$value) = split('=',$item);
 7990:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
 7991:             }
 7992:         }
 7993:     }
 7994:     return \%crsreqresponse;
 7995: }
 7996: 
 7997: # ------------------------------------------------------- Course Group routines
 7998: 
 7999: sub get_coursegroups {
 8000:     my ($cdom,$cnum,$group,$namespace) = @_;
 8001:     return(&dump($namespace,$cdom,$cnum,$group));
 8002: }
 8003: 
 8004: sub modify_coursegroup {
 8005:     my ($cdom,$cnum,$groupsettings) = @_;
 8006:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 8007: }
 8008: 
 8009: sub toggle_coursegroup_status {
 8010:     my ($cdom,$cnum,$group,$action) = @_;
 8011:     my ($from_namespace,$to_namespace);
 8012:     if ($action eq 'delete') {
 8013:         $from_namespace = 'coursegroups';
 8014:         $to_namespace = 'deleted_groups';
 8015:     } else {
 8016:         $from_namespace = 'deleted_groups';
 8017:         $to_namespace = 'coursegroups';
 8018:     }
 8019:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 8020:     if (my $tmp = &error(%curr_group)) {
 8021:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 8022:         return ('read error',$tmp);
 8023:     } else {
 8024:         my %savedsettings = %curr_group; 
 8025:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 8026:         my $deloutcome;
 8027:         if ($result eq 'ok') {
 8028:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 8029:         } else {
 8030:             return ('write error',$result);
 8031:         }
 8032:         if ($deloutcome eq 'ok') {
 8033:             return 'ok';
 8034:         } else {
 8035:             return ('delete error',$deloutcome);
 8036:         }
 8037:     }
 8038: }
 8039: 
 8040: sub modify_group_roles {
 8041:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 8042:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 8043:     my $role = 'gr/'.&escape($userprivs);
 8044:     my ($uname,$udom) = split(/:/,$user);
 8045:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 8046:     if ($result eq 'ok') {
 8047:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 8048:     }
 8049:     return $result;
 8050: }
 8051: 
 8052: sub modify_coursegroup_membership {
 8053:     my ($cdom,$cnum,$membership) = @_;
 8054:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 8055:     return $result;
 8056: }
 8057: 
 8058: sub get_active_groups {
 8059:     my ($udom,$uname,$cdom,$cnum) = @_;
 8060:     my $now = time;
 8061:     my %groups = ();
 8062:     foreach my $key (keys(%env)) {
 8063:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 8064:             my ($start,$end) = split(/\./,$env{$key});
 8065:             if (($end!=0) && ($end<$now)) { next; }
 8066:             if (($start!=0) && ($start>$now)) { next; }
 8067:             if ($1 eq $cdom && $2 eq $cnum) {
 8068:                 $groups{$3} = $env{$key} ;
 8069:             }
 8070:         }
 8071:     }
 8072:     return %groups;
 8073: }
 8074: 
 8075: sub get_group_membership {
 8076:     my ($cdom,$cnum,$group) = @_;
 8077:     return(&dump('groupmembership',$cdom,$cnum,$group));
 8078: }
 8079: 
 8080: sub get_users_groups {
 8081:     my ($udom,$uname,$courseid) = @_;
 8082:     my @usersgroups;
 8083:     my $cachetime=1800;
 8084: 
 8085:     my $hashid="$udom:$uname:$courseid";
 8086:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 8087:     if (defined($cached)) {
 8088:         @usersgroups = split(/:/,$grouplist);
 8089:     } else {  
 8090:         $grouplist = '';
 8091:         my $courseurl = &courseid_to_courseurl($courseid);
 8092:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 8093:         my $access_end = $env{'course.'.$courseid.
 8094:                               '.default_enrollment_end_date'};
 8095:         my $now = time;
 8096:         foreach my $key (keys(%roleshash)) {
 8097:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 8098:                 my $group = $1;
 8099:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 8100:                     my $start = $2;
 8101:                     my $end = $1;
 8102:                     if ($start == -1) { next; } # deleted from group
 8103:                     if (($start!=0) && ($start>$now)) { next; }
 8104:                     if (($end!=0) && ($end<$now)) {
 8105:                         if ($access_end && $access_end < $now) {
 8106:                             if ($access_end - $end < 86400) {
 8107:                                 push(@usersgroups,$group);
 8108:                             }
 8109:                         }
 8110:                         next;
 8111:                     }
 8112:                     push(@usersgroups,$group);
 8113:                 }
 8114:             }
 8115:         }
 8116:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 8117:         $grouplist = join(':',@usersgroups);
 8118:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 8119:     }
 8120:     return @usersgroups;
 8121: }
 8122: 
 8123: sub devalidate_getgroups_cache {
 8124:     my ($udom,$uname,$cdom,$cnum)=@_;
 8125:     my $courseid = $cdom.'_'.$cnum;
 8126: 
 8127:     my $hashid="$udom:$uname:$courseid";
 8128:     &devalidate_cache_new('getgroups',$hashid);
 8129: }
 8130: 
 8131: # ------------------------------------------------------------------ Plain Text
 8132: 
 8133: sub plaintext {
 8134:     my ($short,$type,$cid,$forcedefault) = @_;
 8135:     if ($short =~ m{^cr/}) {
 8136: 	return (split('/',$short))[-1];
 8137:     }
 8138:     if (!defined($cid)) {
 8139:         $cid = $env{'request.course.id'};
 8140:     }
 8141:     my %rolenames = (
 8142:                       Course    => 'std',
 8143:                       Community => 'alt1',
 8144:                     );
 8145:     if ($cid ne '') {
 8146:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 8147:             unless ($forcedefault) {
 8148:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 8149:                 &Apache::lonlocal::mt_escape(\$roletext);
 8150:                 return &Apache::lonlocal::mt($roletext);
 8151:             }
 8152:         }
 8153:     }
 8154:     if ((defined($type)) && (defined($rolenames{$type})) &&
 8155:         (defined($rolenames{$type})) && 
 8156:         (defined($prp{$short}{$rolenames{$type}}))) {
 8157:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 8158:     } elsif ($cid ne '') {
 8159:         my $crstype = $env{'course.'.$cid.'.type'};
 8160:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 8161:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 8162:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 8163:         }
 8164:     }
 8165:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 8166: }
 8167: 
 8168: # ----------------------------------------------------------------- Assign Role
 8169: 
 8170: sub assignrole {
 8171:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 8172:         $context)=@_;
 8173:     my $mrole;
 8174:     if ($role =~ /^cr\//) {
 8175:         my $cwosec=$url;
 8176:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 8177: 	unless (&allowed('ccr',$cwosec)) {
 8178:            my $refused = 1;
 8179:            if ($context eq 'requestcourses') {
 8180:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 8181:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 8182:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 8183:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 8184:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8185:                            if ($crsenv{'internal.courseowner'} eq
 8186:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 8187:                                $refused = '';
 8188:                            }
 8189:                        }
 8190:                    }
 8191:                }
 8192:            }
 8193:            if ($refused) {
 8194:                &logthis('Refused custom assignrole: '.
 8195:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 8196:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 8197:                return 'refused';
 8198:            }
 8199:         }
 8200:         $mrole='cr';
 8201:     } elsif ($role =~ /^gr\//) {
 8202:         my $cwogrp=$url;
 8203:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 8204:         unless (&allowed('mdg',$cwogrp)) {
 8205:             &logthis('Refused group assignrole: '.
 8206:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 8207:                     $env{'user.name'}.' at '.$env{'user.domain'});
 8208:             return 'refused';
 8209:         }
 8210:         $mrole='gr';
 8211:     } else {
 8212:         my $cwosec=$url;
 8213:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 8214:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 8215:             my $refused;
 8216:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 8217:                 if (!(&allowed('c'.$role,$url))) {
 8218:                     $refused = 1;
 8219:                 }
 8220:             } else {
 8221:                 $refused = 1;
 8222:             }
 8223:             if ($refused) {
 8224:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 8225:                 if (!$selfenroll && $context eq 'course') {
 8226:                     my %crsenv;
 8227:                     if ($role eq 'cc' || $role eq 'co') {
 8228:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8229:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 8230:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 8231:                                 if ($crsenv{'internal.courseowner'} eq 
 8232:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 8233:                                     $refused = '';
 8234:                                 }
 8235:                             }
 8236:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 8237:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 8238:                                 if ($crsenv{'internal.courseowner'} eq 
 8239:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 8240:                                     $refused = '';
 8241:                                 }
 8242:                             }
 8243:                         }
 8244:                     }
 8245:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 8246:                     $refused = '';
 8247:                 } elsif ($context eq 'requestcourses') {
 8248:                     my @possroles = ('st','ta','ep','in','cc','co');
 8249:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 8250:                         my $wrongcc;
 8251:                         if ($cnum =~ /^$match_community$/) {
 8252:                             $wrongcc = 1 if ($role eq 'cc');
 8253:                         } else {
 8254:                             $wrongcc = 1 if ($role eq 'co');
 8255:                         }
 8256:                         unless ($wrongcc) {
 8257:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8258:                             if ($crsenv{'internal.courseowner'} eq 
 8259:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 8260:                                 $refused = '';
 8261:                             }
 8262:                         }
 8263:                     }
 8264:                 } elsif ($context eq 'requestauthor') {
 8265:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
 8266:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 8267:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 8268:                             $refused = '';
 8269:                         } else {
 8270:                             my %domdefaults = &get_domain_defaults($udom);
 8271:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 8272:                                 my $checkbystatus;
 8273:                                 if ($env{'user.adv'}) { 
 8274:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 8275:                                     if ($disposition eq 'automatic') {
 8276:                                         $refused = '';
 8277:                                     } elsif ($disposition eq '') {
 8278:                                         $checkbystatus = 1;
 8279:                                     } 
 8280:                                 } else {
 8281:                                     $checkbystatus = 1;
 8282:                                 }
 8283:                                 if ($checkbystatus) {
 8284:                                     if ($env{'environment.inststatus'}) {
 8285:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 8286:                                         foreach my $type (@inststatuses) {
 8287:                                             if (($type ne '') &&
 8288:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 8289:                                                 $refused = '';
 8290:                                             }
 8291:                                         }
 8292:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 8293:                                         $refused = '';
 8294:                                     }
 8295:                                 }
 8296:                             }
 8297:                         }
 8298:                     }
 8299:                 }
 8300:                 if ($refused) {
 8301:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 8302:                              ' '.$role.' '.$end.' '.$start.' by '.
 8303: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 8304:                     return 'refused';
 8305:                 }
 8306:             }
 8307:         } elsif ($role eq 'au') {
 8308:             if ($url ne '/'.$udom.'/') {
 8309:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 8310:                          ' to assign author role for '.$uname.':'.$udom.
 8311:                          ' in domain: '.$url.' refused (wrong domain).');
 8312:                 return 'refused';
 8313:             }
 8314:         }
 8315:         $mrole=$role;
 8316:     }
 8317:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 8318:                 "$udom:$uname:$url".'_'."$mrole=$role";
 8319:     if ($end) { $command.='_'.$end; }
 8320:     if ($start) {
 8321: 	if ($end) { 
 8322:            $command.='_'.$start; 
 8323:         } else {
 8324:            $command.='_0_'.$start;
 8325:         }
 8326:     }
 8327:     my $origstart = $start;
 8328:     my $origend = $end;
 8329:     my $delflag;
 8330: # actually delete
 8331:     if ($deleteflag) {
 8332: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 8333: # modify command to delete the role
 8334:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 8335:                 "$udom:$uname:$url".'_'."$mrole";
 8336: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 8337: # set start and finish to negative values for userrolelog
 8338:            $start=-1;
 8339:            $end=-1;
 8340:            $delflag = 1;
 8341:         }
 8342:     }
 8343: # send command
 8344:     my $answer=&reply($command,&homeserver($uname,$udom));
 8345: # log new user role if status is ok
 8346:     if ($answer eq 'ok') {
 8347: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 8348:         if (($role eq 'cc') || ($role eq 'in') ||
 8349:             ($role eq 'ep') || ($role eq 'ad') ||
 8350:             ($role eq 'ta') || ($role eq 'st') ||
 8351:             ($role=~/^cr/) || ($role eq 'gr') ||
 8352:             ($role eq 'co')) {
 8353: # for course roles, perform group memberships changes triggered by role change.
 8354:             unless ($role =~ /^gr/) {
 8355:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 8356:                                                  $origstart,$selfenroll,$context);
 8357:             }
 8358:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8359:                            $selfenroll,$context);
 8360:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
 8361:                  ($role eq 'au') || ($role eq 'dc')) {
 8362:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8363:                            $context);
 8364:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
 8365:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8366:                              $context); 
 8367:         }
 8368:         if ($role eq 'cc') {
 8369:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 8370:         }
 8371:     }
 8372:     return $answer;
 8373: }
 8374: 
 8375: sub autoupdate_coowners {
 8376:     my ($url,$end,$start,$uname,$udom) = @_;
 8377:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 8378:     if (($cdom ne '') && ($cnum ne '')) {
 8379:         my $now = time;
 8380:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 8381:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 8382:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 8383:             my $instcode = $coursehash{'internal.coursecode'};
 8384:             if ($instcode ne '') {
 8385:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 8386:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 8387:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 8388:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 8389:                         if ($result eq 'valid') {
 8390:                             if ($coursehash{'internal.co-owners'}) {
 8391:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 8392:                                     push(@newcoowners,$coowner);
 8393:                                 }
 8394:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 8395:                                     push(@newcoowners,$uname.':'.$udom);
 8396:                                 }
 8397:                                 @newcoowners = sort(@newcoowners);
 8398:                             } else {
 8399:                                 push(@newcoowners,$uname.':'.$udom);
 8400:                             }
 8401:                         } else {
 8402:                             if ($coursehash{'internal.co-owners'}) {
 8403:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 8404:                                     unless ($coowner eq $uname.':'.$udom) {
 8405:                                         push(@newcoowners,$coowner);
 8406:                                     }
 8407:                                 }
 8408:                                 unless (@newcoowners > 0) {
 8409:                                     $delcoowners = 1;
 8410:                                     $coowners = '';
 8411:                                 }
 8412:                             }
 8413:                         }
 8414:                         if (@newcoowners || $delcoowners) {
 8415:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 8416:                                             $delcoowners,@newcoowners);
 8417:                         }
 8418:                     }
 8419:                 }
 8420:             }
 8421:         }
 8422:     }
 8423: }
 8424: 
 8425: sub store_coowners {
 8426:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 8427:     my $cid = $cdom.'_'.$cnum;
 8428:     my ($coowners,$delresult,$putresult);
 8429:     if (@newcoowners) {
 8430:         $coowners = join(',',@newcoowners);
 8431:         my %coownershash = (
 8432:                             'internal.co-owners' => $coowners,
 8433:                            );
 8434:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 8435:         if ($putresult eq 'ok') {
 8436:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 8437:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 8438:             }
 8439:         }
 8440:     }
 8441:     if ($delcoowners) {
 8442:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 8443:         if ($delresult eq 'ok') {
 8444:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 8445:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 8446:             }
 8447:         }
 8448:     }
 8449:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 8450:         my %crsinfo =
 8451:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 8452:         if (ref($crsinfo{$cid}) eq 'HASH') {
 8453:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 8454:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 8455:         }
 8456:     }
 8457: }
 8458: 
 8459: # -------------------------------------------------- Modify user authentication
 8460: # Overrides without validation
 8461: 
 8462: sub modifyuserauth {
 8463:     my ($udom,$uname,$umode,$upass)=@_;
 8464:     my $uhome=&homeserver($uname,$udom);
 8465:     unless (&allowed('mau',$udom)) { return 'refused'; }
 8466:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 8467:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 8468:              ' in domain '.$env{'request.role.domain'});  
 8469:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 8470: 		     &escape($upass),$uhome);
 8471:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 8472:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 8473:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 8474:     &log($udom,,$uname,$uhome,
 8475:         'Authentication changed by '.$env{'user.domain'}.', '.
 8476:                                      $env{'user.name'}.', '.$umode.
 8477:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 8478:     unless ($reply eq 'ok') {
 8479:         &logthis('Authentication mode error: '.$reply);
 8480: 	return 'error: '.$reply;
 8481:     }   
 8482:     return 'ok';
 8483: }
 8484: 
 8485: # --------------------------------------------------------------- Modify a user
 8486: 
 8487: sub modifyuser {
 8488:     my ($udom,    $uname, $uid,
 8489:         $umode,   $upass, $first,
 8490:         $middle,  $last,  $gene,
 8491:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 8492:     $udom= &LONCAPA::clean_domain($udom);
 8493:     $uname=&LONCAPA::clean_username($uname);
 8494:     my $showcandelete = 'none';
 8495:     if (ref($candelete) eq 'ARRAY') {
 8496:         if (@{$candelete} > 0) {
 8497:             $showcandelete = join(', ',@{$candelete});
 8498:         }
 8499:     }
 8500:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 8501:              $umode.', '.$first.', '.$middle.', '.
 8502: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 8503:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 8504:                                      ' desiredhome not specified'). 
 8505:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 8506:              ' in domain '.$env{'request.role.domain'});
 8507:     my $uhome=&homeserver($uname,$udom,'true');
 8508:     my $newuser;
 8509:     if ($uhome eq 'no_host') {
 8510:         $newuser = 1;
 8511:     }
 8512: # ----------------------------------------------------------------- Create User
 8513:     if (($uhome eq 'no_host') && 
 8514: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 8515:         my $unhome='';
 8516:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 8517:             $unhome = $desiredhome;
 8518: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 8519: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 8520:         } else { # load balancing routine for determining $unhome
 8521:             my $loadm=10000000;
 8522: 	    my %servers = &get_servers($udom,'library');
 8523: 	    foreach my $tryserver (keys(%servers)) {
 8524: 		my $answer=reply('load',$tryserver);
 8525: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 8526: 		    $loadm=$answer;
 8527: 		    $unhome=$tryserver;
 8528: 		}
 8529: 	    }
 8530:         }
 8531:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 8532: 	    return 'error: unable to find a home server for '.$uname.
 8533:                    ' in domain '.$udom;
 8534:         }
 8535:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 8536:                          &escape($upass),$unhome);
 8537: 	unless ($reply eq 'ok') {
 8538:             return 'error: '.$reply;
 8539:         }   
 8540:         $uhome=&homeserver($uname,$udom,'true');
 8541:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 8542: 	    return 'error: unable verify users home machine.';
 8543:         }
 8544:     }   # End of creation of new user
 8545: # ---------------------------------------------------------------------- Add ID
 8546:     if ($uid) {
 8547:        $uid=~tr/A-Z/a-z/;
 8548:        my %uidhash=&idrget($udom,$uname);
 8549:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 8550:          && (!$forceid)) {
 8551: 	  unless ($uid eq $uidhash{$uname}) {
 8552: 	      return 'error: user id "'.$uid.'" does not match '.
 8553:                   'current user id "'.$uidhash{$uname}.'".';
 8554:           }
 8555:        } else {
 8556: 	  &idput($udom,($uname => $uid));
 8557:        }
 8558:     }
 8559: # -------------------------------------------------------------- Add names, etc
 8560:     my @tmp=&get('environment',
 8561: 		   ['firstname','middlename','lastname','generation','id',
 8562:                     'permanentemail','inststatus'],
 8563: 		   $udom,$uname);
 8564:     my (%names,%oldnames);
 8565:     if ($tmp[0] =~ m/^error:.*/) { 
 8566:         %names=(); 
 8567:     } else {
 8568:         %names = @tmp;
 8569:         %oldnames = %names;
 8570:     }
 8571: #
 8572: # If name, email and/or uid are blank (e.g., because an uploaded file
 8573: # of users did not contain them), do not overwrite existing values
 8574: # unless field is in $candelete array ref.  
 8575: #
 8576: 
 8577:     my @fields = ('firstname','middlename','lastname','generation',
 8578:                   'permanentemail','id');
 8579:     my %newvalues;
 8580:     if (ref($candelete) eq 'ARRAY') {
 8581:         foreach my $field (@fields) {
 8582:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 8583:                 if ($field eq 'firstname') {
 8584:                     $names{$field} = $first;
 8585:                 } elsif ($field eq 'middlename') {
 8586:                     $names{$field} = $middle;
 8587:                 } elsif ($field eq 'lastname') {
 8588:                     $names{$field} = $last;
 8589:                 } elsif ($field eq 'generation') { 
 8590:                     $names{$field} = $gene;
 8591:                 } elsif ($field eq 'permanentemail') {
 8592:                     $names{$field} = $email;
 8593:                 } elsif ($field eq 'id') {
 8594:                     $names{$field}  = $uid;
 8595:                 }
 8596:             }
 8597:         }
 8598:     }
 8599:     if ($first)  { $names{'firstname'}  = $first; }
 8600:     if (defined($middle)) { $names{'middlename'} = $middle; }
 8601:     if ($last)   { $names{'lastname'}   = $last; }
 8602:     if (defined($gene))   { $names{'generation'} = $gene; }
 8603:     if ($email) {
 8604:        $email=~s/[^\w\@\.\-\,]//gs;
 8605:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 8606:     }
 8607:     if ($uid) { $names{'id'}  = $uid; }
 8608:     if (defined($inststatus)) {
 8609:         $names{'inststatus'} = '';
 8610:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 8611:         if (ref($usertypes) eq 'HASH') {
 8612:             my @okstatuses; 
 8613:             foreach my $item (split(/:/,$inststatus)) {
 8614:                 if (defined($usertypes->{$item})) {
 8615:                     push(@okstatuses,$item);  
 8616:                 }
 8617:             }
 8618:             if (@okstatuses) {
 8619:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 8620:             }
 8621:         }
 8622:     }
 8623:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 8624:                  $umode.', '.$first.', '.$middle.', '.
 8625:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 8626:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 8627:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 8628:     } else {
 8629:         $logmsg .= ' during self creation';
 8630:     }
 8631:     my $changed;
 8632:     if ($newuser) {
 8633:         $changed = 1;
 8634:     } else {
 8635:         foreach my $field (@fields) {
 8636:             if ($names{$field} ne $oldnames{$field}) {
 8637:                 $changed = 1;
 8638:                 last;
 8639:             }
 8640:         }
 8641:     }
 8642:     unless ($changed) {
 8643:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 8644:         &logthis($logmsg);
 8645:         return 'ok';
 8646:     }
 8647:     my $reply = &put('environment', \%names, $udom,$uname);
 8648:     if ($reply ne 'ok') { 
 8649:         return 'error: '.$reply;
 8650:     }
 8651:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
 8652:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
 8653:     }
 8654:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 8655:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 8656:     $logmsg = 'Success modifying user '.$logmsg;
 8657:     &logthis($logmsg);
 8658:     return 'ok';
 8659: }
 8660: 
 8661: # -------------------------------------------------------------- Modify student
 8662: 
 8663: sub modifystudent {
 8664:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 8665:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 8666:         $selfenroll,$context,$inststatus,$credits)=@_;
 8667:     if (!$cid) {
 8668: 	unless ($cid=$env{'request.course.id'}) {
 8669: 	    return 'not_in_class';
 8670: 	}
 8671:     }
 8672: # --------------------------------------------------------------- Make the user
 8673:     my $reply=&modifyuser
 8674: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 8675:          $desiredhome,$email,$inststatus);
 8676:     unless ($reply eq 'ok') { return $reply; }
 8677:     # This will cause &modify_student_enrollment to get the uid from the
 8678:     # student's environment
 8679:     $uid = undef if (!$forceid);
 8680:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 8681:                                         $gene,$usec,$end,$start,$type,$locktype,
 8682:                                         $cid,$selfenroll,$context,$credits);
 8683:     return $reply;
 8684: }
 8685: 
 8686: sub modify_student_enrollment {
 8687:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
 8688:         $locktype,$cid,$selfenroll,$context,$credits) = @_;
 8689:     my ($cdom,$cnum,$chome);
 8690:     if (!$cid) {
 8691: 	unless ($cid=$env{'request.course.id'}) {
 8692: 	    return 'not_in_class';
 8693: 	}
 8694: 	$cdom=$env{'course.'.$cid.'.domain'};
 8695: 	$cnum=$env{'course.'.$cid.'.num'};
 8696:     } else {
 8697: 	($cdom,$cnum)=split(/_/,$cid);
 8698:     }
 8699:     $chome=$env{'course.'.$cid.'.home'};
 8700:     if (!$chome) {
 8701: 	$chome=&homeserver($cnum,$cdom);
 8702:     }
 8703:     if (!$chome) { return 'unknown_course'; }
 8704:     # Make sure the user exists
 8705:     my $uhome=&homeserver($uname,$udom);
 8706:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8707: 	return 'error: no such user';
 8708:     }
 8709:     # Get student data if we were not given enough information
 8710:     if (!defined($first)  || $first  eq '' || 
 8711:         !defined($last)   || $last   eq '' || 
 8712:         !defined($uid)    || $uid    eq '' || 
 8713:         !defined($middle) || $middle eq '' || 
 8714:         !defined($gene)   || $gene   eq '') {
 8715:         # They did not supply us with enough data to enroll the student, so
 8716:         # we need to pick up more information.
 8717:         my %tmp = &get('environment',
 8718:                        ['firstname','middlename','lastname', 'generation','id']
 8719:                        ,$udom,$uname);
 8720: 
 8721:         #foreach my $key (keys(%tmp)) {
 8722:         #    &logthis("key $key = ".$tmp{$key});
 8723:         #}
 8724:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 8725:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 8726:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 8727:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 8728:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 8729:     }
 8730:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 8731:     my $user = "$uname:$udom";
 8732:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
 8733:     my $reply=cput('classlist',
 8734: 		   {$user => 
 8735: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
 8736: 		   $cdom,$cnum);
 8737:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
 8738:         &devalidate_getsection_cache($udom,$uname,$cid);
 8739:     } else { 
 8740: 	return 'error: '.$reply;
 8741:     }
 8742:     # Add student role to user
 8743:     my $uurl='/'.$cid;
 8744:     $uurl=~s/\_/\//g;
 8745:     if ($usec) {
 8746: 	$uurl.='/'.$usec;
 8747:     }
 8748:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
 8749:                              $selfenroll,$context);
 8750:     if ($result ne 'ok') {
 8751:         if ($old_entry{$user} ne '') {
 8752:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
 8753:         } else {
 8754:             $reply = &del('classlist',[$user],$cdom,$cnum);
 8755:         }
 8756:     }
 8757:     return $result; 
 8758: }
 8759: 
 8760: sub format_name {
 8761:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 8762:     my $name;
 8763:     if ($first ne 'lastname') {
 8764: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 8765:     } else {
 8766: 	if ($lastname=~/\S/) {
 8767: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 8768: 	    $name=~s/\s+,/,/;
 8769: 	} else {
 8770: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 8771: 	}
 8772:     }
 8773:     $name=~s/^\s+//;
 8774:     $name=~s/\s+$//;
 8775:     $name=~s/\s+/ /g;
 8776:     return $name;
 8777: }
 8778: 
 8779: # ------------------------------------------------- Write to course preferences
 8780: 
 8781: sub writecoursepref {
 8782:     my ($courseid,%prefs)=@_;
 8783:     $courseid=~s/^\///;
 8784:     $courseid=~s/\_/\//g;
 8785:     my ($cdomain,$cnum)=split(/\//,$courseid);
 8786:     my $chome=homeserver($cnum,$cdomain);
 8787:     if (($chome eq '') || ($chome eq 'no_host')) { 
 8788: 	return 'error: no such course';
 8789:     }
 8790:     my $cstring='';
 8791:     foreach my $pref (keys(%prefs)) {
 8792: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 8793:     }
 8794:     $cstring=~s/\&$//;
 8795:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 8796: }
 8797: 
 8798: # ---------------------------------------------------------- Make/modify course
 8799: 
 8800: sub createcourse {
 8801:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 8802:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 8803:     $url=&declutter($url);
 8804:     my $cid='';
 8805:     if ($context eq 'requestcourses') {
 8806:         my $can_create = 0;
 8807:         my ($ownername,$ownerdom) = split(':',$course_owner);
 8808:         if ($udom eq $ownerdom) {
 8809:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 8810:                                   $context)) {
 8811:                 $can_create = 1;
 8812:             }
 8813:         } else {
 8814:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 8815:                                            $category);
 8816:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 8817:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 8818:                 if (@curr > 0) {
 8819:                     my @options = qw(approval validate autolimit);
 8820:                     my $optregex = join('|',@options);
 8821:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 8822:                         $can_create = 1;
 8823:                     }
 8824:                 }
 8825:             }
 8826:         }
 8827:         if ($can_create) {
 8828:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 8829:                 unless (&allowed('ccc',$udom)) {
 8830:                     return 'refused'; 
 8831:                 }
 8832:             }
 8833:         } else {
 8834:             return 'refused';
 8835:         }
 8836:     } elsif (!&allowed('ccc',$udom)) {
 8837:         return 'refused';
 8838:     }
 8839: # --------------------------------------------------------------- Get Unique ID
 8840:     my $uname;
 8841:     if ($cnum =~ /^$match_courseid$/) {
 8842:         my $chome=&homeserver($cnum,$udom,'true');
 8843:         if (($chome eq '') || ($chome eq 'no_host')) {
 8844:             $uname = $cnum;
 8845:         } else {
 8846:             $uname = &generate_coursenum($udom,$crstype);
 8847:         }
 8848:     } else {
 8849:         $uname = &generate_coursenum($udom,$crstype);
 8850:     }
 8851:     return $uname if ($uname =~ /^error/);
 8852: # -------------------------------------------------- Check supplied server name
 8853:     if (!defined($course_server)) {
 8854:         if (defined(&domain($udom,'primary'))) {
 8855:             $course_server = &domain($udom,'primary');
 8856:         } else {
 8857:             $course_server = $env{'user.home'}; 
 8858:         }
 8859:     }
 8860:     my %host_servers =
 8861:         &Apache::lonnet::get_servers($udom,'library');
 8862:     unless ($host_servers{$course_server}) {
 8863:         return 'error: invalid home server for course: '.$course_server;
 8864:     }
 8865: # ------------------------------------------------------------- Make the course
 8866:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 8867:                       $course_server);
 8868:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 8869:     my $uhome=&homeserver($uname,$udom,'true');
 8870:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8871: 	return 'error: no such course';
 8872:     }
 8873: # ----------------------------------------------------------------- Course made
 8874: # log existence
 8875:     my $now = time;
 8876:     my $newcourse = {
 8877:                     $udom.'_'.$uname => {
 8878:                                      description => $description,
 8879:                                      inst_code   => $inst_code,
 8880:                                      owner       => $course_owner,
 8881:                                      type        => $crstype,
 8882:                                      creator     => $env{'user.name'}.':'.
 8883:                                                     $env{'user.domain'},
 8884:                                      created     => $now,
 8885:                                      context     => $context,
 8886:                                                 },
 8887:                     };
 8888:     &courseidput($udom,$newcourse,$uhome,'notime');
 8889: # set toplevel url
 8890:     my $topurl=$url;
 8891:     unless ($nonstandard) {
 8892: # ------------------------------------------ For standard courses, make top url
 8893:         my $mapurl=&clutter($url);
 8894:         if ($mapurl eq '/res/') { $mapurl=''; }
 8895:         $env{'form.initmap'}=(<<ENDINITMAP);
 8896: <map>
 8897: <resource id="1" type="start"></resource>
 8898: <resource id="2" src="$mapurl"></resource>
 8899: <resource id="3" type="finish"></resource>
 8900: <link index="1" from="1" to="2"></link>
 8901: <link index="2" from="2" to="3"></link>
 8902: </map>
 8903: ENDINITMAP
 8904:         $topurl=&declutter(
 8905:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 8906:                           );
 8907:     }
 8908: # ----------------------------------------------------------- Write preferences
 8909:     &writecoursepref($udom.'_'.$uname,
 8910:                      ('description'              => $description,
 8911:                       'url'                      => $topurl,
 8912:                       'internal.creator'         => $env{'user.name'}.':'.
 8913:                                                     $env{'user.domain'},
 8914:                       'internal.created'         => $now,
 8915:                       'internal.creationcontext' => $context)
 8916:                     );
 8917:     return '/'.$udom.'/'.$uname;
 8918: }
 8919: 
 8920: # ------------------------------------------------------------------- Create ID
 8921: sub generate_coursenum {
 8922:     my ($udom,$crstype) = @_;
 8923:     my $domdesc = &domain($udom);
 8924:     return 'error: invalid domain' if ($domdesc eq '');
 8925:     my $first;
 8926:     if ($crstype eq 'Community') {
 8927:         $first = '0';
 8928:     } else {
 8929:         $first = int(1+rand(9)); 
 8930:     } 
 8931:     my $uname=$first.
 8932:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8933:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8934:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8935: # ----------------------------------------------- Make sure that does not exist
 8936:     my $uhome=&homeserver($uname,$udom,'true');
 8937:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8938:         if ($crstype eq 'Community') {
 8939:             $first = '0';
 8940:         } else {
 8941:             $first = int(1+rand(9));
 8942:         }
 8943:         $uname=$first.
 8944:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8945:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8946:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8947:         $uhome=&homeserver($uname,$udom,'true');
 8948:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8949:             return 'error: unable to generate unique course-ID';
 8950:         }
 8951:     }
 8952:     return $uname;
 8953: }
 8954: 
 8955: sub is_course {
 8956:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
 8957:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
 8958: 
 8959:     return unless $cdom and $cnum;
 8960: 
 8961:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
 8962:         '.');
 8963: 
 8964:     return unless(exists($courses{$cdom.'_'.$cnum}));
 8965:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
 8966: }
 8967: 
 8968: sub store_userdata {
 8969:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
 8970:     my $result;
 8971:     if ($datakey ne '') {
 8972:         if (ref($storehash) eq 'HASH') {
 8973:             if ($udom eq '' || $uname eq '') {
 8974:                 $udom = $env{'user.domain'};
 8975:                 $uname = $env{'user.name'};
 8976:             }
 8977:             my $uhome=&homeserver($uname,$udom);
 8978:             if (($uhome eq '') || ($uhome eq 'no_host')) {
 8979:                 $result = 'error: no_host';
 8980:             } else {
 8981:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
 8982:                 $storehash->{'host'} = $perlvar{'lonHostID'};
 8983: 
 8984:                 my $namevalue='';
 8985:                 foreach my $key (keys(%{$storehash})) {
 8986:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 8987:                 }
 8988:                 $namevalue=~s/\&$//;
 8989:                 unless ($namespace eq 'courserequests') {
 8990:                     $datakey = &escape($datakey);
 8991:                 }
 8992:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
 8993:                                   $namevalue,$uhome);
 8994:             }
 8995:         } else {
 8996:             $result = 'error: data to store was not a hash reference'; 
 8997:         }
 8998:     } else {
 8999:         $result= 'error: invalid requestkey'; 
 9000:     }
 9001:     return $result;
 9002: }
 9003: 
 9004: # ---------------------------------------------------------- Assign Custom Role
 9005: 
 9006: sub assigncustomrole {
 9007:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 9008:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 9009:                        $end,$start,$deleteflag,$selfenroll,$context);
 9010: }
 9011: 
 9012: # ----------------------------------------------------------------- Revoke Role
 9013: 
 9014: sub revokerole {
 9015:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 9016:     my $now=time;
 9017:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 9018: }
 9019: 
 9020: # ---------------------------------------------------------- Revoke Custom Role
 9021: 
 9022: sub revokecustomrole {
 9023:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 9024:     my $now=time;
 9025:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 9026:            $deleteflag,$selfenroll,$context);
 9027: }
 9028: 
 9029: # ------------------------------------------------------------ Disk usage
 9030: sub diskusage {
 9031:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 9032:     $directorypath =~ s/\/$//;
 9033:     my $listing=&reply('du2:'.&escape($directorypath).':'
 9034:                        .&escape($getpropath).':'.&escape($uname).':'
 9035:                        .&escape($udom),homeserver($uname,$udom));
 9036:     if ($listing eq 'unknown_cmd') {
 9037:         if ($getpropath) {
 9038:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 9039:         }
 9040:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 9041:     }
 9042:     return $listing;
 9043: }
 9044: 
 9045: sub is_locked {
 9046:     my ($file_name, $domain, $user, $which) = @_;
 9047:     my @check;
 9048:     my $is_locked;
 9049:     push (@check,$file_name);
 9050:     my %locked = &get('file_permissions',\@check,
 9051: 		      $env{'user.domain'},$env{'user.name'});
 9052:     my ($tmp)=keys(%locked);
 9053:     if ($tmp=~/^error:/) { undef(%locked); }
 9054:     
 9055:     if (ref($locked{$file_name}) eq 'ARRAY') {
 9056:         $is_locked = 'false';
 9057:         foreach my $entry (@{$locked{$file_name}}) {
 9058:            if (ref($entry) eq 'ARRAY') {
 9059:                $is_locked = 'true';
 9060:                if (ref($which) eq 'ARRAY') {
 9061:                    push(@{$which},$entry);
 9062:                } else {
 9063:                    last;
 9064:                }
 9065:            }
 9066:        }
 9067:     } else {
 9068:         $is_locked = 'false';
 9069:     }
 9070:     return $is_locked;
 9071: }
 9072: 
 9073: sub declutter_portfile {
 9074:     my ($file) = @_;
 9075:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 9076:     return $file;
 9077: }
 9078: 
 9079: # ------------------------------------------------------------- Mark as Read Only
 9080: 
 9081: sub mark_as_readonly {
 9082:     my ($domain,$user,$files,$what) = @_;
 9083:     my %current_permissions = &dump('file_permissions',$domain,$user);
 9084:     my ($tmp)=keys(%current_permissions);
 9085:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9086:     foreach my $file (@{$files}) {
 9087: 	$file = &declutter_portfile($file);
 9088:         push(@{$current_permissions{$file}},$what);
 9089:     }
 9090:     &put('file_permissions',\%current_permissions,$domain,$user);
 9091:     return;
 9092: }
 9093: 
 9094: # ------------------------------------------------------------Save Selected Files
 9095: 
 9096: sub save_selected_files {
 9097:     my ($user, $path, @files) = @_;
 9098:     my $filename = $user."savedfiles";
 9099:     my @other_files = &files_not_in_path($user, $path);
 9100:     open (OUT, '>'.$tmpdir.$filename);
 9101:     foreach my $file (@files) {
 9102:         print (OUT $env{'form.currentpath'}.$file."\n");
 9103:     }
 9104:     foreach my $file (@other_files) {
 9105:         print (OUT $file."\n");
 9106:     }
 9107:     close (OUT);
 9108:     return 'ok';
 9109: }
 9110: 
 9111: sub clear_selected_files {
 9112:     my ($user) = @_;
 9113:     my $filename = $user."savedfiles";
 9114:     open (OUT, '>'.LONCAPA::tempdir().$filename);
 9115:     print (OUT undef);
 9116:     close (OUT);
 9117:     return ("ok");    
 9118: }
 9119: 
 9120: sub files_in_path {
 9121:     my ($user, $path) = @_;
 9122:     my $filename = $user."savedfiles";
 9123:     my %return_files;
 9124:     open (IN, '<'.LONCAPA::tempdir().$filename);
 9125:     while (my $line_in = <IN>) {
 9126:         chomp ($line_in);
 9127:         my @paths_and_file = split (m!/!, $line_in);
 9128:         my $file_part = pop (@paths_and_file);
 9129:         my $path_part = join ('/', @paths_and_file);
 9130:         $path_part.='/';
 9131:         my $path_and_file = $path_part.$file_part;
 9132:         if ($path_part eq $path) {
 9133:             $return_files{$file_part}= 'selected';
 9134:         }
 9135:     }
 9136:     close (IN);
 9137:     return (\%return_files);
 9138: }
 9139: 
 9140: # called in portfolio select mode, to show files selected NOT in current directory
 9141: sub files_not_in_path {
 9142:     my ($user, $path) = @_;
 9143:     my $filename = $user."savedfiles";
 9144:     my @return_files;
 9145:     my $path_part;
 9146:     open(IN, '<'.LONCAPA::.$filename);
 9147:     while (my $line = <IN>) {
 9148:         #ok, I know it's clunky, but I want it to work
 9149:         my @paths_and_file = split(m|/|, $line);
 9150:         my $file_part = pop(@paths_and_file);
 9151:         chomp($file_part);
 9152:         my $path_part = join('/', @paths_and_file);
 9153:         $path_part .= '/';
 9154:         my $path_and_file = $path_part.$file_part;
 9155:         if ($path_part ne $path) {
 9156:             push(@return_files, ($path_and_file));
 9157:         }
 9158:     }
 9159:     close(OUT);
 9160:     return (@return_files);
 9161: }
 9162: 
 9163: #------------------------------Submitted/Handedback Portfolio Files Versioning
 9164:  
 9165: sub portfiles_versioning {
 9166:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
 9167:     my $portfolio_root = '/userfiles/portfolio';
 9168:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
 9169:     foreach my $file (@{$portfiles}) {
 9170:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 9171:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 9172:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
 9173:         my $getpropath = 1;
 9174:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
 9175:                                              $stu_name,$getpropath);
 9176:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
 9177:         my $new_answer = 
 9178:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
 9179:         if ($new_answer ne 'problem getting file') {
 9180:             push(@{$versioned_portfiles}, $directory.$new_answer);
 9181:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
 9182:                               [$symb,$env{'request.course.id'},'graded']);
 9183:         }
 9184:     }
 9185: }
 9186: 
 9187: sub get_next_version {
 9188:     my ($answer_name, $answer_ext, $dir_list) = @_;
 9189:     my $version;
 9190:     if (ref($dir_list) eq 'ARRAY') {
 9191:         foreach my $row (@{$dir_list}) {
 9192:             my ($file) = split(/\&/,$row,2);
 9193:             my ($file_name,$file_version,$file_ext) =
 9194:                 &file_name_version_ext($file);
 9195:             if (($file_name eq $answer_name) &&
 9196:                 ($file_ext eq $answer_ext)) {
 9197:                      # gets here if filename and extension match,
 9198:                      # regardless of version
 9199:                 if ($file_version ne '') {
 9200:                     # a versioned file is found  so save it for later
 9201:                     if ($file_version > $version) {
 9202:                         $version = $file_version;
 9203:                     }
 9204:                 }
 9205:             }
 9206:         }
 9207:     }
 9208:     $version ++;
 9209:     return($version);
 9210: }
 9211: 
 9212: sub version_selected_portfile {
 9213:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 9214:     my ($answer_name,$answer_ver,$answer_ext) =
 9215:         &file_name_version_ext($file_name);
 9216:     my $new_answer;
 9217:     $env{'form.copy'} =
 9218:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 9219:     if($env{'form.copy'} eq '-1') {
 9220:         $new_answer = 'problem getting file';
 9221:     } else {
 9222:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 9223:         my $copy_result = 
 9224:             &finishuserfileupload($stu_name,$domain,'copy',
 9225:                                   '/portfolio'.$directory.$new_answer);
 9226:     }
 9227:     undef($env{'form.copy'});
 9228:     return ($new_answer);
 9229: }
 9230: 
 9231: sub file_name_version_ext {
 9232:     my ($file)=@_;
 9233:     my @file_parts = split(/\./, $file);
 9234:     my ($name,$version,$ext);
 9235:     if (@file_parts > 1) {
 9236:         $ext=pop(@file_parts);
 9237:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 9238:             $version=pop(@file_parts);
 9239:         }
 9240:         $name=join('.',@file_parts);
 9241:     } else {
 9242:         $name=join('.',@file_parts);
 9243:     }
 9244:     return($name,$version,$ext);
 9245: }
 9246: 
 9247: #----------------------------------------------Get portfolio file permissions
 9248: 
 9249: sub get_portfile_permissions {
 9250:     my ($domain,$user) = @_;
 9251:     my %current_permissions = &dump('file_permissions',$domain,$user);
 9252:     my ($tmp)=keys(%current_permissions);
 9253:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9254:     return \%current_permissions;
 9255: }
 9256: 
 9257: #---------------------------------------------Get portfolio file access controls
 9258: 
 9259: sub get_access_controls {
 9260:     my ($current_permissions,$group,$file) = @_;
 9261:     my %access;
 9262:     my $real_file = $file;
 9263:     $file =~ s/\.meta$//;
 9264:     if (defined($file)) {
 9265:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 9266:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 9267:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 9268:             }
 9269:         }
 9270:     } else {
 9271:         foreach my $key (keys(%{$current_permissions})) {
 9272:             if ($key =~ /\0accesscontrol$/) {
 9273:                 if (defined($group)) {
 9274:                     if ($key !~ m-^\Q$group\E/-) {
 9275:                         next;
 9276:                     }
 9277:                 }
 9278:                 my ($fullpath) = split(/\0/,$key);
 9279:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 9280:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 9281:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 9282:                     }
 9283:                 }
 9284:             }
 9285:         }
 9286:     }
 9287:     return %access;
 9288: }
 9289: 
 9290: sub modify_access_controls {
 9291:     my ($file_name,$changes,$domain,$user)=@_;
 9292:     my ($outcome,$deloutcome);
 9293:     my %store_permissions;
 9294:     my %new_values;
 9295:     my %new_control;
 9296:     my %translation;
 9297:     my @deletions = ();
 9298:     my $now = time;
 9299:     if (exists($$changes{'activate'})) {
 9300:         if (ref($$changes{'activate'}) eq 'HASH') {
 9301:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 9302:             my $numnew = scalar(@newitems);
 9303:             for (my $i=0; $i<$numnew; $i++) {
 9304:                 my $newkey = $newitems[$i];
 9305:                 my $newid = &Apache::loncommon::get_cgi_id();
 9306:                 if ($newkey =~ /^\d+:/) { 
 9307:                     $newkey =~ s/^(\d+)/$newid/;
 9308:                     $translation{$1} = $newid;
 9309:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 9310:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 9311:                     $translation{$1} = $newid;
 9312:                 }
 9313:                 $new_values{$file_name."\0".$newkey} = 
 9314:                                           $$changes{'activate'}{$newitems[$i]};
 9315:                 $new_control{$newkey} = $now;
 9316:             }
 9317:         }
 9318:     }
 9319:     my %todelete;
 9320:     my %changed_items;
 9321:     foreach my $action ('delete','update') {
 9322:         if (exists($$changes{$action})) {
 9323:             if (ref($$changes{$action}) eq 'HASH') {
 9324:                 foreach my $key (keys(%{$$changes{$action}})) {
 9325:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 9326:                     if ($action eq 'delete') { 
 9327:                         $todelete{$itemnum} = 1;
 9328:                     } else {
 9329:                         $changed_items{$itemnum} = $key;
 9330:                     }
 9331:                 }
 9332:             }
 9333:         }
 9334:     }
 9335:     # get lock on access controls for file.
 9336:     my $lockhash = {
 9337:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 9338:                                                        ':'.$env{'user.domain'},
 9339:                    }; 
 9340:     my $tries = 0;
 9341:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 9342:    
 9343:     while (($gotlock ne 'ok') && $tries <3) {
 9344:         $tries ++;
 9345:         sleep 1;
 9346:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 9347:     }
 9348:     if ($gotlock eq 'ok') {
 9349:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 9350:         my ($tmp)=keys(%curr_permissions);
 9351:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 9352:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 9353:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 9354:             if (ref($curr_controls) eq 'HASH') {
 9355:                 foreach my $control_item (keys(%{$curr_controls})) {
 9356:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 9357:                     if (defined($todelete{$itemnum})) {
 9358:                         push(@deletions,$file_name."\0".$control_item);
 9359:                     } else {
 9360:                         if (defined($changed_items{$itemnum})) {
 9361:                             $new_control{$changed_items{$itemnum}} = $now;
 9362:                             push(@deletions,$file_name."\0".$control_item);
 9363:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 9364:                         } else {
 9365:                             $new_control{$control_item} = $$curr_controls{$control_item};
 9366:                         }
 9367:                     }
 9368:                 }
 9369:             }
 9370:         }
 9371:         my ($group);
 9372:         if (&is_course($domain,$user)) {
 9373:             ($group,my $file) = split(/\//,$file_name,2);
 9374:         }
 9375:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 9376:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 9377:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 9378:         #  remove lock
 9379:         my @del_lock = ($file_name."\0".'locked_access_records');
 9380:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 9381:         my $sqlresult =
 9382:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 9383:                                     $group);
 9384:     } else {
 9385:         $outcome = "error: could not obtain lockfile\n";  
 9386:     }
 9387:     return ($outcome,$deloutcome,\%new_values,\%translation);
 9388: }
 9389: 
 9390: sub make_public_indefinitely {
 9391:     my (@requrl) = @_;
 9392:     return &automated_portfile_access('public',\@requrl);
 9393: }
 9394: 
 9395: sub automated_portfile_access {
 9396:     my ($accesstype,$addsref,$delsref,$info) = @_;
 9397:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
 9398:         return 'invalid';
 9399:     }
 9400:     my %urls;
 9401:     if (ref($addsref) eq 'ARRAY') {
 9402:         foreach my $requrl (@{$addsref}) {
 9403:             if (&is_portfolio_url($requrl)) {
 9404:                 unless (exists($urls{$requrl})) {
 9405:                     $urls{$requrl} = 'add';
 9406:                 }
 9407:             }
 9408:         }
 9409:     }
 9410:     if (ref($delsref) eq 'ARRAY') {
 9411:         foreach my $requrl (@{$delsref}) { 
 9412:             if (&is_portfolio_url($requrl)) {
 9413:                 unless (exists($urls{$requrl})) {
 9414:                     $urls{$requrl} = 'delete'; 
 9415:                 }
 9416:             }
 9417:         }
 9418:     }
 9419:     unless (keys(%urls)) {
 9420:         return 'invalid';
 9421:     }
 9422:     my $ip;
 9423:     if ($accesstype eq 'ip') {
 9424:         if (ref($info) eq 'HASH') {
 9425:             if ($info->{'ip'} ne '') {
 9426:                 $ip = $info->{'ip'};
 9427:             }
 9428:         }
 9429:         if ($ip eq '') {
 9430:             return 'invalid';
 9431:         }
 9432:     }
 9433:     my $errors;
 9434:     my $now = time;
 9435:     my %current_perms;
 9436:     foreach my $requrl (sort(keys(%urls))) {
 9437:         my $action;
 9438:         if ($urls{$requrl} eq 'add') {
 9439:             $action = 'activate';
 9440:         } else {
 9441:             $action = 'none';
 9442:         }
 9443:         my $aclnum = 0;
 9444:         my (undef,$udom,$unum,$file_name,$group) =
 9445:             &parse_portfolio_url($requrl);
 9446:         unless (exists($current_perms{$unum.':'.$udom})) {
 9447:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
 9448:         }
 9449:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
 9450:                                                    $group,$file_name);
 9451:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 9452:             my ($num,$scope,$end,$start) = 
 9453:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 9454:             if ($scope eq $accesstype) {
 9455:                 if (($start <= $now) && ($end == 0)) {
 9456:                     if ($accesstype eq 'ip') {
 9457:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
 9458:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
 9459:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
 9460:                                     if ($urls{$requrl} eq 'add') {
 9461:                                         $action = 'none';
 9462:                                         last;
 9463:                                     } else {
 9464:                                         $action = 'delete';
 9465:                                         $aclnum = $num;
 9466:                                         last;
 9467:                                     }
 9468:                                 }
 9469:                             }
 9470:                         }
 9471:                     } elsif ($accesstype eq 'public') {
 9472:                         if ($urls{$requrl} eq 'add') {
 9473:                             $action = 'none';
 9474:                             last;
 9475:                         } else {
 9476:                             $action = 'delete';
 9477:                             $aclnum = $num;
 9478:                             last;
 9479:                         }
 9480:                     }
 9481:                 } elsif ($accesstype eq 'public') {
 9482:                     $action = 'update';
 9483:                     $aclnum = $num;
 9484:                     last;
 9485:                 }
 9486:             }
 9487:         }
 9488:         if ($action eq 'none') {
 9489:             next;
 9490:         } else {
 9491:             my %changes;
 9492:             my $newend = 0;
 9493:             my $newstart = $now;
 9494:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
 9495:             $changes{$action}{$newkey} = {
 9496:                 type => $accesstype,
 9497:                 time => {
 9498:                     start => $newstart,
 9499:                     end   => $newend,
 9500:                 },
 9501:             };
 9502:             if ($accesstype eq 'ip') {
 9503:                 $changes{$action}{$newkey}{'ip'} = [$ip];
 9504:             }
 9505:             my ($outcome,$deloutcome,$new_values,$translation) =
 9506:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 9507:             unless ($outcome eq 'ok') {
 9508:                 $errors .= $outcome.' ';
 9509:             }
 9510:         }
 9511:     }
 9512:     if ($errors) {
 9513:         $errors =~ s/\s$//;
 9514:         return $errors;
 9515:     } else {
 9516:         return 'ok';
 9517:     }
 9518: }
 9519: 
 9520: #------------------------------------------------------Get Marked as Read Only
 9521: 
 9522: sub get_marked_as_readonly {
 9523:     my ($domain,$user,$what,$group) = @_;
 9524:     my $current_permissions = &get_portfile_permissions($domain,$user);
 9525:     my @readonly_files;
 9526:     my $cmp1=$what;
 9527:     if (ref($what)) { $cmp1=join('',@{$what}) };
 9528:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 9529:         if (defined($group)) {
 9530:             if ($file_name !~ m-^\Q$group\E/-) {
 9531:                 next;
 9532:             }
 9533:         }
 9534:         if (ref($value) eq "ARRAY"){
 9535:             foreach my $stored_what (@{$value}) {
 9536:                 my $cmp2=$stored_what;
 9537:                 if (ref($stored_what) eq 'ARRAY') {
 9538:                     $cmp2=join('',@{$stored_what});
 9539:                 }
 9540:                 if ($cmp1 eq $cmp2) {
 9541:                     push(@readonly_files, $file_name);
 9542:                     last;
 9543:                 } elsif (!defined($what)) {
 9544:                     push(@readonly_files, $file_name);
 9545:                     last;
 9546:                 }
 9547:             }
 9548:         }
 9549:     }
 9550:     return @readonly_files;
 9551: }
 9552: #-----------------------------------------------------------Get Marked as Read Only Hash
 9553: 
 9554: sub get_marked_as_readonly_hash {
 9555:     my ($current_permissions,$group,$what) = @_;
 9556:     my %readonly_files;
 9557:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 9558:         if (defined($group)) {
 9559:             if ($file_name !~ m-^\Q$group\E/-) {
 9560:                 next;
 9561:             }
 9562:         }
 9563:         if (ref($value) eq "ARRAY"){
 9564:             foreach my $stored_what (@{$value}) {
 9565:                 if (ref($stored_what) eq 'ARRAY') {
 9566:                     foreach my $lock_descriptor(@{$stored_what}) {
 9567:                         if ($lock_descriptor eq 'graded') {
 9568:                             $readonly_files{$file_name} = 'graded';
 9569:                         } elsif ($lock_descriptor eq 'handback') {
 9570:                             $readonly_files{$file_name} = 'handback';
 9571:                         } else {
 9572:                             if (!exists($readonly_files{$file_name})) {
 9573:                                 $readonly_files{$file_name} = 'locked';
 9574:                             }
 9575:                         }
 9576:                     }
 9577:                 } 
 9578:             }
 9579:         } 
 9580:     }
 9581:     return %readonly_files;
 9582: }
 9583: # ------------------------------------------------------------ Unmark as Read Only
 9584: 
 9585: sub unmark_as_readonly {
 9586:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 9587:     # for portfolio submissions, $what contains [$symb,$crsid] 
 9588:     my ($domain,$user,$what,$file_name,$group) = @_;
 9589:     $file_name = &declutter_portfile($file_name);
 9590:     my $symb_crs = $what;
 9591:     if (ref($what)) { $symb_crs=join('',@$what); }
 9592:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 9593:     my ($tmp)=keys(%current_permissions);
 9594:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9595:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 9596:     foreach my $file (@readonly_files) {
 9597: 	my $clean_file = &declutter_portfile($file);
 9598: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 9599: 	my $current_locks = $current_permissions{$file};
 9600:         my @new_locks;
 9601:         my @del_keys;
 9602:         if (ref($current_locks) eq "ARRAY"){
 9603:             foreach my $locker (@{$current_locks}) {
 9604:                 my $compare=$locker;
 9605:                 if (ref($locker) eq 'ARRAY') {
 9606:                     $compare=join('',@{$locker});
 9607:                     if ($compare ne $symb_crs) {
 9608:                         push(@new_locks, $locker);
 9609:                     }
 9610:                 }
 9611:             }
 9612:             if (scalar(@new_locks) > 0) {
 9613:                 $current_permissions{$file} = \@new_locks;
 9614:             } else {
 9615:                 push(@del_keys, $file);
 9616:                 &del('file_permissions',\@del_keys, $domain, $user);
 9617:                 delete($current_permissions{$file});
 9618:             }
 9619:         }
 9620:     }
 9621:     &put('file_permissions',\%current_permissions,$domain,$user);
 9622:     return;
 9623: }
 9624: 
 9625: # ------------------------------------------------------------ Directory lister
 9626: 
 9627: sub dirlist {
 9628:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 9629:     $uri=~s/^\///;
 9630:     $uri=~s/\/$//;
 9631:     my ($udom, $uname);
 9632:     if ($getuserdir) {
 9633:         $udom = $userdomain;
 9634:         $uname = $username;
 9635:     } else {
 9636:         (undef,$udom,$uname)=split(/\//,$uri);
 9637:         if(defined($userdomain)) {
 9638:             $udom = $userdomain;
 9639:         }
 9640:         if(defined($username)) {
 9641:             $uname = $username;
 9642:         }
 9643:     }
 9644:     my ($dirRoot,$listing,@listing_results);
 9645: 
 9646:     $dirRoot = $perlvar{'lonDocRoot'};
 9647:     if (defined($getpropath)) {
 9648:         $dirRoot = &propath($udom,$uname);
 9649:         $dirRoot =~ s/\/$//;
 9650:     } elsif (defined($getuserdir)) {
 9651:         my $subdir=$uname.'__';
 9652:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 9653:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 9654:                    ."/$udom/$subdir/$uname";
 9655:     } elsif (defined($alternateRoot)) {
 9656:         $dirRoot = $alternateRoot;
 9657:     }
 9658: 
 9659:     if($udom) {
 9660:         if($uname) {
 9661:             my $uhome = &homeserver($uname,$udom);
 9662:             if ($uhome eq 'no_host') {
 9663:                 return ([],'no_host');
 9664:             }
 9665:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 9666:                               .$getuserdir.':'.&escape($dirRoot)
 9667:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
 9668:             if ($listing eq 'unknown_cmd') {
 9669:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
 9670:             } else {
 9671:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 9672:             }
 9673:             if ($listing eq 'unknown_cmd') {
 9674:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
 9675:                 @listing_results = split(/:/,$listing);
 9676:             } else {
 9677:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 9678:             }
 9679:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
 9680:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
 9681:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 9682:                 return ([],$listing);
 9683:             } else {
 9684:                 return (\@listing_results);
 9685:             }
 9686:         } elsif(!$alternateRoot) {
 9687:             my (%allusers,%listerror);
 9688: 	    my %servers = &get_servers($udom,'library');
 9689:  	    foreach my $tryserver (keys(%servers)) {
 9690:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 9691:                                   &escape($udom),$tryserver);
 9692:                 if ($listing eq 'unknown_cmd') {
 9693: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 9694: 				      $udom, $tryserver);
 9695:                 } else {
 9696:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 9697:                 }
 9698: 		if ($listing eq 'unknown_cmd') {
 9699: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 9700: 				      $udom, $tryserver);
 9701: 		    @listing_results = split(/:/,$listing);
 9702: 		} else {
 9703: 		    @listing_results =
 9704: 			map { &unescape($_); } split(/:/,$listing);
 9705: 		}
 9706:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
 9707:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
 9708:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 9709:                     $listerror{$tryserver} = $listing;
 9710:                 } else {
 9711: 		    foreach my $line (@listing_results) {
 9712: 			my ($entry) = split(/&/,$line,2);
 9713: 			$allusers{$entry} = 1;
 9714: 		    }
 9715: 		}
 9716:             }
 9717:             my @alluserslist=();
 9718:             foreach my $user (sort(keys(%allusers))) {
 9719:                 push(@alluserslist,$user.'&user');
 9720:             }
 9721:             return (\@alluserslist);
 9722:         } else {
 9723:             return ([],'missing username');
 9724:         }
 9725:     } elsif(!defined($getpropath)) {
 9726:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
 9727:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
 9728:         return (\@all_domains);
 9729:     } else {
 9730:         return ([],'missing domain');
 9731:     }
 9732: }
 9733: 
 9734: # --------------------------------------------- GetFileTimestamp
 9735: # This function utilizes dirlist and returns the date stamp for
 9736: # when it was last modified.  It will also return an error of -1
 9737: # if an error occurs
 9738: 
 9739: sub GetFileTimestamp {
 9740:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 9741:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 9742:     $studentName   = &LONCAPA::clean_username($studentName);
 9743:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
 9744:                                     undef,$getuserdir);
 9745:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 9746:         return -1;
 9747:     }
 9748:     if (ref($fileref) eq 'ARRAY') {
 9749:         my @stats = split('&',$fileref->[0]);
 9750:         # @stats contains first the filename, then the stat output
 9751:         return $stats[10]; # so this is 10 instead of 9.
 9752:     } else {
 9753:         return -1;
 9754:     }
 9755: }
 9756: 
 9757: sub stat_file {
 9758:     my ($uri) = @_;
 9759:     $uri = &clutter_with_no_wrapper($uri);
 9760: 
 9761:     my ($udom,$uname,$file);
 9762:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 9763: 	($udom,$uname,$file) =
 9764: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 9765: 	$file = 'userfiles/'.$file;
 9766:     }
 9767:     if ($uri =~ m-^/res/-) {
 9768: 	($udom,$uname) = 
 9769: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 9770: 	$file = $uri;
 9771:     }
 9772: 
 9773:     if (!$udom || !$uname || !$file) {
 9774: 	# unable to handle the uri
 9775: 	return ();
 9776:     }
 9777:     my $getpropath;
 9778:     if ($file =~ /^userfiles\//) {
 9779:         $getpropath = 1;
 9780:     }
 9781:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
 9782:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 9783:         return ();
 9784:     } else {
 9785:         if (ref($listref) eq 'ARRAY') {
 9786:             my @stats = split('&',$listref->[0]);
 9787: 	    shift(@stats); #filename is first
 9788: 	    return @stats;
 9789:         }
 9790:     }
 9791:     return ();
 9792: }
 9793: 
 9794: # -------------------------------------------------------- Value of a Condition
 9795: 
 9796: # gets the value of a specific preevaluated condition
 9797: #    stored in the string  $env{user.state.<cid>}
 9798: # or looks up a condition reference in the bighash and if if hasn't
 9799: # already been evaluated recurses into docondval to get the value of
 9800: # the condition, then memoizing it to 
 9801: #   $env{user.state.<cid>.<condition>}
 9802: sub directcondval {
 9803:     my $number=shift;
 9804:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 9805: 	&Apache::lonuserstate::evalstate();
 9806:     }
 9807:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 9808: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 9809:     } elsif ($number =~ /^_/) {
 9810: 	my $sub_condition;
 9811: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9812: 		&GDBM_READER(),0640)) {
 9813: 	    $sub_condition=$bighash{'conditions'.$number};
 9814: 	    untie(%bighash);
 9815: 	}
 9816: 	my $value = &docondval($sub_condition);
 9817: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 9818: 	return $value;
 9819:     }
 9820:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 9821:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 9822:     } else {
 9823:        return 2;
 9824:     }
 9825: }
 9826: 
 9827: # get the collection of conditions for this resource
 9828: sub condval {
 9829:     my $condidx=shift;
 9830:     my $allpathcond='';
 9831:     foreach my $cond (split(/\|/,$condidx)) {
 9832: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 9833: 	    $allpathcond.=
 9834: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 9835: 	}
 9836:     }
 9837:     $allpathcond=~s/\|$//;
 9838:     return &docondval($allpathcond);
 9839: }
 9840: 
 9841: #evaluates an expression of conditions
 9842: sub docondval {
 9843:     my ($allpathcond) = @_;
 9844:     my $result=0;
 9845:     if ($env{'request.course.id'}
 9846: 	&& defined($allpathcond)) {
 9847: 	my $operand='|';
 9848: 	my @stack;
 9849: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 9850: 	    if ($chunk eq '(') {
 9851: 		push @stack,($operand,$result);
 9852: 	    } elsif ($chunk eq ')') {
 9853: 		my $before=pop @stack;
 9854: 		if (pop @stack eq '&') {
 9855: 		    $result=$result>$before?$before:$result;
 9856: 		} else {
 9857: 		    $result=$result>$before?$result:$before;
 9858: 		}
 9859: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 9860: 		$operand=$chunk;
 9861: 	    } else {
 9862: 		my $new=directcondval($chunk);
 9863: 		if ($operand eq '&') {
 9864: 		    $result=$result>$new?$new:$result;
 9865: 		} else {
 9866: 		    $result=$result>$new?$result:$new;
 9867: 		}
 9868: 	    }
 9869: 	}
 9870:     }
 9871:     return $result;
 9872: }
 9873: 
 9874: # ---------------------------------------------------- Devalidate courseresdata
 9875: 
 9876: sub devalidatecourseresdata {
 9877:     my ($coursenum,$coursedomain)=@_;
 9878:     my $hashid=$coursenum.':'.$coursedomain;
 9879:     &devalidate_cache_new('courseres',$hashid);
 9880: }
 9881: 
 9882: 
 9883: # --------------------------------------------------- Course Resourcedata Query
 9884: #
 9885: #  Parameters:
 9886: #      $coursenum    - Number of the course.
 9887: #      $coursedomain - Domain at which the course was created.
 9888: #  Returns:
 9889: #     A hash of the course parameters along (I think) with timestamps
 9890: #     and version info.
 9891: 
 9892: sub get_courseresdata {
 9893:     my ($coursenum,$coursedomain)=@_;
 9894:     my $coursehom=&homeserver($coursenum,$coursedomain);
 9895:     my $hashid=$coursenum.':'.$coursedomain;
 9896:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 9897:     my %dumpreply;
 9898:     unless (defined($cached)) {
 9899: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 9900: 	$result=\%dumpreply;
 9901: 	my ($tmp) = keys(%dumpreply);
 9902: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9903: 	    &do_cache_new('courseres',$hashid,$result,600);
 9904: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 9905: 	    return $tmp;
 9906: 	} elsif ($tmp =~ /^(error)/) {
 9907: 	    $result=undef;
 9908: 	    &do_cache_new('courseres',$hashid,$result,600);
 9909: 	}
 9910:     }
 9911:     return $result;
 9912: }
 9913: 
 9914: sub devalidateuserresdata {
 9915:     my ($uname,$udom)=@_;
 9916:     my $hashid="$udom:$uname";
 9917:     &devalidate_cache_new('userres',$hashid);
 9918: }
 9919: 
 9920: sub get_userresdata {
 9921:     my ($uname,$udom)=@_;
 9922:     #most student don\'t have any data set, check if there is some data
 9923:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 9924: 
 9925:     my $hashid="$udom:$uname";
 9926:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 9927:     if (!defined($cached)) {
 9928: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 9929: 	$result=\%resourcedata;
 9930: 	&do_cache_new('userres',$hashid,$result,600);
 9931:     }
 9932:     my ($tmp)=keys(%$result);
 9933:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 9934: 	return $result;
 9935:     }
 9936:     #error 2 occurs when the .db doesn't exist
 9937:     if ($tmp!~/error: 2 /) {
 9938: 	&logthis("<font color=\"blue\">WARNING:".
 9939: 		 " Trying to get resource data for ".
 9940: 		 $uname." at ".$udom.": ".
 9941: 		 $tmp."</font>");
 9942:     } elsif ($tmp=~/error: 2 /) {
 9943: 	#&EXT_cache_set($udom,$uname);
 9944: 	&do_cache_new('userres',$hashid,undef,600);
 9945: 	undef($tmp); # not really an error so don't send it back
 9946:     }
 9947:     return $tmp;
 9948: }
 9949: #----------------------------------------------- resdata - return resource data
 9950: #  Purpose:
 9951: #    Return resource data for either users or for a course.
 9952: #  Parameters:
 9953: #     $name      - Course/user name.
 9954: #     $domain    - Name of the domain the user/course is registered on.
 9955: #     $type      - Type of thing $name is (must be 'course' or 'user'
 9956: #     @which     - Array of names of resources desired.
 9957: #  Returns:
 9958: #     The value of the first reasource in @which that is found in the
 9959: #     resource hash.
 9960: #  Exceptional Conditions:
 9961: #     If the $type passed in is not valid (not the string 'course' or 
 9962: #     'user', an undefined  reference is returned.
 9963: #     If none of the resources are found, an undef is returned
 9964: sub resdata {
 9965:     my ($name,$domain,$type,@which)=@_;
 9966:     my $result;
 9967:     if ($type eq 'course') {
 9968: 	$result=&get_courseresdata($name,$domain);
 9969:     } elsif ($type eq 'user') {
 9970: 	$result=&get_userresdata($name,$domain);
 9971:     }
 9972:     if (!ref($result)) { return $result; }    
 9973:     foreach my $item (@which) {
 9974: 	if (defined($result->{$item->[0]})) {
 9975: 	    return [$result->{$item->[0]},$item->[1]];
 9976: 	}
 9977:     }
 9978:     return undef;
 9979: }
 9980: 
 9981: sub get_numsuppfiles {
 9982:     my ($cnum,$cdom,$ignorecache)=@_;
 9983:     my $hashid=$cnum.':'.$cdom;
 9984:     my ($suppcount,$cached);
 9985:     unless ($ignorecache) {
 9986:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
 9987:     }
 9988:     unless (defined($cached)) {
 9989:         my $chome=&homeserver($cnum,$cdom);
 9990:         unless ($chome eq 'no_host') {
 9991:             ($suppcount,my $errors) = (0,0);
 9992:             my $suppmap = 'supplemental.sequence';
 9993:             ($suppcount,$errors) = 
 9994:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
 9995:         }
 9996:         &do_cache_new('suppcount',$hashid,$suppcount,600);
 9997:     }
 9998:     return $suppcount;
 9999: }
10000: 
10001: #
10002: # EXT resource caching routines
10003: #
10004: 
10005: sub clear_EXT_cache_status {
10006:     &delenv('cache.EXT.');
10007: }
10008: 
10009: sub EXT_cache_status {
10010:     my ($target_domain,$target_user) = @_;
10011:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
10012:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
10013:         # We know already the user has no data
10014:         return 1;
10015:     } else {
10016:         return 0;
10017:     }
10018: }
10019: 
10020: sub EXT_cache_set {
10021:     my ($target_domain,$target_user) = @_;
10022:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
10023:     #&appenv({$cachename => time});
10024: }
10025: 
10026: # --------------------------------------------------------- Value of a Variable
10027: sub EXT {
10028: 
10029:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
10030:     unless ($varname) { return ''; }
10031:     #get real user name/domain, courseid and symb
10032:     my $courseid;
10033:     my $publicuser;
10034:     if ($symbparm) {
10035: 	$symbparm=&get_symb_from_alias($symbparm);
10036:     }
10037:     if (!($uname && $udom)) {
10038:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
10039:       if (!$symbparm) {	$symbparm=$cursymb; }
10040:     } else {
10041: 	$courseid=$env{'request.course.id'};
10042:     }
10043:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
10044:     my $rest;
10045:     if (defined($therest[0])) {
10046:        $rest=join('.',@therest);
10047:     } else {
10048:        $rest='';
10049:     }
10050: 
10051:     my $qualifierrest=$qualifier;
10052:     if ($rest) { $qualifierrest.='.'.$rest; }
10053:     my $spacequalifierrest=$space;
10054:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
10055:     if ($realm eq 'user') {
10056: # --------------------------------------------------------------- user.resource
10057: 	if ($space eq 'resource') {
10058: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
10059: 		  || defined($Apache::lonhomework::parsing_a_task))
10060: 		 &&
10061: 		 ($symbparm eq &symbread()) ) {	
10062: 		# if we are in the middle of processing the resource the
10063: 		# get the value we are planning on committing
10064:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
10065:                     return $Apache::lonhomework::results{$qualifierrest};
10066:                 } else {
10067:                     return $Apache::lonhomework::history{$qualifierrest};
10068:                 }
10069: 	    } else {
10070: 		my %restored;
10071: 		if ($publicuser || $env{'request.state'} eq 'construct') {
10072: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
10073: 		} else {
10074: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
10075: 		}
10076: 		return $restored{$qualifierrest};
10077: 	    }
10078: # ----------------------------------------------------------------- user.access
10079:         } elsif ($space eq 'access') {
10080: 	    # FIXME - not supporting calls for a specific user
10081:             return &allowed($qualifier,$rest);
10082: # ------------------------------------------ user.preferences, user.environment
10083:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
10084: 	    if (($uname eq $env{'user.name'}) &&
10085: 		($udom eq $env{'user.domain'})) {
10086: 		return $env{join('.',('environment',$qualifierrest))};
10087: 	    } else {
10088: 		my %returnhash;
10089: 		if (!$publicuser) {
10090: 		    %returnhash=&userenvironment($udom,$uname,
10091: 						 $qualifierrest);
10092: 		}
10093: 		return $returnhash{$qualifierrest};
10094: 	    }
10095: # ----------------------------------------------------------------- user.course
10096:         } elsif ($space eq 'course') {
10097: 	    # FIXME - not supporting calls for a specific user
10098:             return $env{join('.',('request.course',$qualifier))};
10099: # ------------------------------------------------------------------- user.role
10100:         } elsif ($space eq 'role') {
10101: 	    # FIXME - not supporting calls for a specific user
10102:             my ($role,$where)=split(/\./,$env{'request.role'});
10103:             if ($qualifier eq 'value') {
10104: 		return $role;
10105:             } elsif ($qualifier eq 'extent') {
10106:                 return $where;
10107:             }
10108: # ----------------------------------------------------------------- user.domain
10109:         } elsif ($space eq 'domain') {
10110:             return $udom;
10111: # ------------------------------------------------------------------- user.name
10112:         } elsif ($space eq 'name') {
10113:             return $uname;
10114: # ---------------------------------------------------- Any other user namespace
10115:         } else {
10116: 	    my %reply;
10117: 	    if (!$publicuser) {
10118: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
10119: 	    }
10120: 	    return $reply{$qualifierrest};
10121:         }
10122:     } elsif ($realm eq 'query') {
10123: # ---------------------------------------------- pull stuff out of query string
10124:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
10125: 						[$spacequalifierrest]);
10126: 	return $env{'form.'.$spacequalifierrest}; 
10127:    } elsif ($realm eq 'request') {
10128: # ------------------------------------------------------------- request.browser
10129:         if ($space eq 'browser') {
10130:             return $env{'browser.'.$qualifier};
10131: # ------------------------------------------------------------ request.filename
10132:         } else {
10133:             return $env{'request.'.$spacequalifierrest};
10134:         }
10135:     } elsif ($realm eq 'course') {
10136: # ---------------------------------------------------------- course.description
10137:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
10138:     } elsif ($realm eq 'resource') {
10139: 
10140: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
10141: 	    if (!$symbparm) { $symbparm=&symbread(); }
10142: 	}
10143: 
10144:         if ($qualifier eq '') {
10145: 	    if ($space eq 'title') {
10146: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
10147: 	        return &gettitle($symbparm);
10148: 	    }
10149: 	
10150: 	    if ($space eq 'map') {
10151: 	        my ($map) = &decode_symb($symbparm);
10152: 	        return &symbread($map);
10153: 	    }
10154:             if ($space eq 'maptitle') {
10155:                 my ($map) = &decode_symb($symbparm);
10156:                 return &gettitle($map);
10157:             }
10158: 	    if ($space eq 'filename') {
10159: 	        if ($symbparm) {
10160: 		    return &clutter((&decode_symb($symbparm))[2]);
10161: 	        }
10162: 	        return &hreflocation('',$env{'request.filename'});
10163: 	    }
10164: 
10165:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
10166:                 if ($space eq 'visibleparts') {
10167:                     my $navmap = Apache::lonnavmaps::navmap->new();
10168:                     my $item;
10169:                     if (ref($navmap)) {
10170:                         my $res = $navmap->getBySymb($symbparm);
10171:                         my $parts = $res->parts();
10172:                         if (ref($parts) eq 'ARRAY') {
10173:                             $item = join(',',@{$parts});
10174:                         }
10175:                         undef($navmap);
10176:                     }
10177:                     return $item;
10178:                 }
10179:             }
10180:         }
10181: 
10182: 	my ($section, $group, @groups);
10183: 	my ($courselevelm,$courselevel);
10184:         if (($courseid eq '') && ($cid)) {
10185:             $courseid = $cid;
10186:         }
10187: 	if (($symbparm && $courseid) && 
10188: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
10189: 
10190: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
10191: 
10192: # ----------------------------------------------------- Cascading lookup scheme
10193: 	    my $symbp=$symbparm;
10194: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
10195: 
10196: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
10197: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
10198: 
10199: 	    if (($env{'user.name'} eq $uname) &&
10200: 		($env{'user.domain'} eq $udom)) {
10201: 		$section=$env{'request.course.sec'};
10202:                 @groups = split(/:/,$env{'request.course.groups'});  
10203:                 @groups=&sort_course_groups($courseid,@groups); 
10204: 	    } else {
10205: 		if (! defined($usection)) {
10206: 		    $section=&getsection($udom,$uname,$courseid);
10207: 		} else {
10208: 		    $section = $usection;
10209: 		}
10210:                 @groups = &get_users_groups($udom,$uname,$courseid);
10211: 	    }
10212: 
10213: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
10214: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
10215: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
10216: 
10217: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
10218: 	    my $courselevelr=$courseid.'.'.$symbparm;
10219: 	    $courselevelm=$courseid.'.'.$mapparm;
10220: 
10221: # ----------------------------------------------------------- first, check user
10222: 
10223: 	    my $userreply=&resdata($uname,$udom,'user',
10224: 				       ([$courselevelr,'resource'],
10225: 					[$courselevelm,'map'     ],
10226: 					[$courselevel, 'course'  ]));
10227: 	    if (defined($userreply)) { return &get_reply($userreply); }
10228: 
10229: # ------------------------------------------------ second, check some of course
10230:             my $coursereply;
10231:             if (@groups > 0) {
10232:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
10233:                                        $mapparm,$spacequalifierrest);
10234:                 if (defined($coursereply)) { return &get_reply($coursereply); }
10235:             }
10236: 
10237: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10238: 				  $env{'course.'.$courseid.'.domain'},
10239: 				  'course',
10240: 				  ([$seclevelr,   'resource'],
10241: 				   [$seclevelm,   'map'     ],
10242: 				   [$seclevel,    'course'  ],
10243: 				   [$courselevelr,'resource']));
10244: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
10245: 
10246: # ------------------------------------------------------ third, check map parms
10247: 	    my %parmhash=();
10248: 	    my $thisparm='';
10249: 	    if (tie(%parmhash,'GDBM_File',
10250: 		    $env{'request.course.fn'}.'_parms.db',
10251: 		    &GDBM_READER(),0640)) {
10252: 		$thisparm=$parmhash{$symbparm};
10253: 		untie(%parmhash);
10254: 	    }
10255: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
10256: 	}
10257: # ------------------------------------------ fourth, look in resource metadata
10258: 
10259: 	$spacequalifierrest=~s/\./\_/;
10260: 	my $filename;
10261: 	if (!$symbparm) { $symbparm=&symbread(); }
10262: 	if ($symbparm) {
10263: 	    $filename=(&decode_symb($symbparm))[2];
10264: 	} else {
10265: 	    $filename=$env{'request.filename'};
10266: 	}
10267: 	my $metadata=&metadata($filename,$spacequalifierrest);
10268: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
10269: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
10270: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
10271: 
10272: # ---------------------------------------------- fourth, look in rest of course
10273: 	if ($symbparm && defined($courseid) && 
10274: 	    $courseid eq $env{'request.course.id'}) {
10275: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10276: 				     $env{'course.'.$courseid.'.domain'},
10277: 				     'course',
10278: 				     ([$courselevelm,'map'   ],
10279: 				      [$courselevel, 'course']));
10280: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
10281: 	}
10282: # ------------------------------------------------------------------ Cascade up
10283: 	unless ($space eq '0') {
10284: 	    my @parts=split(/_/,$space);
10285: 	    my $id=pop(@parts);
10286: 	    my $part=join('_',@parts);
10287: 	    if ($part eq '') { $part='0'; }
10288: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
10289: 				 $symbparm,$udom,$uname,$section,1);
10290: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
10291: 	}
10292: 	if ($recurse) { return undef; }
10293: 	my $pack_def=&packages_tab_default($filename,$varname);
10294: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
10295: # ---------------------------------------------------- Any other user namespace
10296:     } elsif ($realm eq 'environment') {
10297: # ----------------------------------------------------------------- environment
10298: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
10299: 	    return $env{'environment.'.$spacequalifierrest};
10300: 	} else {
10301: 	    if ($uname eq 'anonymous' && $udom eq '') {
10302: 		return '';
10303: 	    }
10304: 	    my %returnhash=&userenvironment($udom,$uname,
10305: 					    $spacequalifierrest);
10306: 	    return $returnhash{$spacequalifierrest};
10307: 	}
10308:     } elsif ($realm eq 'system') {
10309: # ----------------------------------------------------------------- system.time
10310: 	if ($space eq 'time') {
10311: 	    return time;
10312:         }
10313:     } elsif ($realm eq 'server') {
10314: # ----------------------------------------------------------------- system.time
10315: 	if ($space eq 'name') {
10316: 	    return $ENV{'SERVER_NAME'};
10317:         }
10318:     }
10319:     return '';
10320: }
10321: 
10322: sub get_reply {
10323:     my ($reply_value) = @_;
10324:     if (ref($reply_value) eq 'ARRAY') {
10325:         if (wantarray) {
10326: 	    return @$reply_value;
10327:         }
10328:         return $reply_value->[0];
10329:     } else {
10330:         return $reply_value;
10331:     }
10332: }
10333: 
10334: sub check_group_parms {
10335:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10336:     my @groupitems = ();
10337:     my $resultitem;
10338:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
10339:     foreach my $group (@{$groups}) {
10340:         foreach my $level (@levels) {
10341:              my $item = $courseid.'.['.$group.'].'.$level->[0];
10342:              push(@groupitems,[$item,$level->[1]]);
10343:         }
10344:     }
10345:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10346:                             $env{'course.'.$courseid.'.domain'},
10347:                                      'course',@groupitems);
10348:     return $coursereply;
10349: }
10350: 
10351: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
10352:     my ($courseid,@groups) = @_;
10353:     @groups = sort(@groups);
10354:     return @groups;
10355: }
10356: 
10357: sub packages_tab_default {
10358:     my ($uri,$varname)=@_;
10359:     my (undef,$part,$name)=split(/\./,$varname);
10360: 
10361:     my (@extension,@specifics,$do_default);
10362:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
10363: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
10364: 	if ($pack_type eq 'default') {
10365: 	    $do_default=1;
10366: 	} elsif ($pack_type eq 'extension') {
10367: 	    push(@extension,[$package,$pack_type,$pack_part]);
10368: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
10369: 	    # only look at packages defaults for packages that this id is
10370: 	    push(@specifics,[$package,$pack_type,$pack_part]);
10371: 	}
10372:     }
10373:     # first look for a package that matches the requested part id
10374:     foreach my $package (@specifics) {
10375: 	my (undef,$pack_type,$pack_part)=@{$package};
10376: 	next if ($pack_part ne $part);
10377: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10378: 	    return $packagetab{"$pack_type&$name&default"};
10379: 	}
10380:     }
10381:     # look for any possible matching non extension_ package
10382:     foreach my $package (@specifics) {
10383: 	my (undef,$pack_type,$pack_part)=@{$package};
10384: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10385: 	    return $packagetab{"$pack_type&$name&default"};
10386: 	}
10387: 	if ($pack_type eq 'part') { $pack_part='0'; }
10388: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10389: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
10390: 	}
10391:     }
10392:     # look for any posible extension_ match
10393:     foreach my $package (@extension) {
10394: 	my ($package,$pack_type)=@{$package};
10395: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10396: 	    return $packagetab{"$pack_type&$name&default"};
10397: 	}
10398: 	if (defined($packagetab{$package."&$name&default"})) {
10399: 	    return $packagetab{$package."&$name&default"};
10400: 	}
10401:     }
10402:     # look for a global default setting
10403:     if ($do_default && defined($packagetab{"default&$name&default"})) {
10404: 	return $packagetab{"default&$name&default"};
10405:     }
10406:     return undef;
10407: }
10408: 
10409: sub add_prefix_and_part {
10410:     my ($prefix,$part)=@_;
10411:     my $keyroot;
10412:     if (defined($prefix) && $prefix !~ /^__/) {
10413: 	# prefix that has a part already
10414: 	$keyroot=$prefix;
10415:     } elsif (defined($prefix)) {
10416: 	# prefix that is missing a part
10417: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10418:     } else {
10419: 	# no prefix at all
10420: 	if (defined($part)) { $keyroot='_'.$part; }
10421:     }
10422:     return $keyroot;
10423: }
10424: 
10425: # ---------------------------------------------------------------- Get metadata
10426: 
10427: my %metaentry;
10428: my %importedpartids;
10429: sub metadata {
10430:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
10431:     $uri=&declutter($uri);
10432:     # if it is a non metadata possible uri return quickly
10433:     if (($uri eq '') || 
10434: 	(($uri =~ m|^/*adm/|) && 
10435: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
10436:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
10437: 	return undef;
10438:     }
10439:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
10440: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
10441: 	return undef;
10442:     }
10443:     my $filename=$uri;
10444:     $uri=~s/\.meta$//;
10445: #
10446: # Is the metadata already cached?
10447: # Look at timestamp of caching
10448: # Everything is cached by the main uri, libraries are never directly cached
10449: #
10450:     if (!defined($liburi)) {
10451: 	my ($result,$cached)=&is_cached_new('meta',$uri);
10452: 	if (defined($cached)) { return $result->{':'.$what}; }
10453:     }
10454:     {
10455: # Imported parts would go here
10456:         my %importedids=();
10457:         my @origfileimportpartids=();
10458:         my $importedparts=0;
10459: #
10460: # Is this a recursive call for a library?
10461: #
10462: #	if (! exists($metacache{$uri})) {
10463: #	    $metacache{$uri}={};
10464: #	}
10465: 	my $cachetime = 60*60;
10466:         if ($liburi) {
10467: 	    $liburi=&declutter($liburi);
10468:             $filename=$liburi;
10469:         } else {
10470: 	    &devalidate_cache_new('meta',$uri);
10471: 	    undef(%metaentry);
10472: 	}
10473:         my %metathesekeys=();
10474:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
10475: 	my $metastring;
10476: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
10477: 	    my $which = &hreflocation('','/'.($liburi || $uri));
10478: 	    $metastring = 
10479: 		&Apache::lonnet::ssi_body($which,
10480: 					  ('grade_target' => 'meta'));
10481: 	    $cachetime = 1; # only want this cached in the child not long term
10482: 	} elsif (($uri !~ m -^(editupload)/-) && 
10483:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
10484: 	    my $file=&filelocation('',&clutter($filename));
10485: 	    #push(@{$metaentry{$uri.'.file'}},$file);
10486: 	    $metastring=&getfile($file);
10487: 	}
10488:         my $parser=HTML::LCParser->new(\$metastring);
10489:         my $token;
10490:         undef %metathesekeys;
10491:         while ($token=$parser->get_token) {
10492: 	    if ($token->[0] eq 'S') {
10493: 		if (defined($token->[2]->{'package'})) {
10494: #
10495: # This is a package - get package info
10496: #
10497: 		    my $package=$token->[2]->{'package'};
10498: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10499: 		    if (defined($token->[2]->{'id'})) { 
10500: 			$keyroot.='_'.$token->[2]->{'id'}; 
10501: 		    }
10502: 		    if ($metaentry{':packages'}) {
10503: 			$metaentry{':packages'}.=','.$package.$keyroot;
10504: 		    } else {
10505: 			$metaentry{':packages'}=$package.$keyroot;
10506: 		    }
10507: 		    foreach my $pack_entry (keys(%packagetab)) {
10508: 			my $part=$keyroot;
10509: 			$part=~s/^\_//;
10510: 			if ($pack_entry=~/^\Q$package\E\&/ || 
10511: 			    $pack_entry=~/^\Q$package\E_0\&/) {
10512: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
10513: 			    # ignore package.tab specified default values
10514:                             # here &package_tab_default() will fetch those
10515: 			    if ($subp eq 'default') { next; }
10516: 			    my $value=$packagetab{$pack_entry};
10517: 			    my $unikey;
10518: 			    if ($pack =~ /_0$/) {
10519: 				$unikey='parameter_0_'.$name;
10520: 				$part=0;
10521: 			    } else {
10522: 				$unikey='parameter'.$keyroot.'_'.$name;
10523: 			    }
10524: 			    if ($subp eq 'display') {
10525: 				$value.=' [Part: '.$part.']';
10526: 			    }
10527: 			    $metaentry{':'.$unikey.'.part'}=$part;
10528: 			    $metathesekeys{$unikey}=1;
10529: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10530: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
10531: 			    }
10532: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
10533: 				$metaentry{':'.$unikey}=
10534: 				    $metaentry{':'.$unikey.'.default'};
10535: 			    }
10536: 			}
10537: 		    }
10538: 		} else {
10539: #
10540: # This is not a package - some other kind of start tag
10541: #
10542: 		    my $entry=$token->[1];
10543: 		    my $unikey='';
10544: 
10545: 		    if ($entry eq 'import') {
10546: #
10547: # Importing a library here
10548: #
10549:                         my $location=$parser->get_text('/import');
10550:                         my $dir=$filename;
10551:                         $dir=~s|[^/]*$||;
10552:                         $location=&filelocation($dir,$location);
10553:                        
10554:                         my $importmode=$token->[2]->{'importmode'};
10555:                         if ($importmode eq 'problem') {
10556: # Import as problem/response
10557:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10558:                         } elsif ($importmode eq 'part') {
10559: # Import as part(s)
10560:                            $importedparts=1;
10561: # We need to get the original file and the imported file to get the part order correct
10562: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10563: # Load and inspect original file
10564:                            if ($#origfileimportpartids<0) {
10565:                               undef(%importedpartids);
10566:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10567:                               my $origfile=&getfile($origfilelocation);
10568:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10569:                            }
10570: 
10571: # Load and inspect imported file
10572:                            my $impfile=&getfile($location);
10573:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10574:                            if ($#impfilepartids>=0) {
10575: # This problem had parts
10576:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
10577:                            } else {
10578: # Importing by turning a single problem into a problem part
10579: # It gets the import-tags ID as part-ID
10580:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
10581:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
10582:                            }
10583:                         } else {
10584: # Normal import
10585:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10586:                            if (defined($token->[2]->{'id'})) {
10587:                               $unikey.='_'.$token->[2]->{'id'};
10588:                            }
10589:                         }
10590: 
10591: 			if ($depthcount<20) {
10592: 			    my $metadata = 
10593: 				&metadata($uri,'keys', $location,$unikey,
10594: 					  $depthcount+1);
10595: 			    foreach my $meta (split(',',$metadata)) {
10596: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
10597: 				$metathesekeys{$meta}=1;
10598: 			    }
10599: 			
10600:                         }
10601: 		    } else {
10602: #
10603: # Not importing, some other kind of non-package, non-library start tag
10604: # 
10605:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10606:                         if (defined($token->[2]->{'id'})) {
10607:                             $unikey.='_'.$token->[2]->{'id'};
10608:                         }
10609: 			if (defined($token->[2]->{'name'})) { 
10610: 			    $unikey.='_'.$token->[2]->{'name'}; 
10611: 			}
10612: 			$metathesekeys{$unikey}=1;
10613: 			foreach my $param (@{$token->[3]}) {
10614: 			    $metaentry{':'.$unikey.'.'.$param} =
10615: 				$token->[2]->{$param};
10616: 			}
10617: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
10618: 			my $default=$metaentry{':'.$unikey.'.default'};
10619: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10620: 		 # only ws inside the tag, and not in default, so use default
10621: 		 # as value
10622: 			    $metaentry{':'.$unikey}=$default;
10623: 			} elsif ( $internaltext =~ /\S/ ) {
10624: 		  # something interesting inside the tag
10625: 			    $metaentry{':'.$unikey}=$internaltext;
10626: 			} else {
10627: 		  # no interesting values, don't set a default
10628: 			}
10629: # end of not-a-package not-a-library import
10630: 		    }
10631: # end of not-a-package start tag
10632: 		}
10633: # the next is the end of "start tag"
10634: 	    }
10635: 	}
10636: 	my ($extension) = ($uri =~ /\.(\w+)$/);
10637: 	$extension = lc($extension);
10638: 	if ($extension eq 'htm') { $extension='html'; }
10639: 
10640: 	foreach my $key (keys(%packagetab)) {
10641: 	    #no specific packages #how's our extension
10642: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
10643: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
10644: 					 \%metathesekeys);
10645: 	}
10646: 
10647: 	if (!exists($metaentry{':packages'})
10648: 	    || $packagetab{"import_defaults&extension_$extension"}) {
10649: 	    foreach my $key (keys(%packagetab)) {
10650: 		#no specific packages well let's get default then
10651: 		if ($key!~/^default&/) { next; }
10652: 		&metadata_create_package_def($uri,$key,'default',
10653: 					     \%metathesekeys);
10654: 	    }
10655: 	}
10656: # are there custom rights to evaluate
10657: 	if ($metaentry{':copyright'} eq 'custom') {
10658: 
10659:     #
10660:     # Importing a rights file here
10661:     #
10662: 	    unless ($depthcount) {
10663: 		my $location=$metaentry{':customdistributionfile'};
10664: 		my $dir=$filename;
10665: 		$dir=~s|[^/]*$||;
10666: 		$location=&filelocation($dir,$location);
10667: 		my $rights_metadata =
10668: 		    &metadata($uri,'keys',$location,'_rights',
10669: 			      $depthcount+1);
10670: 		foreach my $rights (split(',',$rights_metadata)) {
10671: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10672: 		    $metathesekeys{$rights}=1;
10673: 		}
10674: 	    }
10675: 	}
10676: 	# uniqifiy package listing
10677: 	my %seen;
10678: 	my @uniq_packages =
10679: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10680: 	$metaentry{':packages'} = join(',',@uniq_packages);
10681: 
10682:         if ($importedparts) {
10683: # We had imported parts and need to rebuild partorder
10684:            $metaentry{':partorder'}='';
10685:            $metathesekeys{'partorder'}=1;
10686:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10687:                if ($origfileimportpartids[$index] eq 'part') {
10688: # original part, part of the problem
10689:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10690:                } else {
10691: # we have imported parts at this position
10692:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10693:                }
10694:            }
10695:            $metaentry{':partorder'}=~s/^\,//;
10696:         }
10697: 
10698: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
10699: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
10700: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
10701: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
10702: # this is the end of "was not already recently cached
10703:     }
10704:     return $metaentry{':'.$what};
10705: }
10706: 
10707: sub metadata_create_package_def {
10708:     my ($uri,$key,$package,$metathesekeys)=@_;
10709:     my ($pack,$name,$subp)=split(/\&/,$key);
10710:     if ($subp eq 'default') { next; }
10711:     
10712:     if (defined($metaentry{':packages'})) {
10713: 	$metaentry{':packages'}.=','.$package;
10714:     } else {
10715: 	$metaentry{':packages'}=$package;
10716:     }
10717:     my $value=$packagetab{$key};
10718:     my $unikey;
10719:     $unikey='parameter_0_'.$name;
10720:     $metaentry{':'.$unikey.'.part'}=0;
10721:     $$metathesekeys{$unikey}=1;
10722:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10723: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
10724:     }
10725:     if (defined($metaentry{':'.$unikey.'.default'})) {
10726: 	$metaentry{':'.$unikey}=
10727: 	    $metaentry{':'.$unikey.'.default'};
10728:     }
10729: }
10730: 
10731: sub metadata_generate_part0 {
10732:     my ($metadata,$metacache,$uri) = @_;
10733:     my %allnames;
10734:     foreach my $metakey (keys(%$metadata)) {
10735: 	if ($metakey=~/^parameter\_(.*)/) {
10736: 	  my $part=$$metacache{':'.$metakey.'.part'};
10737: 	  my $name=$$metacache{':'.$metakey.'.name'};
10738: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
10739: 	    $allnames{$name}=$part;
10740: 	  }
10741: 	}
10742:     }
10743:     foreach my $name (keys(%allnames)) {
10744:       $$metadata{"parameter_0_$name"}=1;
10745:       my $key=":parameter_0_$name";
10746:       $$metacache{"$key.part"}='0';
10747:       $$metacache{"$key.name"}=$name;
10748:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
10749: 					   $allnames{$name}.'_'.$name.
10750: 					   '.type'};
10751:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
10752: 			     '.display'};
10753:       my $expr='[Part: '.$allnames{$name}.']';
10754:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
10755:       $$metacache{"$key.display"}=$olddis;
10756:     }
10757: }
10758: 
10759: # ------------------------------------------------------ Devalidate title cache
10760: 
10761: sub devalidate_title_cache {
10762:     my ($url)=@_;
10763:     if (!$env{'request.course.id'}) { return; }
10764:     my $symb=&symbread($url);
10765:     if (!$symb) { return; }
10766:     my $key=$env{'request.course.id'}."\0".$symb;
10767:     &devalidate_cache_new('title',$key);
10768: }
10769: 
10770: # ------------------------------------------------- Get the title of a course
10771: 
10772: sub current_course_title {
10773:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10774: }
10775: # ------------------------------------------------- Get the title of a resource
10776: 
10777: sub gettitle {
10778:     my $urlsymb=shift;
10779:     my $symb=&symbread($urlsymb);
10780:     if ($symb) {
10781: 	my $key=$env{'request.course.id'}."\0".$symb;
10782: 	my ($result,$cached)=&is_cached_new('title',$key);
10783: 	if (defined($cached)) { 
10784: 	    return $result;
10785: 	}
10786: 	my ($map,$resid,$url)=&decode_symb($symb);
10787: 	my $title='';
10788: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10789: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10790: 	} else {
10791: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10792: 		    &GDBM_READER(),0640)) {
10793: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
10794: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
10795: 		untie(%bighash);
10796: 	    }
10797: 	}
10798: 	$title=~s/\&colon\;/\:/gs;
10799: 	if ($title) {
10800: # Remember both $symb and $title for dynamic metadata
10801:             $accesshash{$symb.'___crstitle'}=$title;
10802:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
10803: # Cache this title and then return it
10804: 	    return &do_cache_new('title',$key,$title,600);
10805: 	}
10806: 	$urlsymb=$url;
10807:     }
10808:     my $title=&metadata($urlsymb,'title');
10809:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
10810:     return $title;
10811: }
10812: 
10813: sub get_slot {
10814:     my ($which,$cnum,$cdom)=@_;
10815:     if (!$cnum || !$cdom) {
10816: 	(undef,my $courseid)=&whichuser();
10817: 	$cdom=$env{'course.'.$courseid.'.domain'};
10818: 	$cnum=$env{'course.'.$courseid.'.num'};
10819:     }
10820:     my $key=join("\0",'slots',$cdom,$cnum,$which);
10821:     my %slotinfo;
10822:     if (exists($remembered{$key})) {
10823: 	$slotinfo{$which} = $remembered{$key};
10824:     } else {
10825: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
10826: 	&Apache::lonhomework::showhash(%slotinfo);
10827: 	my ($tmp)=keys(%slotinfo);
10828: 	if ($tmp=~/^error:/) { return (); }
10829: 	$remembered{$key} = $slotinfo{$which};
10830:     }
10831:     if (ref($slotinfo{$which}) eq 'HASH') {
10832: 	return %{$slotinfo{$which}};
10833:     }
10834:     return $slotinfo{$which};
10835: }
10836: 
10837: sub get_reservable_slots {
10838:     my ($cnum,$cdom,$uname,$udom) = @_;
10839:     my $now = time;
10840:     my $reservable_info;
10841:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10842:     if (exists($remembered{$key})) {
10843:         $reservable_info = $remembered{$key};
10844:     } else {
10845:         my %resv;
10846:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10847:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10848:         $reservable_info = \%resv;
10849:         $remembered{$key} = $reservable_info;
10850:     }
10851:     return $reservable_info;
10852: }
10853: 
10854: sub get_course_slots {
10855:     my ($cnum,$cdom) = @_;
10856:     my $hashid=$cnum.':'.$cdom;
10857:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10858:     if (defined($cached)) {
10859:         if (ref($result) eq 'HASH') {
10860:             return %{$result};
10861:         }
10862:     } else {
10863:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10864:         my ($tmp) = keys(%slots);
10865:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10866:             &do_cache_new('allslots',$hashid,\%slots,600);
10867:             return %slots;
10868:         }
10869:     }
10870:     return;
10871: }
10872: 
10873: sub devalidate_slots_cache {
10874:     my ($cnum,$cdom)=@_;
10875:     my $hashid=$cnum.':'.$cdom;
10876:     &devalidate_cache_new('allslots',$hashid);
10877: }
10878: 
10879: sub get_coursechange {
10880:     my ($cdom,$cnum) = @_;
10881:     if ($cdom eq '' || $cnum eq '') {
10882:         return unless ($env{'request.course.id'});
10883:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10884:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10885:     }
10886:     my $hashid=$cdom.'_'.$cnum;
10887:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
10888:     if ((defined($cached)) && ($change ne '')) {
10889:         return $change;
10890:     } else {
10891:         my %crshash;
10892:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10893:         if ($crshash{'internal.contentchange'} eq '') {
10894:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
10895:             if ($change eq '') {
10896:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
10897:                 $change = $crshash{'internal.created'};
10898:             }
10899:         } else {
10900:             $change = $crshash{'internal.contentchange'};
10901:         }
10902:         my $cachetime = 600;
10903:         &do_cache_new('crschange',$hashid,$change,$cachetime);
10904:     }
10905:     return $change;
10906: }
10907: 
10908: sub devalidate_coursechange_cache {
10909:     my ($cnum,$cdom)=@_;
10910:     my $hashid=$cnum.':'.$cdom;
10911:     &devalidate_cache_new('crschange',$hashid);
10912: }
10913: 
10914: # ------------------------------------------------- Update symbolic store links
10915: 
10916: sub symblist {
10917:     my ($mapname,%newhash)=@_;
10918:     $mapname=&deversion(&declutter($mapname));
10919:     my %hash;
10920:     if (($env{'request.course.fn'}) && (%newhash)) {
10921:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10922:                       &GDBM_WRCREAT(),0640)) {
10923: 	    foreach my $url (keys(%newhash)) {
10924: 		next if ($url eq 'last_known'
10925: 			 && $env{'form.no_update_last_known'});
10926: 		$hash{declutter($url)}=&encode_symb($mapname,
10927: 						    $newhash{$url}->[1],
10928: 						    $newhash{$url}->[0]);
10929:             }
10930:             if (untie(%hash)) {
10931: 		return 'ok';
10932:             }
10933:         }
10934:     }
10935:     return 'error';
10936: }
10937: 
10938: # --------------------------------------------------------------- Verify a symb
10939: 
10940: sub symbverify {
10941:     my ($symb,$thisurl,$encstate)=@_;
10942:     my $thisfn=$thisurl;
10943:     $thisfn=&declutter($thisfn);
10944: # direct jump to resource in page or to a sequence - will construct own symbs
10945:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10946: # check URL part
10947:     my ($map,$resid,$url)=&decode_symb($symb);
10948: 
10949:     unless ($url eq $thisfn) { return 0; }
10950: 
10951:     $symb=&symbclean($symb);
10952:     $thisurl=&deversion($thisurl);
10953:     $thisfn=&deversion($thisfn);
10954: 
10955:     my %bighash;
10956:     my $okay=0;
10957: 
10958:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10959:                             &GDBM_READER(),0640)) {
10960:         my $noclutter;
10961:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10962:             $thisurl =~ s/\?.+$//;
10963:             if ($map =~ m{^uploaded/.+\.page$}) {
10964:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
10965:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
10966:                 $noclutter = 1;
10967:             }
10968:         }
10969:         my $ids;
10970:         if ($noclutter) {
10971:             $ids=$bighash{'ids_'.$thisurl};
10972:         } else {
10973:             $ids=$bighash{'ids_'.&clutter($thisurl)};
10974:         }
10975:         unless ($ids) {
10976:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
10977:             $ids=$bighash{$idkey};
10978:         }
10979:         if ($ids) {
10980: # ------------------------------------------------------------------- Has ID(s)
10981:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
10982:                 $symb =~ s/\?.+$//;
10983:             }
10984: 	    foreach my $id (split(/\,/,$ids)) {
10985: 	       my ($mapid,$resid)=split(/\./,$id);
10986:                if (
10987:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
10988:    eq $symb) {
10989:                    if (ref($encstate)) {
10990:                        $$encstate = $bighash{'encrypted_'.$id};
10991:                    }
10992: 		   if (($env{'request.role.adv'}) ||
10993: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
10994:                        ($thisurl eq '/adm/navmaps')) {
10995: 		       $okay=1;
10996:                        last;
10997: 		   }
10998: 	       }
10999: 	   }
11000:         }
11001: 	untie(%bighash);
11002:     }
11003:     return $okay;
11004: }
11005: 
11006: # --------------------------------------------------------------- Clean-up symb
11007: 
11008: sub symbclean {
11009:     my $symb=shift;
11010:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
11011: # remove version from map
11012:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
11013: 
11014: # remove version from URL
11015:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
11016: 
11017: # remove wrapper
11018: 
11019:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
11020:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
11021:     return $symb;
11022: }
11023: 
11024: # ---------------------------------------------- Split symb to find map and url
11025: 
11026: sub encode_symb {
11027:     my ($map,$resid,$url)=@_;
11028:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
11029: }
11030: 
11031: sub decode_symb {
11032:     my $symb=shift;
11033:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
11034:     my ($map,$resid,$url)=split(/___/,$symb);
11035:     return (&fixversion($map),$resid,&fixversion($url));
11036: }
11037: 
11038: sub fixversion {
11039:     my $fn=shift;
11040:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
11041:     my %bighash;
11042:     my $uri=&clutter($fn);
11043:     my $key=$env{'request.course.id'}.'_'.$uri;
11044: # is this cached?
11045:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
11046:     if (defined($cached)) { return $result; }
11047: # unfortunately not cached, or expired
11048:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11049: 	    &GDBM_READER(),0640)) {
11050:  	if ($bighash{'version_'.$uri}) {
11051:  	    my $version=$bighash{'version_'.$uri};
11052:  	    unless (($version eq 'mostrecent') || 
11053: 		    ($version==&getversion($uri))) {
11054:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
11055:  	    }
11056:  	}
11057:  	untie %bighash;
11058:     }
11059:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
11060: }
11061: 
11062: sub deversion {
11063:     my $url=shift;
11064:     $url=~s/\.\d+\.(\w+)$/\.$1/;
11065:     return $url;
11066: }
11067: 
11068: # ------------------------------------------------------ Return symb list entry
11069: 
11070: sub symbread {
11071:     my ($thisfn,$donotrecurse)=@_;
11072:     my $cache_str='request.symbread.cached.'.$thisfn;
11073:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
11074: # no filename provided? try from environment
11075:     unless ($thisfn) {
11076:         if ($env{'request.symb'}) {
11077: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
11078: 	}
11079: 	$thisfn=$env{'request.filename'};
11080:     }
11081:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
11082: # is that filename actually a symb? Verify, clean, and return
11083:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
11084: 	if (&symbverify($thisfn,$1)) {
11085: 	    return $env{$cache_str}=&symbclean($thisfn);
11086: 	}
11087:     }
11088:     $thisfn=declutter($thisfn);
11089:     my %hash;
11090:     my %bighash;
11091:     my $syval='';
11092:     if (($env{'request.course.fn'}) && ($thisfn)) {
11093:         my $targetfn = $thisfn;
11094:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
11095:             $targetfn = 'adm/wrapper/'.$thisfn;
11096:         }
11097: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
11098: 	    $targetfn=$1;
11099: 	}
11100:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
11101:                       &GDBM_READER(),0640)) {
11102: 	    $syval=$hash{$targetfn};
11103:             untie(%hash);
11104:         }
11105: # ---------------------------------------------------------- There was an entry
11106:         if ($syval) {
11107: 	    #unless ($syval=~/\_\d+$/) {
11108: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
11109: 		    #&appenv({'request.ambiguous' => $thisfn});
11110: 		    #return $env{$cache_str}='';
11111: 		#}    
11112: 		#$syval.=$1;
11113: 	    #}
11114:         } else {
11115: # ------------------------------------------------------- Was not in symb table
11116:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11117:                             &GDBM_READER(),0640)) {
11118: # ---------------------------------------------- Get ID(s) for current resource
11119:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
11120:               unless ($ids) { 
11121:                  $ids=$bighash{'ids_/'.$thisfn};
11122:               }
11123:               unless ($ids) {
11124: # alias?
11125: 		  $ids=$bighash{'mapalias_'.$thisfn};
11126:               }
11127:               if ($ids) {
11128: # ------------------------------------------------------------------- Has ID(s)
11129:                  my @possibilities=split(/\,/,$ids);
11130:                  if ($#possibilities==0) {
11131: # ----------------------------------------------- There is only one possibility
11132: 		     my ($mapid,$resid)=split(/\./,$ids);
11133: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
11134: 						    $resid,$thisfn);
11135:                  } elsif (!$donotrecurse) {
11136: # ------------------------------------------ There is more than one possibility
11137:                      my $realpossible=0;
11138:                      foreach my $id (@possibilities) {
11139: 			 my $file=$bighash{'src_'.$id};
11140:                          if (&allowed('bre',$file)) {
11141:          		    my ($mapid,$resid)=split(/\./,$id);
11142:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
11143: 				$realpossible++;
11144:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
11145: 						    $resid,$thisfn);
11146:                             }
11147: 			 }
11148:                      }
11149: 		     if ($realpossible!=1) { $syval=''; }
11150:                  } else {
11151:                      $syval='';
11152:                  }
11153: 	      }
11154:               untie(%bighash)
11155:            }
11156:         }
11157:         if ($syval) {
11158: 	    return $env{$cache_str}=$syval;
11159:         }
11160:     }
11161:     &appenv({'request.ambiguous' => $thisfn});
11162:     return $env{$cache_str}='';
11163: }
11164: 
11165: # ---------------------------------------------------------- Return random seed
11166: 
11167: sub numval {
11168:     my $txt=shift;
11169:     $txt=~tr/A-J/0-9/;
11170:     $txt=~tr/a-j/0-9/;
11171:     $txt=~tr/K-T/0-9/;
11172:     $txt=~tr/k-t/0-9/;
11173:     $txt=~tr/U-Z/0-5/;
11174:     $txt=~tr/u-z/0-5/;
11175:     $txt=~s/\D//g;
11176:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
11177:     return int($txt);
11178: }
11179: 
11180: sub numval2 {
11181:     my $txt=shift;
11182:     $txt=~tr/A-J/0-9/;
11183:     $txt=~tr/a-j/0-9/;
11184:     $txt=~tr/K-T/0-9/;
11185:     $txt=~tr/k-t/0-9/;
11186:     $txt=~tr/U-Z/0-5/;
11187:     $txt=~tr/u-z/0-5/;
11188:     $txt=~s/\D//g;
11189:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11190:     my $total;
11191:     foreach my $val (@txts) { $total+=$val; }
11192:     if ($_64bit) { if ($total > 2**32) { return -1; } }
11193:     return int($total);
11194: }
11195: 
11196: sub numval3 {
11197:     use integer;
11198:     my $txt=shift;
11199:     $txt=~tr/A-J/0-9/;
11200:     $txt=~tr/a-j/0-9/;
11201:     $txt=~tr/K-T/0-9/;
11202:     $txt=~tr/k-t/0-9/;
11203:     $txt=~tr/U-Z/0-5/;
11204:     $txt=~tr/u-z/0-5/;
11205:     $txt=~s/\D//g;
11206:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11207:     my $total;
11208:     foreach my $val (@txts) { $total+=$val; }
11209:     if ($_64bit) { $total=(($total<<32)>>32); }
11210:     return $total;
11211: }
11212: 
11213: sub digest {
11214:     my ($data)=@_;
11215:     my $digest=&Digest::MD5::md5($data);
11216:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
11217:     my ($e,$f);
11218:     {
11219:         use integer;
11220:         $e=($a+$b);
11221:         $f=($c+$d);
11222:         if ($_64bit) {
11223:             $e=(($e<<32)>>32);
11224:             $f=(($f<<32)>>32);
11225:         }
11226:     }
11227:     if (wantarray) {
11228: 	return ($e,$f);
11229:     } else {
11230: 	my $g;
11231: 	{
11232: 	    use integer;
11233: 	    $g=($e+$f);
11234: 	    if ($_64bit) {
11235: 		$g=(($g<<32)>>32);
11236: 	    }
11237: 	}
11238: 	return $g;
11239:     }
11240: }
11241: 
11242: sub latest_rnd_algorithm_id {
11243:     return '64bit5';
11244: }
11245: 
11246: sub get_rand_alg {
11247:     my ($courseid)=@_;
11248:     if (!$courseid) { $courseid=(&whichuser())[1]; }
11249:     if ($courseid) {
11250: 	return $env{"course.$courseid.rndseed"};
11251:     }
11252:     return &latest_rnd_algorithm_id();
11253: }
11254: 
11255: sub validCODE {
11256:     my ($CODE)=@_;
11257:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
11258:     return 0;
11259: }
11260: 
11261: sub getCODE {
11262:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
11263:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
11264: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
11265: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
11266: 	return $Apache::lonhomework::history{'resource.CODE'};
11267:     }
11268:     return undef;
11269: }
11270: #
11271: #  Determines the random seed for a specific context:
11272: #
11273: # parameters:
11274: #   symb      - in course context the symb for the seed.
11275: #   course_id - The course id of the form domain_coursenum.
11276: #   domain    - Domain for the user.
11277: #   course    - Course for the user.
11278: #   cenv      - environment of the course.
11279: #
11280: # NOTE:
11281: #   All parameters are picked out of the environment if missing
11282: #   or not defined.
11283: #   If a symb cannot be determined the current time is used instead.
11284: #
11285: #  For a given well defined symb, courside, domain, username,
11286: #  and course environment, the seed is reproducible.
11287: #
11288: sub rndseed {
11289:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
11290:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
11291:     if (!defined($symb)) {
11292: 	unless ($symb=$wsymb) { return time; }
11293:     }
11294:     if (!defined $courseid) { 
11295: 	$courseid=$wcourseid; 
11296:     }
11297:     if (!defined $domain) { $domain=$wdomain; }
11298:     if (!defined $username) { $username=$wusername }
11299: 
11300:     my $which;
11301:     if (defined($cenv->{'rndseed'})) {
11302: 	$which = $cenv->{'rndseed'};
11303:     } else {
11304: 	$which =&get_rand_alg($courseid);
11305:     }
11306:     if (defined(&getCODE())) {
11307: 
11308: 	if ($which eq '64bit5') {
11309: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
11310: 	} elsif ($which eq '64bit4') {
11311: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
11312: 	} else {
11313: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
11314: 	}
11315:     } elsif ($which eq '64bit5') {
11316: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
11317:     } elsif ($which eq '64bit4') {
11318: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
11319:     } elsif ($which eq '64bit3') {
11320: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
11321:     } elsif ($which eq '64bit2') {
11322: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
11323:     } elsif ($which eq '64bit') {
11324: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
11325:     }
11326:     return &rndseed_32bit($symb,$courseid,$domain,$username);
11327: }
11328: 
11329: sub rndseed_32bit {
11330:     my ($symb,$courseid,$domain,$username)=@_;
11331:     {
11332: 	use integer;
11333: 	my $symbchck=unpack("%32C*",$symb) << 27;
11334: 	my $symbseed=numval($symb) << 22;
11335: 	my $namechck=unpack("%32C*",$username) << 17;
11336: 	my $nameseed=numval($username) << 12;
11337: 	my $domainseed=unpack("%32C*",$domain) << 7;
11338: 	my $courseseed=unpack("%32C*",$courseid);
11339: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
11340: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11341: 	#&logthis("rndseed :$num:$symb");
11342: 	if ($_64bit) { $num=(($num<<32)>>32); }
11343: 	return $num;
11344:     }
11345: }
11346: 
11347: sub rndseed_64bit {
11348:     my ($symb,$courseid,$domain,$username)=@_;
11349:     {
11350: 	use integer;
11351: 	my $symbchck=unpack("%32S*",$symb) << 21;
11352: 	my $symbseed=numval($symb) << 10;
11353: 	my $namechck=unpack("%32S*",$username);
11354: 	
11355: 	my $nameseed=numval($username) << 21;
11356: 	my $domainseed=unpack("%32S*",$domain) << 10;
11357: 	my $courseseed=unpack("%32S*",$courseid);
11358: 	
11359: 	my $num1=$symbchck+$symbseed+$namechck;
11360: 	my $num2=$nameseed+$domainseed+$courseseed;
11361: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11362: 	#&logthis("rndseed :$num:$symb");
11363: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11364: 	return "$num1,$num2";
11365:     }
11366: }
11367: 
11368: sub rndseed_64bit2 {
11369:     my ($symb,$courseid,$domain,$username)=@_;
11370:     {
11371: 	use integer;
11372: 	# strings need to be an even # of cahracters long, it it is odd the
11373:         # last characters gets thrown away
11374: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11375: 	my $symbseed=numval($symb) << 10;
11376: 	my $namechck=unpack("%32S*",$username.' ');
11377: 	
11378: 	my $nameseed=numval($username) << 21;
11379: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11380: 	my $courseseed=unpack("%32S*",$courseid.' ');
11381: 	
11382: 	my $num1=$symbchck+$symbseed+$namechck;
11383: 	my $num2=$nameseed+$domainseed+$courseseed;
11384: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11385: 	#&logthis("rndseed :$num:$symb");
11386: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11387: 	return "$num1,$num2";
11388:     }
11389: }
11390: 
11391: sub rndseed_64bit3 {
11392:     my ($symb,$courseid,$domain,$username)=@_;
11393:     {
11394: 	use integer;
11395: 	# strings need to be an even # of cahracters long, it it is odd the
11396:         # last characters gets thrown away
11397: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11398: 	my $symbseed=numval2($symb) << 10;
11399: 	my $namechck=unpack("%32S*",$username.' ');
11400: 	
11401: 	my $nameseed=numval2($username) << 21;
11402: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11403: 	my $courseseed=unpack("%32S*",$courseid.' ');
11404: 	
11405: 	my $num1=$symbchck+$symbseed+$namechck;
11406: 	my $num2=$nameseed+$domainseed+$courseseed;
11407: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11408: 	#&logthis("rndseed :$num1:$num2:$_64bit");
11409: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11410: 	
11411: 	return "$num1:$num2";
11412:     }
11413: }
11414: 
11415: sub rndseed_64bit4 {
11416:     my ($symb,$courseid,$domain,$username)=@_;
11417:     {
11418: 	use integer;
11419: 	# strings need to be an even # of cahracters long, it it is odd the
11420:         # last characters gets thrown away
11421: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11422: 	my $symbseed=numval3($symb) << 10;
11423: 	my $namechck=unpack("%32S*",$username.' ');
11424: 	
11425: 	my $nameseed=numval3($username) << 21;
11426: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11427: 	my $courseseed=unpack("%32S*",$courseid.' ');
11428: 	
11429: 	my $num1=$symbchck+$symbseed+$namechck;
11430: 	my $num2=$nameseed+$domainseed+$courseseed;
11431: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11432: 	#&logthis("rndseed :$num1:$num2:$_64bit");
11433: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11434: 	
11435: 	return "$num1:$num2";
11436:     }
11437: }
11438: 
11439: sub rndseed_64bit5 {
11440:     my ($symb,$courseid,$domain,$username)=@_;
11441:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11442:     return "$num1:$num2";
11443: }
11444: 
11445: sub rndseed_CODE_64bit {
11446:     my ($symb,$courseid,$domain,$username)=@_;
11447:     {
11448: 	use integer;
11449: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
11450: 	my $symbseed=numval2($symb);
11451: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11452: 	my $CODEseed=numval(&getCODE());
11453: 	my $courseseed=unpack("%32S*",$courseid.' ');
11454: 	my $num1=$symbseed+$CODEchck;
11455: 	my $num2=$CODEseed+$courseseed+$symbchck;
11456: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11457: 	#&logthis("rndseed :$num1:$num2:$symb");
11458: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
11459: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
11460: 	return "$num1:$num2";
11461:     }
11462: }
11463: 
11464: sub rndseed_CODE_64bit4 {
11465:     my ($symb,$courseid,$domain,$username)=@_;
11466:     {
11467: 	use integer;
11468: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
11469: 	my $symbseed=numval3($symb);
11470: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11471: 	my $CODEseed=numval3(&getCODE());
11472: 	my $courseseed=unpack("%32S*",$courseid.' ');
11473: 	my $num1=$symbseed+$CODEchck;
11474: 	my $num2=$CODEseed+$courseseed+$symbchck;
11475: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11476: 	#&logthis("rndseed :$num1:$num2:$symb");
11477: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
11478: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
11479: 	return "$num1:$num2";
11480:     }
11481: }
11482: 
11483: sub rndseed_CODE_64bit5 {
11484:     my ($symb,$courseid,$domain,$username)=@_;
11485:     my $code = &getCODE();
11486:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
11487:     return "$num1:$num2";
11488: }
11489: 
11490: sub setup_random_from_rndseed {
11491:     my ($rndseed)=@_;
11492:     if ($rndseed =~/([,:])/) {
11493:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
11494:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
11495:             &Math::Random::random_set_seed_from_phrase($rndseed);
11496:         } else {
11497:             &Math::Random::random_set_seed($num1,$num2);
11498:         }
11499:     } else {
11500: 	&Math::Random::random_set_seed_from_phrase($rndseed);
11501:     }
11502: }
11503: 
11504: sub latest_receipt_algorithm_id {
11505:     return 'receipt3';
11506: }
11507: 
11508: sub recunique {
11509:     my $fucourseid=shift;
11510:     my $unique;
11511:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11512: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11513: 	$unique=$env{"course.$fucourseid.internal.encseed"};
11514:     } else {
11515: 	$unique=$perlvar{'lonReceipt'};
11516:     }
11517:     return unpack("%32C*",$unique);
11518: }
11519: 
11520: sub recprefix {
11521:     my $fucourseid=shift;
11522:     my $prefix;
11523:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11524: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11525: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
11526:     } else {
11527: 	$prefix=$perlvar{'lonHostID'};
11528:     }
11529:     return unpack("%32C*",$prefix);
11530: }
11531: 
11532: sub ireceipt {
11533:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
11534: 
11535:     my $return =&recprefix($fucourseid).'-';
11536: 
11537:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11538: 	$env{'request.state'} eq 'construct') {
11539: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11540: 	return $return;
11541:     }
11542: 
11543:     my $cuname=unpack("%32C*",$funame);
11544:     my $cudom=unpack("%32C*",$fudom);
11545:     my $cucourseid=unpack("%32C*",$fucourseid);
11546:     my $cusymb=unpack("%32C*",$fusymb);
11547:     my $cunique=&recunique($fucourseid);
11548:     my $cpart=unpack("%32S*",$part);
11549:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11550: 
11551: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
11552: 			       
11553: 	$return.= ($cunique%$cuname+
11554: 		   $cunique%$cudom+
11555: 		   $cusymb%$cuname+
11556: 		   $cusymb%$cudom+
11557: 		   $cucourseid%$cuname+
11558: 		   $cucourseid%$cudom+
11559: 		   $cpart%$cuname+
11560: 		   $cpart%$cudom);
11561:     } else {
11562: 	$return.= ($cunique%$cuname+
11563: 		   $cunique%$cudom+
11564: 		   $cusymb%$cuname+
11565: 		   $cusymb%$cudom+
11566: 		   $cucourseid%$cuname+
11567: 		   $cucourseid%$cudom);
11568:     }
11569:     return $return;
11570: }
11571: 
11572: sub receipt {
11573:     my ($part)=@_;
11574:     my ($symb,$courseid,$domain,$name) = &whichuser();
11575:     return &ireceipt($name,$domain,$courseid,$symb,$part);
11576: }
11577: 
11578: sub whichuser {
11579:     my ($passedsymb)=@_;
11580:     my ($symb,$courseid,$domain,$name,$publicuser);
11581:     if (defined($env{'form.grade_symb'})) {
11582: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11583: 	my $allowed=&allowed('vgr',$tmp_courseid);
11584: 	if (!$allowed &&
11585: 	    exists($env{'request.course.sec'}) &&
11586: 	    $env{'request.course.sec'} !~ /^\s*$/) {
11587: 	    $allowed=&allowed('vgr',$tmp_courseid.
11588: 			      '/'.$env{'request.course.sec'});
11589: 	}
11590: 	if ($allowed) {
11591: 	    ($symb)=&get_env_multiple('form.grade_symb');
11592: 	    $courseid=$tmp_courseid;
11593: 	    ($domain)=&get_env_multiple('form.grade_domain');
11594: 	    ($name)=&get_env_multiple('form.grade_username');
11595: 	    return ($symb,$courseid,$domain,$name,$publicuser);
11596: 	}
11597:     }
11598:     if (!$passedsymb) {
11599: 	$symb=&symbread();
11600:     } else {
11601: 	$symb=$passedsymb;
11602:     }
11603:     $courseid=$env{'request.course.id'};
11604:     $domain=$env{'user.domain'};
11605:     $name=$env{'user.name'};
11606:     if ($name eq 'public' && $domain eq 'public') {
11607: 	if (!defined($env{'form.username'})) {
11608: 	    $env{'form.username'}.=time.rand(10000000);
11609: 	}
11610: 	$name.=$env{'form.username'};
11611:     }
11612:     return ($symb,$courseid,$domain,$name,$publicuser);
11613: 
11614: }
11615: 
11616: # ------------------------------------------------------------ Serves up a file
11617: # returns either the contents of the file or 
11618: # -1 if the file doesn't exist
11619: #
11620: # if the target is a file that was uploaded via DOCS, 
11621: # a check will be made to see if a current copy exists on the local server,
11622: # if it does this will be served, otherwise a copy will be retrieved from
11623: # the home server for the course and stored in /home/httpd/html/userfiles on
11624: # the local server.   
11625: 
11626: sub getfile {
11627:     my ($file) = @_;
11628:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
11629:     &repcopy($file);
11630:     return &readfile($file);
11631: }
11632: 
11633: sub repcopy_userfile {
11634:     my ($file)=@_;
11635:     my $londocroot = $perlvar{'lonDocRoot'};
11636:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
11637:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
11638:     my ($cdom,$cnum,$filename) = 
11639: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
11640:     my $uri="/uploaded/$cdom/$cnum/$filename";
11641:     if (-e "$file") {
11642: # we already have a local copy, check it out
11643: 	my @fileinfo = stat($file);
11644: 	my $rtncode;
11645: 	my $info;
11646: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
11647: 	if ($lwpresp ne 'ok') {
11648: # there is no such file anymore, even though we had a local copy
11649: 	    if ($rtncode eq '404') {
11650: 		unlink($file);
11651: 	    }
11652: 	    return -1;
11653: 	}
11654: 	if ($info < $fileinfo[9]) {
11655: # nice, the file we have is up-to-date, just say okay
11656: 	    return 'ok';
11657: 	} else {
11658: # the file is outdated, get rid of it
11659: 	    unlink($file);
11660: 	}
11661:     }
11662: # one way or the other, at this point, we don't have the file
11663: # construct the correct path for the file
11664:     my @parts = ($cdom,$cnum); 
11665:     if ($filename =~ m|^(.+)/[^/]+$|) {
11666: 	push @parts, split(/\//,$1);
11667:     }
11668:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11669:     foreach my $part (@parts) {
11670: 	$path .= '/'.$part;
11671: 	if (!-e $path) {
11672: 	    mkdir($path,0770);
11673: 	}
11674:     }
11675: # now the path exists for sure
11676: # get a user agent
11677:     my $ua=new LWP::UserAgent;
11678:     my $transferfile=$file.'.in.transfer';
11679: # FIXME: this should flock
11680:     if (-e $transferfile) { return 'ok'; }
11681:     my $request;
11682:     $uri=~s/^\///;
11683:     my $homeserver = &homeserver($cnum,$cdom);
11684:     my $protocol = $protocol{$homeserver};
11685:     $protocol = 'http' if ($protocol ne 'https');
11686:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
11687:     my $response=$ua->request($request,$transferfile);
11688: # did it work?
11689:     if ($response->is_error()) {
11690: 	unlink($transferfile);
11691: 	&logthis("Userfile repcopy failed for $uri");
11692: 	return -1;
11693:     }
11694: # worked, rename the transfer file
11695:     rename($transferfile,$file);
11696:     return 'ok';
11697: }
11698: 
11699: sub tokenwrapper {
11700:     my $uri=shift;
11701:     $uri=~s|^https?\://([^/]+)||;
11702:     $uri=~s|^/||;
11703:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
11704:     my $token=$1;
11705:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
11706:     if ($udom && $uname && $file) {
11707: 	$file=~s|(\?\.*)*$||;
11708:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
11709:         my $homeserver = &homeserver($uname,$udom);
11710:         my $protocol = $protocol{$homeserver};
11711:         $protocol = 'http' if ($protocol ne 'https');
11712:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
11713:                (($uri=~/\?/)?'&':'?').'token='.$token.
11714:                                '&tokenissued='.$perlvar{'lonHostID'};
11715:     } else {
11716:         return '/adm/notfound.html';
11717:     }
11718: }
11719: 
11720: # call with reqtype HEAD: get last modification time
11721: # call with reqtype GET: get the file contents
11722: # Do not call this with reqtype GET for large files! It loads everything into memory
11723: #
11724: sub getuploaded {
11725:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11726:     $uri=~s/^\///;
11727:     my $homeserver = &homeserver($cnum,$cdom);
11728:     my $protocol = $protocol{$homeserver};
11729:     $protocol = 'http' if ($protocol ne 'https');
11730:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
11731:     my $ua=new LWP::UserAgent;
11732:     my $request=new HTTP::Request($reqtype,$uri);
11733:     my $response=$ua->request($request);
11734:     $$rtncode = $response->code;
11735:     if (! $response->is_success()) {
11736: 	return 'failed';
11737:     }      
11738:     if ($reqtype eq 'HEAD') {
11739: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
11740:     } elsif ($reqtype eq 'GET') {
11741: 	$$info = $response->content;
11742:     }
11743:     return 'ok';
11744: }
11745: 
11746: sub readfile {
11747:     my $file = shift;
11748:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
11749:     my $fh;
11750:     open($fh,"<$file");
11751:     my $a='';
11752:     while (my $line = <$fh>) { $a .= $line; }
11753:     return $a;
11754: }
11755: 
11756: sub filelocation {
11757:     my ($dir,$file) = @_;
11758:     my $location;
11759:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
11760: 
11761:     if ($file =~ m-^/adm/-) {
11762: 	$file=~s-^/adm/wrapper/-/-;
11763: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
11764:     }
11765: 
11766:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
11767:         $location = $file;
11768:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
11769:         my ($udom,$uname,$filename)=
11770:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
11771:         my $home=&homeserver($uname,$udom);
11772:         my $is_me=0;
11773:         my @ids=&current_machine_ids();
11774:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11775:         if ($is_me) {
11776:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
11777:         } else {
11778:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11779:   	      $udom.'/'.$uname.'/'.$filename;
11780:         }
11781:     } elsif ($file =~ m-^/adm/-) {
11782: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
11783:     } else {
11784:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
11785:         $file=~s:^/(res|priv)/:/:;
11786:         my $space=$1;
11787:         if ( !( $file =~ m:^/:) ) {
11788:             $location = $dir. '/'.$file;
11789:         } else {
11790:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
11791:         }
11792:     }
11793:     $location=~s://+:/:g; # remove duplicate /
11794:     while ($location=~m{/\.\./}) {
11795: 	if ($location =~ m{/[^/]+/\.\./}) {
11796: 	    $location=~ s{/[^/]+/\.\./}{/}g;
11797: 	} else {
11798: 	    $location=~ s{/\.\./}{/}g;
11799: 	}
11800:     } #remove dir/..
11801:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11802:     return $location;
11803: }
11804: 
11805: sub hreflocation {
11806:     my ($dir,$file)=@_;
11807:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
11808: 	$file=filelocation($dir,$file);
11809:     } elsif ($file=~m-^/adm/-) {
11810: 	$file=~s-^/adm/wrapper/-/-;
11811: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
11812:     }
11813:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11814: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11815:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
11816: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11817: 	        {/uploaded/$1/$2/}x;
11818:     }
11819:     if ($file=~ m{^/userfiles/}) {
11820: 	$file =~ s{^/userfiles/}{/uploaded/};
11821:     }
11822:     return $file;
11823: }
11824: 
11825: 
11826: 
11827: 
11828: 
11829: sub current_machine_domains {
11830:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
11831: }
11832: 
11833: sub machine_domains {
11834:     my ($hostname) = @_;
11835:     my @domains;
11836:     my %hostname = &all_hostnames();
11837:     while( my($id, $name) = each(%hostname)) {
11838: #	&logthis("-$id-$name-$hostname-");
11839: 	if ($hostname eq $name) {
11840: 	    push(@domains,&host_domain($id));
11841: 	}
11842:     }
11843:     return @domains;
11844: }
11845: 
11846: sub current_machine_ids {
11847:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
11848: }
11849: 
11850: sub machine_ids {
11851:     my ($hostname) = @_;
11852:     $hostname ||= &hostname($perlvar{'lonHostID'});
11853:     my @ids;
11854:     my %name_to_host = &all_names();
11855:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11856: 	return @{ $name_to_host{$hostname} };
11857:     }
11858:     return;
11859: }
11860: 
11861: sub additional_machine_domains {
11862:     my @domains;
11863:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
11864:     while( my $line = <$fh>) {
11865:         $line =~ s/\s//g;
11866:         push(@domains,$line);
11867:     }
11868:     return @domains;
11869: }
11870: 
11871: sub default_login_domain {
11872:     my $domain = $perlvar{'lonDefDomain'};
11873:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
11874:     foreach my $posdom (&current_machine_domains(),
11875:                         &additional_machine_domains()) {
11876:         if (lc($posdom) eq lc($testdomain)) {
11877:             $domain=$posdom;
11878:             last;
11879:         }
11880:     }
11881:     return $domain;
11882: }
11883: 
11884: # ------------------------------------------------------------- Declutters URLs
11885: 
11886: sub declutter {
11887:     my $thisfn=shift;
11888:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
11889:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
11890:         $thisfn=~s{^/home/httpd/html}{};
11891:     }
11892:     $thisfn=~s/^\///;
11893:     $thisfn=~s|^adm/wrapper/||;
11894:     $thisfn=~s|^adm/coursedocs/showdoc/||;
11895:     $thisfn=~s/^res\///;
11896:     $thisfn=~s/^priv\///;
11897:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
11898:         $thisfn=~s/\?.+$//;
11899:     }
11900:     return $thisfn;
11901: }
11902: 
11903: # ------------------------------------------------------------- Clutter up URLs
11904: 
11905: sub clutter {
11906:     my $thisfn='/'.&declutter(shift);
11907:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
11908: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
11909:        $thisfn='/res'.$thisfn; 
11910:     }
11911:     if ($thisfn !~m|^/adm|) {
11912: 	if ($thisfn =~ m|^/ext/|) {
11913: 	    $thisfn='/adm/wrapper'.$thisfn;
11914: 	} else {
11915: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
11916: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
11917: 	    if ($embstyle eq 'ssi'
11918: 		|| ($embstyle eq 'hdn')
11919: 		|| ($embstyle eq 'rat')
11920: 		|| ($embstyle eq 'prv')
11921: 		|| ($embstyle eq 'ign')) {
11922: 		#do nothing with these
11923: 	    } elsif (($embstyle eq 'img') 
11924: 		|| ($embstyle eq 'emb')
11925: 		|| ($embstyle eq 'wrp')) {
11926: 		$thisfn='/adm/wrapper'.$thisfn;
11927: 	    } elsif ($embstyle eq 'unk'
11928: 		     && $thisfn!~/\.(sequence|page)$/) {
11929: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
11930: 	    } else {
11931: #		&logthis("Got a blank emb style");
11932: 	    }
11933: 	}
11934:     }
11935:     return $thisfn;
11936: }
11937: 
11938: sub clutter_with_no_wrapper {
11939:     my $uri = &clutter(shift);
11940:     if ($uri =~ m-^/adm/-) {
11941: 	$uri =~ s-^/adm/wrapper/-/-;
11942: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
11943:     }
11944:     return $uri;
11945: }
11946: 
11947: sub freeze_escape {
11948:     my ($value)=@_;
11949:     if (ref($value)) {
11950: 	$value=&nfreeze($value);
11951: 	return '__FROZEN__'.&escape($value);
11952:     }
11953:     return &escape($value);
11954: }
11955: 
11956: 
11957: sub thaw_unescape {
11958:     my ($value)=@_;
11959:     if ($value =~ /^__FROZEN__/) {
11960: 	substr($value,0,10,undef);
11961: 	$value=&unescape($value);
11962: 	return &thaw($value);
11963:     }
11964:     return &unescape($value);
11965: }
11966: 
11967: sub correct_line_ends {
11968:     my ($result)=@_;
11969:     $$result =~s/\r\n/\n/mg;
11970:     $$result =~s/\r/\n/mg;
11971: }
11972: # ================================================================ Main Program
11973: 
11974: sub goodbye {
11975:    &logthis("Starting Shut down");
11976: #not converted to using infrastruture and probably shouldn't be
11977:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
11978: #converted
11979: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
11980:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
11981: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
11982: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
11983: #1.1 only
11984: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
11985: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
11986: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
11987: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
11988:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
11989:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
11990:    &logthis(sprintf("%-20s is %s",'hits',$hits));
11991:    &flushcourselogs();
11992:    &logthis("Shutting down");
11993: }
11994: 
11995: sub get_dns {
11996:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
11997:     if (!$ignore_cache) {
11998: 	my ($content,$cached)=
11999: 	    &Apache::lonnet::is_cached_new('dns',$url);
12000: 	if ($cached) {
12001: 	    &$func($content,$hashref);
12002: 	    return;
12003: 	}
12004:     }
12005: 
12006:     my %alldns;
12007:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12008:     foreach my $dns (<$config>) {
12009: 	next if ($dns !~ /^\^(\S*)/x);
12010:         my $line = $1;
12011:         my ($host,$protocol) = split(/:/,$line);
12012:         if ($protocol ne 'https') {
12013:             $protocol = 'http';
12014:         }
12015: 	$alldns{$host} = $protocol;
12016:     }
12017:     while (%alldns) {
12018: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
12019: 	my $ua=new LWP::UserAgent;
12020:         $ua->timeout(30);
12021: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
12022: 	my $response=$ua->request($request);
12023:         delete($alldns{$dns});
12024: 	next if ($response->is_error());
12025: 	my @content = split("\n",$response->content);
12026: 	unless ($nocache) {
12027: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
12028: 	}
12029: 	&$func(\@content,$hashref);
12030: 	return;
12031:     }
12032:     close($config);
12033:     my $which = (split('/',$url))[3];
12034:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
12035:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
12036:     my @content = <$config>;
12037:     &$func(\@content,$hashref);
12038:     return;
12039: }
12040: 
12041: # ------------------------------------------------------Get DNS checksums file
12042: sub parse_dns_checksums_tab {
12043:     my ($lines,$hashref) = @_;
12044:     my $lonhost = $perlvar{'lonHostID'};
12045:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
12046:     my $loncaparev = &get_server_loncaparev($machine_dom);
12047:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
12048:     my $webconfdir = '/etc/httpd/conf';
12049:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
12050:         $webconfdir = '/etc/apache2';
12051:     } elsif ($distro =~ /^sles(\d+)$/) {
12052:         if ($1 >= 10) {
12053:             $webconfdir = '/etc/apache2';
12054:         }
12055:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
12056:         if ($1 >= 10.0) {
12057:             $webconfdir = '/etc/apache2';
12058:         }
12059:     }
12060:     my ($release,$timestamp) = split(/\-/,$loncaparev);
12061:     my (%chksum,%revnum);
12062:     if (ref($lines) eq 'ARRAY') {
12063:         chomp(@{$lines});
12064:         my $version = shift(@{$lines});
12065:         if ($version eq $release) {  
12066:             foreach my $line (@{$lines}) {
12067:                 my ($file,$version,$shasum) = split(/,/,$line);
12068:                 if ($file =~ m{^/etc/httpd/conf}) {
12069:                     if ($webconfdir eq '/etc/apache2') {
12070:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
12071:                     }
12072:                 }
12073:                 $chksum{$file} = $shasum;
12074:                 $revnum{$file} = $version;
12075:             }
12076:             if (ref($hashref) eq 'HASH') {
12077:                 %{$hashref} = (
12078:                                 sums     => \%chksum,
12079:                                 versions => \%revnum,
12080:                               );
12081:             }
12082:         }
12083:     }
12084:     return;
12085: }
12086: 
12087: sub fetch_dns_checksums {
12088:     my %checksums;
12089:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
12090:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
12091:     my ($release,$timestamp) = split(/\-/,$loncaparev);
12092:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
12093:              \%checksums);
12094:     return \%checksums;
12095: }
12096: 
12097: # ------------------------------------------------------------ Read domain file
12098: {
12099:     my $loaded;
12100:     my %domain;
12101: 
12102:     sub parse_domain_tab {
12103: 	my ($lines) = @_;
12104: 	foreach my $line (@$lines) {
12105: 	    next if ($line =~ /^(\#|\s*$ )/x);
12106: 
12107: 	    chomp($line);
12108: 	    my ($name,@elements) = split(/:/,$line,9);
12109: 	    my %this_domain;
12110: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
12111: 			       'lang_def', 'city', 'longi', 'lati',
12112: 			       'primary') {
12113: 		$this_domain{$field} = shift(@elements);
12114: 	    }
12115: 	    $domain{$name} = \%this_domain;
12116: 	}
12117:     }
12118: 
12119:     sub reset_domain_info {
12120: 	undef($loaded);
12121: 	undef(%domain);
12122:     }
12123: 
12124:     sub load_domain_tab {
12125: 	my ($ignore_cache) = @_;
12126: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
12127: 	my $fh;
12128: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
12129: 	    my @lines = <$fh>;
12130: 	    &parse_domain_tab(\@lines);
12131: 	}
12132: 	close($fh);
12133: 	$loaded = 1;
12134:     }
12135: 
12136:     sub domain {
12137: 	&load_domain_tab() if (!$loaded);
12138: 
12139: 	my ($name,$what) = @_;
12140: 	return if ( !exists($domain{$name}) );
12141: 
12142: 	if (!$what) {
12143: 	    return $domain{$name}{'description'};
12144: 	}
12145: 	return $domain{$name}{$what};
12146:     }
12147: 
12148:     sub domain_info {
12149:         &load_domain_tab() if (!$loaded);
12150:         return %domain;
12151:     }
12152: 
12153: }
12154: 
12155: 
12156: # ------------------------------------------------------------- Read hosts file
12157: {
12158:     my %hostname;
12159:     my %hostdom;
12160:     my %libserv;
12161:     my $loaded;
12162:     my %name_to_host;
12163:     my %internetdom;
12164:     my %LC_dns_serv;
12165: 
12166:     sub parse_hosts_tab {
12167: 	my ($file) = @_;
12168: 	foreach my $configline (@$file) {
12169: 	    next if ($configline =~ /^(\#|\s*$ )/x);
12170:             chomp($configline);
12171: 	    if ($configline =~ /^\^/) {
12172:                 if ($configline =~ /^\^([\w.\-]+)/) {
12173:                     $LC_dns_serv{$1} = 1;
12174:                 }
12175:                 next;
12176:             }
12177: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
12178: 	    $name=~s/\s//g;
12179: 	    if ($id && $domain && $role && $name) {
12180: 		$hostname{$id}=$name;
12181: 		push(@{$name_to_host{$name}}, $id);
12182: 		$hostdom{$id}=$domain;
12183: 		if ($role eq 'library') { $libserv{$id}=$name; }
12184:                 if (defined($protocol)) {
12185:                     if ($protocol eq 'https') {
12186:                         $protocol{$id} = $protocol;
12187:                     } else {
12188:                         $protocol{$id} = 'http'; 
12189:                     }
12190:                 } else {
12191:                     $protocol{$id} = 'http';
12192:                 }
12193:                 if (defined($intdom)) {
12194:                     $internetdom{$id} = $intdom;
12195:                 }
12196: 	    }
12197: 	}
12198:     }
12199:     
12200:     sub reset_hosts_info {
12201: 	&purge_remembered();
12202: 	&reset_domain_info();
12203: 	&reset_hosts_ip_info();
12204: 	undef(%name_to_host);
12205: 	undef(%hostname);
12206: 	undef(%hostdom);
12207: 	undef(%libserv);
12208: 	undef($loaded);
12209:     }
12210: 
12211:     sub load_hosts_tab {
12212: 	my ($ignore_cache) = @_;
12213: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
12214: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12215: 	my @config = <$config>;
12216: 	&parse_hosts_tab(\@config);
12217: 	close($config);
12218: 	$loaded=1;
12219:     }
12220: 
12221:     sub hostname {
12222: 	&load_hosts_tab() if (!$loaded);
12223: 
12224: 	my ($lonid) = @_;
12225: 	return $hostname{$lonid};
12226:     }
12227: 
12228:     sub all_hostnames {
12229: 	&load_hosts_tab() if (!$loaded);
12230: 
12231: 	return %hostname;
12232:     }
12233: 
12234:     sub all_names {
12235: 	&load_hosts_tab() if (!$loaded);
12236: 
12237: 	return %name_to_host;
12238:     }
12239: 
12240:     sub all_host_domain {
12241:         &load_hosts_tab() if (!$loaded);
12242:         return %hostdom;
12243:     }
12244: 
12245:     sub is_library {
12246: 	&load_hosts_tab() if (!$loaded);
12247: 
12248: 	return exists($libserv{$_[0]});
12249:     }
12250: 
12251:     sub all_library {
12252: 	&load_hosts_tab() if (!$loaded);
12253: 
12254: 	return %libserv;
12255:     }
12256: 
12257:     sub unique_library {
12258: 	#2x reverse removes all hostnames that appear more than once
12259:         my %unique = reverse &all_library();
12260:         return reverse %unique;
12261:     }
12262: 
12263:     sub get_servers {
12264: 	&load_hosts_tab() if (!$loaded);
12265: 
12266: 	my ($domain,$type) = @_;
12267: 	my %possible_hosts = ($type eq 'library') ? %libserv
12268: 	                                          : %hostname;
12269: 	my %result;
12270: 	if (ref($domain) eq 'ARRAY') {
12271: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
12272: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
12273: 		    $result{$host} = $hostname;
12274: 		}
12275: 	    }
12276: 	} else {
12277: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
12278: 		if ($hostdom{$host} eq $domain) {
12279: 		    $result{$host} = $hostname;
12280: 		}
12281: 	    }
12282: 	}
12283: 	return %result;
12284:     }
12285: 
12286:     sub get_unique_servers {
12287:         my %unique = reverse &get_servers(@_);
12288: 	return reverse %unique;
12289:     }
12290: 
12291:     sub host_domain {
12292: 	&load_hosts_tab() if (!$loaded);
12293: 
12294: 	my ($lonid) = @_;
12295: 	return $hostdom{$lonid};
12296:     }
12297: 
12298:     sub all_domains {
12299: 	&load_hosts_tab() if (!$loaded);
12300: 
12301: 	my %seen;
12302: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
12303: 	return @uniq;
12304:     }
12305: 
12306:     sub internet_dom {
12307:         &load_hosts_tab() if (!$loaded);
12308: 
12309:         my ($lonid) = @_;
12310:         return $internetdom{$lonid};
12311:     }
12312: 
12313:     sub is_LC_dns {
12314:         &load_hosts_tab() if (!$loaded);
12315: 
12316:         my ($hostname) = @_;
12317:         return exists($LC_dns_serv{$hostname});
12318:     }
12319: 
12320: }
12321: 
12322: { 
12323:     my %iphost;
12324:     my %name_to_ip;
12325:     my %lonid_to_ip;
12326: 
12327:     sub get_hosts_from_ip {
12328: 	my ($ip) = @_;
12329: 	my %iphosts = &get_iphost();
12330: 	if (ref($iphosts{$ip})) {
12331: 	    return @{$iphosts{$ip}};
12332: 	}
12333: 	return;
12334:     }
12335:     
12336:     sub reset_hosts_ip_info {
12337: 	undef(%iphost);
12338: 	undef(%name_to_ip);
12339: 	undef(%lonid_to_ip);
12340:     }
12341: 
12342:     sub get_host_ip {
12343: 	my ($lonid) = @_;
12344: 	if (exists($lonid_to_ip{$lonid})) {
12345: 	    return $lonid_to_ip{$lonid};
12346: 	}
12347: 	my $name=&hostname($lonid);
12348:    	my $ip = gethostbyname($name);
12349: 	return if (!$ip || length($ip) ne 4);
12350: 	$ip=inet_ntoa($ip);
12351: 	$name_to_ip{$name}   = $ip;
12352: 	$lonid_to_ip{$lonid} = $ip;
12353: 	return $ip;
12354:     }
12355:     
12356:     sub get_iphost {
12357: 	my ($ignore_cache) = @_;
12358: 
12359: 	if (!$ignore_cache) {
12360: 	    if (%iphost) {
12361: 		return %iphost;
12362: 	    }
12363: 	    my ($ip_info,$cached)=
12364: 		&Apache::lonnet::is_cached_new('iphost','iphost');
12365: 	    if ($cached) {
12366: 		%iphost      = %{$ip_info->[0]};
12367: 		%name_to_ip  = %{$ip_info->[1]};
12368: 		%lonid_to_ip = %{$ip_info->[2]};
12369: 		return %iphost;
12370: 	    }
12371: 	}
12372: 
12373: 	# get yesterday's info for fallback
12374: 	my %old_name_to_ip;
12375: 	my ($ip_info,$cached)=
12376: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
12377: 	if ($cached) {
12378: 	    %old_name_to_ip = %{$ip_info->[1]};
12379: 	}
12380: 
12381: 	my %name_to_host = &all_names();
12382: 	foreach my $name (keys(%name_to_host)) {
12383: 	    my $ip;
12384: 	    if (!exists($name_to_ip{$name})) {
12385: 		$ip = gethostbyname($name);
12386: 		if (!$ip || length($ip) ne 4) {
12387: 		    if (defined($old_name_to_ip{$name})) {
12388: 			$ip = $old_name_to_ip{$name};
12389: 			&logthis("Can't find $name defaulting to old $ip");
12390: 		    } else {
12391: 			&logthis("Name $name no IP found");
12392: 			next;
12393: 		    }
12394: 		} else {
12395: 		    $ip=inet_ntoa($ip);
12396: 		}
12397: 		$name_to_ip{$name} = $ip;
12398: 	    } else {
12399: 		$ip = $name_to_ip{$name};
12400: 	    }
12401: 	    foreach my $id (@{ $name_to_host{$name} }) {
12402: 		$lonid_to_ip{$id} = $ip;
12403: 	    }
12404: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
12405: 	}
12406: 	&do_cache_new('iphost','iphost',
12407: 		      [\%iphost,\%name_to_ip,\%lonid_to_ip],
12408: 		      48*60*60);
12409: 
12410: 	return %iphost;
12411:     }
12412: 
12413:     #
12414:     #  Given a DNS returns the loncapa host name for that DNS 
12415:     # 
12416:     sub host_from_dns {
12417:         my ($dns) = @_;
12418:         my @hosts;
12419:         my $ip;
12420: 
12421:         if (exists($name_to_ip{$dns})) {
12422:             $ip = $name_to_ip{$dns};
12423:         }
12424:         if (!$ip) {
12425:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12426:             if (length($ip) == 4) { 
12427: 	        $ip   = &IO::Socket::inet_ntoa($ip);
12428:             }
12429:         }
12430:         if ($ip) {
12431: 	    @hosts = get_hosts_from_ip($ip);
12432: 	    return $hosts[0];
12433:         }
12434:         return undef;
12435:     }
12436: 
12437:     sub get_internet_names {
12438:         my ($lonid) = @_;
12439:         return if ($lonid eq '');
12440:         my ($idnref,$cached)=
12441:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
12442:         if ($cached) {
12443:             return $idnref;
12444:         }
12445:         my $ip = &get_host_ip($lonid);
12446:         my @hosts = &get_hosts_from_ip($ip);
12447:         my %iphost = &get_iphost();
12448:         my (@idns,%seen);
12449:         foreach my $id (@hosts) {
12450:             my $dom = &host_domain($id);
12451:             my $prim_id = &domain($dom,'primary');
12452:             my $prim_ip = &get_host_ip($prim_id);
12453:             next if ($seen{$prim_ip});
12454:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12455:                 foreach my $id (@{$iphost{$prim_ip}}) {
12456:                     my $intdom = &internet_dom($id);
12457:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
12458:                         push(@idns,$intdom);
12459:                     }
12460:                 }
12461:             }
12462:             $seen{$prim_ip} = 1;
12463:         }
12464:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
12465:     }
12466: 
12467: }
12468: 
12469: sub all_loncaparevs {
12470:     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);
12471: }
12472: 
12473: # ---------------------------------------------------------- Read loncaparev table
12474: {
12475:     sub load_loncaparevs { 
12476:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12477:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12478:                 while (my $configline=<$config>) {
12479:                     chomp($configline);
12480:                     my ($hostid,$loncaparev)=split(/:/,$configline);
12481:                     $loncaparevs{$hostid}=$loncaparev;
12482:                 }
12483:                 close($config);
12484:             }
12485:         }
12486:     }
12487: }
12488: 
12489: # ---------------------------------------------------------- Read serverhostID table
12490: {
12491:     sub load_serverhomeIDs {
12492:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12493:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12494:                 while (my $configline=<$config>) {
12495:                     chomp($configline);
12496:                     my ($name,$id)=split(/:/,$configline);
12497:                     $serverhomeIDs{$name}=$id;
12498:                 }
12499:                 close($config);
12500:             }
12501:         }
12502:     }
12503: }
12504: 
12505: 
12506: BEGIN {
12507: 
12508: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12509:     unless ($readit) {
12510: {
12511:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12512:     %perlvar = (%perlvar,%{$configvars});
12513: }
12514: 
12515: 
12516: # ------------------------------------------------------ Read spare server file
12517: {
12518:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
12519: 
12520:     while (my $configline=<$config>) {
12521:        chomp($configline);
12522:        if ($configline) {
12523: 	   my ($host,$type) = split(':',$configline,2);
12524: 	   if (!defined($type) || $type eq '') { $type = 'default' };
12525: 	   push(@{ $spareid{$type} }, $host);
12526:        }
12527:     }
12528:     close($config);
12529: }
12530: # ------------------------------------------------------------ Read permissions
12531: {
12532:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
12533: 
12534:     while (my $configline=<$config>) {
12535: 	chomp($configline);
12536: 	if ($configline) {
12537: 	    my ($role,$perm)=split(/ /,$configline);
12538: 	    if ($perm ne '') { $pr{$role}=$perm; }
12539: 	}
12540:     }
12541:     close($config);
12542: }
12543: 
12544: # -------------------------------------------- Read plain texts for permissions
12545: {
12546:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
12547: 
12548:     while (my $configline=<$config>) {
12549: 	chomp($configline);
12550: 	if ($configline) {
12551: 	    my ($short,@plain)=split(/:/,$configline);
12552:             %{$prp{$short}} = ();
12553: 	    if (@plain > 0) {
12554:                 $prp{$short}{'std'} = $plain[0];
12555:                 for (my $i=1; $i<@plain; $i++) {
12556:                     $prp{$short}{'alt'.$i} = $plain[$i];  
12557:                 }
12558:             }
12559: 	}
12560:     }
12561:     close($config);
12562: }
12563: 
12564: # ---------------------------------------------------------- Read package table
12565: {
12566:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
12567: 
12568:     while (my $configline=<$config>) {
12569: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
12570: 	chomp($configline);
12571: 	my ($short,$plain)=split(/:/,$configline);
12572: 	my ($pack,$name)=split(/\&/,$short);
12573: 	if ($plain ne '') {
12574: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
12575: 	    $packagetab{$short}=$plain; 
12576: 	}
12577:     }
12578:     close($config);
12579: }
12580: 
12581: # ---------------------------------------------------------- Read loncaparev table
12582: 
12583: &load_loncaparevs();
12584: 
12585: # ---------------------------------------------------------- Read serverhostID table
12586: 
12587: &load_serverhomeIDs();
12588: 
12589: # ---------------------------------------------------------- Read releaseslist XML
12590: {
12591:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12592:     if (-e $file) {
12593:         my $parser = HTML::LCParser->new($file);
12594:         while (my $token = $parser->get_token()) {
12595:             if ($token->[0] eq 'S') {
12596:                 my $item = $token->[1];
12597:                 my $name = $token->[2]{'name'};
12598:                 my $value = $token->[2]{'value'};
12599:                 if ($item ne '' && $name ne '' && $value ne '') {
12600:                     my $release = $parser->get_text();
12601:                     $release =~ s/(^\s*|\s*$ )//gx;
12602:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
12603:                 }
12604:             }
12605:         }
12606:     }
12607: }
12608: 
12609: # ---------------------------------------------------------- Read managers table
12610: {
12611:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12612:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12613:             while (my $configline=<$config>) {
12614:                 chomp($configline);
12615:                 next if ($configline =~ /^\#/);
12616:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12617:                     $managerstab{$configline} = 1;
12618:                 }
12619:             }
12620:             close($config);
12621:         }
12622:     }
12623: }
12624: 
12625: # ------------- set up temporary directory
12626: {
12627:     $tmpdir = LONCAPA::tempdir();
12628: 
12629: }
12630: 
12631: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
12632: 				'compress_threshold'=> 20_000,
12633:  			        });
12634: 
12635: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
12636: $dumpcount=0;
12637: $locknum=0;
12638: 
12639: &logtouch();
12640: &logthis('<font color="yellow">INFO: Read configuration</font>');
12641: $readit=1;
12642:     {
12643: 	use integer;
12644: 	my $test=(2**32)+1;
12645: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
12646: 	&logthis(" Detected 64bit platform ($_64bit)");
12647:     }
12648: }
12649: }
12650: 
12651: 1;
12652: __END__
12653: 
12654: =pod
12655: 
12656: =head1 NAME
12657: 
12658: Apache::lonnet - Subroutines to ask questions about things in the network.
12659: 
12660: =head1 SYNOPSIS
12661: 
12662: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
12663: 
12664:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12665: 
12666: Common parameters:
12667: 
12668: =over 4
12669: 
12670: =item *
12671: 
12672: $uname : an internal username (if $cname expecting a course Id specifically)
12673: 
12674: =item *
12675: 
12676: $udom : a domain (if $cdom expecting a course's domain specifically)
12677: 
12678: =item *
12679: 
12680: $symb : a resource instance identifier
12681: 
12682: =item *
12683: 
12684: $namespace : the name of a .db file that contains the data needed or
12685: being set.
12686: 
12687: =back
12688: 
12689: =head1 OVERVIEW
12690: 
12691: lonnet provides subroutines which interact with the
12692: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12693: about classes, users, and resources.
12694: 
12695: For many of these objects you can also use this to store data about
12696: them or modify them in various ways.
12697: 
12698: =head2 Symbs
12699: 
12700: To identify a specific instance of a resource, LON-CAPA uses symbols
12701: or "symbs"X<symb>. These identifiers are built from the URL of the
12702: map, the resource number of the resource in the map, and the URL of
12703: the resource itself. The latter is somewhat redundant, but might help
12704: if maps change.
12705: 
12706: An example is
12707: 
12708:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12709: 
12710: The respective map entry is
12711: 
12712:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
12713:   title="Problem 2">
12714:  </resource>
12715: 
12716: Symbs are used by the random number generator, as well as to store and
12717: restore data specific to a certain instance of for example a problem.
12718: 
12719: =head2 Storing And Retrieving Data
12720: 
12721: X<store()>X<cstore()>X<restore()>Three of the most important functions
12722: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12723: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12724: is is the non-critical message twin of cstore. These functions are for
12725: handlers to store a perl hash to a user's permanent data space in an
12726: easy manner, and to retrieve it again on another call. It is expected
12727: that a handler would use this once at the beginning to retrieve data,
12728: and then again once at the end to send only the new data back.
12729: 
12730: The data is stored in the user's data directory on the user's
12731: homeserver under the ID of the course.
12732: 
12733: The hash that is returned by restore will have all of the previous
12734: value for all of the elements of the hash.
12735: 
12736: Example:
12737: 
12738:  #creating a hash
12739:  my %hash;
12740:  $hash{'foo'}='bar';
12741: 
12742:  #storing it
12743:  &Apache::lonnet::cstore(\%hash);
12744: 
12745:  #changing a value
12746:  $hash{'foo'}='notbar';
12747: 
12748:  #adding a new value
12749:  $hash{'bar'}='foo';
12750:  &Apache::lonnet::cstore(\%hash);
12751: 
12752:  #retrieving the hash
12753:  my %history=&Apache::lonnet::restore();
12754: 
12755:  #print the hash
12756:  foreach my $key (sort(keys(%history))) {
12757:    print("\%history{$key} = $history{$key}");
12758:  }
12759: 
12760: Will print out:
12761: 
12762:  %history{1:foo} = bar
12763:  %history{1:keys} = foo:timestamp
12764:  %history{1:timestamp} = 990455579
12765:  %history{2:bar} = foo
12766:  %history{2:foo} = notbar
12767:  %history{2:keys} = foo:bar:timestamp
12768:  %history{2:timestamp} = 990455580
12769:  %history{bar} = foo
12770:  %history{foo} = notbar
12771:  %history{timestamp} = 990455580
12772:  %history{version} = 2
12773: 
12774: Note that the special hash entries C<keys>, C<version> and
12775: C<timestamp> were added to the hash. C<version> will be equal to the
12776: total number of versions of the data that have been stored. The
12777: C<timestamp> attribute will be the UNIX time the hash was
12778: stored. C<keys> is available in every historical section to list which
12779: keys were added or changed at a specific historical revision of a
12780: hash.
12781: 
12782: B<Warning>: do not store the hash that restore returns directly. This
12783: will cause a mess since it will restore the historical keys as if the
12784: were new keys. I.E. 1:foo will become 1:1:foo etc.
12785: 
12786: Calling convention:
12787: 
12788:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
12789:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
12790: 
12791: For more detailed information, see lonnet specific documentation.
12792: 
12793: =head1 RETURN MESSAGES
12794: 
12795: =over 4
12796: 
12797: =item * B<con_lost>: unable to contact remote host
12798: 
12799: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12800: when the connection is brought back up
12801: 
12802: =item * B<con_failed>: unable to contact remote host and unable to save message
12803: for later delivery
12804: 
12805: =item * B<error:>: an error a occurred, a description of the error follows the :
12806: 
12807: =item * B<no_such_host>: unable to fund a host associated with the user/domain
12808: that was requested
12809: 
12810: =back
12811: 
12812: =head1 PUBLIC SUBROUTINES
12813: 
12814: =head2 Session Environment Functions
12815: 
12816: =over 4
12817: 
12818: =item * 
12819: X<appenv()>
12820: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
12821: the user envirnoment file, and will be restored for each access this
12822: user makes during this session, also modifies the %env for the current
12823: process. Optional rolesarrayref - if defined contains a reference to an array
12824: of roles which are exempt from the restriction on modifying user.role entries 
12825: in the user's environment.db and in %env.    
12826: 
12827: =item *
12828: X<delenv()>
12829: B<delenv($delthis,$regexp)>: removes all items from the session
12830: environment file that begin with $delthis. If the 
12831: optional second arg - $regexp - is true, $delthis is treated as a 
12832: regular expression, otherwise \Q$delthis\E is used. 
12833: The values are also deleted from the current processes %env.
12834: 
12835: =item * get_env_multiple($name) 
12836: 
12837: gets $name from the %env hash, it seemlessly handles the cases where multiple
12838: values may be defined and end up as an array ref.
12839: 
12840: returns an array of values
12841: 
12842: =back
12843: 
12844: =head2 User Information
12845: 
12846: =over 4
12847: 
12848: =item *
12849: X<queryauthenticate()>
12850: B<queryauthenticate($uname,$udom)>: try to determine user's current 
12851: authentication scheme
12852: 
12853: =item *
12854: X<authenticate()>
12855: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
12856: authenticate user from domain's lib servers (first use the current
12857: one). C<$upass> should be the users password.
12858: $checkdefauth is optional (value is 1 if a check should be made to
12859:    authenticate user using default authentication method, and allow
12860:    account creation if username does not have account in the domain).
12861: $clientcancheckhost is optional (value is 1 if checking whether the
12862:    server can host will occur on the client side in lonauth.pm).   
12863: 
12864: =item *
12865: X<homeserver()>
12866: B<homeserver($uname,$udom)>: find the server which has
12867: the user's directory and files (there must be only one), this caches
12868: the answer, and also caches if there is a borken connection.
12869: 
12870: =item *
12871: X<idget()>
12872: B<idget($udom,@ids)>: find the usernames behind a list of IDs
12873: (IDs are a unique resource in a domain, there must be only 1 ID per
12874: username, and only 1 username per ID in a specific domain) (returns
12875: hash: id=>name,id=>name)
12876: 
12877: =item *
12878: X<idrget()>
12879: B<idrget($udom,@unames)>: find the IDs behind a list of
12880: usernames (returns hash: name=>id,name=>id)
12881: 
12882: =item *
12883: X<idput()>
12884: B<idput($udom,%ids)>: store away a list of names and associated IDs
12885: 
12886: =item *
12887: X<rolesinit()>
12888: B<rolesinit($udom,$username)>: get user privileges.
12889: returns user role, first access and timer interval hashes
12890: 
12891: =item *
12892: X<privileged()>
12893: B<privileged($username,$domain)>: returns a true if user has a
12894: privileged and active role (i.e. su or dc), false otherwise.
12895: 
12896: =item *
12897: X<getsection()>
12898: B<getsection($udom,$uname,$cname)>: finds the section of student in the
12899: course $cname, return section name/number or '' for "not in course"
12900: and '-1' for "no section"
12901: 
12902: =item *
12903: X<userenvironment()>
12904: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
12905: passed in @what from the requested user's environment, returns a hash
12906: 
12907: =item * 
12908: X<userlog_query()>
12909: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
12910: activity.log file. %filters defines filters applied when parsing the
12911: log file. These can be start or end timestamps, or the type of action
12912: - log to look for Login or Logout events, check for Checkin or
12913: Checkout, role for role selection. The response is in the form
12914: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
12915: escaped strings of the action recorded in the activity.log file.
12916: 
12917: =back
12918: 
12919: =head2 User Roles
12920: 
12921: =over 4
12922: 
12923: =item *
12924: 
12925: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
12926:  F: full access
12927:  U,I,K: authentication modes (cxx only)
12928:  '': forbidden
12929:  1: user needs to choose course
12930:  2: browse allowed
12931:  A: passphrase authentication needed
12932: 
12933: =item *
12934: 
12935: constructaccess($url,$setpriv) : check for access to construction space URL
12936: 
12937: See if the owner domain and name in the URL match those in the
12938: expected environment.  If so, return three element list
12939: ($ownername,$ownerdomain,$ownerhome).
12940: 
12941: Otherwise return the null string.
12942: 
12943: If second argument 'setpriv' is true, it assigns the privileges,
12944: and returns the same three element list, unless the owner has
12945: blocked "ad hoc" Domain Coordinator access to the Author Space,
12946: in which case the null string is returned.
12947: 
12948: =item *
12949: 
12950: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
12951: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
12952: and course level
12953: 
12954: =item *
12955: 
12956: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
12957: (rolesplain.tab); plain text explanation of a user role term.
12958: $type is Course (default) or Community.
12959: If $forcedefault evaluates to true, text returned will be default 
12960: text for $type. Otherwise, if this is a course, the text returned 
12961: will be a custom name for the role (if defined in the course's 
12962: environment).  If no custom name is defined the default is returned.
12963:    
12964: =item *
12965: 
12966: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
12967: All arguments are optional. Returns a hash of a roles, either for
12968: co-author/assistant author roles for a user's Construction Space
12969: (default), or if $context is 'userroles', roles for the user himself,
12970: In the hash, keys are set to colon-separated $uname,$udom,$role, and
12971: (optionally) if $withsec is true, a fourth colon-separated item - $section.
12972: For each key, value is set to colon-separated start and end times for
12973: the role.  If no username and domain are specified, will default to
12974: current user/domain. Types, roles, and roledoms are references to arrays
12975: of role statuses (active, future or previous), roles 
12976: (e.g., cc,in, st etc.) and domains of the roles which can be used
12977: to restrict the list of roles reported. If no array ref is 
12978: provided for types, will default to return only active roles.
12979: 
12980: =item *
12981: 
12982: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
12983: user: $uname:$udom has a role in the course: $cdom_$cnum. 
12984: 
12985: Additional optional arguments are: $type (if role checking is to be restricted 
12986: to certain user status types -- previous (expired roles), active (currently
12987: available roles) or future (roles available in the future), and
12988: $hideprivileged -- if true will not report course roles for users who
12989: have active Domain Coordinator role in course's domain or in additional
12990: domains (specified in 'Domains to check for privileged users' in course
12991: environment -- set via:  Course Settings -> Classlists and staff listing).
12992: 
12993: =item *
12994: 
12995: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
12996: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
12997: $possdomains and $possroles are optional array refs -- to domains to check and
12998: roles to check.  If $possdomains is not specified, a dump will be done of the
12999: users' roles.db to check for a dc or su role in any domain. This can be
13000: time consuming if &privileged is called repeatedly (e.g., when displaying a
13001: classlist), so in such cases, supplying a $possdomains array is preferred, as
13002: this then allows &privileged_by_domain() to be used, which caches the identity
13003: of privileged users, eliminating the need for repeated calls to &dump().
13004: 
13005: =item *
13006: 
13007: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
13008: where the outer hash keys are domains specified in the $possdomains array ref,
13009: next inner hash keys are privileged roles specified in the $roles array ref,
13010: and the innermost hash contains key = value pairs for username:domain = end:start
13011: for active or future "privileged" users with that role in that domain. To avoid
13012: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
13013: innerhash are cached using priv_$role and $dom as the identifiers.
13014: 
13015: =back
13016: 
13017: =head2 User Modification
13018: 
13019: =over 4
13020: 
13021: =item *
13022: 
13023: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
13024: user for the level given by URL.  Optional start and end dates (leave empty
13025: string or zero for "no date")
13026: 
13027: =item *
13028: 
13029: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
13030: change a users, password, possible return values are: ok,
13031: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
13032: refused
13033: 
13034: =item *
13035: 
13036: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
13037: 
13038: =item *
13039: 
13040: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
13041:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
13042: 
13043: will update user information (firstname,middlename,lastname,generation,
13044: permanentemail), and if forceid is true, student/employee ID also.
13045: A user's institutional affiliation(s) can also be updated.
13046: User information fields will not be overwritten with empty entries 
13047: unless the field is included in the $candelete array reference.
13048: This array is included when a single user is modified via "Manage Users",
13049: or when Autoupdate.pl is run by cron in a domain.
13050: 
13051: =item *
13052: 
13053: modifystudent
13054: 
13055: modify a student's enrollment and identification information.
13056: The course id is resolved based on the current user's environment.  
13057: This means the invoking user must be a course coordinator or otherwise
13058: associated with a course.
13059: 
13060: This call is essentially a wrapper for lonnet::modifyuser and
13061: lonnet::modify_student_enrollment
13062: 
13063: Inputs: 
13064: 
13065: =over 4
13066: 
13067: =item B<$udom> Student's loncapa domain
13068: 
13069: =item B<$uname> Student's loncapa login name
13070: 
13071: =item B<$uid> Student/Employee ID
13072: 
13073: =item B<$umode> Student's authentication mode
13074: 
13075: =item B<$upass> Student's password
13076: 
13077: =item B<$first> Student's first name
13078: 
13079: =item B<$middle> Student's middle name
13080: 
13081: =item B<$last> Student's last name
13082: 
13083: =item B<$gene> Student's generation
13084: 
13085: =item B<$usec> Student's section in course
13086: 
13087: =item B<$end> Unix time of the roles expiration
13088: 
13089: =item B<$start> Unix time of the roles start date
13090: 
13091: =item B<$forceid> If defined, allow $uid to be changed
13092: 
13093: =item B<$desiredhome> server to use as home server for student
13094: 
13095: =item B<$email> Student's permanent e-mail address
13096: 
13097: =item B<$type> Type of enrollment (auto or manual)
13098: 
13099: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
13100: 
13101: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
13102: 
13103: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
13104: 
13105: =item B<$context> role change context (shown in User Management Logs display in a course)
13106: 
13107: =item B<$inststatus> institutional status of user - : separated string of escaped status types
13108: 
13109: =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.
13110: 
13111: =back
13112: 
13113: =item *
13114: 
13115: modify_student_enrollment
13116: 
13117: Change a student's enrollment status in a class.  The environment variable
13118: 'role.request.course' must be defined for this function to proceed.
13119: 
13120: Inputs:
13121: 
13122: =over 4
13123: 
13124: =item $udom, student's domain
13125: 
13126: =item $uname, student's name
13127: 
13128: =item $uid, student's user id
13129: 
13130: =item $first, student's first name
13131: 
13132: =item $middle
13133: 
13134: =item $last
13135: 
13136: =item $gene
13137: 
13138: =item $usec
13139: 
13140: =item $end
13141: 
13142: =item $start
13143: 
13144: =item $type
13145: 
13146: =item $locktype
13147: 
13148: =item $cid
13149: 
13150: =item $selfenroll
13151: 
13152: =item $context
13153: 
13154: =item $credits, number of credits student will earn from this class
13155: 
13156: =back
13157: 
13158: 
13159: =item *
13160: 
13161: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
13162: custom role; give a custom role to a user for the level given by URL.  Specify
13163: name and domain of role author, and role name
13164: 
13165: =item *
13166: 
13167: revokerole($udom,$uname,$url,$role) : revoke a role for url
13168: 
13169: =item *
13170: 
13171: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
13172: 
13173: =back
13174: 
13175: =head2 Course Infomation
13176: 
13177: =over 4
13178: 
13179: =item *
13180: 
13181: coursedescription($courseid,$options) : returns a hash of information about the
13182: specified course id, including all environment settings for the
13183: course, the description of the course will be in the hash under the
13184: key 'description'
13185: 
13186: $options is an optional parameter that if supplied is a hash reference that controls
13187: what how this function works.  It has the following key/values:
13188: 
13189: =over 4
13190: 
13191: =item freshen_cache
13192: 
13193: If defined, and the environment cache for the course is valid, it is 
13194: returned in the returned hash.
13195: 
13196: =item one_time
13197: 
13198: If defined, the last cache time is set to _now_
13199: 
13200: =item user
13201: 
13202: If defined, the supplied username is used instead of the current user.
13203: 
13204: 
13205: =back
13206: 
13207: =item *
13208: 
13209: resdata($name,$domain,$type,@which) : request for current parameter
13210: setting for a specific $type, where $type is either 'course' or 'user',
13211: @what should be a list of parameters to ask about. This routine caches
13212: answers for 10 minutes.
13213: 
13214: =item *
13215: 
13216: get_courseresdata($courseid, $domain) : dump the entire course resource
13217: data base, returning a hash that is keyed by the resource name and has
13218: values that are the resource value.  I believe that the timestamps and
13219: versions are also returned.
13220: 
13221: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
13222: supplemental content area. This routine caches the number of files for 
13223: 10 minutes.
13224: 
13225: =back
13226: 
13227: =head2 Course Modification
13228: 
13229: =over 4
13230: 
13231: =item *
13232: 
13233: writecoursepref($courseid,%prefs) : write preferences (environment
13234: database) for a course
13235: 
13236: =item *
13237: 
13238: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
13239: 
13240: =item *
13241: 
13242: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
13243: 
13244: =item *
13245: 
13246: is_course($courseid), is_course($cdom, $cnum)
13247: 
13248: Accepts either a combined $courseid (in the form of domain_courseid) or the
13249: two component version $cdom, $cnum. It checks if the specified course exists.
13250: 
13251: Returns:
13252:     undef if the course doesn't exist, otherwise
13253:     in scalar context the combined courseid.
13254:     in list context the two components of the course identifier, domain and 
13255:     courseid.    
13256: 
13257: =back
13258: 
13259: =head2 Resource Subroutines
13260: 
13261: =over 4
13262: 
13263: =item *
13264: 
13265: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
13266: 
13267: =item *
13268: 
13269: repcopy($filename) : subscribes to the requested file, and attempts to
13270: replicate from the owning library server, Might return
13271: 'unavailable', 'not_found', 'forbidden', 'ok', or
13272: 'bad_request', also attempts to grab the metadata for the
13273: resource. Expects the local filesystem pathname
13274: (/home/httpd/html/res/....)
13275: 
13276: =back
13277: 
13278: =head2 Resource Information
13279: 
13280: =over 4
13281: 
13282: =item *
13283: 
13284: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
13285: and returns the value of a variety of different possible values,
13286: $varname should be a request string, and the other parameters can be
13287: used to specify who and what one is asking about. Ordinarily, $cid 
13288: does not need to be specified, as it is retrived from 
13289: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
13290: within lonuserstate::loadmap() when initializing a course, before
13291: $env{'request.course.id'} has been set, so it needs to be provided
13292: in that one case.
13293: 
13294: Possible values for $varname are environment.lastname (or other item
13295: from the envirnment hash), user.name (or someother aspect about the
13296: user), resource.0.maxtries (or some other part and parameter of a
13297: resource)
13298: 
13299: =item *
13300: 
13301: directcondval($number) : get current value of a condition; reads from a state
13302: string
13303: 
13304: =item *
13305: 
13306: condval($condidx) : value of condition index based on state
13307: 
13308: =item *
13309: 
13310: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
13311: resource's metadata, $what should be either a specific key, or either
13312: 'keys' (to get a list of possible keys) or 'packages' to get a list of
13313: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
13314: 
13315: this function automatically caches all requests
13316: 
13317: =item *
13318: 
13319: metadata_query($query,$custom,$customshow) : make a metadata query against the
13320: network of library servers; returns file handle of where SQL and regex results
13321: will be stored for query
13322: 
13323: =item *
13324: 
13325: symbread($filename) : return symbolic list entry (filename argument optional);
13326: returns the data handle
13327: 
13328: =item *
13329: 
13330: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
13331: and is a possible symb for the URL in $thisfn, and if is an encrypted
13332: resource that the user accessed using /enc/ returns a 1 on success, 0
13333: on failure, user must be in a course, as it assumes the existence of
13334: the course initial hash, and uses $env('request.course.id'}.  The third
13335: arg is an optional reference to a scalar.  If this arg is passed in the 
13336: call to symbverify, it will be set to 1 if the symb has been set to be 
13337: encrypted; otherwise it will be null.  
13338: 
13339: =item *
13340: 
13341: symbclean($symb) : removes versions numbers from a symb, returns the
13342: cleaned symb
13343: 
13344: =item *
13345: 
13346: is_on_map($uri) : checks if the $uri is somewhere on the current
13347: course map, user must be in a course for it to work.
13348: 
13349: =item *
13350: 
13351: numval($salt) : return random seed value (addend for rndseed)
13352: 
13353: =item *
13354: 
13355: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13356: a random seed, all arguments are optional, if they aren't sent it uses the
13357: environment to derive them. Note: if symb isn't sent and it can't get one
13358: from &symbread it will use the current time as its return value
13359: 
13360: =item *
13361: 
13362: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13363: unfakeable, receipt
13364: 
13365: =item *
13366: 
13367: receipt() : API to ireceipt working off of env values; given out to users
13368: 
13369: =item *
13370: 
13371: countacc($url) : count the number of accesses to a given URL
13372: 
13373: =item *
13374: 
13375: 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
13376: 
13377: =item *
13378: 
13379: 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)
13380: 
13381: =item *
13382: 
13383: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
13384: 
13385: =item *
13386: 
13387: devalidate($symb) : devalidate temporary spreadsheet calculations,
13388: forcing spreadsheet to reevaluate the resource scores next time.
13389: 
13390: =item * 
13391: 
13392: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13393: when viewing in course context.
13394: 
13395:  input: six args -- filename (decluttered), course number, course domain,
13396:                     url, symb (if registered) and group (if this is a 
13397:                     group item -- e.g., bulletin board, group page etc.).
13398: 
13399:  output: array of five scalars --
13400:          $cfile -- url for file editing if editable on current server
13401:          $home -- homeserver of resource (i.e., for author if published,
13402:                                           or course if uploaded.).
13403:          $switchserver --  1 if server switch will be needed.
13404:          $forceedit -- 1 if icon/link should be to go to edit mode 
13405:          $forceview -- 1 if icon/link should be to go to view mode
13406: 
13407: =item *
13408: 
13409: is_course_upload($file,$cnum,$cdom)
13410: 
13411: Used in course context to determine if current file was uploaded to 
13412: the course (i.e., would be found in /userfiles/docs on the course's 
13413: homeserver.
13414: 
13415:   input: 3 args -- filename (decluttered), course number and course domain.
13416:   output: boolean -- 1 if file was uploaded.
13417: 
13418: =back
13419: 
13420: =head2 Storing/Retreiving Data
13421: 
13422: =over 4
13423: 
13424: =item *
13425: 
13426: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
13427: permanently for this url; hashref needs to be given and should be a \%hashname;
13428: the remaining args aren't required and if they aren't passed or are '' they will
13429: be derived from the env (with the exception of $laststore, which is an 
13430: optional arg used when a user's submission is stored in grading).
13431: $laststore is $version=$timestamp, where $version is the most recent version
13432: number retrieved for the corresponding $symb in the $namespace db file, and
13433: $timestamp is the timestamp for that transaction (UNIX time).
13434: $laststore is currently only passed when cstore() is called by 
13435: structuretags::finalize_storage().
13436: 
13437: =item *
13438: 
13439: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
13440: but uses critical subroutine
13441: 
13442: =item *
13443: 
13444: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13445: all args are optional
13446: 
13447: =item *
13448: 
13449: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
13450: dumps the complete (or key matching regexp) namespace into a hash
13451: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13452: normally &store()ed into
13453: 
13454: $range should be either an integer '100' (give me the first 100
13455:                                            matching records)
13456:               or be  two integers sperated by a - with no spaces
13457:                  '30-50' (give me the 30th through the 50th matching
13458:                           records)
13459: 
13460: 
13461: =item *
13462: 
13463: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
13464: replaces a &store() version of data with a replacement set of data
13465: for a particular resource in a namespace passed in the $storehash hash 
13466: reference. If $tolog is true, the transaction is logged in the courselog
13467: with an action=PUTSTORE.
13468: 
13469: =item *
13470: 
13471: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13472: works very similar to store/cstore, but all data is stored in a
13473: temporary location and can be reset using tmpreset, $storehash should
13474: be a hash reference, returns nothing on success
13475: 
13476: =item *
13477: 
13478: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13479: similar to restore, but all data is stored in a temporary location and
13480: can be reset using tmpreset. Returns a hash of values on success,
13481: error string otherwise.
13482: 
13483: =item *
13484: 
13485: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13486: deltes all keys for $symb form the temporary storage hash.
13487: 
13488: =item *
13489: 
13490: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13491: reference filled in from namesp ($udom and $uname are optional)
13492: 
13493: =item *
13494: 
13495: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13496: namesp ($udom and $uname are optional)
13497: 
13498: =item *
13499: 
13500: dump($namespace,$udom,$uname,$regexp,$range) : 
13501: dumps the complete (or key matching regexp) namespace into a hash
13502: ($udom, $uname, $regexp, $range are optional)
13503: 
13504: $range should be either an integer '100' (give me the first 100
13505:                                            matching records)
13506:               or be  two integers sperated by a - with no spaces
13507:                  '30-50' (give me the 30th through the 50th matching
13508:                           records)
13509: =item *
13510: 
13511: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13512: $store can be a scalar, an array reference, or if the amount to be 
13513: incremented is > 1, a hash reference.
13514: 
13515: ($udom and $uname are optional)
13516: 
13517: =item *
13518: 
13519: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13520: ($udom and $uname are optional)
13521: 
13522: =item *
13523: 
13524: cput($namespace,$storehash,$udom,$uname) : critical put
13525: ($udom and $uname are optional)
13526: 
13527: =item *
13528: 
13529: newput($namespace,$storehash,$udom,$uname) :
13530: 
13531: Attempts to store the items in the $storehash, but only if they don't
13532: currently exist, if this succeeds you can be certain that you have 
13533: successfully created a new key value pair in the $namespace db.
13534: 
13535: 
13536: Args:
13537:  $namespace: name of database to store values to
13538:  $storehash: hashref to store to the db
13539:  $udom: (optional) domain of user containing the db
13540:  $uname: (optional) name of user caontaining the db
13541: 
13542: Returns:
13543:  'ok' -> succeeded in storing all keys of $storehash
13544:  'key_exists: <key>' -> failed to anything out of $storehash, as at
13545:                         least <key> already existed in the db (other
13546:                         requested keys may also already exist)
13547:  'error: <msg>' -> unable to tie the DB or other error occurred
13548:  'con_lost' -> unable to contact request server
13549:  'refused' -> action was not allowed by remote machine
13550: 
13551: 
13552: =item *
13553: 
13554: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13555: reference filled in from namesp (encrypts the return communication)
13556: ($udom and $uname are optional)
13557: 
13558: =item *
13559: 
13560: log($udom,$name,$home,$message) : write to permanent log for user; use
13561: critical subroutine
13562: 
13563: =item *
13564: 
13565: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13566: array reference filled in from namespace found in domain level on either
13567: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
13568: 
13569: =item *
13570: 
13571: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
13572: domain level either on specified domain server ($uhome) or primary domain 
13573: server ($udom and $uhome are optional)
13574: 
13575: =item * 
13576: 
13577: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
13578: for: authentication, language, quotas, timezone, date locale, and portal URL in
13579: the target domain.
13580: 
13581: May also include additional key => value pairs for the following groups:
13582: 
13583: =over
13584: 
13585: =item
13586: disk quotas (MB allocated by default to portfolios and authoring spaces).
13587: 
13588: =over
13589: 
13590: =item defaultquota, authorquota
13591: 
13592: =back
13593: 
13594: =item
13595: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
13596: portfolio for users).
13597: 
13598: =over
13599: 
13600: =item
13601: aboutme, blog, webdav, portfolio
13602: 
13603: =back
13604: 
13605: =item
13606: requestcourses: ability to request courses, and how requests are processed.
13607: 
13608: =over
13609: 
13610: =item
13611: official, unofficial, community, textbook
13612: 
13613: =back
13614: 
13615: =item
13616: inststatus: types of institutional affiliation, and order in which they are displayed.
13617: 
13618: =over
13619: 
13620: =item
13621: inststatustypes, inststatusorder, inststatusguest
13622: 
13623: =back
13624: 
13625: =item
13626: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
13627: for course's uploaded content.
13628: 
13629: =over
13630: 
13631: =item
13632: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
13633: communityquota, textbookquota
13634: 
13635: =back
13636: 
13637: =item
13638: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
13639: on your servers.
13640: 
13641: =over
13642: 
13643: =item 
13644: remotesessions, hostedsessions
13645: 
13646: =back
13647: 
13648: =back
13649: 
13650: In cases where a domain coordinator has never used the "Set Domain Configuration"
13651: utility to create a configuration.db file on a domain's primary library server 
13652: only the following domain defaults: auth_def, auth_arg_def, lang_def
13653: -- corresponding values are authentication type (internal, krb4, krb5,
13654: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
13655: will be available. Values are retrieved from cache (if current), unless the
13656: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
13657: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
13658: 
13659: Typical usage:
13660: 
13661: %domdefaults = &get_domain_defaults($target_domain);
13662: 
13663: =back
13664: 
13665: =head2 Network Status Functions
13666: 
13667: =over 4
13668: 
13669: =item *
13670: 
13671: dirlist() : return directory list based on URI (first arg).
13672: 
13673: Inputs: 1 required, 5 optional.
13674: 
13675: =over
13676: 
13677: =item 
13678: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13679: 
13680: =item
13681: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
13682: 
13683: =item
13684: $username -  username of user/course to be listed. Extracted from $uri if absent. 
13685: 
13686: =item
13687: $getpropath - boolean: 1 if prepend path using &propath(). 
13688: 
13689: =item
13690: $getuserdir - boolean: 1 if prepend path for "userfiles".
13691: 
13692: =item 
13693: $alternateRoot - path to prepend in place of path from $uri.
13694: 
13695: =back
13696: 
13697: Returns: Array of up to two items.
13698: 
13699: =over
13700: 
13701: a reference to an array of files/subdirectories
13702: 
13703: =over
13704: 
13705: Each element in the array of files/subdirectories is a & separated list of
13706: item name and the result of running stat on the item.  If dirlist was requested
13707: for a file instead of a directory, the item name will be ''. For a directory 
13708: listing, if the item is a metadata file, the element will end &N&M 
13709: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13710: default copyright set (1).  
13711: 
13712: =back
13713: 
13714: a scalar containing error condition (if encountered).
13715: 
13716: =over
13717: 
13718: =item 
13719: no_host (no homeserver identified for $username:$domain).
13720: 
13721: =item 
13722: no_such_host (server contacted for listing not identified as valid host).
13723: 
13724: =item 
13725: con_lost (connection to remote server failed).
13726: 
13727: =item 
13728: refused (invalid $username:$domain received on lond side).
13729: 
13730: =item 
13731: no_such_dir (directory at specified path on lond side does not exist). 
13732: 
13733: =item 
13734: empty (directory at specified path on lond side is empty).
13735: 
13736: =over
13737: 
13738: This is currently not encountered because the &ls3, &ls2, 
13739: &ls (_handler) routines on the lond side do not filter out
13740: . and .. from a directory listing. 
13741: 
13742: =back
13743: 
13744: =back
13745: 
13746: =back
13747: 
13748: =item *
13749: 
13750: spareserver() : find server with least workload from spare.tab
13751: 
13752: 
13753: =item *
13754: 
13755: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13756: if there is no corresponding loncapa host.
13757: 
13758: =back
13759: 
13760: 
13761: =head2 Apache Request
13762: 
13763: =over 4
13764: 
13765: =item *
13766: 
13767: ssi($url,%hash) : server side include, does a complete request cycle on url to
13768: localhost, posts hash
13769: 
13770: =back
13771: 
13772: =head2 Data to String to Data
13773: 
13774: =over 4
13775: 
13776: =item *
13777: 
13778: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13779: and '&' separators, supports elements that are arrayrefs and hashrefs
13780: 
13781: =item *
13782: 
13783: hashref2str($hashref) : convert a hashref into a string complete with
13784: escaping and '=' and '&' separators, supports elements that are
13785: arrayrefs and hashrefs
13786: 
13787: =item *
13788: 
13789: arrayref2str($arrayref) : convert an arrayref into a string complete
13790: with escaping and '&' separators, supports elements that are arrayrefs
13791: and hashrefs
13792: 
13793: =item *
13794: 
13795: str2hash($string) : convert string to hash using unescaping and
13796: splitting on '=' and '&', supports elements that are arrayrefs and
13797: hashrefs
13798: 
13799: =item *
13800: 
13801: str2array($string) : convert string to hash using unescaping and
13802: splitting on '&', supports elements that are arrayrefs and hashrefs
13803: 
13804: =back
13805: 
13806: =head2 Logging Routines
13807: 
13808: 
13809: These routines allow one to make log messages in the lonnet.log and
13810: lonnet.perm logfiles.
13811: 
13812: =over 4
13813: 
13814: =item *
13815: 
13816: logtouch() : make sure the logfile, lonnet.log, exists
13817: 
13818: =item *
13819: 
13820: logthis() : append message to the normal lonnet.log file, it gets
13821: preiodically rolled over and deleted.
13822: 
13823: =item *
13824: 
13825: logperm() : append a permanent message to lonnet.perm.log, this log
13826: file never gets deleted by any automated portion of the system, only
13827: messages of critical importance should go in here.
13828: 
13829: 
13830: =back
13831: 
13832: =head2 General File Helper Routines
13833: 
13834: =over 4
13835: 
13836: =item *
13837: 
13838: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
13839: (a) files in /uploaded
13840:   (i) If a local copy of the file exists - 
13841:       compares modification date of local copy with last-modified date for 
13842:       definitive version stored on home server for course. If local copy is 
13843:       stale, requests a new version from the home server and stores it. 
13844:       If the original has been removed from the home server, then local copy 
13845:       is unlinked.
13846:   (ii) If local copy does not exist -
13847:       requests the file from the home server and stores it. 
13848:   
13849:   If $caller is 'uploadrep':  
13850:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
13851:     for request for files originally uploaded via DOCS. 
13852:      - returns 'ok' if fresh local copy now available, -1 otherwise.
13853:   
13854:   Otherwise:
13855:      This indicates a call from the content generation phase of the request.
13856:      -  returns the entire contents of the file or -1.
13857:      
13858: (b) files in /res
13859:    - returns the entire contents of a file or -1; 
13860:    it properly subscribes to and replicates the file if neccessary.
13861: 
13862: 
13863: =item *
13864: 
13865: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
13866:                   reference
13867: 
13868: returns either a stat() list of data about the file or an empty list
13869: if the file doesn't exist or couldn't find out about it (connection
13870: problems or user unknown)
13871: 
13872: =item *
13873: 
13874: filelocation($dir,$file) : returns file system location of a file
13875: based on URI; meant to be "fairly clean" absolute reference, $dir is a
13876: directory that relative $file lookups are to looked in ($dir of /a/dir
13877: and a file of ../bob will become /a/bob)
13878: 
13879: =item *
13880: 
13881: hreflocation($dir,$file) : returns file system location or a URL; same as
13882: filelocation except for hrefs
13883: 
13884: =item *
13885: 
13886: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
13887: also removes beginning /home/httpd/html unless /priv/ follows it.
13888: 
13889: =back
13890: 
13891: =head2 Usererfile file routines (/uploaded*)
13892: 
13893: =over 4
13894: 
13895: =item *
13896: 
13897: userfileupload(): main rotine for putting a file in a user or course's
13898:                   filespace, arguments are,
13899: 
13900:  formname - required - this is the name of the element in $env where the
13901:            filename, and the contents of the file to create/modifed exist
13902:            the filename is in $env{'form.'.$formname.'.filename'} and the
13903:            contents of the file is located in $env{'form.'.$formname}
13904:  context - if coursedoc, store the file in the course of the active role
13905:              of the current user; 
13906:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
13907:            if 'canceloverwrite': delete file in tmp/overwrites directory
13908:  subdir - required - subdirectory to put the file in under ../userfiles/
13909:          if undefined, it will be placed in "unknown"
13910: 
13911:  (This routine calls clean_filename() to remove any dangerous
13912:  characters from the filename, and then calls finuserfileupload() to
13913:  complete the transaction)
13914: 
13915:  returns either the url of the uploaded file (/uploaded/....) if successful
13916:  and /adm/notfound.html if unsuccessful
13917: 
13918: =item *
13919: 
13920: clean_filename(): routine for cleaing a filename up for storage in
13921:                  userfile space, argument is:
13922: 
13923:  filename - proposed filename
13924: 
13925: returns: the new clean filename
13926: 
13927: =item *
13928: 
13929: finishuserfileupload(): routine that creates and sends the file to
13930: userspace, probably shouldn't be called directly
13931: 
13932:   docuname: username or courseid of destination for the file
13933:   docudom: domain of user/course of destination for the file
13934:   formname: same as for userfileupload()
13935:   fname: filename (including subdirectories) for the file
13936:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
13937:   allfiles: reference to hash used to store objects found by parser
13938:   codebase: reference to hash used for codebases of java objects found by parser
13939:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
13940:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
13941:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
13942:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
13943:   context: if 'overwrite', will move the uploaded file from its temporary location to
13944:             userfiles to facilitate overwriting a previously uploaded file with same name.
13945:   mimetype: reference to scalar to accommodate mime type determined
13946:             from File::MMagic if $parser = parse.
13947: 
13948:  returns either the url of the uploaded file (/uploaded/....) if successful
13949:  and /adm/notfound.html if unsuccessful (or an error message if context 
13950:  was 'overwrite').
13951:  
13952: 
13953: =item *
13954: 
13955: renameuserfile(): renames an existing userfile to a new name
13956: 
13957:   Args:
13958:    docuname: username or courseid of destination for the file
13959:    docudom: domain of user/course of destination for the file
13960:    old: current file name (including any subdirs under userfiles)
13961:    new: desired file name (including any subdirs under userfiles)
13962: 
13963: =item *
13964: 
13965: mkdiruserfile(): creates a directory is a userfiles dir
13966: 
13967:   Args:
13968:    docuname: username or courseid of destination for the file
13969:    docudom: domain of user/course of destination for the file
13970:    dir: dir to create (including any subdirs under userfiles)
13971: 
13972: =item *
13973: 
13974: removeuserfile(): removes a file that exists in userfiles
13975: 
13976:   Args:
13977:    docuname: username or courseid of destination for the file
13978:    docudom: domain of user/course of destination for the file
13979:    fname: filname to delete (including any subdirs under userfiles)
13980: 
13981: =item *
13982: 
13983: removeuploadedurl(): convience function for removeuserfile()
13984: 
13985:   Args:
13986:    url:  a full /uploaded/... url to delete
13987: 
13988: =item * 
13989: 
13990: get_portfile_permissions():
13991:   Args:
13992:     domain: domain of user or course contain the portfolio files
13993:     user: name of user or num of course contain the portfolio files
13994:   Returns:
13995:     hashref of a dump of the proper file_permissions.db
13996:    
13997: 
13998: =item * 
13999: 
14000: get_access_controls():
14001: 
14002: Args:
14003:   current_permissions: the hash ref returned from get_portfile_permissions()
14004:   group: (optional) the group you want the files associated with
14005:   file: (optional) the file you want access info on
14006: 
14007: Returns:
14008:     a hash (keys are file names) of hashes containing
14009:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
14010:         values are XML containing access control settings (see below) 
14011: 
14012: Internal notes:
14013: 
14014:  access controls are stored in file_permissions.db as key=value pairs.
14015:     key -> path to file/file_name\0uniqueID:scope_end_start
14016:         where scope -> public,guest,course,group,domains or users.
14017:               end -> UNIX time for end of access (0 -> no end date)
14018:               start -> UNIX time for start of access
14019: 
14020:     value -> XML description of access control
14021:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
14022:             <start></start>
14023:             <end></end>
14024: 
14025:             <password></password>  for scope type = guest
14026: 
14027:             <domain></domain>     for scope type = course or group
14028:             <number></number>
14029:             <roles id="">
14030:              <role></role>
14031:              <access></access>
14032:              <section></section>
14033:              <group></group>
14034:             </roles>
14035: 
14036:             <dom></dom>         for scope type = domains
14037: 
14038:             <users>             for scope type = users
14039:              <user>
14040:               <uname></uname>
14041:               <udom></udom>
14042:              </user>
14043:             </users>
14044:            </scope> 
14045:               
14046:  Access data is also aggregated for each file in an additional key=value pair:
14047:  key -> path to file/file_name\0accesscontrol 
14048:  value -> reference to hash
14049:           hash contains key = value pairs
14050:           where key = uniqueID:scope_end_start
14051:                 value = UNIX time record was last updated
14052: 
14053:           Used to improve speed of look-ups of access controls for each file.  
14054:  
14055:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
14056: 
14057: =item *
14058: 
14059: modify_access_controls():
14060: 
14061: Modifies access controls for a portfolio file
14062: Args
14063: 1. file name
14064: 2. reference to hash of required changes,
14065: 3. domain
14066: 4. username
14067:   where domain,username are the domain of the portfolio owner 
14068:   (either a user or a course) 
14069: 
14070: Returns:
14071: 1. result of additions or updates ('ok' or 'error', with error message). 
14072: 2. result of deletions ('ok' or 'error', with error message).
14073: 3. reference to hash of any new or updated access controls.
14074: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
14075:    key = integer (inbound ID)
14076:    value = uniqueID
14077: 
14078: =item *
14079: 
14080: get_timebased_id():
14081: 
14082: Attempts to get a unique timestamp-based suffix for use with items added to a 
14083: course via the Course Editor (e.g., folders, composite pages, 
14084: group bulletin boards).
14085: 
14086: Args: (first three required; six others optional)
14087: 
14088: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
14089:    docssequence, or name of group
14090: 
14091: 2. keyid (alphanumeric): name of temporary locking key in hash,
14092:    e.g., num, boardids
14093: 
14094: 3. namespace: name of gdbm file used to store suffixes already assigned;  
14095:    file will be named nohist_namespace.db
14096: 
14097: 4. cdom: domain of course; default is current course domain from %env
14098: 
14099: 5. cnum: course number; default is current course number from %env
14100: 
14101: 6. idtype: set to concat if an additional digit is to be appended to the 
14102:    unix timestamp to form the suffix, if the plain timestamp is already
14103:    in use.  Default is to not do this, but simply increment the unix 
14104:    timestamp by 1 until a unique key is obtained.
14105: 
14106: 7. who: holder of locking key; defaults to user:domain for user.
14107: 
14108: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
14109:    retrying); default is 3.
14110: 
14111: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
14112: 
14113: Returns:
14114: 
14115: 1. suffix obtained (numeric)
14116: 
14117: 2. result of deleting locking key (ok if deleted, or lock never obtained)
14118: 
14119: 3. error: contains (localized) error message if an error occurred.
14120: 
14121: 
14122: =back
14123: 
14124: =head2 HTTP Helper Routines
14125: 
14126: =over 4
14127: 
14128: =item *
14129: 
14130: escape() : unpack non-word characters into CGI-compatible hex codes
14131: 
14132: =item *
14133: 
14134: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
14135: 
14136: =back
14137: 
14138: =head1 PRIVATE SUBROUTINES
14139: 
14140: =head2 Underlying communication routines (Shouldn't call)
14141: 
14142: =over 4
14143: 
14144: =item *
14145: 
14146: subreply() : tries to pass a message to lonc, returns con_lost if incapable
14147: 
14148: =item *
14149: 
14150: reply() : uses subreply to send a message to remote machine, logs all failures
14151: 
14152: =item *
14153: 
14154: critical() : passes a critical message to another server; if cannot
14155: get through then place message in connection buffer directory and
14156: returns con_delayed, if incapable of saving message, returns
14157: con_failed
14158: 
14159: =item *
14160: 
14161: reconlonc() : tries to reconnect lonc client processes.
14162: 
14163: =back
14164: 
14165: =head2 Resource Access Logging
14166: 
14167: =over 4
14168: 
14169: =item *
14170: 
14171: flushcourselogs() : flush (save) buffer logs and access logs
14172: 
14173: =item *
14174: 
14175: courselog($what) : save message for course in hash
14176: 
14177: =item *
14178: 
14179: courseacclog($what) : save message for course using &courselog().  Perform
14180: special processing for specific resource types (problems, exams, quizzes, etc).
14181: 
14182: =item *
14183: 
14184: goodbye() : flush course logs and log shutting down; it is called in srm.conf
14185: as a PerlChildExitHandler
14186: 
14187: =back
14188: 
14189: =head2 Other
14190: 
14191: =over 4
14192: 
14193: =item *
14194: 
14195: symblist($mapname,%newhash) : update symbolic storage links
14196: 
14197: =back
14198: 
14199: =cut
14200: 

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