File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1258: download - view: text, annotated - select for diffs
Sun May 4 21:49:00 2014 UTC (10 years, 2 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Catalog type set for domain (authenticated and unauthenticated) included
  in domain defaults (cached).
- Display of prompts on roles/courses screen for users without any active
  roles depend on catalog type set for user's domain (or default domain,
  if unauthenticated).

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1258 2014/05/04 21:49:00 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: =pod
   31: 
   32: =head1 NAME
   33: 
   34: Apache::lonnet.pm
   35: 
   36: =head1 SYNOPSIS
   37: 
   38: This file is an interface to the lonc processes of
   39: the LON-CAPA network as well as set of elaborated functions for handling information
   40: necessary for navigating through a given cluster of LON-CAPA machines within a
   41: domain. There are over 40 specialized functions in this module which handle the
   42: reading and transmission of metadata, user information (ids, names, environments, roles,
   43: logs), file information (storage, reading, directories, extensions, replication, embedded
   44: styles and descriptors), educational resources (course descriptions, section names and
   45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
   46: and from more descriptive phrases or explanations.
   47: 
   48: This is part of the LearningOnline Network with CAPA project
   49: described at http://www.lon-capa.org.
   50: 
   51: =head1 Package Variables
   52: 
   53: These are largely undocumented, so if you decipher one please note it here.
   54: 
   55: =over 4
   56: 
   57: =item $processmarker
   58: 
   59: Contains the time this process was started and this servers host id.
   60: 
   61: =item $dumpcount
   62: 
   63: Counts the number of times a message log flush has been attempted (regardless
   64: of success) by this process.  Used as part of the filename when messages are
   65: delayed.
   66: 
   67: =back
   68: 
   69: =cut
   70: 
   71: package Apache::lonnet;
   72: 
   73: use strict;
   74: use LWP::UserAgent();
   75: use HTTP::Date;
   76: use Image::Magick;
   77: 
   78: 
   79: use Encode;
   80: 
   81: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
   82:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
   83:             %managerstab);
   84: 
   85: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   86:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   87:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   88:     %courseownerbuf, %coursetypebuf,$locknum);
   89: 
   90: use IO::Socket;
   91: use GDBM_File;
   92: use HTML::LCParser;
   93: use Fcntl qw(:flock);
   94: use Storable qw(thaw nfreeze);
   95: use Time::HiRes qw( gettimeofday tv_interval );
   96: use Cache::Memcached;
   97: use Digest::MD5;
   98: use Math::Random;
   99: use File::MMagic;
  100: use LONCAPA qw(:DEFAULT :match);
  101: use LONCAPA::Configuration;
  102: use LONCAPA::lonmetadata;
  103: use LONCAPA::Lond;
  104: 
  105: use File::Copy;
  106: 
  107: my $readit;
  108: my $max_connection_retries = 10;     # Or some such value.
  109: 
  110: require Exporter;
  111: 
  112: our @ISA = qw (Exporter);
  113: our @EXPORT = qw(%env);
  114: 
  115: 
  116: # ------------------------------------ Logging (parameters, docs, slots, roles)
  117: {
  118:     my $logid;
  119:     sub write_log {
  120: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  121:         if ($context eq 'course') {
  122:             if (($cnum eq '') || ($cdom eq '')) {
  123:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  124:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  125:             }
  126:         }
  127: 	$logid ++;
  128:         my $now = time();
  129: 	my $id=$now.'00000'.$$.'00000'.$logid;
  130:         my $logentry = { 
  131:                           $id => {
  132:                                    'exe_uname' => $env{'user.name'},
  133:                                    'exe_udom'  => $env{'user.domain'},
  134:                                    'exe_time'  => $now,
  135:                                    'exe_ip'    => $ENV{'REMOTE_ADDR'},
  136:                                    'delflag'   => $delflag,
  137:                                    'logentry'  => $storehash,
  138:                                    'uname'     => $uname,
  139:                                    'udom'      => $udom,
  140:                                   }
  141:                        };
  142: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
  143:     }
  144: }
  145: 
  146: sub logtouch {
  147:     my $execdir=$perlvar{'lonDaemons'};
  148:     unless (-e "$execdir/logs/lonnet.log") {	
  149: 	open(my $fh,">>$execdir/logs/lonnet.log");
  150: 	close $fh;
  151:     }
  152:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  153:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  154: }
  155: 
  156: sub logthis {
  157:     my $message=shift;
  158:     my $execdir=$perlvar{'lonDaemons'};
  159:     my $now=time;
  160:     my $local=localtime($now);
  161:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  162: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  163: 	print $fh $logstring;
  164: 	close($fh);
  165:     }
  166:     return 1;
  167: }
  168: 
  169: sub logperm {
  170:     my $message=shift;
  171:     my $execdir=$perlvar{'lonDaemons'};
  172:     my $now=time;
  173:     my $local=localtime($now);
  174:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  175: 	print $fh "$now:$message:$local\n";
  176: 	close($fh);
  177:     }
  178:     return 1;
  179: }
  180: 
  181: sub create_connection {
  182:     my ($hostname,$lonid) = @_;
  183:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  184: 				     Type    => SOCK_STREAM,
  185: 				     Timeout => 10);
  186:     return 0 if (!$client);
  187:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  188:     my $result = <$client>;
  189:     chomp($result);
  190:     return 1 if ($result eq 'done');
  191:     return 0;
  192: }
  193: 
  194: sub get_server_timezone {
  195:     my ($cnum,$cdom) = @_;
  196:     my $home=&homeserver($cnum,$cdom);
  197:     if ($home ne 'no_host') {
  198:         my $cachetime = 24*3600;
  199:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  200:         if (defined($cached)) {
  201:             return $timezone;
  202:         } else {
  203:             my $timezone = &reply('servertimezone',$home);
  204:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  205:         }
  206:     }
  207: }
  208: 
  209: sub get_server_distarch {
  210:     my ($lonhost,$ignore_cache) = @_;
  211:     if (defined($lonhost)) {
  212:         if (!defined(&hostname($lonhost))) {
  213:             return;
  214:         }
  215:         my $cachetime = 12*3600;
  216:         if (!$ignore_cache) {
  217:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  218:             if (defined($cached)) {
  219:                 return $distarch;
  220:             }
  221:         }
  222:         my $rep = &reply('serverdistarch',$lonhost);
  223:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  224:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  225:                 $rep eq '') {
  226:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  227:         }
  228:     }
  229:     return;
  230: }
  231: 
  232: sub get_server_loncaparev {
  233:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  234:     if (defined($lonhost)) {
  235:         if (!defined(&hostname($lonhost))) {
  236:             undef($lonhost);
  237:         }
  238:     }
  239:     if (!defined($lonhost)) {
  240:         if (defined(&domain($dom,'primary'))) {
  241:             $lonhost=&domain($dom,'primary');
  242:             if ($lonhost eq 'no_host') {
  243:                 undef($lonhost);
  244:             }
  245:         }
  246:     }
  247:     if (defined($lonhost)) {
  248:         my $cachetime = 12*3600;
  249:         if (!$ignore_cache) {
  250:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  251:             if (defined($cached)) {
  252:                 return $loncaparev;
  253:             }
  254:         }
  255:         my ($answer,$loncaparev);
  256:         my @ids=&current_machine_ids();
  257:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  258:             $answer = $perlvar{'lonVersion'};
  259:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  260:                 $loncaparev = $1;
  261:             }
  262:         } else {
  263:             $answer = &reply('serverloncaparev',$lonhost);
  264:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  265:                 if ($caller eq 'loncron') {
  266:                     my $ua=new LWP::UserAgent;
  267:                     $ua->timeout(4);
  268:                     my $protocol = $protocol{$lonhost};
  269:                     $protocol = 'http' if ($protocol ne 'https');
  270:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
  271:                     my $request=new HTTP::Request('GET',$url);
  272:                     my $response=$ua->request($request);
  273:                     unless ($response->is_error()) {
  274:                         my $content = $response->content;
  275:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  276:                             $loncaparev = $1;
  277:                         }
  278:                     }
  279:                 } else {
  280:                     $loncaparev = $loncaparevs{$lonhost};
  281:                 }
  282:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  283:                 $loncaparev = $1;
  284:             }
  285:         }
  286:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  287:     }
  288: }
  289: 
  290: sub get_server_homeID {
  291:     my ($hostname,$ignore_cache,$caller) = @_;
  292:     unless ($ignore_cache) {
  293:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  294:         if (defined($cached)) {
  295:             return $serverhomeID;
  296:         }
  297:     }
  298:     my $cachetime = 12*3600;
  299:     my $serverhomeID;
  300:     if ($caller eq 'loncron') { 
  301:         my @machine_ids = &machine_ids($hostname);
  302:         foreach my $id (@machine_ids) {
  303:             my $response = &reply('serverhomeID',$id);
  304:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  305:                 $serverhomeID = $response;
  306:                 last;
  307:             }
  308:         }
  309:         if ($serverhomeID eq '') {
  310:             $serverhomeID = $machine_ids[-1];
  311:         }
  312:     } else {
  313:         $serverhomeID = $serverhomeIDs{$hostname};
  314:     }
  315:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  316: }
  317: 
  318: sub get_remote_globals {
  319:     my ($lonhost,$whathash,$ignore_cache) = @_;
  320:     my ($result,%returnhash,%whatneeded);
  321:     if (ref($whathash) eq 'HASH') {
  322:         foreach my $what (sort(keys(%{$whathash}))) {
  323:             my $hashid = $lonhost.'-'.$what;
  324:             my ($response,$cached);
  325:             unless ($ignore_cache) {
  326:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  327:             }
  328:             if (defined($cached)) {
  329:                 $returnhash{$what} = $response;
  330:             } else {
  331:                 $whatneeded{$what} = 1;
  332:             }
  333:         }
  334:         if (keys(%whatneeded) == 0) {
  335:             $result = 'ok';
  336:         } else {
  337:             my $requested = &freeze_escape(\%whatneeded);
  338:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  339:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  340:                 ($rep eq 'unknown_cmd')) {
  341:                 $result = $rep;
  342:             } else {
  343:                 $result = 'ok';
  344:                 my @pairs=split(/\&/,$rep);
  345:                 foreach my $item (@pairs) {
  346:                     my ($key,$value)=split(/=/,$item,2);
  347:                     my $what = &unescape($key);
  348:                     my $hashid = $lonhost.'-'.$what;
  349:                     $returnhash{$what}=&thaw_unescape($value);
  350:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  351:                 }
  352:             }
  353:         }
  354:     }
  355:     return ($result,\%returnhash);
  356: }
  357: 
  358: sub remote_devalidate_cache {
  359:     my ($lonhost,$cachekeys) = @_;
  360:     my $items;
  361:     return unless (ref($cachekeys) eq 'ARRAY');
  362:     my $cachestr = join('&',@{$cachekeys});
  363:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
  364:     return $response;
  365: }
  366: 
  367: # -------------------------------------------------- Non-critical communication
  368: sub subreply {
  369:     my ($cmd,$server)=@_;
  370:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  371:     #
  372:     #  With loncnew process trimming, there's a timing hole between lonc server
  373:     #  process exit and the master server picking up the listen on the AF_UNIX
  374:     #  socket.  In that time interval, a lock file will exist:
  375: 
  376:     my $lockfile=$peerfile.".lock";
  377:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  378: 	sleep(1);
  379:     }
  380:     # At this point, either a loncnew parent is listening or an old lonc
  381:     # or loncnew child is listening so we can connect or everything's dead.
  382:     #
  383:     #   We'll give the connection a few tries before abandoning it.  If
  384:     #   connection is not possible, we'll con_lost back to the client.
  385:     #   
  386:     my $client;
  387:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  388: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  389: 				      Type    => SOCK_STREAM,
  390: 				      Timeout => 10);
  391: 	if ($client) {
  392: 	    last;		# Connected!
  393: 	} else {
  394: 	    &create_connection(&hostname($server),$server);
  395: 	}
  396:         sleep(1);		# Try again later if failed connection.
  397:     }
  398:     my $answer;
  399:     if ($client) {
  400: 	print $client "sethost:$server:$cmd\n";
  401: 	$answer=<$client>;
  402: 	if (!$answer) { $answer="con_lost"; }
  403: 	chomp($answer);
  404:     } else {
  405: 	$answer = 'con_lost';	# Failed connection.
  406:     }
  407:     return $answer;
  408: }
  409: 
  410: sub reply {
  411:     my ($cmd,$server)=@_;
  412:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  413:     my $answer=subreply($cmd,$server);
  414:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  415:        &logthis("<font color=\"blue\">WARNING:".
  416:                 " $cmd to $server returned $answer</font>");
  417:     }
  418:     return $answer;
  419: }
  420: 
  421: # ----------------------------------------------------------- Send USR1 to lonc
  422: 
  423: sub reconlonc {
  424:     my ($lonid) = @_;
  425:     my $hostname = &hostname($lonid);
  426:     if ($lonid) {
  427: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  428: 	if ($hostname && -e $peerfile) {
  429: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  430: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  431: 					     Type    => SOCK_STREAM,
  432: 					     Timeout => 10);
  433: 	    if ($client) {
  434: 		print $client ("reset_retries\n");
  435: 		my $answer=<$client>;
  436: 		#reset just this one.
  437: 	    }
  438: 	}
  439: 	return;
  440:     }
  441: 
  442:     &logthis("Trying to reconnect lonc");
  443:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  444:     if (open(my $fh,"<$loncfile")) {
  445: 	my $loncpid=<$fh>;
  446:         chomp($loncpid);
  447:         if (kill 0 => $loncpid) {
  448: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  449:             kill USR1 => $loncpid;
  450:             sleep 1;
  451:          } else {
  452: 	    &logthis(
  453:                "<font color=\"blue\">WARNING:".
  454:                " lonc at pid $loncpid not responding, giving up</font>");
  455:         }
  456:     } else {
  457: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  458:     }
  459: }
  460: 
  461: # ------------------------------------------------------ Critical communication
  462: 
  463: sub critical {
  464:     my ($cmd,$server)=@_;
  465:     unless (&hostname($server)) {
  466:         &logthis("<font color=\"blue\">WARNING:".
  467:                " Critical message to unknown server ($server)</font>");
  468:         return 'no_such_host';
  469:     }
  470:     my $answer=reply($cmd,$server);
  471:     if ($answer eq 'con_lost') {
  472: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  473: 	my $answer=reply($cmd,$server);
  474:         if ($answer eq 'con_lost') {
  475:             my $now=time;
  476:             my $middlename=$cmd;
  477:             $middlename=substr($middlename,0,16);
  478:             $middlename=~s/\W//g;
  479:             my $dfilename=
  480:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  481:             $dumpcount++;
  482:             {
  483: 		my $dfh;
  484: 		if (open($dfh,">$dfilename")) {
  485: 		    print $dfh "$cmd\n"; 
  486: 		    close($dfh);
  487: 		}
  488:             }
  489:             sleep 2;
  490:             my $wcmd='';
  491:             {
  492: 		my $dfh;
  493: 		if (open($dfh,"<$dfilename")) {
  494: 		    $wcmd=<$dfh>; 
  495: 		    close($dfh);
  496: 		}
  497:             }
  498:             chomp($wcmd);
  499:             if ($wcmd eq $cmd) {
  500: 		&logthis("<font color=\"blue\">WARNING: ".
  501:                          "Connection buffer $dfilename: $cmd</font>");
  502:                 &logperm("D:$server:$cmd");
  503: 	        return 'con_delayed';
  504:             } else {
  505:                 &logthis("<font color=\"red\">CRITICAL:"
  506:                         ." Critical connection failed: $server $cmd</font>");
  507:                 &logperm("F:$server:$cmd");
  508:                 return 'con_failed';
  509:             }
  510:         }
  511:     }
  512:     return $answer;
  513: }
  514: 
  515: # ------------------------------------------- check if return value is an error
  516: 
  517: sub error {
  518:     my ($result) = @_;
  519:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  520: 	if ($2 == 2) { return undef; }
  521: 	return $1;
  522:     }
  523:     return undef;
  524: }
  525: 
  526: sub convert_and_load_session_env {
  527:     my ($lonidsdir,$handle)=@_;
  528:     my @profile;
  529:     {
  530: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  531: 	if (!$opened) {
  532: 	    return 0;
  533: 	}
  534: 	flock($idf,LOCK_SH);
  535: 	@profile=<$idf>;
  536: 	close($idf);
  537:     }
  538:     my %temp_env;
  539:     foreach my $line (@profile) {
  540: 	if ($line !~ m/=/) {
  541: 	    return 0;
  542: 	}
  543: 	chomp($line);
  544: 	my ($envname,$envvalue)=split(/=/,$line,2);
  545: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  546:     }
  547:     unlink("$lonidsdir/$handle.id");
  548:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  549: 	    0640)) {
  550: 	%disk_env = %temp_env;
  551: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  552: 	untie(%disk_env);
  553:     }
  554:     return 1;
  555: }
  556: 
  557: # ------------------------------------------- Transfer profile into environment
  558: my $env_loaded;
  559: sub transfer_profile_to_env {
  560:     my ($lonidsdir,$handle,$force_transfer) = @_;
  561:     if (!$force_transfer && $env_loaded) { return; } 
  562: 
  563:     if (!defined($lonidsdir)) {
  564: 	$lonidsdir = $perlvar{'lonIDsDir'};
  565:     }
  566:     if (!defined($handle)) {
  567:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  568:     }
  569: 
  570:     my $convert;
  571:     {
  572:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  573: 	if (!$opened) {
  574: 	    return;
  575: 	}
  576: 	flock($idf,LOCK_SH);
  577: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  578: 		&GDBM_READER(),0640)) {
  579: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  580: 	    untie(%disk_env);
  581: 	} else {
  582: 	    $convert = 1;
  583: 	}
  584:     }
  585:     if ($convert) {
  586: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  587: 	    &logthis("Failed to load session, or convert session.");
  588: 	}
  589:     }
  590: 
  591:     my %remove;
  592:     while ( my $envname = each(%env) ) {
  593:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  594:             if ($time < time-300) {
  595:                 $remove{$key}++;
  596:             }
  597:         }
  598:     }
  599: 
  600:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  601:     $env_loaded=1;
  602:     foreach my $expired_key (keys(%remove)) {
  603:         &delenv($expired_key);
  604:     }
  605: }
  606: 
  607: # ---------------------------------------------------- Check for valid session 
  608: sub check_for_valid_session {
  609:     my ($r,$name,$userhashref) = @_;
  610:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  611:     if ($name eq '') {
  612:         $name = 'lonID';
  613:     }
  614:     my $lonid=$cookies{$name};
  615:     return undef if (!$lonid);
  616: 
  617:     my $handle=&LONCAPA::clean_handle($lonid->value);
  618:     my $lonidsdir;
  619:     if ($name eq 'lonDAV') {
  620:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  621:     } else {
  622:         $lonidsdir=$r->dir_config('lonIDsDir');
  623:     }
  624:     return undef if (!-e "$lonidsdir/$handle.id");
  625: 
  626:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  627:     return undef if (!$opened);
  628: 
  629:     flock($idf,LOCK_SH);
  630:     my %disk_env;
  631:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  632: 	    &GDBM_READER(),0640)) {
  633: 	return undef;	
  634:     }
  635: 
  636:     if (!defined($disk_env{'user.name'})
  637: 	|| !defined($disk_env{'user.domain'})) {
  638: 	return undef;
  639:     }
  640: 
  641:     if (ref($userhashref) eq 'HASH') {
  642:         $userhashref->{'name'} = $disk_env{'user.name'};
  643:         $userhashref->{'domain'} = $disk_env{'user.domain'};
  644:     }
  645: 
  646:     return $handle;
  647: }
  648: 
  649: sub timed_flock {
  650:     my ($file,$lock_type) = @_;
  651:     my $failed=0;
  652:     eval {
  653: 	local $SIG{__DIE__}='DEFAULT';
  654: 	local $SIG{ALRM}=sub {
  655: 	    $failed=1;
  656: 	    die("failed lock");
  657: 	};
  658: 	alarm(13);
  659: 	flock($file,$lock_type);
  660: 	alarm(0);
  661:     };
  662:     if ($failed) {
  663: 	return undef;
  664:     } else {
  665: 	return 1;
  666:     }
  667: }
  668: 
  669: # ---------------------------------------------------------- Append Environment
  670: 
  671: sub appenv {
  672:     my ($newenv,$roles) = @_;
  673:     if (ref($newenv) eq 'HASH') {
  674:         foreach my $key (keys(%{$newenv})) {
  675:             my $refused = 0;
  676: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  677:                 $refused = 1;
  678:                 if (ref($roles) eq 'ARRAY') {
  679:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
  680:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  681:                         $refused = 0;
  682:                     }
  683:                 }
  684:             }
  685:             if ($refused) {
  686:                 &logthis("<font color=\"blue\">WARNING: ".
  687:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  688:                          .'</font>');
  689: 	        delete($newenv->{$key});
  690:             } else {
  691:                 $env{$key}=$newenv->{$key};
  692:             }
  693:         }
  694:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  695:         if ($opened
  696: 	    && &timed_flock($env_file,LOCK_EX)
  697: 	    &&
  698: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  699: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  700: 	    while (my ($key,$value) = each(%{$newenv})) {
  701: 	        $disk_env{$key} = $value;
  702: 	    }
  703: 	    untie(%disk_env);
  704:         }
  705:     }
  706:     return 'ok';
  707: }
  708: # ----------------------------------------------------- Delete from Environment
  709: 
  710: sub delenv {
  711:     my ($delthis,$regexp,$roles) = @_;
  712:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  713:         my $refused = 1;
  714:         if (ref($roles) eq 'ARRAY') {
  715:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  716:             if (grep(/^\Q$role\E$/,@{$roles})) {
  717:                 $refused = 0;
  718:             }
  719:         }
  720:         if ($refused) {
  721:             &logthis("<font color=\"blue\">WARNING: ".
  722:                      "Attempt to delete from environment ".$delthis);
  723:             return 'error';
  724:         }
  725:     }
  726:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  727:     if ($opened
  728: 	&& &timed_flock($env_file,LOCK_EX)
  729: 	&&
  730: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  731: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  732: 	foreach my $key (keys(%disk_env)) {
  733: 	    if ($regexp) {
  734:                 if ($key=~/^$delthis/) {
  735:                     delete($env{$key});
  736:                     delete($disk_env{$key});
  737:                 } 
  738:             } else {
  739:                 if ($key=~/^\Q$delthis\E/) {
  740: 		    delete($env{$key});
  741: 		    delete($disk_env{$key});
  742: 	        }
  743:             }
  744: 	}
  745: 	untie(%disk_env);
  746:     }
  747:     return 'ok';
  748: }
  749: 
  750: sub get_env_multiple {
  751:     my ($name) = @_;
  752:     my @values;
  753:     if (defined($env{$name})) {
  754:         # exists is it an array
  755:         if (ref($env{$name})) {
  756:             @values=@{ $env{$name} };
  757:         } else {
  758:             $values[0]=$env{$name};
  759:         }
  760:     }
  761:     return(@values);
  762: }
  763: 
  764: # ------------------------------------------------------------------- Locking
  765: 
  766: sub set_lock {
  767:     my ($text)=@_;
  768:     $locknum++;
  769:     my $id=$$.'-'.$locknum;
  770:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  771:              'session.lock.'.$id => $text});
  772:     return $id;
  773: }
  774: 
  775: sub get_locks {
  776:     my $num=0;
  777:     my %texts=();
  778:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  779:        if ($lock=~/\w/) {
  780:           $num++;
  781:           $texts{$lock}=$env{'session.lock.'.$lock};
  782:        }
  783:    }
  784:    return ($num,%texts);
  785: }
  786: 
  787: sub remove_lock {
  788:     my ($id)=@_;
  789:     my $newlocks='';
  790:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  791:        if (($lock=~/\w/) && ($lock ne $id)) {
  792:           $newlocks.=','.$lock;
  793:        }
  794:     }
  795:     &appenv({'session.locks' => $newlocks});
  796:     &delenv('session.lock.'.$id);
  797: }
  798: 
  799: sub remove_all_locks {
  800:     my $activelocks=$env{'session.locks'};
  801:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  802:        if ($lock=~/\w/) {
  803:           &remove_lock($lock);
  804:        }
  805:     }
  806: }
  807: 
  808: 
  809: # ------------------------------------------ Find out current server userload
  810: sub userload {
  811:     my $numusers=0;
  812:     {
  813: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  814: 	my $filename;
  815: 	my $curtime=time;
  816: 	while ($filename=readdir(LONIDS)) {
  817: 	    next if ($filename eq '.' || $filename eq '..');
  818: 	    next if ($filename =~ /publicuser_\d+\.id/);
  819: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  820: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  821: 	}
  822: 	closedir(LONIDS);
  823:     }
  824:     my $userloadpercent=0;
  825:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  826:     if ($maxuserload) {
  827: 	$userloadpercent=100*$numusers/$maxuserload;
  828:     }
  829:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  830:     return $userloadpercent;
  831: }
  832: 
  833: # ------------------------------ Find server with least workload from spare.tab
  834: 
  835: sub spareserver {
  836:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  837:     my $spare_server;
  838:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  839:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  840:                                                      :  $userloadpercent;
  841:     my ($uint_dom,$remotesessions);
  842:     if (($udom ne '') && (&domain($udom) ne '')) {
  843:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  844:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  845:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  846:         $remotesessions = $udomdefaults{'remotesessions'};
  847:     }
  848:     my $spareshash = &this_host_spares($udom);
  849:     if (ref($spareshash) eq 'HASH') {
  850:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  851:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  852:                 if ($uint_dom) {
  853:                     next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  854:                                                  $try_server));
  855:                 }
  856: 	        ($spare_server, $lowest_load) =
  857: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  858:             }
  859:         }
  860: 
  861:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
  862: 
  863:         if (!$found_server) {
  864:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
  865: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
  866:                     if ($uint_dom) {
  867:                         next unless (&spare_can_host($udom,$uint_dom,
  868:                                                      $remotesessions,$try_server));
  869:                     }
  870: 	            ($spare_server, $lowest_load) =
  871: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
  872:                 }
  873: 	    }
  874:         }
  875:     }
  876: 
  877:     if (!$want_server_name) {
  878:         my $protocol = 'http';
  879:         if ($protocol{$spare_server} eq 'https') {
  880:             $protocol = $protocol{$spare_server};
  881:         }
  882:         if (defined($spare_server)) {
  883:             my $hostname = &hostname($spare_server);
  884:             if (defined($hostname)) {
  885: 	        $spare_server = $protocol.'://'.$hostname;
  886:             }
  887:         }
  888:     }
  889:     return $spare_server;
  890: }
  891: 
  892: sub compare_server_load {
  893:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
  894: 
  895:     if ($required) {
  896:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
  897:         my $remoterev = &get_server_loncaparev(undef,$try_server);
  898:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
  899:         if (($major eq '' && $minor eq '') ||
  900:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
  901:             return ($spare_server,$lowest_load);
  902:         }
  903:     }
  904: 
  905:     my $loadans     = &reply('load',    $try_server);
  906:     my $userloadans = &reply('userload',$try_server);
  907: 
  908:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  909: 	return ($spare_server, $lowest_load); #didn't get a number from the server
  910:     }
  911: 
  912:     my $load;
  913:     if ($loadans =~ /\d/) {
  914: 	if ($userloadans =~ /\d/) {
  915: 	    #both are numbers, pick the bigger one
  916: 	    $load = ($loadans > $userloadans) ? $loadans 
  917: 		                              : $userloadans;
  918: 	} else {
  919: 	    $load = $loadans;
  920: 	}
  921:     } else {
  922: 	$load = $userloadans;
  923:     }
  924: 
  925:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  926: 	$spare_server = $try_server;
  927: 	$lowest_load  = $load;
  928:     }
  929:     return ($spare_server,$lowest_load);
  930: }
  931: 
  932: # --------------------------- ask offload servers if user already has a session
  933: sub find_existing_session {
  934:     my ($udom,$uname) = @_;
  935:     my $spareshash = &this_host_spares($udom);
  936:     if (ref($spareshash) eq 'HASH') {
  937:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  938:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  939:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  940:             }
  941:         }
  942:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
  943:             foreach my $try_server (@{ $spareshash->{'default'} }) {
  944:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  945:             }
  946:         }
  947:     }
  948:     return;
  949: }
  950: 
  951: # -------------------------------- ask if server already has a session for user
  952: sub has_user_session {
  953:     my ($lonid,$udom,$uname) = @_;
  954:     my $result = &reply(join(':','userhassession',
  955: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  956:     return 1 if ($result eq 'ok');
  957: 
  958:     return 0;
  959: }
  960: 
  961: # --------- determine least loaded server in a user's domain which allows login
  962: 
  963: sub choose_server {
  964:     my ($udom,$checkloginvia,$required) = @_;
  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);
  969:     foreach my $lonhost (keys(%servers)) {
  970:         my $loginvia;
  971:         if ($checkloginvia) {
  972:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
  973:             if ($loginvia) {
  974:                 my ($server,$path) = split(/:/,$loginvia);
  975:                 ($login_host, $lowest_load) =
  976:                     &compare_server_load($server, $login_host, $lowest_load, $required);
  977:                 if ($login_host eq $server) {
  978:                     $portal_path = $path;
  979:                     $isredirect = 1;
  980:                 }
  981:             } else {
  982:                 ($login_host, $lowest_load) =
  983:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
  984:                 if ($login_host eq $lonhost) {
  985:                     $portal_path = '';
  986:                     $isredirect = ''; 
  987:                 }
  988:             }
  989:         } else {
  990:             ($login_host, $lowest_load) =
  991:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
  992:         }
  993:     }
  994:     if ($login_host ne '') {
  995:         $hostname = &hostname($login_host);
  996:     }
  997:     return ($login_host,$hostname,$portal_path,$isredirect);
  998: }
  999: 
 1000: # --------------------------------------------- Try to change a user's password
 1001: 
 1002: sub changepass {
 1003:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
 1004:     $currentpass = &escape($currentpass);
 1005:     $newpass     = &escape($newpass);
 1006:     my $lonhost = $perlvar{'lonHostID'};
 1007:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
 1008: 		       $server);
 1009:     if (! $answer) {
 1010: 	&logthis("No reply on password change request to $server ".
 1011: 		 "by $uname in domain $udom.");
 1012:     } elsif ($answer =~ "^ok") {
 1013:         &logthis("$uname in $udom successfully changed their password ".
 1014: 		 "on $server.");
 1015:     } elsif ($answer =~ "^pwchange_failure") {
 1016: 	&logthis("$uname in $udom was unable to change their password ".
 1017: 		 "on $server.  The action was blocked by either lcpasswd ".
 1018: 		 "or pwchange");
 1019:     } elsif ($answer =~ "^non_authorized") {
 1020:         &logthis("$uname in $udom did not get their password correct when ".
 1021: 		 "attempting to change it on $server.");
 1022:     } elsif ($answer =~ "^auth_mode_error") {
 1023:         &logthis("$uname in $udom attempted to change their password despite ".
 1024: 		 "not being locally or internally authenticated on $server.");
 1025:     } elsif ($answer =~ "^unknown_user") {
 1026:         &logthis("$uname in $udom attempted to change their password ".
 1027: 		 "on $server but were unable to because $server is not ".
 1028: 		 "their home server.");
 1029:     } elsif ($answer =~ "^refused") {
 1030: 	&logthis("$server refused to change $uname in $udom password because ".
 1031: 		 "it was sent an unencrypted request to change the password.");
 1032:     } elsif ($answer =~ "invalid_client") {
 1033:         &logthis("$server refused to change $uname in $udom password because ".
 1034:                  "it was a reset by e-mail originating from an invalid server.");
 1035:     }
 1036:     return $answer;
 1037: }
 1038: 
 1039: # ----------------------- Try to determine user's current authentication scheme
 1040: 
 1041: sub queryauthenticate {
 1042:     my ($uname,$udom)=@_;
 1043:     my $uhome=&homeserver($uname,$udom);
 1044:     if (!$uhome) {
 1045: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1046: 	return 'no_host';
 1047:     }
 1048:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1049:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1050: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1051:     }
 1052:     return $answer;
 1053: }
 1054: 
 1055: # --------- Try to authenticate user from domain's lib servers (first this one)
 1056: 
 1057: sub authenticate {
 1058:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1059:     $upass=&escape($upass);
 1060:     $uname= &LONCAPA::clean_username($uname);
 1061:     my $uhome=&homeserver($uname,$udom,1);
 1062:     my $newhome;
 1063:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1064: # Maybe the machine was offline and only re-appeared again recently?
 1065:         &reconlonc();
 1066: # One more
 1067: 	$uhome=&homeserver($uname,$udom,1);
 1068:         if (($uhome eq 'no_host') && $checkdefauth) {
 1069:             if (defined(&domain($udom,'primary'))) {
 1070:                 $newhome=&domain($udom,'primary');
 1071:             }
 1072:             if ($newhome ne '') {
 1073:                 $uhome = $newhome;
 1074:             }
 1075:         }
 1076: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1077: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1078: 	    return 'no_host';
 1079:         }
 1080:     }
 1081:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1082:     if ($answer eq 'authorized') {
 1083:         if ($newhome) {
 1084:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1085:             return 'no_account_on_host'; 
 1086:         } else {
 1087:             &logthis("User $uname at $udom authorized by $uhome");
 1088:             return $uhome;
 1089:         }
 1090:     }
 1091:     if ($answer eq 'non_authorized') {
 1092: 	&logthis("User $uname at $udom rejected by $uhome");
 1093: 	return 'no_host'; 
 1094:     }
 1095:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1096:     return 'no_host';
 1097: }
 1098: 
 1099: sub can_host_session {
 1100:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1101:     my $canhost = 1;
 1102:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1103:     if (ref($remotesessions) eq 'HASH') {
 1104:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1105:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1106:                 $canhost = 0;
 1107:             } else {
 1108:                 $canhost = 1;
 1109:             }
 1110:         }
 1111:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1112:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1113:                 $canhost = 1;
 1114:             } else {
 1115:                 $canhost = 0;
 1116:             }
 1117:         }
 1118:         if ($canhost) {
 1119:             if ($remotesessions->{'version'} ne '') {
 1120:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1121:                 if ($reqmajor ne '' && $reqminor ne '') {
 1122:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1123:                         my $major = $1;
 1124:                         my $minor = $2;
 1125:                         if (($major < $reqmajor ) ||
 1126:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1127:                             $canhost = 0;
 1128:                         }
 1129:                     } else {
 1130:                         $canhost = 0;
 1131:                     }
 1132:                 }
 1133:             }
 1134:         }
 1135:     }
 1136:     if ($canhost) {
 1137:         if (ref($hostedsessions) eq 'HASH') {
 1138:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1139:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1140:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1141:                 if (($uint_dom ne '') && 
 1142:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1143:                     $canhost = 0;
 1144:                 } else {
 1145:                     $canhost = 1;
 1146:                 }
 1147:             }
 1148:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1149:                 if (($uint_dom ne '') && 
 1150:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1151:                     $canhost = 1;
 1152:                 } else {
 1153:                     $canhost = 0;
 1154:                 }
 1155:             }
 1156:         }
 1157:     }
 1158:     return $canhost;
 1159: }
 1160: 
 1161: sub spare_can_host {
 1162:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1163:     my $canhost=1;
 1164:     my @intdoms;
 1165:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
 1166:     if (ref($internet_names) eq 'ARRAY') {
 1167:         @intdoms = @{$internet_names};
 1168:     }
 1169:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1170:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
 1171:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
 1172:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
 1173:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
 1174:         $canhost = &can_host_session($udom,$try_server,$remoterev,
 1175:                                      $remotesessions,
 1176:                                      $defdomdefaults{'hostedsessions'});
 1177:     }
 1178:     return $canhost;
 1179: }
 1180: 
 1181: sub this_host_spares {
 1182:     my ($dom) = @_;
 1183:     my ($dom_in_use,$lonhost_in_use,$result);
 1184:     my @hosts = &current_machine_ids();
 1185:     foreach my $lonhost (@hosts) {
 1186:         if (&host_domain($lonhost) eq $dom) {
 1187:             $dom_in_use = $dom;
 1188:             $lonhost_in_use = $lonhost;
 1189:             last;
 1190:         }
 1191:     }
 1192:     if ($dom_in_use ne '') {
 1193:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1194:     }
 1195:     if (ref($result) ne 'HASH') {
 1196:         $lonhost_in_use = $perlvar{'lonHostID'};
 1197:         $dom_in_use = &host_domain($lonhost_in_use);
 1198:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1199:         if (ref($result) ne 'HASH') {
 1200:             $result = \%spareid;
 1201:         }
 1202:     }
 1203:     return $result;
 1204: }
 1205: 
 1206: sub spares_for_offload  {
 1207:     my ($dom_in_use,$lonhost_in_use) = @_;
 1208:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1209:     if (defined($cached)) {
 1210:         return $result;
 1211:     } else {
 1212:         my $cachetime = 60*60*24;
 1213:         my %domconfig =
 1214:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1215:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1216:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1217:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1218:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1219:                 }
 1220:             }
 1221:         }
 1222:     }
 1223:     return;
 1224: }
 1225: 
 1226: sub get_lonbalancer_config {
 1227:     my ($servers) = @_;
 1228:     my ($currbalancer,$currtargets);
 1229:     if (ref($servers) eq 'HASH') {
 1230:         foreach my $server (keys(%{$servers})) {
 1231:             my %what = (
 1232:                          spareid => 1,
 1233:                          perlvar => 1,
 1234:                        );
 1235:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1236:             if ($result eq 'ok') {
 1237:                 if (ref($returnhash) eq 'HASH') {
 1238:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1239:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1240:                             $currbalancer = $server;
 1241:                             $currtargets = {};
 1242:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1243:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1244:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1245:                                 }
 1246:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1247:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1248:                                 }
 1249:                             }
 1250:                             last;
 1251:                         }
 1252:                     }
 1253:                 }
 1254:             }
 1255:         }
 1256:     }
 1257:     return ($currbalancer,$currtargets);
 1258: }
 1259: 
 1260: sub check_loadbalancing {
 1261:     my ($uname,$udom) = @_;
 1262:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1263:         $rule_in_effect,$offloadto,$otherserver);
 1264:     my $lonhost = $perlvar{'lonHostID'};
 1265:     my @hosts = &current_machine_ids();
 1266:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1267:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1268:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1269:     my $serverhomedom = &host_domain($lonhost);
 1270: 
 1271:     my $cachetime = 60*60*24;
 1272: 
 1273:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1274:         $dom_in_use = $udom;
 1275:         $homeintdom = 1;
 1276:     } else {
 1277:         $dom_in_use = $serverhomedom;
 1278:     }
 1279:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1280:     unless (defined($cached)) {
 1281:         my %domconfig =
 1282:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1283:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1284:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1285:         }
 1286:     }
 1287:     if (ref($result) eq 'HASH') {
 1288:         ($is_balancer,$currtargets,$currrules) = 
 1289:             &check_balancer_result($result,@hosts);
 1290:         if ($is_balancer) {
 1291:             if (ref($currrules) eq 'HASH') {
 1292:                 if ($homeintdom) {
 1293:                     if ($uname ne '') {
 1294:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1295:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1296:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1297:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1298:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1299:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1300:                             }
 1301:                         }
 1302:                         if ($rule_in_effect eq '') {
 1303:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1304:                             if ($userenv{'inststatus'} ne '') {
 1305:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1306:                                 my ($othertitle,$usertypes,$types) =
 1307:                                     &Apache::loncommon::sorted_inst_types($udom);
 1308:                                 if (ref($types) eq 'ARRAY') {
 1309:                                     foreach my $type (@{$types}) {
 1310:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1311:                                             if (exists($currrules->{$type})) {
 1312:                                                 $rule_in_effect = $currrules->{$type};
 1313:                                             }
 1314:                                         }
 1315:                                     }
 1316:                                 }
 1317:                             } else {
 1318:                                 if (exists($currrules->{'default'})) {
 1319:                                     $rule_in_effect = $currrules->{'default'};
 1320:                                 }
 1321:                             }
 1322:                         }
 1323:                     } else {
 1324:                         if (exists($currrules->{'default'})) {
 1325:                             $rule_in_effect = $currrules->{'default'};
 1326:                         }
 1327:                     }
 1328:                 } else {
 1329:                     if ($currrules->{'_LC_external'} ne '') {
 1330:                         $rule_in_effect = $currrules->{'_LC_external'};
 1331:                     }
 1332:                 }
 1333:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1334:                                                        $uname,$udom);
 1335:             }
 1336:         }
 1337:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1338:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1339:         unless (defined($cached)) {
 1340:             my %domconfig =
 1341:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1342:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1343:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1344:             }
 1345:         }
 1346:         if (ref($result) eq 'HASH') {
 1347:             ($is_balancer,$currtargets,$currrules) = 
 1348:                 &check_balancer_result($result,@hosts);
 1349:             if ($is_balancer) {
 1350:                 if (ref($currrules) eq 'HASH') {
 1351:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1352:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1353:                     }
 1354:                 }
 1355:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1356:                                                        $uname,$udom);
 1357:             }
 1358:         } else {
 1359:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1360:                 $is_balancer = 1;
 1361:                 $offloadto = &this_host_spares($dom_in_use);
 1362:             }
 1363:         }
 1364:     } else {
 1365:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1366:             $is_balancer = 1;
 1367:             $offloadto = &this_host_spares($dom_in_use);
 1368:         }
 1369:     }
 1370:     if ($is_balancer) {
 1371:         my $lowest_load = 30000;
 1372:         if (ref($offloadto) eq 'HASH') {
 1373:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1374:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1375:                     ($otherserver,$lowest_load) =
 1376:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1377:                 }
 1378:             }
 1379:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1380: 
 1381:             if (!$found_server) {
 1382:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1383:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1384:                         ($otherserver,$lowest_load) =
 1385:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1386:                     }
 1387:                 }
 1388:             }
 1389:         } elsif (ref($offloadto) eq 'ARRAY') {
 1390:             if (@{$offloadto} == 1) {
 1391:                 $otherserver = $offloadto->[0];
 1392:             } elsif (@{$offloadto} > 1) {
 1393:                 foreach my $try_server (@{$offloadto}) {
 1394:                     ($otherserver,$lowest_load) =
 1395:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1396:                 }
 1397:             }
 1398:         }
 1399:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1400:             $is_balancer = 0;
 1401:             if ($uname ne '' && $udom ne '') {
 1402:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1403:                     
 1404:                     &appenv({'user.loadbalexempt'     => $lonhost,  
 1405:                              'user.loadbalcheck.time' => time});
 1406:                 }
 1407:             }
 1408:         }
 1409:     }
 1410:     return ($is_balancer,$otherserver);
 1411: }
 1412: 
 1413: sub check_balancer_result {
 1414:     my ($result,@hosts) = @_;
 1415:     my ($is_balancer,$currtargets,$currrules);
 1416:     if (ref($result) eq 'HASH') {
 1417:         if ($result->{'lonhost'} ne '') {
 1418:             my $currbalancer = $result->{'lonhost'};
 1419:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1420:                 $is_balancer = 1;
 1421:                 $currtargets = $result->{'targets'};
 1422:                 $currrules = $result->{'rules'};
 1423:             }
 1424:         } else {
 1425:             foreach my $key (keys(%{$result})) {
 1426:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1427:                     (ref($result->{$key}) eq 'HASH')) {
 1428:                     $is_balancer = 1;
 1429:                     $currrules = $result->{$key}{'rules'};
 1430:                     $currtargets = $result->{$key}{'targets'};
 1431:                     last;
 1432:                 }
 1433:             }
 1434:         }
 1435:     }
 1436:     return ($is_balancer,$currtargets,$currrules);
 1437: }
 1438: 
 1439: sub get_loadbalancer_targets {
 1440:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1441:     my $offloadto;
 1442:     if ($rule_in_effect eq 'none') {
 1443:         return [$perlvar{'lonHostID'}];
 1444:     } elsif ($rule_in_effect eq '') {
 1445:         $offloadto = $currtargets;
 1446:     } else {
 1447:         if ($rule_in_effect eq 'homeserver') {
 1448:             my $homeserver = &homeserver($uname,$udom);
 1449:             if ($homeserver ne 'no_host') {
 1450:                 $offloadto = [$homeserver];
 1451:             }
 1452:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1453:             my %domconfig =
 1454:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1455:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1456:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1457:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1458:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1459:                     }
 1460:                 }
 1461:             } else {
 1462:                 my %servers = &internet_dom_servers($udom);
 1463:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1464:                 if (&hostname($remotebalancer) ne '') {
 1465:                     $offloadto = [$remotebalancer];
 1466:                 }
 1467:             }
 1468:         } elsif (&hostname($rule_in_effect) ne '') {
 1469:             $offloadto = [$rule_in_effect];
 1470:         }
 1471:     }
 1472:     return $offloadto;
 1473: }
 1474: 
 1475: sub internet_dom_servers {
 1476:     my ($dom) = @_;
 1477:     my (%uniqservers,%servers);
 1478:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1479:     my @machinedoms = &machine_domains($primaryserver);
 1480:     foreach my $mdom (@machinedoms) {
 1481:         my %currservers = %servers;
 1482:         my %server = &get_servers($mdom);
 1483:         %servers = (%currservers,%server);
 1484:     }
 1485:     my %by_hostname;
 1486:     foreach my $id (keys(%servers)) {
 1487:         push(@{$by_hostname{$servers{$id}}},$id);
 1488:     }
 1489:     foreach my $hostname (sort(keys(%by_hostname))) {
 1490:         if (@{$by_hostname{$hostname}} > 1) {
 1491:             my $match = 0;
 1492:             foreach my $id (@{$by_hostname{$hostname}}) {
 1493:                 if (&host_domain($id) eq $dom) {
 1494:                     $uniqservers{$id} = $hostname;
 1495:                     $match = 1;
 1496:                 }
 1497:             }
 1498:             unless ($match) {
 1499:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1500:             }
 1501:         } else {
 1502:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1503:         }
 1504:     }
 1505:     return %uniqservers;
 1506: }
 1507: 
 1508: # ---------------------- Find the homebase for a user from domain's lib servers
 1509: 
 1510: my %homecache;
 1511: sub homeserver {
 1512:     my ($uname,$udom,$ignoreBadCache)=@_;
 1513:     my $index="$uname:$udom";
 1514: 
 1515:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1516: 
 1517:     my %servers = &get_servers($udom,'library');
 1518:     foreach my $tryserver (keys(%servers)) {
 1519:         next if ($ignoreBadCache ne 'true' && 
 1520: 		 exists($badServerCache{$tryserver}));
 1521: 
 1522: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1523: 	if ($answer eq 'found') {
 1524: 	    delete($badServerCache{$tryserver}); 
 1525: 	    return $homecache{$index}=$tryserver;
 1526: 	} elsif ($answer eq 'no_host') {
 1527: 	    $badServerCache{$tryserver}=1;
 1528: 	}
 1529:     }    
 1530:     return 'no_host';
 1531: }
 1532: 
 1533: # ------------------------------------- Find the usernames behind a list of IDs
 1534: 
 1535: sub idget {
 1536:     my ($udom,@ids)=@_;
 1537:     my %returnhash=();
 1538:     
 1539:     my %servers = &get_servers($udom,'library');
 1540:     foreach my $tryserver (keys(%servers)) {
 1541: 	my $idlist=join('&',@ids);
 1542: 	$idlist=~tr/A-Z/a-z/; 
 1543: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1544: 	my @answer=();
 1545: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1546: 	    @answer=split(/\&/,$reply);
 1547: 	}                    ;
 1548: 	my $i;
 1549: 	for ($i=0;$i<=$#ids;$i++) {
 1550: 	    if ($answer[$i]) {
 1551: 		$returnhash{$ids[$i]}=$answer[$i];
 1552: 	    } 
 1553: 	}
 1554:     } 
 1555:     return %returnhash;
 1556: }
 1557: 
 1558: # ------------------------------------- Find the IDs behind a list of usernames
 1559: 
 1560: sub idrget {
 1561:     my ($udom,@unames)=@_;
 1562:     my %returnhash=();
 1563:     foreach my $uname (@unames) {
 1564:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1565:     }
 1566:     return %returnhash;
 1567: }
 1568: 
 1569: # ------------------------------- Store away a list of names and associated IDs
 1570: 
 1571: sub idput {
 1572:     my ($udom,%ids)=@_;
 1573:     my %servers=();
 1574:     foreach my $uname (keys(%ids)) {
 1575: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1576:         my $uhom=&homeserver($uname,$udom);
 1577:         if ($uhom ne 'no_host') {
 1578:             my $id=&escape($ids{$uname});
 1579:             $id=~tr/A-Z/a-z/;
 1580:             my $esc_unam=&escape($uname);
 1581: 	    if ($servers{$uhom}) {
 1582: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
 1583:             } else {
 1584:                 $servers{$uhom}=$id.'='.$esc_unam;
 1585:             }
 1586:         }
 1587:     }
 1588:     foreach my $server (keys(%servers)) {
 1589:         &critical('idput:'.$udom.':'.$servers{$server},$server);
 1590:     }
 1591: }
 1592: 
 1593: # ---------------------------------------- Delete unwanted IDs from ids.db file 
 1594: 
 1595: sub iddel {
 1596:     my ($udom,$idshashref,$uhome)=@_;
 1597:     my %result=();
 1598:     unless (ref($idshashref) eq 'HASH') {
 1599:         return %result;
 1600:     }
 1601:     my %servers=();
 1602:     while (my ($id,$uname) = each(%{$idshashref})) {
 1603:         my $uhom;
 1604:         if ($uhome) {
 1605:             $uhom = $uhome;
 1606:         } else {
 1607:             $uhom=&homeserver($uname,$udom);
 1608:         }
 1609:         if ($uhom ne 'no_host') {
 1610:             if ($servers{$uhom}) {
 1611:                 $servers{$uhom}.='&'.&escape($id);
 1612:             } else {
 1613:                 $servers{$uhom}=&escape($id);
 1614:             }
 1615:         }
 1616:     }
 1617:     foreach my $server (keys(%servers)) {
 1618:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
 1619:     }
 1620:     return %result;
 1621: }
 1622: 
 1623: # ------------------------------dump from db file owned by domainconfig user
 1624: sub dump_dom {
 1625:     my ($namespace, $udom, $regexp) = @_;
 1626: 
 1627:     $udom ||= $env{'user.domain'};
 1628: 
 1629:     return () unless $udom;
 1630: 
 1631:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 1632: }
 1633: 
 1634: # ------------------------------------------ get items from domain db files   
 1635: 
 1636: sub get_dom {
 1637:     my ($namespace,$storearr,$udom,$uhome)=@_;
 1638:     my $items='';
 1639:     foreach my $item (@$storearr) {
 1640:         $items.=&escape($item).'&';
 1641:     }
 1642:     $items=~s/\&$//;
 1643:     if (!$udom) {
 1644:         $udom=$env{'user.domain'};
 1645:         if (defined(&domain($udom,'primary'))) {
 1646:             $uhome=&domain($udom,'primary');
 1647:         } else {
 1648:             undef($uhome);
 1649:         }
 1650:     } else {
 1651:         if (!$uhome) {
 1652:             if (defined(&domain($udom,'primary'))) {
 1653:                 $uhome=&domain($udom,'primary');
 1654:             }
 1655:         }
 1656:     }
 1657:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1658:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 1659:         my %returnhash;
 1660:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 1661:             return %returnhash;
 1662:         }
 1663:         my @pairs=split(/\&/,$rep);
 1664:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1665:             return @pairs;
 1666:         }
 1667:         my $i=0;
 1668:         foreach my $item (@$storearr) {
 1669:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 1670:             $i++;
 1671:         }
 1672:         return %returnhash;
 1673:     } else {
 1674:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1675:     }
 1676: }
 1677: 
 1678: # -------------------------------------------- put items in domain db files 
 1679: 
 1680: sub put_dom {
 1681:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1682:     if (!$udom) {
 1683:         $udom=$env{'user.domain'};
 1684:         if (defined(&domain($udom,'primary'))) {
 1685:             $uhome=&domain($udom,'primary');
 1686:         } else {
 1687:             undef($uhome);
 1688:         }
 1689:     } else {
 1690:         if (!$uhome) {
 1691:             if (defined(&domain($udom,'primary'))) {
 1692:                 $uhome=&domain($udom,'primary');
 1693:             }
 1694:         }
 1695:     } 
 1696:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1697:         my $items='';
 1698:         foreach my $item (keys(%$storehash)) {
 1699:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 1700:         }
 1701:         $items=~s/\&$//;
 1702:         return &reply("putdom:$udom:$namespace:$items",$uhome);
 1703:     } else {
 1704:         &logthis("put_dom failed - no homeserver and/or domain");
 1705:     }
 1706: }
 1707: 
 1708: # --------------------- newput for items in db file owned by domainconfig user
 1709: sub newput_dom {
 1710:     my ($namespace,$storehash,$udom) = @_;
 1711:     my $result;
 1712:     if (!$udom) {
 1713:         $udom=$env{'user.domain'};
 1714:     }
 1715:     if ($udom) {
 1716:         my $uname = &get_domainconfiguser($udom);
 1717:         $result = &newput($namespace,$storehash,$udom,$uname);
 1718:     }
 1719:     return $result;
 1720: }
 1721: 
 1722: # --------------------- delete for items in db file owned by domainconfig user
 1723: sub del_dom {
 1724:     my ($namespace,$storearr,$udom)=@_;
 1725:     if (ref($storearr) eq 'ARRAY') {
 1726:         if (!$udom) {
 1727:             $udom=$env{'user.domain'};
 1728:         }
 1729:         if ($udom) {
 1730:             my $uname = &get_domainconfiguser($udom); 
 1731:             return &del($namespace,$storearr,$udom,$uname);
 1732:         }
 1733:     }
 1734: }
 1735: 
 1736: # ----------------------------------construct domainconfig user for a domain 
 1737: sub get_domainconfiguser {
 1738:     my ($udom) = @_;
 1739:     return $udom.'-domainconfig';
 1740: }
 1741: 
 1742: sub retrieve_inst_usertypes {
 1743:     my ($udom) = @_;
 1744:     my (%returnhash,@order);
 1745:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 1746:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 1747:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 1748:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
 1749:     } else {
 1750:         if (defined(&domain($udom,'primary'))) {
 1751:             my $uhome=&domain($udom,'primary');
 1752:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 1753:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 1754:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
 1755:                 return (\%returnhash,\@order);
 1756:             }
 1757:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 1758:             my @pairs=split(/\&/,$hashitems);
 1759:             foreach my $item (@pairs) {
 1760:                 my ($key,$value)=split(/=/,$item,2);
 1761:                 $key = &unescape($key);
 1762:                 next if ($key =~ /^error: 2 /);
 1763:                 $returnhash{$key}=&thaw_unescape($value);
 1764:             }
 1765:             my @esc_order = split(/\&/,$orderitems);
 1766:             foreach my $item (@esc_order) {
 1767:                 push(@order,&unescape($item));
 1768:             }
 1769:         } else {
 1770:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
 1771:         }
 1772:         return (\%returnhash,\@order);
 1773:     }
 1774: }
 1775: 
 1776: sub is_domainimage {
 1777:     my ($url) = @_;
 1778:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1779:         if (&domain($1) ne '') {
 1780:             return '1';
 1781:         }
 1782:     }
 1783:     return;
 1784: }
 1785: 
 1786: sub inst_directory_query {
 1787:     my ($srch) = @_;
 1788:     my $udom = $srch->{'srchdomain'};
 1789:     my %results;
 1790:     my $homeserver = &domain($udom,'primary');
 1791:     my $outcome;
 1792:     if ($homeserver ne '') {
 1793: 	my $queryid=&reply("querysend:instdirsearch:".
 1794: 			   &escape($srch->{'srchby'}).':'.
 1795: 			   &escape($srch->{'srchterm'}).':'.
 1796: 			   &escape($srch->{'srchtype'}),$homeserver);
 1797: 	my $host=&hostname($homeserver);
 1798: 	if ($queryid !~/^\Q$host\E\_/) {
 1799: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1800: 	    return;
 1801: 	}
 1802: 	my $response = &get_query_reply($queryid);
 1803: 	my $maxtries = 5;
 1804: 	my $tries = 1;
 1805: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1806: 	    $response = &get_query_reply($queryid);
 1807: 	    $tries ++;
 1808: 	}
 1809: 
 1810:         if (!&error($response) && $response ne 'refused') {
 1811:             if ($response eq 'unavailable') {
 1812:                 $outcome = $response;
 1813:             } else {
 1814:                 $outcome = 'ok';
 1815:                 my @matches = split(/\n/,$response);
 1816:                 foreach my $match (@matches) {
 1817:                     my ($key,$value) = split(/=/,$match);
 1818:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1819:                 }
 1820:             }
 1821:         }
 1822:     }
 1823:     return ($outcome,%results);
 1824: }
 1825: 
 1826: sub usersearch {
 1827:     my ($srch) = @_;
 1828:     my $dom = $srch->{'srchdomain'};
 1829:     my %results;
 1830:     my %libserv = &all_library();
 1831:     my $query = 'usersearch';
 1832:     foreach my $tryserver (keys(%libserv)) {
 1833:         if (&host_domain($tryserver) eq $dom) {
 1834:             my $host=&hostname($tryserver);
 1835:             my $queryid=
 1836:                 &reply("querysend:".&escape($query).':'.
 1837:                        &escape($srch->{'srchby'}).':'.
 1838:                        &escape($srch->{'srchtype'}).':'.
 1839:                        &escape($srch->{'srchterm'}),$tryserver);
 1840:             if ($queryid !~/^\Q$host\E\_/) {
 1841:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1842:                 next;
 1843:             }
 1844:             my $reply = &get_query_reply($queryid);
 1845:             my $maxtries = 1;
 1846:             my $tries = 1;
 1847:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1848:                 $reply = &get_query_reply($queryid);
 1849:                 $tries ++;
 1850:             }
 1851:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1852:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1853:             } else {
 1854:                 my @matches;
 1855:                 if ($reply =~ /\n/) {
 1856:                     @matches = split(/\n/,$reply);
 1857:                 } else {
 1858:                     @matches = split(/\&/,$reply);
 1859:                 }
 1860:                 foreach my $match (@matches) {
 1861:                     my ($uname,$udom,%userhash);
 1862:                     foreach my $entry (split(/:/,$match)) {
 1863:                         my ($key,$value) =
 1864:                             map {&unescape($_);} split(/=/,$entry);
 1865:                         $userhash{$key} = $value;
 1866:                         if ($key eq 'username') {
 1867:                             $uname = $value;
 1868:                         } elsif ($key eq 'domain') {
 1869:                             $udom = $value;
 1870:                         }
 1871:                     }
 1872:                     $results{$uname.':'.$udom} = \%userhash;
 1873:                 }
 1874:             }
 1875:         }
 1876:     }
 1877:     return %results;
 1878: }
 1879: 
 1880: sub get_instuser {
 1881:     my ($udom,$uname,$id) = @_;
 1882:     my $homeserver = &domain($udom,'primary');
 1883:     my ($outcome,%results);
 1884:     if ($homeserver ne '') {
 1885:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1886:                            &escape($id).':'.&escape($udom),$homeserver);
 1887:         my $host=&hostname($homeserver);
 1888:         if ($queryid !~/^\Q$host\E\_/) {
 1889:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1890:             return;
 1891:         }
 1892:         my $response = &get_query_reply($queryid);
 1893:         my $maxtries = 5;
 1894:         my $tries = 1;
 1895:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1896:             $response = &get_query_reply($queryid);
 1897:             $tries ++;
 1898:         }
 1899:         if (!&error($response) && $response ne 'refused') {
 1900:             if ($response eq 'unavailable') {
 1901:                 $outcome = $response;
 1902:             } else {
 1903:                 $outcome = 'ok';
 1904:                 my @matches = split(/\n/,$response);
 1905:                 foreach my $match (@matches) {
 1906:                     my ($key,$value) = split(/=/,$match);
 1907:                     $results{&unescape($key)} = &thaw_unescape($value);
 1908:                 }
 1909:             }
 1910:         }
 1911:     }
 1912:     my %userinfo;
 1913:     if (ref($results{$uname}) eq 'HASH') {
 1914:         %userinfo = %{$results{$uname}};
 1915:     } 
 1916:     return ($outcome,%userinfo);
 1917: }
 1918: 
 1919: sub inst_rulecheck {
 1920:     my ($udom,$uname,$id,$item,$rules) = @_;
 1921:     my %returnhash;
 1922:     if ($udom ne '') {
 1923:         if (ref($rules) eq 'ARRAY') {
 1924:             @{$rules} = map {&escape($_);} (@{$rules});
 1925:             my $rulestr = join(':',@{$rules});
 1926:             my $homeserver=&domain($udom,'primary');
 1927:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1928:                 my $response;
 1929:                 if ($item eq 'username') {                
 1930:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1931:                                               ':'.&escape($uname).':'.$rulestr,
 1932:                                               $homeserver));
 1933:                 } elsif ($item eq 'id') {
 1934:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1935:                                               ':'.&escape($id).':'.$rulestr,
 1936:                                               $homeserver));
 1937:                 } elsif ($item eq 'selfcreate') {
 1938:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1939:                                                &escape($udom).':'.&escape($uname).
 1940:                                               ':'.$rulestr,$homeserver));
 1941:                 }
 1942:                 if ($response ne 'refused') {
 1943:                     my @pairs=split(/\&/,$response);
 1944:                     foreach my $item (@pairs) {
 1945:                         my ($key,$value)=split(/=/,$item,2);
 1946:                         $key = &unescape($key);
 1947:                         next if ($key =~ /^error: 2 /);
 1948:                         $returnhash{$key}=&thaw_unescape($value);
 1949:                     }
 1950:                 }
 1951:             }
 1952:         }
 1953:     }
 1954:     return %returnhash;
 1955: }
 1956: 
 1957: sub inst_userrules {
 1958:     my ($udom,$check) = @_;
 1959:     my (%ruleshash,@ruleorder);
 1960:     if ($udom ne '') {
 1961:         my $homeserver=&domain($udom,'primary');
 1962:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1963:             my $response;
 1964:             if ($check eq 'id') {
 1965:                 $response=&reply('instidrules:'.&escape($udom),
 1966:                                  $homeserver);
 1967:             } elsif ($check eq 'email') {
 1968:                 $response=&reply('instemailrules:'.&escape($udom),
 1969:                                  $homeserver);
 1970:             } else {
 1971:                 $response=&reply('instuserrules:'.&escape($udom),
 1972:                                  $homeserver);
 1973:             }
 1974:             if (($response ne 'refused') && ($response ne 'error') && 
 1975:                 ($response ne 'unknown_cmd') && 
 1976:                 ($response ne 'no_such_host')) {
 1977:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1978:                 my @pairs=split(/\&/,$hashitems);
 1979:                 foreach my $item (@pairs) {
 1980:                     my ($key,$value)=split(/=/,$item,2);
 1981:                     $key = &unescape($key);
 1982:                     next if ($key =~ /^error: 2 /);
 1983:                     $ruleshash{$key}=&thaw_unescape($value);
 1984:                 }
 1985:                 my @esc_order = split(/\&/,$orderitems);
 1986:                 foreach my $item (@esc_order) {
 1987:                     push(@ruleorder,&unescape($item));
 1988:                 }
 1989:             }
 1990:         }
 1991:     }
 1992:     return (\%ruleshash,\@ruleorder);
 1993: }
 1994: 
 1995: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 1996: 
 1997: sub get_domain_defaults {
 1998:     my ($domain,$ignore_cache) = @_;
 1999:     return if (($domain eq '') || ($domain eq 'public'));
 2000:     my $cachetime = 60*60*24;
 2001:     unless ($ignore_cache) {
 2002:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 2003:         if (defined($cached)) {
 2004:             if (ref($result) eq 'HASH') {
 2005:                 return %{$result};
 2006:             }
 2007:         }
 2008:     }
 2009:     my %domdefaults;
 2010:     my %domconfig =
 2011:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 2012:                                   'requestcourses','inststatus',
 2013:                                   'coursedefaults','usersessions',
 2014:                                   'requestauthor','selfenrollment',
 2015:                                   'coursecategories'],$domain);
 2016:     my @coursetypes = ('official','unofficial','community','textbook');
 2017:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2018:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2019:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2020:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2021:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2022:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2023:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2024:     } else {
 2025:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2026:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2027:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2028:     }
 2029:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2030:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2031:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2032:         } else {
 2033:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2034:         }
 2035:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2036:         foreach my $item (@usertools) {
 2037:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2038:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2039:             }
 2040:         }
 2041:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2042:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2043:         }
 2044:     }
 2045:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2046:         foreach my $item ('official','unofficial','community','textbook') {
 2047:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2048:         }
 2049:     }
 2050:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2051:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2052:     }
 2053:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2054:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
 2055:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2056:         }
 2057:     }
 2058:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2059:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
 2060:         foreach my $type (@coursetypes) {
 2061:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2062:                 unless ($type eq 'community') {
 2063:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
 2064:                 }
 2065:             }
 2066:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2067:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
 2068:             }
 2069:         }
 2070:     }
 2071:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2072:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2073:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2074:         }
 2075:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2076:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2077:         }
 2078:     }
 2079:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
 2080:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
 2081:             my @settings = ('types','registered','enroll_dates','access_dates','section',
 2082:                             'approval','limit');
 2083:             foreach my $type (@coursetypes) {
 2084:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
 2085:                     my @mgrdc = ();
 2086:                     foreach my $item (@settings) {
 2087:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
 2088:                             push(@mgrdc,$item);
 2089:                         }
 2090:                     }
 2091:                     if (@mgrdc) {
 2092:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
 2093:                     }
 2094:                 }
 2095:             }
 2096:         }
 2097:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
 2098:             foreach my $type (@coursetypes) {
 2099:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
 2100:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
 2101:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
 2102:                     }
 2103:                 }
 2104:             }
 2105:         }
 2106:     }
 2107:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2108:         $domdefaults{'catauth'} = 'std';
 2109:         $domdefaults{'catunauth'} = 'std';
 2110:         if ($domconfig{'coursecategories'}{'auth'}) { 
 2111:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
 2112:         }
 2113:         if ($domconfig{'coursecategories'}{'unauth'}) {
 2114:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
 2115:         }
 2116:     }
 2117:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2118:     return %domdefaults;
 2119: }
 2120: 
 2121: # --------------------------------------------------- Assign a key to a student
 2122: 
 2123: sub assign_access_key {
 2124: #
 2125: # a valid key looks like uname:udom#comments
 2126: # comments are being appended
 2127: #
 2128:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2129:     $kdom=
 2130:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2131:     $knum=
 2132:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2133:     $cdom=
 2134:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2135:     $cnum=
 2136:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2137:     $udom=$env{'user.name'} unless (defined($udom));
 2138:     $uname=$env{'user.domain'} unless (defined($uname));
 2139:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2140:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2141:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2142:                                                   # assigned to this person
 2143:                                                   # - this should not happen,
 2144:                                                   # unless something went wrong
 2145:                                                   # the first time around
 2146: # ready to assign
 2147:         $logentry=$1.'; '.$logentry;
 2148:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2149:                                                  $kdom,$knum) eq 'ok') {
 2150: # key now belongs to user
 2151: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2152:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2153:                 &appenv({'environment.'.$envkey => $ckey});
 2154:                 return 'ok';
 2155:             } else {
 2156:                 return 
 2157:   'error: Count not permanently assign key, will need to be re-entered later.';
 2158: 	    }
 2159:         } else {
 2160:             return 'error: Could not assign key, try again later.';
 2161:         }
 2162:     } elsif (!$existing{$ckey}) {
 2163: # the key does not exist
 2164: 	return 'error: The key does not exist';
 2165:     } else {
 2166: # the key is somebody else's
 2167: 	return 'error: The key is already in use';
 2168:     }
 2169: }
 2170: 
 2171: # ------------------------------------------ put an additional comment on a key
 2172: 
 2173: sub comment_access_key {
 2174: #
 2175: # a valid key looks like uname:udom#comments
 2176: # comments are being appended
 2177: #
 2178:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2179:     $cdom=
 2180:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2181:     $cnum=
 2182:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2183:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2184:     if ($existing{$ckey}) {
 2185:         $existing{$ckey}.='; '.$logentry;
 2186: # ready to assign
 2187:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2188:                                                  $cdom,$cnum) eq 'ok') {
 2189: 	    return 'ok';
 2190:         } else {
 2191: 	    return 'error: Count not store comment.';
 2192:         }
 2193:     } else {
 2194: # the key does not exist
 2195: 	return 'error: The key does not exist';
 2196:     }
 2197: }
 2198: 
 2199: # ------------------------------------------------------ Generate a set of keys
 2200: 
 2201: sub generate_access_keys {
 2202:     my ($number,$cdom,$cnum,$logentry)=@_;
 2203:     $cdom=
 2204:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2205:     $cnum=
 2206:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2207:     unless (&allowed('mky',$cdom)) { return 0; }
 2208:     unless (($cdom) && ($cnum)) { return 0; }
 2209:     if ($number>10000) { return 0; }
 2210:     sleep(2); # make sure don't get same seed twice
 2211:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2212:     my $total=0;
 2213:     for (my $i=1;$i<=$number;$i++) {
 2214:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2215:                   sprintf("%lx",int(100000*rand)).'-'.
 2216:                   sprintf("%lx",int(100000*rand));
 2217:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2218:        $newkey=~s/0/h/g; # and also 0 and O
 2219:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2220:        if ($existing{$newkey}) {
 2221:            $i--;
 2222:        } else {
 2223: 	  if (&put('accesskeys',
 2224:               { $newkey => '# generated '.localtime().
 2225:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2226:                            '; '.$logentry },
 2227: 		   $cdom,$cnum) eq 'ok') {
 2228:               $total++;
 2229: 	  }
 2230:        }
 2231:     }
 2232:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2233:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2234:     return $total;
 2235: }
 2236: 
 2237: # ------------------------------------------------------- Validate an accesskey
 2238: 
 2239: sub validate_access_key {
 2240:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2241:     $cdom=
 2242:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2243:     $cnum=
 2244:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2245:     $udom=$env{'user.domain'} unless (defined($udom));
 2246:     $uname=$env{'user.name'} unless (defined($uname));
 2247:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2248:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2249: }
 2250: 
 2251: # ------------------------------------- Find the section of student in a course
 2252: sub devalidate_getsection_cache {
 2253:     my ($udom,$unam,$courseid)=@_;
 2254:     my $hashid="$udom:$unam:$courseid";
 2255:     &devalidate_cache_new('getsection',$hashid);
 2256: }
 2257: 
 2258: sub courseid_to_courseurl {
 2259:     my ($courseid) = @_;
 2260:     #already url style courseid
 2261:     return $courseid if ($courseid =~ m{^/});
 2262: 
 2263:     if (exists($env{'course.'.$courseid.'.num'})) {
 2264: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2265: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2266: 	return "/$cdom/$cnum";
 2267:     }
 2268: 
 2269:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2270:     if (exists($courseinfo{'num'})) {
 2271: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2272:     }
 2273: 
 2274:     return undef;
 2275: }
 2276: 
 2277: sub getsection {
 2278:     my ($udom,$unam,$courseid)=@_;
 2279:     my $cachetime=1800;
 2280: 
 2281:     my $hashid="$udom:$unam:$courseid";
 2282:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2283:     if (defined($cached)) { return $result; }
 2284: 
 2285:     my %Pending; 
 2286:     my %Expired;
 2287:     #
 2288:     # Each role can either have not started yet (pending), be active, 
 2289:     #    or have expired.
 2290:     #
 2291:     # If there is an active role, we are done.
 2292:     #
 2293:     # If there is more than one role which has not started yet, 
 2294:     #     choose the one which will start sooner
 2295:     # If there is one role which has not started yet, return it.
 2296:     #
 2297:     # If there is more than one expired role, choose the one which ended last.
 2298:     # If there is a role which has expired, return it.
 2299:     #
 2300:     $courseid = &courseid_to_courseurl($courseid);
 2301:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 2302:     foreach my $key (keys(%roleshash)) {
 2303:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2304:         my $section=$1;
 2305:         if ($key eq $courseid.'_st') { $section=''; }
 2306:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2307:         my $now=time;
 2308:         if (defined($end) && $end && ($now > $end)) {
 2309:             $Expired{$end}=$section;
 2310:             next;
 2311:         }
 2312:         if (defined($start) && $start && ($now < $start)) {
 2313:             $Pending{$start}=$section;
 2314:             next;
 2315:         }
 2316:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2317:     }
 2318:     #
 2319:     # Presumedly there will be few matching roles from the above
 2320:     # loop and the sorting time will be negligible.
 2321:     if (scalar(keys(%Pending))) {
 2322:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2323:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2324:     } 
 2325:     if (scalar(keys(%Expired))) {
 2326:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2327:         my $time = pop(@sorted);
 2328:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2329:     }
 2330:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2331: }
 2332: 
 2333: sub save_cache {
 2334:     &purge_remembered();
 2335:     #&Apache::loncommon::validate_page();
 2336:     undef(%env);
 2337:     undef($env_loaded);
 2338: }
 2339: 
 2340: my $to_remember=-1;
 2341: my %remembered;
 2342: my %accessed;
 2343: my $kicks=0;
 2344: my $hits=0;
 2345: sub make_key {
 2346:     my ($name,$id) = @_;
 2347:     if (length($id) > 65 
 2348: 	&& length(&escape($id)) > 200) {
 2349: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2350:     }
 2351:     return &escape($name.':'.$id);
 2352: }
 2353: 
 2354: sub devalidate_cache_new {
 2355:     my ($name,$id,$debug) = @_;
 2356:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2357:     $id=&make_key($name,$id);
 2358:     $memcache->delete($id);
 2359:     delete($remembered{$id});
 2360:     delete($accessed{$id});
 2361: }
 2362: 
 2363: sub is_cached_new {
 2364:     my ($name,$id,$debug) = @_;
 2365:     $id=&make_key($name,$id);
 2366:     if (exists($remembered{$id})) {
 2367: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
 2368: 	$accessed{$id}=[&gettimeofday()];
 2369: 	$hits++;
 2370: 	return ($remembered{$id},1);
 2371:     }
 2372:     my $value = $memcache->get($id);
 2373:     if (!(defined($value))) {
 2374: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2375: 	return (undef,undef);
 2376:     }
 2377:     if ($value eq '__undef__') {
 2378: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2379: 	$value=undef;
 2380:     }
 2381:     &make_room($id,$value,$debug);
 2382:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2383:     return ($value,1);
 2384: }
 2385: 
 2386: sub do_cache_new {
 2387:     my ($name,$id,$value,$time,$debug) = @_;
 2388:     $id=&make_key($name,$id);
 2389:     my $setvalue=$value;
 2390:     if (!defined($setvalue)) {
 2391: 	$setvalue='__undef__';
 2392:     }
 2393:     if (!defined($time) ) {
 2394: 	$time=600;
 2395:     }
 2396:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 2397:     my $result = $memcache->set($id,$setvalue,$time);
 2398:     if (! $result) {
 2399: 	&logthis("caching of id -> $id  failed");
 2400: 	$memcache->disconnect_all();
 2401:     }
 2402:     # need to make a copy of $value
 2403:     &make_room($id,$value,$debug);
 2404:     return $value;
 2405: }
 2406: 
 2407: sub make_room {
 2408:     my ($id,$value,$debug)=@_;
 2409: 
 2410:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 2411:                                     : $value;
 2412:     if ($to_remember<0) { return; }
 2413:     $accessed{$id}=[&gettimeofday()];
 2414:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 2415:     my $to_kick;
 2416:     my $max_time=0;
 2417:     foreach my $other (keys(%accessed)) {
 2418: 	if (&tv_interval($accessed{$other}) > $max_time) {
 2419: 	    $to_kick=$other;
 2420: 	    $max_time=&tv_interval($accessed{$other});
 2421: 	}
 2422:     }
 2423:     delete($remembered{$to_kick});
 2424:     delete($accessed{$to_kick});
 2425:     $kicks++;
 2426:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 2427:     return;
 2428: }
 2429: 
 2430: sub purge_remembered {
 2431:     #&logthis("Tossing ".scalar(keys(%remembered)));
 2432:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 2433:     undef(%remembered);
 2434:     undef(%accessed);
 2435: }
 2436: # ------------------------------------- Read an entry from a user's environment
 2437: 
 2438: sub userenvironment {
 2439:     my ($udom,$unam,@what)=@_;
 2440:     my $items;
 2441:     foreach my $item (@what) {
 2442:         $items.=&escape($item).'&';
 2443:     }
 2444:     $items=~s/\&$//;
 2445:     my %returnhash=();
 2446:     my $uhome = &homeserver($unam,$udom);
 2447:     unless ($uhome eq 'no_host') {
 2448:         my @answer=split(/\&/, 
 2449:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 2450:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 2451:             return %returnhash;
 2452:         }
 2453:         my $i;
 2454:         for ($i=0;$i<=$#what;$i++) {
 2455: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 2456:         }
 2457:     }
 2458:     return %returnhash;
 2459: }
 2460: 
 2461: # ---------------------------------------------------------- Get a studentphoto
 2462: sub studentphoto {
 2463:     my ($udom,$unam,$ext) = @_;
 2464:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2465:     if (defined($env{'request.course.id'})) {
 2466:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 2467:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 2468:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 2469:             } else {
 2470:                 my ($result,$perm_reqd)=
 2471: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2472:                 if ($result eq 'ok') {
 2473:                     if (!($perm_reqd eq 'yes')) {
 2474:                         return(&retrievestudentphoto($udom,$unam,$ext));
 2475:                     }
 2476:                 }
 2477:             }
 2478:         }
 2479:     } else {
 2480:         my ($result,$perm_reqd) = 
 2481: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2482:         if ($result eq 'ok') {
 2483:             if (!($perm_reqd eq 'yes')) {
 2484:                 return(&retrievestudentphoto($udom,$unam,$ext));
 2485:             }
 2486:         }
 2487:     }
 2488:     return '/adm/lonKaputt/lonlogo_broken.gif';
 2489: }
 2490: 
 2491: sub retrievestudentphoto {
 2492:     my ($udom,$unam,$ext,$type) = @_;
 2493:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2494:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 2495:     if ($ret eq 'ok') {
 2496:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 2497:         if ($type eq 'thumbnail') {
 2498:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 2499:         }
 2500:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 2501:         return $tokenurl;
 2502:     } else {
 2503:         if ($type eq 'thumbnail') {
 2504:             return '/adm/lonKaputt/genericstudent_tn.gif';
 2505:         } else { 
 2506:             return '/adm/lonKaputt/lonlogo_broken.gif';
 2507:         }
 2508:     }
 2509: }
 2510: 
 2511: # -------------------------------------------------------------------- New chat
 2512: 
 2513: sub chatsend {
 2514:     my ($newentry,$anon,$group)=@_;
 2515:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 2516:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2517:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 2518:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 2519: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 2520: 		   &escape($newentry)).':'.$group,$chome);
 2521: }
 2522: 
 2523: # ------------------------------------------ Find current version of a resource
 2524: 
 2525: sub getversion {
 2526:     my $fname=&clutter(shift);
 2527:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 2528:     return &currentversion(&filelocation('',$fname));
 2529: }
 2530: 
 2531: sub currentversion {
 2532:     my $fname=shift;
 2533:     my $author=$fname;
 2534:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2535:     my ($udom,$uname)=split(/\//,$author);
 2536:     my $home=&homeserver($uname,$udom);
 2537:     if ($home eq 'no_host') { 
 2538:         return -1; 
 2539:     }
 2540:     my $answer=&reply("currentversion:$fname",$home);
 2541:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2542: 	return -1;
 2543:     }
 2544:     return $answer;
 2545: }
 2546: 
 2547: #
 2548: # Return special version number of resource if set by override, empty otherwise
 2549: #
 2550: sub usedversion {
 2551:     my $fname=shift;
 2552:     unless ($fname) { $fname=$env{'request.uri'}; }
 2553:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 2554:     if ($urlversion) { return $urlversion; }
 2555:     return '';
 2556: }
 2557: 
 2558: # ----------------------------- Subscribe to a resource, return URL if possible
 2559: 
 2560: sub subscribe {
 2561:     my $fname=shift;
 2562:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 2563:     $fname=~s/[\n\r]//g;
 2564:     my $author=$fname;
 2565:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2566:     my ($udom,$uname)=split(/\//,$author);
 2567:     my $home=homeserver($uname,$udom);
 2568:     if ($home eq 'no_host') {
 2569:         return 'not_found';
 2570:     }
 2571:     my $answer=reply("sub:$fname",$home);
 2572:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2573: 	$answer.=' by '.$home;
 2574:     }
 2575:     return $answer;
 2576: }
 2577:     
 2578: # -------------------------------------------------------------- Replicate file
 2579: 
 2580: sub repcopy {
 2581:     my $filename=shift;
 2582:     $filename=~s/\/+/\//g;
 2583:     my $londocroot = $perlvar{'lonDocRoot'};
 2584:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 2585:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 2586:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 2587: 	$filename=~m{^/*(uploaded|editupload)/}) {
 2588: 	return &repcopy_userfile($filename);
 2589:     }
 2590:     $filename=~s/[\n\r]//g;
 2591:     my $transname="$filename.in.transfer";
 2592: # FIXME: this should flock
 2593:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 2594:     my $remoteurl=subscribe($filename);
 2595:     if ($remoteurl =~ /^con_lost by/) {
 2596: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2597:            return 'unavailable';
 2598:     } elsif ($remoteurl eq 'not_found') {
 2599: 	   #&logthis("Subscribe returned not_found: $filename");
 2600: 	   return 'not_found';
 2601:     } elsif ($remoteurl =~ /^rejected by/) {
 2602: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2603:            return 'forbidden';
 2604:     } elsif ($remoteurl eq 'directory') {
 2605:            return 'ok';
 2606:     } else {
 2607:         my $author=$filename;
 2608:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2609:         my ($udom,$uname)=split(/\//,$author);
 2610:         my $home=homeserver($uname,$udom);
 2611:         unless ($home eq $perlvar{'lonHostID'}) {
 2612:            my @parts=split(/\//,$filename);
 2613:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 2614:            if ($path ne "$londocroot/res") {
 2615:                &logthis("Malconfiguration for replication: $filename");
 2616: 	       return 'bad_request';
 2617:            }
 2618:            my $count;
 2619:            for ($count=5;$count<$#parts;$count++) {
 2620:                $path.="/$parts[$count]";
 2621:                if ((-e $path)!=1) {
 2622: 		   mkdir($path,0777);
 2623:                }
 2624:            }
 2625:            my $ua=new LWP::UserAgent;
 2626:            my $request=new HTTP::Request('GET',"$remoteurl");
 2627:            my $response=$ua->request($request,$transname);
 2628:            if ($response->is_error()) {
 2629: 	       unlink($transname);
 2630:                my $message=$response->status_line;
 2631:                &logthis("<font color=\"blue\">WARNING:"
 2632:                        ." LWP get: $message: $filename</font>");
 2633:                return 'unavailable';
 2634:            } else {
 2635: 	       if ($remoteurl!~/\.meta$/) {
 2636:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 2637:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 2638:                   if ($mresponse->is_error()) {
 2639: 		      unlink($filename.'.meta');
 2640:                       &logthis(
 2641:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 2642:                   }
 2643: 	       }
 2644:                rename($transname,$filename);
 2645:                return 'ok';
 2646:            }
 2647:        }
 2648:     }
 2649: }
 2650: 
 2651: # ------------------------------------------------ Get server side include body
 2652: sub ssi_body {
 2653:     my ($filelink,%form)=@_;
 2654:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 2655:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 2656:     }
 2657:     my $output='';
 2658:     my $response;
 2659:     if ($filelink=~/^https?\:/) {
 2660:        ($output,$response)=&externalssi($filelink);
 2661:     } else {
 2662:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 2663:        $filelink .= 'inhibitmenu=yes';
 2664:        ($output,$response)=&ssi($filelink,%form);
 2665:     }
 2666:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 2667:     $output=~s/^.*?\<body[^\>]*\>//si;
 2668:     $output=~s/\<\/body\s*\>.*?$//si;
 2669:     if (wantarray) {
 2670:         return ($output, $response);
 2671:     } else {
 2672:         return $output;
 2673:     }
 2674: }
 2675: 
 2676: # --------------------------------------------------------- Server Side Include
 2677: 
 2678: sub absolute_url {
 2679:     my ($host_name) = @_;
 2680:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 2681:     if ($host_name eq '') {
 2682: 	$host_name = $ENV{'SERVER_NAME'};
 2683:     }
 2684:     return $protocol.$host_name;
 2685: }
 2686: 
 2687: #
 2688: #   Server side include.
 2689: # Parameters:
 2690: #  fn     Possibly encrypted resource name/id.
 2691: #  form   Hash that describes how the rendering should be done
 2692: #         and other things.
 2693: # Returns:
 2694: #   Scalar context: The content of the response.
 2695: #   Array context:  2 element list of the content and the full response object.
 2696: #     
 2697: sub ssi {
 2698: 
 2699:     my ($fn,%form)=@_;
 2700:     my $ua=new LWP::UserAgent;
 2701:     my $request;
 2702: 
 2703:     $form{'no_update_last_known'}=1;
 2704:     &Apache::lonenc::check_encrypt(\$fn);
 2705:     if (%form) {
 2706:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 2707:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
 2708:     } else {
 2709:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 2710:     }
 2711: 
 2712:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 2713:     my $response= $ua->request($request);
 2714:     my $content = $response->content;
 2715: 
 2716: 
 2717:     if (wantarray) {
 2718: 	return ($content, $response);
 2719:     } else {
 2720: 	return $content;
 2721:     }
 2722: }
 2723: 
 2724: sub externalssi {
 2725:     my ($url)=@_;
 2726:     my $ua=new LWP::UserAgent;
 2727:     my $request=new HTTP::Request('GET',$url);
 2728:     my $response=$ua->request($request);
 2729:     if (wantarray) {
 2730:         return ($response->content, $response);
 2731:     } else {
 2732:         return $response->content;
 2733:     }
 2734: }
 2735: 
 2736: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 2737: 
 2738: sub allowuploaded {
 2739:     my ($srcurl,$url)=@_;
 2740:     $url=&clutter(&declutter($url));
 2741:     my $dir=$url;
 2742:     $dir=~s/\/[^\/]+$//;
 2743:     my %httpref=();
 2744:     my $httpurl=&hreflocation('',$url);
 2745:     $httpref{'httpref.'.$httpurl}=$srcurl;
 2746:     &Apache::lonnet::appenv(\%httpref);
 2747: }
 2748: 
 2749: #
 2750: # Determine if the current user should be able to edit a particular resource,
 2751: # when viewing in course context.
 2752: # (a) When viewing resource used to determine if "Edit" item is included in 
 2753: #     Functions.
 2754: # (b) When displaying folder contents in course editor, used to determine if
 2755: #     "Edit" link will be displayed alongside resource.
 2756: #
 2757: #  input: six args -- filename (decluttered), course number, course domain,
 2758: #                   url, symb (if registered) and group (if this is a group
 2759: #                   item -- e.g., bulletin board, group page etc.).
 2760: #  output: array of five scalars -- 
 2761: #          $cfile -- url for file editing if editable on current server
 2762: #          $home -- homeserver of resource (i.e., for author if published,
 2763: #                                           or course if uploaded.).
 2764: #          $switchserver --  1 if server switch will be needed.
 2765: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 2766: #          $forceview -- 1 if icon/link should be to go to view mode
 2767: #
 2768: 
 2769: sub can_edit_resource {
 2770:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 2771:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 2772: #
 2773: # For aboutme pages user can only edit his/her own.
 2774: #
 2775:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 2776:         my ($sdom,$sname) = ($1,$2);
 2777:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 2778:             $home = $env{'user.home'};
 2779:             $cfile = $resurl;
 2780:             if ($env{'form.forceedit'}) {
 2781:                 $forceview = 1;
 2782:             } else {
 2783:                 $forceedit = 1;
 2784:             }
 2785:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 2786:         } else {
 2787:             return;
 2788:         }
 2789:     }
 2790: 
 2791:     if ($env{'request.course.id'}) {
 2792:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 2793:         if ($group ne '') {
 2794: # if this is a group homepage or group bulletin board, check group privs
 2795:             my $allowed = 0;
 2796:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 2797:                 if ((&allowed('mdg',$env{'request.course.id'}.
 2798:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 2799:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 2800:                     $allowed = 1;
 2801:                 }
 2802:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 2803:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 2804:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 2805:                     $allowed = 1;
 2806:                 }
 2807:             }
 2808:             if ($allowed) {
 2809:                 $home=&homeserver($cnum,$cdom);
 2810:                 if ($env{'form.forceedit'}) {
 2811:                     $forceview = 1;
 2812:                 } else {
 2813:                     $forceedit = 1;
 2814:                 }
 2815:                 $cfile = $resurl;
 2816:             } else {
 2817:                 return;
 2818:             }
 2819:         } else {
 2820:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 2821:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 2822:                     return;
 2823:                 }
 2824:             } elsif (!$crsedit) {
 2825: #
 2826: # No edit allowed where CC has switched to student role.
 2827: #
 2828:                 return;
 2829:             }
 2830:         }
 2831:     }
 2832: 
 2833:     if ($file ne '') {
 2834:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 2835:             if (&is_course_upload($file,$cnum,$cdom)) {
 2836:                 $uploaded = 1;
 2837:                 $incourse = 1;
 2838:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 2839:                     $cfile = &hreflocation('',$file);
 2840:                     if ($env{'form.forceedit'}) {
 2841:                         $forceview = 1;
 2842:                     } else {
 2843:                         $forceedit = 1;
 2844:                     }
 2845:                 }
 2846:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 2847:                 $incourse = 1;
 2848:                 if ($env{'form.forceedit'}) {
 2849:                     $forceview = 1;
 2850:                 } else {
 2851:                     $forceedit = 1;
 2852:                 }
 2853:                 $cfile = $resurl;
 2854:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 2855:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 2856:                     $incourse = 1;
 2857:                     if ($env{'form.forceedit'}) {
 2858:                         $forceview = 1;
 2859:                     } else {
 2860:                         $forceedit = 1;
 2861:                     }
 2862:                     $cfile = $resurl;
 2863:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 2864:                     $incourse = 1;
 2865:                     $cfile = $resurl.'/smpedit';
 2866:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 2867:                     $incourse = 1;
 2868:                     if ($env{'form.forceedit'}) {
 2869:                         $forceview = 1;
 2870:                     } else {
 2871:                         $forceedit = 1;
 2872:                     }
 2873:                     $cfile = $resurl;
 2874:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 2875:                     $incourse = 1;
 2876:                     if ($env{'form.forceedit'}) {
 2877:                         $forceview = 1;
 2878:                     } else {
 2879:                         $forceedit = 1;
 2880:                     }
 2881:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 2882:                 }
 2883:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 2884:                 my $template = '/res/lib/templates/simpleproblem.problem';
 2885:                 if (&is_on_map($template)) { 
 2886:                     $incourse = 1;
 2887:                     $forceview = 1;
 2888:                     $cfile = $template;
 2889:                 }
 2890:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 2891:                     $incourse = 1;
 2892:                     if ($env{'form.forceedit'}) {
 2893:                         $forceview = 1;
 2894:                     } else {
 2895:                         $forceedit = 1;
 2896:                     }
 2897:                     $cfile = $resurl;
 2898:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 2899:                 $incourse = 1;
 2900:                 $forceview = 1;
 2901:                 if ($symb) {
 2902:                     my ($map,$id,$res)=&decode_symb($symb);
 2903:                     $env{'request.symb'} = $symb;
 2904:                     $cfile = &clutter($res);
 2905:                 } else {
 2906:                     $cfile = $env{'form.suppurl'};
 2907:                     $cfile =~ s{^http://}{};
 2908:                     $cfile = '/adm/wrapper/ext/'.$cfile;
 2909:                 }
 2910:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 2911:                 if ($env{'form.forceedit'}) {
 2912:                     $forceview = 1;
 2913:                 } else {
 2914:                     $forceedit = 1;
 2915:                 }
 2916:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 2917:             }
 2918:         }
 2919:         if ($uploaded || $incourse) {
 2920:             $home=&homeserver($cnum,$cdom);
 2921:         } elsif ($file !~ m{/$}) {
 2922:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 2923:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 2924:             # Check that the user has permission to edit this resource
 2925:             my $setpriv = 1;
 2926:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 2927:             if (defined($cfudom)) {
 2928:                 $home=&homeserver($cfuname,$cfudom);
 2929:                 $cfile=$file;
 2930:             }
 2931:         }
 2932:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 2933:             (($home ne '') && ($home ne 'no_host'))) {
 2934:             my @ids=&current_machine_ids();
 2935:             unless (grep(/^\Q$home\E$/,@ids)) {
 2936:                 $switchserver=1;
 2937:             }
 2938:         }
 2939:     }
 2940:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 2941: }
 2942: 
 2943: sub is_course_upload {
 2944:     my ($file,$cnum,$cdom) = @_;
 2945:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 2946:     $uploadpath =~ s{^\/}{};
 2947:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 2948:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 2949:         return 1;
 2950:     }
 2951:     return;
 2952: }
 2953: 
 2954: sub in_course {
 2955:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 2956:     if ($hideprivileged) {
 2957:         my $skipuser;
 2958:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 2959:         my @possdoms = ($cdom);  
 2960:         if ($coursehash{'checkforpriv'}) { 
 2961:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 2962:         }
 2963:         if (&privileged($uname,$udom,\@possdoms)) {
 2964:             $skipuser = 1;
 2965:             if ($coursehash{'nothideprivileged'}) {
 2966:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2967:                     my $user;
 2968:                     if ($item =~ /:/) {
 2969:                         $user = $item;
 2970:                     } else {
 2971:                         $user = join(':',split(/[\@]/,$item));
 2972:                     }
 2973:                     if ($user eq $uname.':'.$udom) {
 2974:                         undef($skipuser);
 2975:                         last;
 2976:                     }
 2977:                 }
 2978:             }
 2979:             if ($skipuser) {
 2980:                 return 0;
 2981:             }
 2982:         }
 2983:     }
 2984:     $type ||= 'any';
 2985:     if (!defined($cdom) || !defined($cnum)) {
 2986:         my $cid  = $env{'request.course.id'};
 2987:         $cdom = $env{'course.'.$cid.'.domain'};
 2988:         $cnum = $env{'course.'.$cid.'.num'};
 2989:     }
 2990:     my $typesref;
 2991:     if (($type eq 'any') || ($type eq 'all')) {
 2992:         $typesref = ['active','previous','future'];
 2993:     } elsif ($type eq 'previous' || $type eq 'future') {
 2994:         $typesref = [$type];
 2995:     }
 2996:     my %roles = &get_my_roles($uname,$udom,'userroles',
 2997:                               $typesref,undef,[$cdom]);
 2998:     my ($tmp) = keys(%roles);
 2999:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 3000:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 3001:     if (@course_roles > 0) {
 3002:         return 1;
 3003:     }
 3004:     return 0;
 3005: }
 3006: 
 3007: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 3008: # input: action, courseID, current domain, intended
 3009: #        path to file, source of file, instruction to parse file for objects,
 3010: #        ref to hash for embedded objects,
 3011: #        ref to hash for codebase of java objects.
 3012: #        reference to scalar to accommodate mime type determined
 3013: #          from File::MMagic if $parser = parse.
 3014: #
 3015: # output: url to file (if action was uploaddoc), 
 3016: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 3017: #
 3018: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 3019: # course.
 3020: #
 3021: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3022: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 3023: #          course's home server.
 3024: #
 3025: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 3026: #          be copied from $source (current location) to 
 3027: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3028: #         and will then be copied to
 3029: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 3030: #         course's home server.
 3031: #
 3032: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3033: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 3034: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3035: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 3036: #         in course's home server.
 3037: #
 3038: 
 3039: sub process_coursefile {
 3040:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 3041:         $mimetype)=@_;
 3042:     my $fetchresult;
 3043:     my $home=&homeserver($docuname,$docudom);
 3044:     if ($action eq 'propagate') {
 3045:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3046: 			     $home);
 3047:     } else {
 3048:         my $fpath = '';
 3049:         my $fname = $file;
 3050:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3051:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3052:         my $filepath = &build_filepath($fpath);
 3053:         if ($action eq 'copy') {
 3054:             if ($source eq '') {
 3055:                 $fetchresult = 'no source file';
 3056:                 return $fetchresult;
 3057:             } else {
 3058:                 my $destination = $filepath.'/'.$fname;
 3059:                 rename($source,$destination);
 3060:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3061:                                  $home);
 3062:             }
 3063:         } elsif ($action eq 'uploaddoc') {
 3064:             open(my $fh,'>'.$filepath.'/'.$fname);
 3065:             print $fh $env{'form.'.$source};
 3066:             close($fh);
 3067:             if ($parser eq 'parse') {
 3068:                 my $mm = new File::MMagic;
 3069:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 3070:                 if ($type eq 'text/html') {
 3071:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 3072:                     unless ($parse_result eq 'ok') {
 3073:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 3074:                     }
 3075:                 }
 3076:                 if (ref($mimetype)) {
 3077:                     $$mimetype = $type;
 3078:                 } 
 3079:             }
 3080:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3081:                                  $home);
 3082:             if ($fetchresult eq 'ok') {
 3083:                 return '/uploaded/'.$fpath.'/'.$fname;
 3084:             } else {
 3085:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3086:                         ' to host '.$home.': '.$fetchresult);
 3087:                 return '/adm/notfound.html';
 3088:             }
 3089:         }
 3090:     }
 3091:     unless ( $fetchresult eq 'ok') {
 3092:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3093:              ' to host '.$home.': '.$fetchresult);
 3094:     }
 3095:     return $fetchresult;
 3096: }
 3097: 
 3098: sub build_filepath {
 3099:     my ($fpath) = @_;
 3100:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 3101:     unless ($fpath eq '') {
 3102:         my @parts=split('/',$fpath);
 3103:         foreach my $part (@parts) {
 3104:             $filepath.= '/'.$part;
 3105:             if ((-e $filepath)!=1) {
 3106:                 mkdir($filepath,0777);
 3107:             }
 3108:         }
 3109:     }
 3110:     return $filepath;
 3111: }
 3112: 
 3113: sub store_edited_file {
 3114:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 3115:     my $file = $primary_url;
 3116:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 3117:     my $fpath = '';
 3118:     my $fname = $file;
 3119:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3120:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3121:     my $filepath = &build_filepath($fpath);
 3122:     open(my $fh,'>'.$filepath.'/'.$fname);
 3123:     print $fh $content;
 3124:     close($fh);
 3125:     my $home=&homeserver($docuname,$docudom);
 3126:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3127: 			  $home);
 3128:     if ($$fetchresult eq 'ok') {
 3129:         return '/uploaded/'.$fpath.'/'.$fname;
 3130:     } else {
 3131:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3132: 		 ' to host '.$home.': '.$$fetchresult);
 3133:         return '/adm/notfound.html';
 3134:     }
 3135: }
 3136: 
 3137: sub clean_filename {
 3138:     my ($fname,$args)=@_;
 3139: # Replace Windows backslashes by forward slashes
 3140:     $fname=~s/\\/\//g;
 3141:     if (!$args->{'keep_path'}) {
 3142:         # Get rid of everything but the actual filename
 3143: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 3144:     }
 3145: # Replace spaces by underscores
 3146:     $fname=~s/\s+/\_/g;
 3147: # Replace all other weird characters by nothing
 3148:     $fname=~s{[^/\w\.\-]}{}g;
 3149: # Replace all .\d. sequences with _\d. so they no longer look like version
 3150: # numbers
 3151:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 3152:     return $fname;
 3153: }
 3154: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 3155: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 3156: # image with the same aspect ratio as the original, but with dimensions which do 
 3157: # not exceed $resizewidth and $resizeheight.
 3158:  
 3159: sub resizeImage {
 3160:     my ($img_path,$resizewidth,$resizeheight) = @_;
 3161:     my $ima = Image::Magick->new;
 3162:     my $resized;
 3163:     if (-e $img_path) {
 3164:         $ima->Read($img_path);
 3165:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 3166:             my $width = $ima->Get('width');
 3167:             my $height = $ima->Get('height');
 3168:             if ($width > $resizewidth) {
 3169: 	        my $factor = $width/$resizewidth;
 3170:                 my $newheight = $height/$factor;
 3171:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 3172:                 $resized = 1;
 3173:             }
 3174:         }
 3175:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 3176:             my $width = $ima->Get('width');
 3177:             my $height = $ima->Get('height');
 3178:             if ($height > $resizeheight) {
 3179:                 my $factor = $height/$resizeheight;
 3180:                 my $newwidth = $width/$factor;
 3181:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 3182:                 $resized = 1;
 3183:             }
 3184:         }
 3185:         if ($resized) {
 3186:             $ima->Write($img_path);
 3187:         }
 3188:     }
 3189:     return;
 3190: }
 3191: 
 3192: # --------------- Take an uploaded file and put it into the userfiles directory
 3193: # input: $formname - the contents of the file are in $env{"form.$formname"}
 3194: #                    the desired filename is in $env{"form.$formname.filename"}
 3195: #        $context - possible values: coursedoc, existingfile, overwrite, 
 3196: #                                    canceloverwrite, or ''. 
 3197: #                   if 'coursedoc': upload to the current course
 3198: #                   if 'existingfile': write file to tmp/overwrites directory 
 3199: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 3200: #                   $context is passed as argument to &finishuserfileupload
 3201: #        $subdir - directory in userfile to store the file into
 3202: #        $parser - instruction to parse file for objects ($parser = parse)    
 3203: #        $allfiles - reference to hash for embedded objects
 3204: #        $codebase - reference to hash for codebase of java objects
 3205: #        $desuname - username for permanent storage of uploaded file
 3206: #        $dsetudom - domain for permanaent storage of uploaded file
 3207: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 3208: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 3209: #        $resizewidth - width (pixels) to which to resize uploaded image
 3210: #        $resizeheight - height (pixels) to which to resize uploaded image
 3211: #        $mimetype - reference to scalar to accommodate mime type determined
 3212: #                    from File::MMagic.
 3213: # 
 3214: # output: url of file in userspace, or error: <message> 
 3215: #             or /adm/notfound.html if failure to upload occurse
 3216: 
 3217: sub userfileupload {
 3218:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 3219:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 3220:     if (!defined($subdir)) { $subdir='unknown'; }
 3221:     my $fname=$env{'form.'.$formname.'.filename'};
 3222:     $fname=&clean_filename($fname);
 3223:     # See if there is anything left
 3224:     unless ($fname) { return 'error: no uploaded file'; }
 3225:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 3226:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 3227:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 3228:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3229:         my $now = time;
 3230:         my $filepath;
 3231:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 3232:              $filepath = 'tmp/helprequests/'.$now;
 3233:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 3234:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 3235:                          '_'.$env{'user.domain'}.'/pending';
 3236:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3237:             my ($docuname,$docudom);
 3238:             if ($destudom) {
 3239:                 $docudom = $destudom;
 3240:             } else {
 3241:                 $docudom = $env{'user.domain'};
 3242:             }
 3243:             if ($destuname) {
 3244:                 $docuname = $destuname;
 3245:             } else {
 3246:                 $docuname = $env{'user.name'};
 3247:             }
 3248:             if (exists($env{'form.group'})) {
 3249:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3250:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3251:             }
 3252:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 3253:             if ($context eq 'canceloverwrite') {
 3254:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 3255:                 if (-e  $tempfile) {
 3256:                     my @info = stat($tempfile);
 3257:                     if ($info[9] eq $env{'form.timestamp'}) {
 3258:                         unlink($tempfile);
 3259:                     }
 3260:                 }
 3261:                 return;
 3262:             }
 3263:         }
 3264:         # Create the directory if not present
 3265:         my @parts=split(/\//,$filepath);
 3266:         my $fullpath = $perlvar{'lonDaemons'};
 3267:         for (my $i=0;$i<@parts;$i++) {
 3268:             $fullpath .= '/'.$parts[$i];
 3269:             if ((-e $fullpath)!=1) {
 3270:                 mkdir($fullpath,0777);
 3271:             }
 3272:         }
 3273:         open(my $fh,'>'.$fullpath.'/'.$fname);
 3274:         print $fh $env{'form.'.$formname};
 3275:         close($fh);
 3276:         if ($context eq 'existingfile') {
 3277:             my @info = stat($fullpath.'/'.$fname);
 3278:             return ($fullpath.'/'.$fname,$info[9]);
 3279:         } else {
 3280:             return $fullpath.'/'.$fname;
 3281:         }
 3282:     }
 3283:     if ($subdir eq 'scantron') {
 3284:         $fname = 'scantron_orig_'.$fname;
 3285:     } else {
 3286:         $fname="$subdir/$fname";
 3287:     }
 3288:     if ($context eq 'coursedoc') {
 3289: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3290: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3291:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 3292:             return &finishuserfileupload($docuname,$docudom,
 3293: 					 $formname,$fname,$parser,$allfiles,
 3294: 					 $codebase,$thumbwidth,$thumbheight,
 3295:                                          $resizewidth,$resizeheight,$context,$mimetype);
 3296:         } else {
 3297:             if ($env{'form.folder'}) {
 3298:                 $fname=$env{'form.folder'}.'/'.$fname;
 3299:             }
 3300:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 3301: 				       $fname,$formname,$parser,
 3302: 				       $allfiles,$codebase,$mimetype);
 3303:         }
 3304:     } elsif (defined($destuname)) {
 3305:         my $docuname=$destuname;
 3306:         my $docudom=$destudom;
 3307: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3308: 				     $parser,$allfiles,$codebase,
 3309:                                      $thumbwidth,$thumbheight,
 3310:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3311:     } else {
 3312:         my $docuname=$env{'user.name'};
 3313:         my $docudom=$env{'user.domain'};
 3314:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 3315:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3316:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3317:         }
 3318: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3319: 				     $parser,$allfiles,$codebase,
 3320:                                      $thumbwidth,$thumbheight,
 3321:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3322:     }
 3323: }
 3324: 
 3325: sub finishuserfileupload {
 3326:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 3327:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 3328:     my $path=$docudom.'/'.$docuname.'/';
 3329:     my $filepath=$perlvar{'lonDocRoot'};
 3330:   
 3331:     my ($fnamepath,$file,$fetchthumb);
 3332:     $file=$fname;
 3333:     if ($fname=~m|/|) {
 3334:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 3335: 	$path.=$fnamepath.'/';
 3336:     }
 3337:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 3338:     my $count;
 3339:     for ($count=4;$count<=$#parts;$count++) {
 3340:         $filepath.="/$parts[$count]";
 3341:         if ((-e $filepath)!=1) {
 3342: 	    mkdir($filepath,0777);
 3343:         }
 3344:     }
 3345: 
 3346: # Save the file
 3347:     {
 3348: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 3349: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 3350: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 3351: 	    return '/adm/notfound.html';
 3352: 	}
 3353:         if ($context eq 'overwrite') {
 3354:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 3355:             my $target = $filepath.'/'.$file;
 3356:             if (-e $source) {
 3357:                 my @info = stat($source);
 3358:                 if ($info[9] eq $env{'form.timestamp'}) {   
 3359:                     unless (&File::Copy::move($source,$target)) {
 3360:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 3361:                         return "Moving from $source failed";
 3362:                     }
 3363:                 } else {
 3364:                     return "Temporary file: $source had unexpected date/time for last modification";
 3365:                 }
 3366:             } else {
 3367:                 return "Temporary file: $source missing";
 3368:             }
 3369:         } elsif (!print FH ($env{'form.'.$formname})) {
 3370: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 3371: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 3372: 	    return '/adm/notfound.html';
 3373: 	}
 3374: 	close(FH);
 3375:         if ($resizewidth && $resizeheight) {
 3376:             my $mm = new File::MMagic;
 3377:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 3378:             if ($mime_type =~ m{^image/}) {
 3379: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 3380:             }  
 3381: 	}
 3382:     }
 3383:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 3384:         if (ref($mimetype)) {
 3385:             if ($$mimetype eq '') {
 3386:                 my $mm = new File::MMagic;
 3387:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 3388:                 $$mimetype = $type;
 3389:             }
 3390:         }
 3391:     }
 3392:     if ($parser eq 'parse') {
 3393:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 3394:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 3395:                                                        $allfiles,$codebase);
 3396:             unless ($parse_result eq 'ok') {
 3397:                 &logthis('Failed to parse '.$filepath.$file.
 3398: 	   	         ' for embedded media: '.$parse_result); 
 3399:             }
 3400:         }
 3401:     }
 3402:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 3403:         my $input = $filepath.'/'.$file;
 3404:         my $output = $filepath.'/'.'tn-'.$file;
 3405:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 3406:         system("convert -sample $thumbsize $input $output");
 3407:         if (-e $filepath.'/'.'tn-'.$file) {
 3408:             $fetchthumb  = 1; 
 3409:         }
 3410:     }
 3411:  
 3412: # Notify homeserver to grep it
 3413: #
 3414:     my $docuhome=&homeserver($docuname,$docudom);	
 3415:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 3416:     if ($fetchresult eq 'ok') {
 3417:         if ($fetchthumb) {
 3418:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 3419:             if ($thumbresult ne 'ok') {
 3420:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 3421:                          $docuhome.': '.$thumbresult);
 3422:             }
 3423:         }
 3424: #
 3425: # Return the URL to it
 3426:         return '/uploaded/'.$path.$file;
 3427:     } else {
 3428:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 3429: 		 ': '.$fetchresult);
 3430:         return '/adm/notfound.html';
 3431:     }
 3432: }
 3433: 
 3434: sub extract_embedded_items {
 3435:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 3436:     my @state = ();
 3437:     my (%lastids,%related,%shockwave,%flashvars);
 3438:     my %javafiles = (
 3439:                       codebase => '',
 3440:                       code => '',
 3441:                       archive => ''
 3442:                     );
 3443:     my %mediafiles = (
 3444:                       src => '',
 3445:                       movie => '',
 3446:                      );
 3447:     my $p;
 3448:     if ($content) {
 3449:         $p = HTML::LCParser->new($content);
 3450:     } else {
 3451:         $p = HTML::LCParser->new($fullpath);
 3452:     }
 3453:     while (my $t=$p->get_token()) {
 3454: 	if ($t->[0] eq 'S') {
 3455: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 3456: 	    push(@state, $tagname);
 3457:             if (lc($tagname) eq 'allow') {
 3458:                 &add_filetype($allfiles,$attr->{'src'},'src');
 3459:             }
 3460: 	    if (lc($tagname) eq 'img') {
 3461: 		&add_filetype($allfiles,$attr->{'src'},'src');
 3462: 	    }
 3463: 	    if (lc($tagname) eq 'a') {
 3464:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 3465:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3466:                 }
 3467: 	    }
 3468:             if (lc($tagname) eq 'script') {
 3469:                 my $src;
 3470:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 3471:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 3472:                 } else {
 3473:                     if ($attr->{'src'} ne '') {
 3474:                         $src = $attr->{'src'};
 3475:                         &add_filetype($allfiles,$src,'src');
 3476:                     }
 3477:                 }
 3478:                 my $text = $p->get_trimmed_text();
 3479:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 3480:                     my @swfargs = split(/,/,$1);
 3481:                     foreach my $item (@swfargs) {
 3482:                         $item =~ s/["']//g;
 3483:                         $item =~ s/^\s+//;
 3484:                         $item =~ s/\s+$//;
 3485:                     }
 3486:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 3487:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 3488:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 3489:                         } else {
 3490:                             $related{$swfargs[0]} = [$swfargs[2]];
 3491:                         }
 3492:                     }
 3493:                 }
 3494:             }
 3495:             if (lc($tagname) eq 'link') {
 3496:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 3497:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3498:                 }
 3499:             }
 3500: 	    if (lc($tagname) eq 'object' ||
 3501: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 3502: 		foreach my $item (keys(%javafiles)) {
 3503: 		    $javafiles{$item} = '';
 3504: 		}
 3505:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 3506:                     $lastids{lc($tagname)} = $attr->{'id'};
 3507:                 }
 3508: 	    }
 3509: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 3510: 		my $name = lc($attr->{'name'});
 3511: 		foreach my $item (keys(%javafiles)) {
 3512: 		    if ($name eq $item) {
 3513: 			$javafiles{$item} = $attr->{'value'};
 3514: 			last;
 3515: 		    }
 3516: 		}
 3517:                 my $pathfrom;
 3518: 		foreach my $item (keys(%mediafiles)) {
 3519: 		    if ($name eq $item) {
 3520:                         $pathfrom = $attr->{'value'};
 3521:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 3522: 			&add_filetype($allfiles,$pathfrom,$name);
 3523: 			last;
 3524: 		    }
 3525: 		}
 3526:                 if ($name eq 'flashvars') {
 3527:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 3528:                 }
 3529:                 if ($pathfrom ne '') {
 3530:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 3531:                                          $pathfrom);
 3532:                 }
 3533: 	    }
 3534: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 3535: 		foreach my $item (keys(%javafiles)) {
 3536: 		    if ($attr->{$item}) {
 3537: 			$javafiles{$item} = $attr->{$item};
 3538: 			last;
 3539: 		    }
 3540: 		}
 3541: 		foreach my $item (keys(%mediafiles)) {
 3542: 		    if ($attr->{$item}) {
 3543: 			&add_filetype($allfiles,$attr->{$item},$item);
 3544: 			last;
 3545: 		    }
 3546: 		}
 3547:                 if (lc($tagname) eq 'embed') {
 3548:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 3549:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 3550:                                              $attr->{'src'});
 3551:                     }
 3552:                 }
 3553: 	    }
 3554:             if (lc($tagname) eq 'iframe') {
 3555:                 my $src = $attr->{'src'} ;
 3556:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 3557:                     &add_filetype($allfiles,$src,'src');
 3558:                 } elsif ($src =~ m{^/}) {
 3559:                     if ($env{'request.course.id'}) {
 3560:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3561:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3562:                         my $url = &hreflocation('',$fullpath);
 3563:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 3564:                             my $relpath = $1;
 3565:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 3566:                                 &add_filetype($allfiles,$1,'src');
 3567:                             }
 3568:                         }
 3569:                     }
 3570:                 }
 3571:             }
 3572:             if ($t->[4] =~ m{/>$}) {
 3573:                 pop(@state);
 3574:             }
 3575: 	} elsif ($t->[0] eq 'E') {
 3576: 	    my ($tagname) = ($t->[1]);
 3577: 	    if ($javafiles{'codebase'} ne '') {
 3578: 		$javafiles{'codebase'} .= '/';
 3579: 	    }  
 3580: 	    if (lc($tagname) eq 'applet' ||
 3581: 		lc($tagname) eq 'object' ||
 3582: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 3583: 		) {
 3584: 		foreach my $item (keys(%javafiles)) {
 3585: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 3586: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 3587: 			&add_filetype($allfiles,$file,$item);
 3588: 		    }
 3589: 		}
 3590: 	    } 
 3591: 	    pop @state;
 3592: 	}
 3593:     }
 3594:     foreach my $id (sort(keys(%flashvars))) {
 3595:         if ($shockwave{$id} ne '') {
 3596:             my @pairs = split(/\&/,$flashvars{$id});
 3597:             foreach my $pair (@pairs) {
 3598:                 my ($key,$value) = split(/\=/,$pair);
 3599:                 if ($key eq 'thumb') {
 3600:                     &add_filetype($allfiles,$value,$key);
 3601:                 } elsif ($key eq 'content') {
 3602:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 3603:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 3604:                     if ($ext ne '') {
 3605:                         &add_filetype($allfiles,$path.$value,$ext);
 3606:                     }
 3607:                 }
 3608:             }
 3609:         }
 3610:     }
 3611:     return 'ok';
 3612: }
 3613: 
 3614: sub add_filetype {
 3615:     my ($allfiles,$file,$type)=@_;
 3616:     if (exists($allfiles->{$file})) {
 3617: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 3618: 	    push(@{$allfiles->{$file}}, &escape($type));
 3619: 	}
 3620:     } else {
 3621: 	@{$allfiles->{$file}} = (&escape($type));
 3622:     }
 3623: }
 3624: 
 3625: sub embedded_dependency {
 3626:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 3627:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 3628:         if (($identifier ne '') &&
 3629:             (ref($related->{$identifier}) eq 'ARRAY') &&
 3630:             ($pathfrom ne '')) {
 3631:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 3632:             foreach my $dep (@{$related->{$identifier}}) {
 3633:                 &add_filetype($allfiles,$path.$dep,'object');
 3634:             }
 3635:         }
 3636:     }
 3637:     return;
 3638: }
 3639: 
 3640: sub removeuploadedurl {
 3641:     my ($url)=@_;	
 3642:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 3643:     return &removeuserfile($uname,$udom,$fname);
 3644: }
 3645: 
 3646: sub removeuserfile {
 3647:     my ($docuname,$docudom,$fname)=@_;
 3648:     my $home=&homeserver($docuname,$docudom);    
 3649:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 3650:     if ($result eq 'ok') {	
 3651:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 3652:             my $metafile = $fname.'.meta';
 3653:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 3654: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 3655:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 3656:             my $sqlresult = 
 3657:                 &update_portfolio_table($docuname,$docudom,$file,
 3658:                                         'portfolio_metadata',$group,
 3659:                                         'delete');
 3660:         }
 3661:     }
 3662:     return $result;
 3663: }
 3664: 
 3665: sub mkdiruserfile {
 3666:     my ($docuname,$docudom,$dir)=@_;
 3667:     my $home=&homeserver($docuname,$docudom);
 3668:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 3669: }
 3670: 
 3671: sub renameuserfile {
 3672:     my ($docuname,$docudom,$old,$new)=@_;
 3673:     my $home=&homeserver($docuname,$docudom);
 3674:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 3675:                         &escape("$old").':'.&escape("$new"),$home);
 3676:     if ($result eq 'ok') {
 3677:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 3678:             my $oldmeta = $old.'.meta';
 3679:             my $newmeta = $new.'.meta';
 3680:             my $metaresult = 
 3681:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 3682: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 3683:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 3684:             my $sqlresult = 
 3685:                 &update_portfolio_table($docuname,$docudom,$file,
 3686:                                         'portfolio_metadata',$group,
 3687:                                         'delete');
 3688:         }
 3689:     }
 3690:     return $result;
 3691: }
 3692: 
 3693: # ------------------------------------------------------------------------- Log
 3694: 
 3695: sub log {
 3696:     my ($dom,$nam,$hom,$what)=@_;
 3697:     return critical("log:$dom:$nam:$what",$hom);
 3698: }
 3699: 
 3700: # ------------------------------------------------------------------ Course Log
 3701: #
 3702: # This routine flushes several buffers of non-mission-critical nature
 3703: #
 3704: 
 3705: sub flushcourselogs {
 3706:     &logthis('Flushing log buffers');
 3707: #
 3708: # course logs
 3709: # This is a log of all transactions in a course, which can be used
 3710: # for data mining purposes
 3711: #
 3712: # It also collects the courseid database, which lists last transaction
 3713: # times and course titles for all courseids
 3714: #
 3715:     my %courseidbuffer=();
 3716:     foreach my $crsid (keys(%courselogs)) {
 3717:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 3718: 		          &escape($courselogs{$crsid}),
 3719: 		          $coursehombuf{$crsid}) eq 'ok') {
 3720: 	    delete $courselogs{$crsid};
 3721:         } else {
 3722:             &logthis('Failed to flush log buffer for '.$crsid);
 3723:             if (length($courselogs{$crsid})>40000) {
 3724:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 3725:                         " exceeded maximum size, deleting.</font>");
 3726:                delete $courselogs{$crsid};
 3727:             }
 3728:         }
 3729:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 3730:             'description' => $coursedescrbuf{$crsid},
 3731:             'inst_code'    => $courseinstcodebuf{$crsid},
 3732:             'type'        => $coursetypebuf{$crsid},
 3733:             'owner'       => $courseownerbuf{$crsid},
 3734:         };
 3735:     }
 3736: #
 3737: # Write course id database (reverse lookup) to homeserver of courses 
 3738: # Is used in pickcourse
 3739: #
 3740:     foreach my $crs_home (keys(%courseidbuffer)) {
 3741:         my $response = &courseidput(&host_domain($crs_home),
 3742:                                     $courseidbuffer{$crs_home},
 3743:                                     $crs_home,'timeonly');
 3744:     }
 3745: #
 3746: # File accesses
 3747: # Writes to the dynamic metadata of resources to get hit counts, etc.
 3748: #
 3749:     foreach my $entry (keys(%accesshash)) {
 3750:         if ($entry =~ /___count$/) {
 3751:             my ($dom,$name);
 3752:             ($dom,$name,undef)=
 3753: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 3754:             if (! defined($dom) || $dom eq '' || 
 3755:                 ! defined($name) || $name eq '') {
 3756:                 my $cid = $env{'request.course.id'};
 3757:                 $dom  = $env{'request.'.$cid.'.domain'};
 3758:                 $name = $env{'request.'.$cid.'.num'};
 3759:             }
 3760:             my $value = $accesshash{$entry};
 3761:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 3762:             my %temphash=($url => $value);
 3763:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 3764:             if ($result eq 'ok') {
 3765:                 delete $accesshash{$entry};
 3766:             }
 3767:         } else {
 3768:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 3769:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 3770:             my %temphash=($entry => $accesshash{$entry});
 3771:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 3772:                 delete $accesshash{$entry};
 3773:             }
 3774:         }
 3775:     }
 3776: #
 3777: # Roles
 3778: # Reverse lookup of user roles for course faculty/staff and co-authorship
 3779: #
 3780:     foreach my $entry (keys(%userrolehash)) {
 3781:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 3782: 	    split(/\:/,$entry);
 3783:         if (&Apache::lonnet::put('nohist_userroles',
 3784:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 3785:                 $rudom,$runame) eq 'ok') {
 3786: 	    delete $userrolehash{$entry};
 3787:         }
 3788:     }
 3789: #
 3790: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 3791: #
 3792:     my %domrolebuffer = ();
 3793:     foreach my $entry (keys(%domainrolehash)) {
 3794:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 3795:         if ($domrolebuffer{$rudom}) {
 3796:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 3797:                       '='.&escape($domainrolehash{$entry});
 3798:         } else {
 3799:             $domrolebuffer{$rudom}.=&escape($entry).
 3800:                       '='.&escape($domainrolehash{$entry});
 3801:         }
 3802:         delete $domainrolehash{$entry};
 3803:     }
 3804:     foreach my $dom (keys(%domrolebuffer)) {
 3805: 	my %servers = &get_servers($dom,'library');
 3806: 	foreach my $tryserver (keys(%servers)) {
 3807: 	    unless (&reply('domroleput:'.$dom.':'.
 3808: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 3809: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 3810: 	    }
 3811:         }
 3812:     }
 3813:     $dumpcount++;
 3814: }
 3815: 
 3816: sub courselog {
 3817:     my $what=shift;
 3818:     $what=time.':'.$what;
 3819:     unless ($env{'request.course.id'}) { return ''; }
 3820:     $coursedombuf{$env{'request.course.id'}}=
 3821:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 3822:     $coursenumbuf{$env{'request.course.id'}}=
 3823:        $env{'course.'.$env{'request.course.id'}.'.num'};
 3824:     $coursehombuf{$env{'request.course.id'}}=
 3825:        $env{'course.'.$env{'request.course.id'}.'.home'};
 3826:     $coursedescrbuf{$env{'request.course.id'}}=
 3827:        $env{'course.'.$env{'request.course.id'}.'.description'};
 3828:     $courseinstcodebuf{$env{'request.course.id'}}=
 3829:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 3830:     $courseownerbuf{$env{'request.course.id'}}=
 3831:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 3832:     $coursetypebuf{$env{'request.course.id'}}=
 3833:        $env{'course.'.$env{'request.course.id'}.'.type'};
 3834:     if (defined $courselogs{$env{'request.course.id'}}) {
 3835: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 3836:     } else {
 3837: 	$courselogs{$env{'request.course.id'}}.=$what;
 3838:     }
 3839:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 3840: 	&flushcourselogs();
 3841:     }
 3842: }
 3843: 
 3844: sub courseacclog {
 3845:     my $fnsymb=shift;
 3846:     unless ($env{'request.course.id'}) { return ''; }
 3847:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 3848:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 3849:         $what.=':POST';
 3850:         # FIXME: Probably ought to escape things....
 3851: 	foreach my $key (keys(%env)) {
 3852:             if ($key=~/^form\.(.*)/) {
 3853:                 my $formitem = $1;
 3854:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 3855:                     $what.=':'.$formitem.'='.$env{$key};
 3856:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 3857:                     $what.=':'.$formitem.'='.$env{$key};
 3858:                 }
 3859:             }
 3860:         }
 3861:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 3862:         # FIXME: We should not be depending on a form parameter that someone
 3863:         # editing lonsearchcat.pm might change in the future.
 3864:         if ($env{'form.phase'} eq 'course_search') {
 3865:             $what.= ':POST';
 3866:             # FIXME: Probably ought to escape things....
 3867:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 3868:                                  'crsdiscuss') {
 3869:                 $what.=':'.$element.'='.$env{'form.'.$element};
 3870:             }
 3871:         }
 3872:     }
 3873:     &courselog($what);
 3874: }
 3875: 
 3876: sub countacc {
 3877:     my $url=&declutter(shift);
 3878:     return if (! defined($url) || $url eq '');
 3879:     unless ($env{'request.course.id'}) { return ''; }
 3880: #
 3881: # Mark that this url was used in this course
 3882: #
 3883:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 3884: #
 3885: # Increase the access count for this resource in this child process
 3886: #
 3887:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 3888:     $accesshash{$key}++;
 3889: }
 3890: 
 3891: sub linklog {
 3892:     my ($from,$to)=@_;
 3893:     $from=&declutter($from);
 3894:     $to=&declutter($to);
 3895:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 3896:     $accesshash{$to.'___'.$from.'___goto'}=1;
 3897: }
 3898: 
 3899: sub statslog {
 3900:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 3901:     if ($users<2) { return; }
 3902:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 3903:             'course'       => $env{'request.course.id'},
 3904:             'sections'     => '"all"',
 3905:             'num_students' => $users,
 3906:             'part'         => $part,
 3907:             'symb'         => $symb,
 3908:             'mean_tries'   => $av_attempts,
 3909:             'deg_of_diff'  => $degdiff});
 3910:     foreach my $key (keys(%dynstore)) {
 3911:         $accesshash{$key}=$dynstore{$key};
 3912:     }
 3913: }
 3914:   
 3915: sub userrolelog {
 3916:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 3917:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 3918:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3919:        $userrolehash
 3920:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3921:                     =$tend.':'.$tstart;
 3922:     }
 3923:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 3924:        $userrolehash
 3925:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 3926:                     =$tend.':'.$tstart;
 3927:     }
 3928:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
 3929:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3930:        $domainrolehash
 3931:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3932:                     = $tend.':'.$tstart;
 3933:     }
 3934: }
 3935: 
 3936: sub courserolelog {
 3937:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 3938:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 3939:         my $cdom = $1;
 3940:         my $cnum = $2;
 3941:         my $sec = $3;
 3942:         my $namespace = 'rolelog';
 3943:         my %storehash = (
 3944:                            role    => $trole,
 3945:                            start   => $tstart,
 3946:                            end     => $tend,
 3947:                            selfenroll => $selfenroll,
 3948:                            context    => $context,
 3949:                         );
 3950:         if ($trole eq 'gr') {
 3951:             $namespace = 'groupslog';
 3952:             $storehash{'group'} = $sec;
 3953:         } else {
 3954:             $storehash{'section'} = $sec;
 3955:         }
 3956:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 3957:                    $domain,$cnum,$cdom);
 3958:         if (($trole ne 'st') || ($sec ne '')) {
 3959:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 3960:         }
 3961:     }
 3962:     return;
 3963: }
 3964: 
 3965: sub domainrolelog {
 3966:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 3967:     if ($area =~ m{^/($match_domain)/$}) {
 3968:         my $cdom = $1;
 3969:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 3970:         my $namespace = 'rolelog';
 3971:         my %storehash = (
 3972:                            role    => $trole,
 3973:                            start   => $tstart,
 3974:                            end     => $tend,
 3975:                            context => $context,
 3976:                         );
 3977:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 3978:                    $domain,$domconfiguser,$cdom);
 3979:     }
 3980:     return;
 3981: 
 3982: }
 3983: 
 3984: sub coauthorrolelog {
 3985:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 3986:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 3987:         my $audom = $1;
 3988:         my $auname = $2;
 3989:         my $namespace = 'rolelog';
 3990:         my %storehash = (
 3991:                            role    => $trole,
 3992:                            start   => $tstart,
 3993:                            end     => $tend,
 3994:                            context => $context,
 3995:                         );
 3996:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 3997:                    $domain,$auname,$audom);
 3998:     }
 3999:     return;
 4000: }
 4001: 
 4002: sub get_course_adv_roles {
 4003:     my ($cid,$codes) = @_;
 4004:     $cid=$env{'request.course.id'} unless (defined($cid));
 4005:     my %coursehash=&coursedescription($cid);
 4006:     my $crstype = &Apache::loncommon::course_type($cid);
 4007:     my %nothide=();
 4008:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4009:         if ($user !~ /:/) {
 4010: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 4011:         } else {
 4012:             $nothide{$user}=1;
 4013:         }
 4014:     }
 4015:     my @possdoms = ($coursehash{'domain'});
 4016:     if ($coursehash{'checkforpriv'}) {
 4017:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 4018:     }
 4019:     my %returnhash=();
 4020:     my %dumphash=
 4021:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 4022:     my $now=time;
 4023:     my %privileged;
 4024:     foreach my $entry (keys(%dumphash)) {
 4025: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4026:         if (($tstart) && ($tstart<0)) { next; }
 4027:         if (($tend) && ($tend<$now)) { next; }
 4028:         if (($tstart) && ($now<$tstart)) { next; }
 4029:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 4030: 	if ($username eq '' || $domain eq '') { next; }
 4031:         if ((&privileged($username,$domain,\@possdoms)) &&
 4032:             (!$nothide{$username.':'.$domain})) { next; }
 4033: 	if ($role eq 'cr') { next; }
 4034:         if ($codes) {
 4035:             if ($section) { $role .= ':'.$section; }
 4036:             if ($returnhash{$role}) {
 4037:                 $returnhash{$role}.=','.$username.':'.$domain;
 4038:             } else {
 4039:                 $returnhash{$role}=$username.':'.$domain;
 4040:             }
 4041:         } else {
 4042:             my $key=&plaintext($role,$crstype);
 4043:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 4044:             if ($returnhash{$key}) {
 4045: 	        $returnhash{$key}.=','.$username.':'.$domain;
 4046:             } else {
 4047:                 $returnhash{$key}=$username.':'.$domain;
 4048:             }
 4049:         }
 4050:     }
 4051:     return %returnhash;
 4052: }
 4053: 
 4054: sub get_my_roles {
 4055:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 4056:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 4057:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 4058:     my (%dumphash,%nothide);
 4059:     if ($context eq 'userroles') {
 4060:         %dumphash = &dump('roles',$udom,$uname);
 4061:     } else {
 4062:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 4063:         if ($hidepriv) {
 4064:             my %coursehash=&coursedescription($udom.'_'.$uname);
 4065:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4066:                 if ($user !~ /:/) {
 4067:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 4068:                 } else {
 4069:                     $nothide{$user} = 1;
 4070:                 }
 4071:             }
 4072:         }
 4073:     }
 4074:     my %returnhash=();
 4075:     my $now=time;
 4076:     my %privileged;
 4077:     foreach my $entry (keys(%dumphash)) {
 4078:         my ($role,$tend,$tstart);
 4079:         if ($context eq 'userroles') {
 4080:             next if ($entry =~ /^rolesdef/);
 4081: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 4082:         } else {
 4083:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4084:         }
 4085:         if (($tstart) && ($tstart<0)) { next; }
 4086:         my $status = 'active';
 4087:         if (($tend) && ($tend<=$now)) {
 4088:             $status = 'previous';
 4089:         } 
 4090:         if (($tstart) && ($now<$tstart)) {
 4091:             $status = 'future';
 4092:         }
 4093:         if (ref($types) eq 'ARRAY') {
 4094:             if (!grep(/^\Q$status\E$/,@{$types})) {
 4095:                 next;
 4096:             } 
 4097:         } else {
 4098:             if ($status ne 'active') {
 4099:                 next;
 4100:             }
 4101:         }
 4102:         my ($rolecode,$username,$domain,$section,$area);
 4103:         if ($context eq 'userroles') {
 4104:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 4105:             (undef,$domain,$username,$section) = split(/\//,$area);
 4106:         } else {
 4107:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 4108:         }
 4109:         if (ref($roledoms) eq 'ARRAY') {
 4110:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 4111:                 next;
 4112:             }
 4113:         }
 4114:         if (ref($roles) eq 'ARRAY') {
 4115:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 4116:                 if ($role =~ /^cr\//) {
 4117:                     if (!grep(/^cr$/,@{$roles})) {
 4118:                         next;
 4119:                     }
 4120:                 } elsif ($role =~ /^gr\//) {
 4121:                     if (!grep(/^gr$/,@{$roles})) {
 4122:                         next;
 4123:                     }
 4124:                 } else {
 4125:                     next;
 4126:                 }
 4127:             }
 4128:         }
 4129:         if ($hidepriv) {
 4130:             my @privroles = ('dc','su');
 4131:             if ($context eq 'userroles') {
 4132:                 next if (grep(/^\Q$role\E$/,@privroles));
 4133:             } else {
 4134:                 my $possdoms = [$domain];
 4135:                 if (ref($roledoms) eq 'ARRAY') {
 4136:                    push(@{$possdoms},@{$roledoms}); 
 4137:                 }
 4138:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 4139:                     if (!$nothide{$username.':'.$domain}) {
 4140:                         next;
 4141:                     }
 4142:                 }
 4143:             }
 4144:         }
 4145:         if ($withsec) {
 4146:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 4147:                 $tstart.':'.$tend;
 4148:         } else {
 4149:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 4150:         }
 4151:     }
 4152:     return %returnhash;
 4153: }
 4154: 
 4155: # ----------------------------------------------------- Frontpage Announcements
 4156: #
 4157: #
 4158: 
 4159: sub postannounce {
 4160:     my ($server,$text)=@_;
 4161:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 4162:     unless ($text=~/\w/) { $text=''; }
 4163:     return &reply('setannounce:'.&escape($text),$server);
 4164: }
 4165: 
 4166: sub getannounce {
 4167: 
 4168:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 4169: 	my $announcement='';
 4170: 	while (my $line = <$fh>) { $announcement .= $line; }
 4171: 	close($fh);
 4172: 	if ($announcement=~/\w/) { 
 4173: 	    return 
 4174:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 4175:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 4176: 	} else {
 4177: 	    return '';
 4178: 	}
 4179:     } else {
 4180: 	return '';
 4181:     }
 4182: }
 4183: 
 4184: # ---------------------------------------------------------- Course ID routines
 4185: # Deal with domain's nohist_courseid.db files
 4186: #
 4187: 
 4188: sub courseidput {
 4189:     my ($domain,$storehash,$coursehome,$caller) = @_;
 4190:     return unless (ref($storehash) eq 'HASH');
 4191:     my $outcome;
 4192:     if ($caller eq 'timeonly') {
 4193:         my $cids = '';
 4194:         foreach my $item (keys(%$storehash)) {
 4195:             $cids.=&escape($item).'&';
 4196:         }
 4197:         $cids=~s/\&$//;
 4198:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 4199:                           $coursehome);       
 4200:     } else {
 4201:         my $items = '';
 4202:         foreach my $item (keys(%$storehash)) {
 4203:             $items.= &escape($item).'='.
 4204:                      &freeze_escape($$storehash{$item}).'&';
 4205:         }
 4206:         $items=~s/\&$//;
 4207:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 4208:                           $coursehome);
 4209:     }
 4210:     if ($outcome eq 'unknown_cmd') {
 4211:         my $what;
 4212:         foreach my $cid (keys(%$storehash)) {
 4213:             $what .= &escape($cid).'=';
 4214:             foreach my $item ('description','inst_code','owner','type') {
 4215:                 $what .= &escape($storehash->{$cid}{$item}).':';
 4216:             }
 4217:             $what =~ s/\:$/&/;
 4218:         }
 4219:         $what =~ s/\&$//;  
 4220:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 4221:     } else {
 4222:         return $outcome;
 4223:     }
 4224: }
 4225: 
 4226: sub courseiddump {
 4227:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 4228:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 4229:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 4230:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 4231:         $hasuniquecode)=@_;
 4232:     my $as_hash = 1;
 4233:     my %returnhash;
 4234:     if (!$domfilter) { $domfilter=''; }
 4235:     my %libserv = &all_library();
 4236:     foreach my $tryserver (keys(%libserv)) {
 4237:         if ( (  $hostidflag == 1 
 4238: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 4239: 	     || (!defined($hostidflag)) ) {
 4240: 
 4241: 	    if (($domfilter eq '') ||
 4242: 		(&host_domain($tryserver) eq $domfilter)) {
 4243:                 my $rep;
 4244:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 4245:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 4246:                         join(":", (&host_domain($tryserver), $sincefilter, 
 4247:                                 &escape($descfilter), &escape($instcodefilter), 
 4248:                                 &escape($ownerfilter), &escape($coursefilter),
 4249:                                 &escape($typefilter), &escape($regexp_ok), 
 4250:                                 $as_hash, &escape($selfenrollonly), 
 4251:                                 &escape($catfilter), $showhidden, $caller, 
 4252:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 4253:                                 &escape($createdbefore), &escape($createdafter), 
 4254:                                 &escape($creationcontext), $domcloner, $hasuniquecode)));
 4255:                 } else {
 4256:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 4257:                              $sincefilter.':'.&escape($descfilter).':'.
 4258:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 4259:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 4260:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 4261:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 4262:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 4263:                              &escape($cc_clone).':'.$cloneonly.':'.
 4264:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 4265:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode,
 4266:                              $tryserver);
 4267:                 }
 4268:                      
 4269:                 my @pairs=split(/\&/,$rep);
 4270:                 foreach my $item (@pairs) {
 4271:                     my ($key,$value)=split(/\=/,$item,2);
 4272:                     $key = &unescape($key);
 4273:                     next if ($key =~ /^error: 2 /);
 4274:                     my $result = &thaw_unescape($value);
 4275:                     if (ref($result) eq 'HASH') {
 4276:                         $returnhash{$key}=$result;
 4277:                     } else {
 4278:                         my @responses = split(/:/,$value);
 4279:                         my @items = ('description','inst_code','owner','type');
 4280:                         for (my $i=0; $i<@responses; $i++) {
 4281:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 4282:                         }
 4283:                     }
 4284:                 }
 4285:             }
 4286:         }
 4287:     }
 4288:     return %returnhash;
 4289: }
 4290: 
 4291: sub courselastaccess {
 4292:     my ($cdom,$cnum,$hostidref) = @_;
 4293:     my %returnhash;
 4294:     if ($cdom && $cnum) {
 4295:         my $chome = &homeserver($cnum,$cdom);
 4296:         if ($chome ne 'no_host') {
 4297:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 4298:             &extract_lastaccess(\%returnhash,$rep);
 4299:         }
 4300:     } else {
 4301:         if (!$cdom) { $cdom=''; }
 4302:         my %libserv = &all_library();
 4303:         foreach my $tryserver (keys(%libserv)) {
 4304:             if (ref($hostidref) eq 'ARRAY') {
 4305:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 4306:             } 
 4307:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 4308:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 4309:                 &extract_lastaccess(\%returnhash,$rep);
 4310:             }
 4311:         }
 4312:     }
 4313:     return %returnhash;
 4314: }
 4315: 
 4316: sub extract_lastaccess {
 4317:     my ($returnhash,$rep) = @_;
 4318:     if (ref($returnhash) eq 'HASH') {
 4319:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 4320:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 4321:                  $rep eq '') {
 4322:             my @pairs=split(/\&/,$rep);
 4323:             foreach my $item (@pairs) {
 4324:                 my ($key,$value)=split(/\=/,$item,2);
 4325:                 $key = &unescape($key);
 4326:                 next if ($key =~ /^error: 2 /);
 4327:                 $returnhash->{$key} = &thaw_unescape($value);
 4328:             }
 4329:         }
 4330:     }
 4331:     return;
 4332: }
 4333: 
 4334: # ---------------------------------------------------------- DC e-mail
 4335: 
 4336: sub dcmailput {
 4337:     my ($domain,$msgid,$message,$server)=@_;
 4338:     my $status = &Apache::lonnet::critical(
 4339:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 4340:        &escape($message),$server);
 4341:     return $status;
 4342: }
 4343: 
 4344: sub dcmaildump {
 4345:     my ($dom,$startdate,$enddate,$senders) = @_;
 4346:     my %returnhash=();
 4347: 
 4348:     if (defined(&domain($dom,'primary'))) {
 4349:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 4350:                                                          &escape($enddate).':';
 4351: 	my @esc_senders=map { &escape($_)} @$senders;
 4352: 	$cmd.=&escape(join('&',@esc_senders));
 4353: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 4354:             my ($key,$value) = split(/\=/,$line,2);
 4355:             if (($key) && ($value)) {
 4356:                 $returnhash{&unescape($key)} = &unescape($value);
 4357:             }
 4358:         }
 4359:     }
 4360:     return %returnhash;
 4361: }
 4362: # ---------------------------------------------------------- Domain roles
 4363: 
 4364: sub get_domain_roles {
 4365:     my ($dom,$roles,$startdate,$enddate)=@_;
 4366:     if ((!defined($startdate)) || ($startdate eq '')) {
 4367:         $startdate = '.';
 4368:     }
 4369:     if ((!defined($enddate)) || ($enddate eq '')) {
 4370:         $enddate = '.';
 4371:     }
 4372:     my $rolelist;
 4373:     if (ref($roles) eq 'ARRAY') {
 4374:         $rolelist = join('&',@{$roles});
 4375:     }
 4376:     my %personnel = ();
 4377: 
 4378:     my %servers = &get_servers($dom,'library');
 4379:     foreach my $tryserver (keys(%servers)) {
 4380: 	%{$personnel{$tryserver}}=();
 4381: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 4382: 					    &escape($startdate).':'.
 4383: 					    &escape($enddate).':'.
 4384: 					    &escape($rolelist), $tryserver))) {
 4385: 	    my ($key,$value) = split(/\=/,$line,2);
 4386: 	    if (($key) && ($value)) {
 4387: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 4388: 	    }
 4389: 	}
 4390:     }
 4391:     return %personnel;
 4392: }
 4393: 
 4394: # ----------------------------------------------------------- Interval timing 
 4395: 
 4396: {
 4397: # Caches needed for speedup of navmaps
 4398: # We don't want to cache this for very long at all (5 seconds at most)
 4399: # 
 4400: # The user for whom we cache
 4401: my $cachedkey='';
 4402: # The cached times for this user
 4403: my %cachedtimes=();
 4404: # When this was last done
 4405: my $cachedtime=();
 4406: 
 4407: sub load_all_first_access {
 4408:     my ($uname,$udom)=@_;
 4409:     if (($cachedkey eq $uname.':'.$udom) &&
 4410:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
 4411:         return;
 4412:     }
 4413:     $cachedtime=time;
 4414:     $cachedkey=$uname.':'.$udom;
 4415:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 4416: }
 4417: 
 4418: sub get_first_access {
 4419:     my ($type,$argsymb,$argmap)=@_;
 4420:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4421:     if ($argsymb) { $symb=$argsymb; }
 4422:     my ($map,$id,$res)=&decode_symb($symb);
 4423:     if ($argmap) { $map = $argmap; }
 4424:     if ($type eq 'course') {
 4425: 	$res='course';
 4426:     } elsif ($type eq 'map') {
 4427: 	$res=&symbread($map);
 4428:     } else {
 4429: 	$res=$symb;
 4430:     }
 4431:     &load_all_first_access($uname,$udom);
 4432:     return $cachedtimes{"$courseid\0$res"};
 4433: }
 4434: 
 4435: sub set_first_access {
 4436:     my ($type,$interval)=@_;
 4437:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4438:     my ($map,$id,$res)=&decode_symb($symb);
 4439:     if ($type eq 'course') {
 4440: 	$res='course';
 4441:     } elsif ($type eq 'map') {
 4442: 	$res=&symbread($map);
 4443:     } else {
 4444: 	$res=$symb;
 4445:     }
 4446:     $cachedkey='';
 4447:     my $firstaccess=&get_first_access($type,$symb,$map);
 4448:     if (!$firstaccess) {
 4449:         my $start = time;
 4450: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 4451:                           $udom,$uname);
 4452:         if ($putres eq 'ok') {
 4453:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 4454:                  $udom,$uname); 
 4455:             &appenv(
 4456:                      {
 4457:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 4458:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 4459:                      }
 4460:                   );
 4461:         }
 4462:         return $putres;
 4463:     }
 4464:     return 'already_set';
 4465: }
 4466: }
 4467: # --------------------------------------------- Set Expire Date for Spreadsheet
 4468: 
 4469: sub expirespread {
 4470:     my ($uname,$udom,$stype,$usymb)=@_;
 4471:     my $cid=$env{'request.course.id'}; 
 4472:     if ($cid) {
 4473:        my $now=time;
 4474:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 4475:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 4476:                             $env{'course.'.$cid.'.num'}.
 4477: 	        	    ':nohist_expirationdates:'.
 4478:                             &escape($key).'='.$now,
 4479:                             $env{'course.'.$cid.'.home'})
 4480:     }
 4481:     return 'ok';
 4482: }
 4483: 
 4484: # ----------------------------------------------------- Devalidate Spreadsheets
 4485: 
 4486: sub devalidate {
 4487:     my ($symb,$uname,$udom)=@_;
 4488:     my $cid=$env{'request.course.id'}; 
 4489:     if ($cid) {
 4490:         # delete the stored spreadsheets for
 4491:         # - the student level sheet of this user in course's homespace
 4492:         # - the assessment level sheet for this resource 
 4493:         #   for this user in user's homespace
 4494: 	# - current conditional state info
 4495: 	my $key=$uname.':'.$udom.':';
 4496:         my $status=
 4497: 	    &del('nohist_calculatedsheets',
 4498: 		 [$key.'studentcalc:'],
 4499: 		 $env{'course.'.$cid.'.domain'},
 4500: 		 $env{'course.'.$cid.'.num'})
 4501: 		.' '.
 4502: 	    &del('nohist_calculatedsheets_'.$cid,
 4503: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 4504:         unless ($status eq 'ok ok') {
 4505:            &logthis('Could not devalidate spreadsheet '.
 4506:                     $uname.' at '.$udom.' for '.
 4507: 		    $symb.': '.$status);
 4508:         }
 4509: 	&delenv('user.state.'.$cid);
 4510:     }
 4511: }
 4512: 
 4513: sub get_scalar {
 4514:     my ($string,$end) = @_;
 4515:     my $value;
 4516:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 4517: 	$value = $1;
 4518:     } elsif ($$string =~ s/^([^&]*?)&//) {
 4519: 	$value = $1;
 4520:     }
 4521:     return &unescape($value);
 4522: }
 4523: 
 4524: sub array2str {
 4525:   my (@array) = @_;
 4526:   my $result=&arrayref2str(\@array);
 4527:   $result=~s/^__ARRAY_REF__//;
 4528:   $result=~s/__END_ARRAY_REF__$//;
 4529:   return $result;
 4530: }
 4531: 
 4532: sub arrayref2str {
 4533:   my ($arrayref) = @_;
 4534:   my $result='__ARRAY_REF__';
 4535:   foreach my $elem (@$arrayref) {
 4536:     if(ref($elem) eq 'ARRAY') {
 4537:       $result.=&arrayref2str($elem).'&';
 4538:     } elsif(ref($elem) eq 'HASH') {
 4539:       $result.=&hashref2str($elem).'&';
 4540:     } elsif(ref($elem)) {
 4541:       #print("Got a ref of ".(ref($elem))." skipping.");
 4542:     } else {
 4543:       $result.=&escape($elem).'&';
 4544:     }
 4545:   }
 4546:   $result=~s/\&$//;
 4547:   $result .= '__END_ARRAY_REF__';
 4548:   return $result;
 4549: }
 4550: 
 4551: sub hash2str {
 4552:   my (%hash) = @_;
 4553:   my $result=&hashref2str(\%hash);
 4554:   $result=~s/^__HASH_REF__//;
 4555:   $result=~s/__END_HASH_REF__$//;
 4556:   return $result;
 4557: }
 4558: 
 4559: sub hashref2str {
 4560:   my ($hashref)=@_;
 4561:   my $result='__HASH_REF__';
 4562:   foreach my $key (sort(keys(%$hashref))) {
 4563:     if (ref($key) eq 'ARRAY') {
 4564:       $result.=&arrayref2str($key).'=';
 4565:     } elsif (ref($key) eq 'HASH') {
 4566:       $result.=&hashref2str($key).'=';
 4567:     } elsif (ref($key)) {
 4568:       $result.='=';
 4569:       #print("Got a ref of ".(ref($key))." skipping.");
 4570:     } else {
 4571: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 4572:     }
 4573: 
 4574:     if(ref($hashref->{$key}) eq 'ARRAY') {
 4575:       $result.=&arrayref2str($hashref->{$key}).'&';
 4576:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 4577:       $result.=&hashref2str($hashref->{$key}).'&';
 4578:     } elsif(ref($hashref->{$key})) {
 4579:        $result.='&';
 4580:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 4581:     } else {
 4582:       $result.=&escape($hashref->{$key}).'&';
 4583:     }
 4584:   }
 4585:   $result=~s/\&$//;
 4586:   $result .= '__END_HASH_REF__';
 4587:   return $result;
 4588: }
 4589: 
 4590: sub str2hash {
 4591:     my ($string)=@_;
 4592:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 4593:     return %$hash;
 4594: }
 4595: 
 4596: sub str2hashref {
 4597:   my ($string) = @_;
 4598: 
 4599:   my %hash;
 4600: 
 4601:   if($string !~ /^__HASH_REF__/) {
 4602:       if (! ($string eq '' || !defined($string))) {
 4603: 	  $hash{'error'}='Not hash reference';
 4604:       }
 4605:       return (\%hash, $string);
 4606:   }
 4607: 
 4608:   $string =~ s/^__HASH_REF__//;
 4609: 
 4610:   while($string !~ /^__END_HASH_REF__/) {
 4611:       #key
 4612:       my $key='';
 4613:       if($string =~ /^__HASH_REF__/) {
 4614:           ($key, $string)=&str2hashref($string);
 4615:           if(defined($key->{'error'})) {
 4616:               $hash{'error'}='Bad data';
 4617:               return (\%hash, $string);
 4618:           }
 4619:       } elsif($string =~ /^__ARRAY_REF__/) {
 4620:           ($key, $string)=&str2arrayref($string);
 4621:           if($key->[0] eq 'Array reference error') {
 4622:               $hash{'error'}='Bad data';
 4623:               return (\%hash, $string);
 4624:           }
 4625:       } else {
 4626:           $string =~ s/^(.*?)=//;
 4627: 	  $key=&unescape($1);
 4628:       }
 4629:       $string =~ s/^=//;
 4630: 
 4631:       #value
 4632:       my $value='';
 4633:       if($string =~ /^__HASH_REF__/) {
 4634:           ($value, $string)=&str2hashref($string);
 4635:           if(defined($value->{'error'})) {
 4636:               $hash{'error'}='Bad data';
 4637:               return (\%hash, $string);
 4638:           }
 4639:       } elsif($string =~ /^__ARRAY_REF__/) {
 4640:           ($value, $string)=&str2arrayref($string);
 4641:           if($value->[0] eq 'Array reference error') {
 4642:               $hash{'error'}='Bad data';
 4643:               return (\%hash, $string);
 4644:           }
 4645:       } else {
 4646: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 4647:       }
 4648:       $string =~ s/^&//;
 4649: 
 4650:       $hash{$key}=$value;
 4651:   }
 4652: 
 4653:   $string =~ s/^__END_HASH_REF__//;
 4654: 
 4655:   return (\%hash, $string);
 4656: }
 4657: 
 4658: sub str2array {
 4659:     my ($string)=@_;
 4660:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 4661:     return @$array;
 4662: }
 4663: 
 4664: sub str2arrayref {
 4665:   my ($string) = @_;
 4666:   my @array;
 4667: 
 4668:   if($string !~ /^__ARRAY_REF__/) {
 4669:       if (! ($string eq '' || !defined($string))) {
 4670: 	  $array[0]='Array reference error';
 4671:       }
 4672:       return (\@array, $string);
 4673:   }
 4674: 
 4675:   $string =~ s/^__ARRAY_REF__//;
 4676: 
 4677:   while($string !~ /^__END_ARRAY_REF__/) {
 4678:       my $value='';
 4679:       if($string =~ /^__HASH_REF__/) {
 4680:           ($value, $string)=&str2hashref($string);
 4681:           if(defined($value->{'error'})) {
 4682:               $array[0] ='Array reference error';
 4683:               return (\@array, $string);
 4684:           }
 4685:       } elsif($string =~ /^__ARRAY_REF__/) {
 4686:           ($value, $string)=&str2arrayref($string);
 4687:           if($value->[0] eq 'Array reference error') {
 4688:               $array[0] ='Array reference error';
 4689:               return (\@array, $string);
 4690:           }
 4691:       } else {
 4692: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 4693:       }
 4694:       $string =~ s/^&//;
 4695: 
 4696:       push(@array, $value);
 4697:   }
 4698: 
 4699:   $string =~ s/^__END_ARRAY_REF__//;
 4700: 
 4701:   return (\@array, $string);
 4702: }
 4703: 
 4704: # -------------------------------------------------------------------Temp Store
 4705: 
 4706: sub tmpreset {
 4707:   my ($symb,$namespace,$domain,$stuname) = @_;
 4708:   if (!$symb) {
 4709:     $symb=&symbread();
 4710:     if (!$symb) { $symb= $env{'request.url'}; }
 4711:   }
 4712:   $symb=escape($symb);
 4713: 
 4714:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4715:   $namespace=~s/\//\_/g;
 4716:   $namespace=~s/\W//g;
 4717: 
 4718:   if (!$domain) { $domain=$env{'user.domain'}; }
 4719:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4720:   if ($domain eq 'public' && $stuname eq 'public') {
 4721:       $stuname=$ENV{'REMOTE_ADDR'};
 4722:   }
 4723:   my $path=LONCAPA::tempdir();
 4724:   my %hash;
 4725:   if (tie(%hash,'GDBM_File',
 4726: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4727: 	  &GDBM_WRCREAT(),0640)) {
 4728:     foreach my $key (keys(%hash)) {
 4729:       if ($key=~ /:$symb/) {
 4730: 	delete($hash{$key});
 4731:       }
 4732:     }
 4733:   }
 4734: }
 4735: 
 4736: sub tmpstore {
 4737:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4738: 
 4739:   if (!$symb) {
 4740:     $symb=&symbread();
 4741:     if (!$symb) { $symb= $env{'request.url'}; }
 4742:   }
 4743:   $symb=escape($symb);
 4744: 
 4745:   if (!$namespace) {
 4746:     # I don't think we would ever want to store this for a course.
 4747:     # it seems this will only be used if we don't have a course.
 4748:     #$namespace=$env{'request.course.id'};
 4749:     #if (!$namespace) {
 4750:       $namespace=$env{'request.state'};
 4751:     #}
 4752:   }
 4753:   $namespace=~s/\//\_/g;
 4754:   $namespace=~s/\W//g;
 4755:   if (!$domain) { $domain=$env{'user.domain'}; }
 4756:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4757:   if ($domain eq 'public' && $stuname eq 'public') {
 4758:       $stuname=$ENV{'REMOTE_ADDR'};
 4759:   }
 4760:   my $now=time;
 4761:   my %hash;
 4762:   my $path=LONCAPA::tempdir();
 4763:   if (tie(%hash,'GDBM_File',
 4764: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4765: 	  &GDBM_WRCREAT(),0640)) {
 4766:     $hash{"version:$symb"}++;
 4767:     my $version=$hash{"version:$symb"};
 4768:     my $allkeys=''; 
 4769:     foreach my $key (keys(%$storehash)) {
 4770:       $allkeys.=$key.':';
 4771:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 4772:     }
 4773:     $hash{"$version:$symb:timestamp"}=$now;
 4774:     $allkeys.='timestamp';
 4775:     $hash{"$version:keys:$symb"}=$allkeys;
 4776:     if (untie(%hash)) {
 4777:       return 'ok';
 4778:     } else {
 4779:       return "error:$!";
 4780:     }
 4781:   } else {
 4782:     return "error:$!";
 4783:   }
 4784: }
 4785: 
 4786: # -----------------------------------------------------------------Temp Restore
 4787: 
 4788: sub tmprestore {
 4789:   my ($symb,$namespace,$domain,$stuname) = @_;
 4790: 
 4791:   if (!$symb) {
 4792:     $symb=&symbread();
 4793:     if (!$symb) { $symb= $env{'request.url'}; }
 4794:   }
 4795:   $symb=escape($symb);
 4796: 
 4797:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4798: 
 4799:   if (!$domain) { $domain=$env{'user.domain'}; }
 4800:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4801:   if ($domain eq 'public' && $stuname eq 'public') {
 4802:       $stuname=$ENV{'REMOTE_ADDR'};
 4803:   }
 4804:   my %returnhash;
 4805:   $namespace=~s/\//\_/g;
 4806:   $namespace=~s/\W//g;
 4807:   my %hash;
 4808:   my $path=LONCAPA::tempdir();
 4809:   if (tie(%hash,'GDBM_File',
 4810: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4811: 	  &GDBM_READER(),0640)) {
 4812:     my $version=$hash{"version:$symb"};
 4813:     $returnhash{'version'}=$version;
 4814:     my $scope;
 4815:     for ($scope=1;$scope<=$version;$scope++) {
 4816:       my $vkeys=$hash{"$scope:keys:$symb"};
 4817:       my @keys=split(/:/,$vkeys);
 4818:       my $key;
 4819:       $returnhash{"$scope:keys"}=$vkeys;
 4820:       foreach $key (@keys) {
 4821: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4822: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4823:       }
 4824:     }
 4825:     if (!(untie(%hash))) {
 4826:       return "error:$!";
 4827:     }
 4828:   } else {
 4829:     return "error:$!";
 4830:   }
 4831:   return %returnhash;
 4832: }
 4833: 
 4834: # ----------------------------------------------------------------------- Store
 4835: 
 4836: sub store {
 4837:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4838:     my $home='';
 4839: 
 4840:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4841: 
 4842:     $symb=&symbclean($symb);
 4843:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4844: 
 4845:     if (!$domain) { $domain=$env{'user.domain'}; }
 4846:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4847: 
 4848:     &devalidate($symb,$stuname,$domain);
 4849: 
 4850:     $symb=escape($symb);
 4851:     if (!$namespace) { 
 4852:        unless ($namespace=$env{'request.course.id'}) { 
 4853:           return ''; 
 4854:        } 
 4855:     }
 4856:     if (!$home) { $home=$env{'user.home'}; }
 4857: 
 4858:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4859:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4860: 
 4861:     my $namevalue='';
 4862:     foreach my $key (keys(%$storehash)) {
 4863:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4864:     }
 4865:     $namevalue=~s/\&$//;
 4866:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 4867:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4868: }
 4869: 
 4870: # -------------------------------------------------------------- Critical Store
 4871: 
 4872: sub cstore {
 4873:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4874:     my $home='';
 4875: 
 4876:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4877: 
 4878:     $symb=&symbclean($symb);
 4879:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4880: 
 4881:     if (!$domain) { $domain=$env{'user.domain'}; }
 4882:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4883: 
 4884:     &devalidate($symb,$stuname,$domain);
 4885: 
 4886:     $symb=escape($symb);
 4887:     if (!$namespace) { 
 4888:        unless ($namespace=$env{'request.course.id'}) { 
 4889:           return ''; 
 4890:        } 
 4891:     }
 4892:     if (!$home) { $home=$env{'user.home'}; }
 4893: 
 4894:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4895:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4896: 
 4897:     my $namevalue='';
 4898:     foreach my $key (keys(%$storehash)) {
 4899:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4900:     }
 4901:     $namevalue=~s/\&$//;
 4902:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 4903:     return critical
 4904:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4905: }
 4906: 
 4907: # --------------------------------------------------------------------- Restore
 4908: 
 4909: sub restore {
 4910:     my ($symb,$namespace,$domain,$stuname) = @_;
 4911:     my $home='';
 4912: 
 4913:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4914: 
 4915:     if (!$symb) {
 4916:         return if ($namespace eq 'courserequests');
 4917:         unless ($symb=escape(&symbread())) { return ''; }
 4918:     } else {
 4919:         unless ($namespace eq 'courserequests') {
 4920:             $symb=&escape(&symbclean($symb));
 4921:         }
 4922:     }
 4923:     if (!$namespace) { 
 4924:        unless ($namespace=$env{'request.course.id'}) { 
 4925:           return ''; 
 4926:        } 
 4927:     }
 4928:     if (!$domain) { $domain=$env{'user.domain'}; }
 4929:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4930:     if (!$home) { $home=$env{'user.home'}; }
 4931:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 4932: 
 4933:     my %returnhash=();
 4934:     foreach my $line (split(/\&/,$answer)) {
 4935: 	my ($name,$value)=split(/\=/,$line);
 4936:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 4937:     }
 4938:     my $version;
 4939:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 4940:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 4941:           $returnhash{$item}=$returnhash{$version.':'.$item};
 4942:        }
 4943:     }
 4944:     return %returnhash;
 4945: }
 4946: 
 4947: # ---------------------------------------------------------- Course Description
 4948: #
 4949: #  
 4950: 
 4951: sub coursedescription {
 4952:     my ($courseid,$args)=@_;
 4953:     $courseid=~s/^\///;
 4954:     $courseid=~s/\_/\//g;
 4955:     my ($cdomain,$cnum)=split(/\//,$courseid);
 4956:     my $chome=&homeserver($cnum,$cdomain);
 4957:     my $normalid=$cdomain.'_'.$cnum;
 4958:     # need to always cache even if we get errors otherwise we keep 
 4959:     # trying and trying and trying to get the course description.
 4960:     my %envhash=();
 4961:     my %returnhash=();
 4962:     
 4963:     my $expiretime=600;
 4964:     if ($env{'request.course.id'} eq $normalid) {
 4965: 	$expiretime=120;
 4966:     }
 4967: 
 4968:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 4969:     if (!$args->{'freshen_cache'}
 4970: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 4971: 	foreach my $key (keys(%env)) {
 4972: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 4973: 	    my ($setting) = $1;
 4974: 	    $returnhash{$setting} = $env{$key};
 4975: 	}
 4976: 	return %returnhash;
 4977:     }
 4978: 
 4979:     # get the data again
 4980: 
 4981:     if (!$args->{'one_time'}) {
 4982: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 4983:     }
 4984: 
 4985:     if ($chome ne 'no_host') {
 4986:        %returnhash=&dump('environment',$cdomain,$cnum);
 4987:        if (!exists($returnhash{'con_lost'})) {
 4988: 	   my $username = $env{'user.name'}; # Defult username
 4989: 	   if(defined $args->{'user'}) {
 4990: 	       $username = $args->{'user'};
 4991: 	   }
 4992:            $returnhash{'home'}= $chome;
 4993: 	   $returnhash{'domain'} = $cdomain;
 4994: 	   $returnhash{'num'} = $cnum;
 4995:            if (!defined($returnhash{'type'})) {
 4996:                $returnhash{'type'} = 'Course';
 4997:            }
 4998:            while (my ($name,$value) = each %returnhash) {
 4999:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 5000:            }
 5001:            $returnhash{'url'}=&clutter($returnhash{'url'});
 5002:            $returnhash{'fn'}=LONCAPA::tempdir() .
 5003: 	       $username.'_'.$cdomain.'_'.$cnum;
 5004:            $envhash{'course.'.$normalid.'.home'}=$chome;
 5005:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 5006:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 5007:        }
 5008:     }
 5009:     if (!$args->{'one_time'}) {
 5010: 	&appenv(\%envhash);
 5011:     }
 5012:     return %returnhash;
 5013: }
 5014: 
 5015: sub update_released_required {
 5016:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 5017:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 5018:         $cid = $env{'request.course.id'};
 5019:         $cdom = $env{'course.'.$cid.'.domain'};
 5020:         $cnum = $env{'course.'.$cid.'.num'};
 5021:         $chome = $env{'course.'.$cid.'.home'};
 5022:     }
 5023:     if ($needsrelease) {
 5024:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 5025:         my $needsupdate;
 5026:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 5027:             $needsupdate = 1;
 5028:         } else {
 5029:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 5030:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 5031:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 5032:                 $needsupdate = 1;
 5033:             }
 5034:         }
 5035:         if ($needsupdate) {
 5036:             my %needshash = (
 5037:                              'internal.releaserequired' => $needsrelease,
 5038:                             );
 5039:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 5040:             if ($putresult eq 'ok') {
 5041:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 5042:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 5043:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 5044:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 5045:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 5046:                 }
 5047:             }
 5048:         }
 5049:     }
 5050:     return;
 5051: }
 5052: 
 5053: # -------------------------------------------------See if a user is privileged
 5054: 
 5055: sub privileged {
 5056:     my ($username,$domain,$possdomains,$possroles)=@_;
 5057:     my $now = time;
 5058:     my $roles;
 5059:     if (ref($possroles) eq 'ARRAY') {
 5060:         $roles = $possroles; 
 5061:     } else {
 5062:         $roles = ['dc','su'];
 5063:     }
 5064:     if (ref($possdomains) eq 'ARRAY') {
 5065:         my %privileged = &privileged_by_domain($possdomains,$roles);
 5066:         foreach my $dom (@{$possdomains}) {
 5067:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 5068:                 (ref($privileged{$dom}) eq 'HASH')) {
 5069:                 foreach my $role (@{$roles}) {
 5070:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5071:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 5072:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 5073:                             return 1 unless (($end && $end < $now) ||
 5074:                                              ($start && $start > $now));
 5075:                         }
 5076:                     }
 5077:                 }
 5078:             }
 5079:         }
 5080:     } else {
 5081:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 5082:         my $now = time;
 5083: 
 5084:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
 5085:             my ($trole, $tend, $tstart) = split(/_/, $role);
 5086:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 5087:                 return 1 unless ($tend && $tend < $now) 
 5088:                         or ($tstart && $tstart > $now);
 5089:             }
 5090:         }
 5091:     }
 5092:     return 0;
 5093: }
 5094: 
 5095: sub privileged_by_domain {
 5096:     my ($domains,$roles) = @_;
 5097:     my %privileged = ();
 5098:     my $cachetime = 60*60*24;
 5099:     my $now = time;
 5100:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 5101:         return %privileged;
 5102:     }
 5103:     foreach my $dom (@{$domains}) {
 5104:         next if (ref($privileged{$dom}) eq 'HASH');
 5105:         my $needroles;
 5106:         foreach my $role (@{$roles}) {
 5107:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 5108:             if (defined($cached)) {
 5109:                 if (ref($result) eq 'HASH') {
 5110:                     $privileged{$dom}{$role} = $result;
 5111:                 }
 5112:             } else {
 5113:                 $needroles = 1;
 5114:             }
 5115:         }
 5116:         if ($needroles) {
 5117:             my %dompersonnel = &get_domain_roles($dom,$roles);
 5118:             $privileged{$dom} = {};
 5119:             foreach my $server (keys(%dompersonnel)) {
 5120:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 5121:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 5122:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 5123:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 5124:                         next if ($end && $end < $now);
 5125:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 5126:                             $dompersonnel{$server}{$item};
 5127:                     }
 5128:                 }
 5129:             }
 5130:             if (ref($privileged{$dom}) eq 'HASH') {
 5131:                 foreach my $role (@{$roles}) {
 5132:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5133:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 5134:                     } else {
 5135:                         my %hash = ();
 5136:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 5137:                     }
 5138:                 }
 5139:             }
 5140:         }
 5141:     }
 5142:     return %privileged;
 5143: }
 5144: 
 5145: # -------------------------------------------------------- Get user privileges
 5146: 
 5147: sub rolesinit {
 5148:     my ($domain, $username) = @_;
 5149:     my %userroles = ('user.login.time' => time);
 5150:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 5151: 
 5152:     # firstaccess and timerinterval are related to timed maps/resources. 
 5153:     # also, blocking can be triggered by an activating timer
 5154:     # it's saved in the user's %env.
 5155:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 5156:     my %timerinterval = &dump('timerinterval', $domain, $username);
 5157:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 5158:         %timerintchk, %timerintenv);
 5159: 
 5160:     foreach my $key (keys(%firstaccess)) {
 5161:         my ($cid, $rest) = split(/\0/, $key);
 5162:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 5163:     }
 5164: 
 5165:     foreach my $key (keys(%timerinterval)) {
 5166:         my ($cid,$rest) = split(/\0/,$key);
 5167:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 5168:     }
 5169: 
 5170:     my %allroles=();
 5171:     my %allgroups=();
 5172: 
 5173:     for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
 5174:         my $role = $rolesdump{$area};
 5175:         $area =~ s/\_\w\w$//;
 5176: 
 5177:         my ($trole, $tend, $tstart, $group_privs);
 5178: 
 5179:         if ($role =~ /^cr/) {
 5180:         # Custom role, defined by a user 
 5181:         # e.g., user.role.cr/msu/smith/mynewrole
 5182:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 5183:                 $trole = $1;
 5184:                 ($tend, $tstart) = split('_', $2);
 5185:             } else {
 5186:                 $trole = $role;
 5187:             }
 5188:         } elsif ($role =~ m|^gr/|) {
 5189:         # Role of member in a group, defined within a course/community
 5190:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 5191:             ($trole, $tend, $tstart) = split(/_/, $role);
 5192:             next if $tstart eq '-1';
 5193:             ($trole, $group_privs) = split(/\//, $trole);
 5194:             $group_privs = &unescape($group_privs);
 5195:         } else {
 5196:         # Just a normal role, defined in roles.tab
 5197:             ($trole, $tend, $tstart) = split(/_/,$role);
 5198:         }
 5199: 
 5200:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 5201:                  $username);
 5202:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 5203: 
 5204:         # role expired or not available yet?
 5205:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 5206:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 5207: 
 5208:         next if $area eq '' or $trole eq '';
 5209: 
 5210:         my $spec = "$trole.$area";
 5211:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 5212: 
 5213:         if ($trole =~ /^cr\//) {
 5214:         # Custom role, defined by a user
 5215:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 5216:         } elsif ($trole eq 'gr') {
 5217:         # Role of a member in a group, defined within a course/community
 5218:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 5219:             next;
 5220:         } else {
 5221:         # Normal role, defined in roles.tab
 5222:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 5223:         }
 5224: 
 5225:         my $cid = $tdomain.'_'.$trest;
 5226:         unless ($firstaccchk{$cid}) {
 5227:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 5228:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 5229:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 5230:                         $coursetimerstarts{$cid}{$item}; 
 5231:                 }
 5232:             }
 5233:             $firstaccchk{$cid} = 1;
 5234:         }
 5235:         unless ($timerintchk{$cid}) {
 5236:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 5237:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 5238:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 5239:                        $coursetimerintervals{$cid}{$item};
 5240:                 }
 5241:             }
 5242:             $timerintchk{$cid} = 1;
 5243:         }
 5244:     }
 5245: 
 5246:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
 5247:         \%allroles, \%allgroups);
 5248:     $env{'user.adv'} = $userroles{'user.adv'};
 5249: 
 5250:     return (\%userroles,\%firstaccenv,\%timerintenv);
 5251: }
 5252: 
 5253: sub set_arearole {
 5254:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 5255:     unless ($nolog) {
 5256: # log the associated role with the area
 5257:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 5258:     }
 5259:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 5260: }
 5261: 
 5262: sub custom_roleprivs {
 5263:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 5264:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 5265:     my $homsvr = &homeserver($rauthor,$rdomain);
 5266:     if (&hostname($homsvr) ne '') {
 5267:         my ($rdummy,$roledef)=
 5268:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 5269:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 5270:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 5271:             if (defined($syspriv)) {
 5272:                 if ($trest =~ /^$match_community$/) {
 5273:                     $syspriv =~ s/bre\&S//; 
 5274:                 }
 5275:                 $$allroles{'cm./'}.=':'.$syspriv;
 5276:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 5277:             }
 5278:             if ($tdomain ne '') {
 5279:                 if (defined($dompriv)) {
 5280:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 5281:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 5282:                 }
 5283:                 if (($trest ne '') && (defined($coursepriv))) {
 5284:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 5285:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 5286:                 }
 5287:             }
 5288:         }
 5289:     }
 5290: }
 5291: 
 5292: sub group_roleprivs {
 5293:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 5294:     my $access = 1;
 5295:     my $now = time;
 5296:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 5297:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 5298:     if ($access) {
 5299:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 5300:         $$allgroups{$course}{$group} .=':'.$group_privs;
 5301:     }
 5302: }
 5303: 
 5304: sub standard_roleprivs {
 5305:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 5306:     if (defined($pr{$trole.':s'})) {
 5307:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 5308:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 5309:     }
 5310:     if ($tdomain ne '') {
 5311:         if (defined($pr{$trole.':d'})) {
 5312:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 5313:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 5314:         }
 5315:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 5316:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 5317:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 5318:         }
 5319:     }
 5320: }
 5321: 
 5322: sub set_userprivs {
 5323:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 5324:     my $author=0;
 5325:     my $adv=0;
 5326:     my %grouproles = ();
 5327:     if (keys(%{$allgroups}) > 0) {
 5328:         my @groupkeys; 
 5329:         foreach my $role (keys(%{$allroles})) {
 5330:             push(@groupkeys,$role);
 5331:         }
 5332:         if (ref($groups_roles) eq 'HASH') {
 5333:             foreach my $key (keys(%{$groups_roles})) {
 5334:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 5335:                     push(@groupkeys,$key);
 5336:                 }
 5337:             }
 5338:         }
 5339:         if (@groupkeys > 0) {
 5340:             foreach my $role (@groupkeys) {
 5341:                 my ($trole,$area,$sec,$extendedarea);
 5342:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 5343:                     $trole = $1;
 5344:                     $area = $2;
 5345:                     $sec = $3;
 5346:                     $extendedarea = $area.$sec;
 5347:                     if (exists($$allgroups{$area})) {
 5348:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 5349:                             my $spec = $trole.'.'.$extendedarea;
 5350:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 5351:                                                 $$allgroups{$area}{$group};
 5352:                         }
 5353:                     }
 5354:                 }
 5355:             }
 5356:         }
 5357:     }
 5358:     foreach my $group (keys(%grouproles)) {
 5359:         $$allroles{$group} = $grouproles{$group};
 5360:     }
 5361:     foreach my $role (keys(%{$allroles})) {
 5362:         my %thesepriv;
 5363:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 5364:         foreach my $item (split(/:/,$$allroles{$role})) {
 5365:             if ($item ne '') {
 5366:                 my ($privilege,$restrictions)=split(/&/,$item);
 5367:                 if ($restrictions eq '') {
 5368:                     $thesepriv{$privilege}='F';
 5369:                 } elsif ($thesepriv{$privilege} ne 'F') {
 5370:                     $thesepriv{$privilege}.=$restrictions;
 5371:                 }
 5372:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 5373:             }
 5374:         }
 5375:         my $thesestr='';
 5376:         foreach my $priv (sort(keys(%thesepriv))) {
 5377: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 5378: 	}
 5379:         $userroles->{'user.priv.'.$role} = $thesestr;
 5380:     }
 5381:     return ($author,$adv);
 5382: }
 5383: 
 5384: sub role_status {
 5385:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 5386:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 5387:         my ($one,$two) = split(m{\./},$rolekey,2);
 5388:         (undef,undef,$$role) = split(/\./,$one,3);
 5389:         unless (!defined($$role) || $$role eq '') {
 5390:             $$where = '/'.$two;
 5391:             $$trolecode=$$role.'.'.$$where;
 5392:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 5393:             $$tstatus='is';
 5394:             if ($$tstart && $$tstart>$update) {
 5395:                 $$tstatus='future';
 5396:                 if ($$tstart<$now) {
 5397:                     if ($$tstart && $$tstart>$refresh) {
 5398:                         if (($$where ne '') && ($$role ne '')) {
 5399:                             my (%allroles,%allgroups,$group_privs,
 5400:                                 %groups_roles,@rolecodes);
 5401:                             my %userroles = (
 5402:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 5403:                             );
 5404:                             @rolecodes = ('cm'); 
 5405:                             my $spec=$$role.'.'.$$where;
 5406:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 5407:                             if ($$role =~ /^cr\//) {
 5408:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 5409:                                 push(@rolecodes,'cr');
 5410:                             } elsif ($$role eq 'gr') {
 5411:                                 push(@rolecodes,$$role);
 5412:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 5413:                                                     $env{'user.name'});
 5414:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 5415:                                 (undef,my $group_privs) = split(/\//,$trole);
 5416:                                 $group_privs = &unescape($group_privs);
 5417:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 5418:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 5419:                                 &get_groups_roles($tdomain,$trest,
 5420:                                                   \%course_roles,\@rolecodes,
 5421:                                                   \%groups_roles);
 5422:                             } else {
 5423:                                 push(@rolecodes,$$role);
 5424:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 5425:                             }
 5426:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
 5427:                             &appenv(\%userroles,\@rolecodes);
 5428:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5429:                         }
 5430:                     }
 5431:                     $$tstatus = 'is';
 5432:                 }
 5433:             }
 5434:             if ($$tend) {
 5435:                 if ($$tend<$update) {
 5436:                     $$tstatus='expired';
 5437:                 } elsif ($$tend<$now) {
 5438:                     $$tstatus='will_not';
 5439:                 }
 5440:             }
 5441:         }
 5442:     }
 5443: }
 5444: 
 5445: sub get_groups_roles {
 5446:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 5447:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 5448:                   (ref($rolecodes) eq 'ARRAY') && 
 5449:                   (ref($groups_roles) eq 'HASH')); 
 5450:     if (keys(%{$cdom_courseroles}) > 0) {
 5451:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 5452:         if ($cdom ne '' && $cnum ne '') {
 5453:             foreach my $key (keys(%{$cdom_courseroles})) {
 5454:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 5455:                     my $crsrole = $1;
 5456:                     my $crssec = $2;
 5457:                     if ($crsrole =~ /^cr/) {
 5458:                         unless (grep(/^cr$/,@{$rolecodes})) {
 5459:                             push(@{$rolecodes},'cr');
 5460:                         }
 5461:                     } else {
 5462:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 5463:                             push(@{$rolecodes},$crsrole);
 5464:                         }
 5465:                     }
 5466:                     my $rolekey = "$crsrole./$cdom/$cnum";
 5467:                     if ($crssec ne '') {
 5468:                         $rolekey .= "/$crssec";
 5469:                     }
 5470:                     $rolekey .= './';
 5471:                     $groups_roles->{$rolekey} = $rolecodes;
 5472:                 }
 5473:             }
 5474:         }
 5475:     }
 5476:     return;
 5477: }
 5478: 
 5479: sub delete_env_groupprivs {
 5480:     my ($where,$courseroles,$possroles) = @_;
 5481:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 5482:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 5483:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 5484:         %{$courseroles->{$udom}} =
 5485:             &get_my_roles('','','userroles',['active'],
 5486:                           $possroles,[$udom],1);
 5487:     }
 5488:     if (ref($courseroles->{$udom}) eq 'HASH') {
 5489:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 5490:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 5491:             my $area = '/'.$cdom.'/'.$cnum;
 5492:             my $privkey = "user.priv.$crsrole.$area";
 5493:             if ($crssec ne '') {
 5494:                 $privkey .= '/'.$crssec;
 5495:             }
 5496:             $privkey .= ".$area/$group";
 5497:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 5498:         }
 5499:     }
 5500:     return;
 5501: }
 5502: 
 5503: sub check_adhoc_privs {
 5504:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
 5505:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 5506:     my $setprivs;
 5507:     if ($env{$cckey}) {
 5508:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 5509:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 5510:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 5511:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5512:             $setprivs = 1;
 5513:         }
 5514:     } else {
 5515:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5516:         $setprivs = 1;
 5517:     }
 5518:     return $setprivs;
 5519: }
 5520: 
 5521: sub set_adhoc_privileges {
 5522: # role can be cc or ca
 5523:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
 5524:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 5525:     my $spec = $role.'.'.$area;
 5526:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 5527:                                   $env{'user.name'},1);
 5528:     my %ccrole = ();
 5529:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
 5530:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
 5531:     &appenv(\%userroles,[$role,'cm']);
 5532:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5533:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 5534:         &appenv( {'request.role'        => $spec,
 5535:                   'request.role.domain' => $dcdom,
 5536:                   'request.course.sec'  => ''
 5537:                  }
 5538:                );
 5539:         my $tadv=0;
 5540:         if (&allowed('adv') eq 'F') { $tadv=1; }
 5541:         &appenv({'request.role.adv'    => $tadv});
 5542:     }
 5543: }
 5544: 
 5545: # --------------------------------------------------------------- get interface
 5546: 
 5547: sub get {
 5548:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5549:    my $items='';
 5550:    foreach my $item (@$storearr) {
 5551:        $items.=&escape($item).'&';
 5552:    }
 5553:    $items=~s/\&$//;
 5554:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5555:    if (!$uname) { $uname=$env{'user.name'}; }
 5556:    my $uhome=&homeserver($uname,$udomain);
 5557: 
 5558:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 5559:    my @pairs=split(/\&/,$rep);
 5560:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 5561:      return @pairs;
 5562:    }
 5563:    my %returnhash=();
 5564:    my $i=0;
 5565:    foreach my $item (@$storearr) {
 5566:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5567:       $i++;
 5568:    }
 5569:    return %returnhash;
 5570: }
 5571: 
 5572: # --------------------------------------------------------------- del interface
 5573: 
 5574: sub del {
 5575:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5576:    my $items='';
 5577:    foreach my $item (@$storearr) {
 5578:        $items.=&escape($item).'&';
 5579:    }
 5580: 
 5581:    $items=~s/\&$//;
 5582:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5583:    if (!$uname) { $uname=$env{'user.name'}; }
 5584:    my $uhome=&homeserver($uname,$udomain);
 5585:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 5586: }
 5587: 
 5588: # -------------------------------------------------------------- dump interface
 5589: 
 5590: sub unserialize {
 5591:     my ($rep, $escapedkeys) = @_;
 5592: 
 5593:     return {} if $rep =~ /^error/;
 5594: 
 5595:     my %returnhash=();
 5596: 	foreach my $item (split(/\&/,$rep)) {
 5597: 	    my ($key, $value) = split(/=/, $item, 2);
 5598: 	    $key = unescape($key) unless $escapedkeys;
 5599: 	    next if $key =~ /^error: 2 /;
 5600: 	    $returnhash{$key} = &thaw_unescape($value);
 5601: 	}
 5602:     #return %returnhash;
 5603:     return \%returnhash;
 5604: }        
 5605: 
 5606: # see Lond::dump_with_regexp
 5607: # if $escapedkeys hash keys won't get unescaped.
 5608: sub dump {
 5609:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 5610:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5611:     if (!$uname) { $uname=$env{'user.name'}; }
 5612:     my $uhome=&homeserver($uname,$udomain);
 5613: 
 5614:     my $reply;
 5615:     if (grep { $_ eq $uhome } current_machine_ids()) {
 5616:         # user is hosted on this machine
 5617:         $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 5618:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 5619:         return %{unserialize($reply, $escapedkeys)};
 5620:     }
 5621:     if ($regexp) {
 5622: 	$regexp=&escape($regexp);
 5623:     } else {
 5624: 	$regexp='.';
 5625:     }
 5626:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 5627:     my @pairs=split(/\&/,$rep);
 5628:     my %returnhash=();
 5629:     if (!($rep =~ /^error/ )) {
 5630: 	foreach my $item (@pairs) {
 5631: 	    my ($key,$value)=split(/=/,$item,2);
 5632:         $key = unescape($key) unless $escapedkeys;
 5633:         #$key = &unescape($key);
 5634: 	    next if ($key =~ /^error: 2 /);
 5635: 	    $returnhash{$key}=&thaw_unescape($value);
 5636: 	}
 5637:     }
 5638:     return %returnhash;
 5639: }
 5640: 
 5641: 
 5642: # --------------------------------------------------------- dumpstore interface
 5643: 
 5644: sub dumpstore {
 5645:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 5646:    # same as dump but keys must be escaped. They may contain colon separated
 5647:    # lists of values that may themself contain colons (e.g. symbs).
 5648:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 5649: }
 5650: 
 5651: # -------------------------------------------------------------- keys interface
 5652: 
 5653: sub getkeys {
 5654:    my ($namespace,$udomain,$uname)=@_;
 5655:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5656:    if (!$uname) { $uname=$env{'user.name'}; }
 5657:    my $uhome=&homeserver($uname,$udomain);
 5658:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 5659:    my @keyarray=();
 5660:    foreach my $key (split(/\&/,$rep)) {
 5661:       next if ($key =~ /^error: 2 /);
 5662:       push(@keyarray,&unescape($key));
 5663:    }
 5664:    return @keyarray;
 5665: }
 5666: 
 5667: # --------------------------------------------------------------- currentdump
 5668: sub currentdump {
 5669:    my ($courseid,$sdom,$sname)=@_;
 5670:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 5671:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 5672:    $sname    = $env{'user.name'}         if (! defined($sname));
 5673:    my $uhome = &homeserver($sname,$sdom);
 5674:    my $rep;
 5675: 
 5676:    if (grep { $_ eq $uhome } current_machine_ids()) {
 5677:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 5678:                    $courseid)));
 5679:    } else {
 5680:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 5681:    }
 5682: 
 5683:    return if ($rep =~ /^(error:|no_such_host)/);
 5684:    #
 5685:    my %returnhash=();
 5686:    #
 5687:    if ($rep eq "unknown_cmd") { 
 5688:        # an old lond will not know currentdump
 5689:        # Do a dump and make it look like a currentdump
 5690:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 5691:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 5692:        my %hash = @tmp;
 5693:        @tmp=();
 5694:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 5695:    } else {
 5696:        my @pairs=split(/\&/,$rep);
 5697:        foreach my $pair (@pairs) {
 5698:            my ($key,$value)=split(/=/,$pair,2);
 5699:            my ($symb,$param) = split(/:/,$key);
 5700:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 5701:                                                         &thaw_unescape($value);
 5702:        }
 5703:    }
 5704:    return %returnhash;
 5705: }
 5706: 
 5707: sub convert_dump_to_currentdump{
 5708:     my %hash = %{shift()};
 5709:     my %returnhash;
 5710:     # Code ripped from lond, essentially.  The only difference
 5711:     # here is the unescaping done by lonnet::dump().  Conceivably
 5712:     # we might run in to problems with parameter names =~ /^v\./
 5713:     while (my ($key,$value) = each(%hash)) {
 5714:         my ($v,$symb,$param) = split(/:/,$key);
 5715: 	$symb  = &unescape($symb);
 5716: 	$param = &unescape($param);
 5717:         next if ($v eq 'version' || $symb eq 'keys');
 5718:         next if (exists($returnhash{$symb}) &&
 5719:                  exists($returnhash{$symb}->{$param}) &&
 5720:                  $returnhash{$symb}->{'v.'.$param} > $v);
 5721:         $returnhash{$symb}->{$param}=$value;
 5722:         $returnhash{$symb}->{'v.'.$param}=$v;
 5723:     }
 5724:     #
 5725:     # Remove all of the keys in the hashes which keep track of
 5726:     # the version of the parameter.
 5727:     while (my ($symb,$param_hash) = each(%returnhash)) {
 5728:         # use a foreach because we are going to delete from the hash.
 5729:         foreach my $key (keys(%$param_hash)) {
 5730:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 5731:         }
 5732:     }
 5733:     return \%returnhash;
 5734: }
 5735: 
 5736: # ------------------------------------------------------ critical inc interface
 5737: 
 5738: sub cinc {
 5739:     return &inc(@_,'critical');
 5740: }
 5741: 
 5742: # --------------------------------------------------------------- inc interface
 5743: 
 5744: sub inc {
 5745:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 5746:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5747:     if (!$uname) { $uname=$env{'user.name'}; }
 5748:     my $uhome=&homeserver($uname,$udomain);
 5749:     my $items='';
 5750:     if (! ref($store)) {
 5751:         # got a single value, so use that instead
 5752:         $items = &escape($store).'=&';
 5753:     } elsif (ref($store) eq 'SCALAR') {
 5754:         $items = &escape($$store).'=&';        
 5755:     } elsif (ref($store) eq 'ARRAY') {
 5756:         $items = join('=&',map {&escape($_);} @{$store});
 5757:     } elsif (ref($store) eq 'HASH') {
 5758:         while (my($key,$value) = each(%{$store})) {
 5759:             $items.= &escape($key).'='.&escape($value).'&';
 5760:         }
 5761:     }
 5762:     $items=~s/\&$//;
 5763:     if ($critical) {
 5764: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 5765:     } else {
 5766: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 5767:     }
 5768: }
 5769: 
 5770: # --------------------------------------------------------------- put interface
 5771: 
 5772: sub put {
 5773:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5774:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5775:    if (!$uname) { $uname=$env{'user.name'}; }
 5776:    my $uhome=&homeserver($uname,$udomain);
 5777:    my $items='';
 5778:    foreach my $item (keys(%$storehash)) {
 5779:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5780:    }
 5781:    $items=~s/\&$//;
 5782:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5783: }
 5784: 
 5785: # ------------------------------------------------------------ newput interface
 5786: 
 5787: sub newput {
 5788:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5789:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5790:    if (!$uname) { $uname=$env{'user.name'}; }
 5791:    my $uhome=&homeserver($uname,$udomain);
 5792:    my $items='';
 5793:    foreach my $key (keys(%$storehash)) {
 5794:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5795:    }
 5796:    $items=~s/\&$//;
 5797:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 5798: }
 5799: 
 5800: # ---------------------------------------------------------  putstore interface
 5801: 
 5802: sub putstore {
 5803:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5804:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5805:    if (!$uname) { $uname=$env{'user.name'}; }
 5806:    my $uhome=&homeserver($uname,$udomain);
 5807:    my $items='';
 5808:    foreach my $key (keys(%$storehash)) {
 5809:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 5810:    }
 5811:    $items=~s/\&$//;
 5812:    my $esc_symb=&escape($symb);
 5813:    my $esc_v=&escape($version);
 5814:    my $reply =
 5815:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 5816: 	      $uhome);
 5817:    if ($reply eq 'unknown_cmd') {
 5818:        # gfall back to way things use to be done
 5819:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 5820: 			    $uname);
 5821:    }
 5822:    return $reply;
 5823: }
 5824: 
 5825: sub old_putstore {
 5826:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5827:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5828:     if (!$uname) { $uname=$env{'user.name'}; }
 5829:     my $uhome=&homeserver($uname,$udomain);
 5830:     my %newstorehash;
 5831:     foreach my $item (keys(%$storehash)) {
 5832: 	my $key = $version.':'.&escape($symb).':'.$item;
 5833: 	$newstorehash{$key} = $storehash->{$item};
 5834:     }
 5835:     my $items='';
 5836:     my %allitems = ();
 5837:     foreach my $item (keys(%newstorehash)) {
 5838: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 5839: 	    my $key = $1.':keys:'.$2;
 5840: 	    $allitems{$key} .= $3.':';
 5841: 	}
 5842: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 5843:     }
 5844:     foreach my $item (keys(%allitems)) {
 5845: 	$allitems{$item} =~ s/\:$//;
 5846: 	$items.= $item.'='.$allitems{$item}.'&';
 5847:     }
 5848:     $items=~s/\&$//;
 5849:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5850: }
 5851: 
 5852: # ------------------------------------------------------ critical put interface
 5853: 
 5854: sub cput {
 5855:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5856:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5857:    if (!$uname) { $uname=$env{'user.name'}; }
 5858:    my $uhome=&homeserver($uname,$udomain);
 5859:    my $items='';
 5860:    foreach my $item (keys(%$storehash)) {
 5861:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5862:    }
 5863:    $items=~s/\&$//;
 5864:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 5865: }
 5866: 
 5867: # -------------------------------------------------------------- eget interface
 5868: 
 5869: sub eget {
 5870:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5871:    my $items='';
 5872:    foreach my $item (@$storearr) {
 5873:        $items.=&escape($item).'&';
 5874:    }
 5875:    $items=~s/\&$//;
 5876:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5877:    if (!$uname) { $uname=$env{'user.name'}; }
 5878:    my $uhome=&homeserver($uname,$udomain);
 5879:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 5880:    my @pairs=split(/\&/,$rep);
 5881:    my %returnhash=();
 5882:    my $i=0;
 5883:    foreach my $item (@$storearr) {
 5884:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5885:       $i++;
 5886:    }
 5887:    return %returnhash;
 5888: }
 5889: 
 5890: # ------------------------------------------------------------ tmpput interface
 5891: sub tmpput {
 5892:     my ($storehash,$server,$context)=@_;
 5893:     my $items='';
 5894:     foreach my $item (keys(%$storehash)) {
 5895: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5896:     }
 5897:     $items=~s/\&$//;
 5898:     if (defined($context)) {
 5899:         $items .= ':'.&escape($context);
 5900:     }
 5901:     return &reply("tmpput:$items",$server);
 5902: }
 5903: 
 5904: # ------------------------------------------------------------ tmpget interface
 5905: sub tmpget {
 5906:     my ($token,$server)=@_;
 5907:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5908:     my $rep=&reply("tmpget:$token",$server);
 5909:     my %returnhash;
 5910:     foreach my $item (split(/\&/,$rep)) {
 5911: 	my ($key,$value)=split(/=/,$item);
 5912:         next if ($key =~ /^error: 2 /);
 5913: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 5914:     }
 5915:     return %returnhash;
 5916: }
 5917: 
 5918: # ------------------------------------------------------------ tmpdel interface
 5919: sub tmpdel {
 5920:     my ($token,$server)=@_;
 5921:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5922:     return &reply("tmpdel:$token",$server);
 5923: }
 5924: 
 5925: # ------------------------------------------------------------ get_timebased_id 
 5926: 
 5927: sub get_timebased_id {
 5928:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 5929:         $maxtries) = @_;
 5930:     my ($newid,$error,$dellock);
 5931:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 5932:         return ('','ok','invalid call to get suffix');
 5933:     }
 5934: 
 5935: # set defaults for any optional args for which values were not supplied
 5936:     if ($who eq '') {
 5937:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 5938:     }
 5939:     if (!$locktries) {
 5940:         $locktries = 3;
 5941:     }
 5942:     if (!$maxtries) {
 5943:         $maxtries = 10;
 5944:     }
 5945:     
 5946:     if (($cdom eq '') || ($cnum eq '')) {
 5947:         if ($env{'request.course.id'}) {
 5948:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5949:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5950:         }
 5951:         if (($cdom eq '') || ($cnum eq '')) {
 5952:             return ('','ok','call to get suffix not in course context');
 5953:         }
 5954:     }
 5955: 
 5956: # construct locking item
 5957:     my $lockhash = {
 5958:                       $prefix."\0".'locked_'.$keyid => $who,
 5959:                    };
 5960:     my $tries = 0;
 5961: 
 5962: # attempt to get lock on nohist_$namespace file
 5963:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 5964:     while (($gotlock ne 'ok') && $tries <$locktries) {
 5965:         $tries ++;
 5966:         sleep 1;
 5967:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 5968:     }
 5969: 
 5970: # attempt to get unique identifier, based on current timestamp
 5971:     if ($gotlock eq 'ok') {
 5972:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 5973:         my $id = time;
 5974:         $newid = $id;
 5975:         my $idtries = 0;
 5976:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 5977:             if ($idtype eq 'concat') {
 5978:                 $newid = $id.$idtries;
 5979:             } else {
 5980:                 $newid ++;
 5981:             }
 5982:             $idtries ++;
 5983:         }
 5984:         if (!exists($inuse{$prefix."\0".$newid})) {
 5985:             my %new_item =  (
 5986:                               $prefix."\0".$newid => $who,
 5987:                             );
 5988:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 5989:                                                  $cdom,$cnum);
 5990:             if ($putresult ne 'ok') {
 5991:                 undef($newid);
 5992:                 $error = 'error saving new item: '.$putresult;
 5993:             }
 5994:         } else {
 5995:              $error = ('error: no unique suffix available for the new item ');
 5996:         }
 5997: #  remove lock
 5998:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 5999:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 6000:     } else {
 6001:         $error = "error: could not obtain lockfile\n";
 6002:         $dellock = 'ok';
 6003:     }
 6004:     return ($newid,$dellock,$error);
 6005: }
 6006: 
 6007: # -------------------------------------------------- portfolio access checking
 6008: 
 6009: sub portfolio_access {
 6010:     my ($requrl) = @_;
 6011:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 6012:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 6013:     if ($result) {
 6014:         my %setters;
 6015:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 6016:             my ($startblock,$endblock) =
 6017:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 6018:             if ($startblock && $endblock) {
 6019:                 return 'B';
 6020:             }
 6021:         } else {
 6022:             my ($startblock,$endblock) =
 6023:                 &Apache::loncommon::blockcheck(\%setters,'port');
 6024:             if ($startblock && $endblock) {
 6025:                 return 'B';
 6026:             }
 6027:         }
 6028:     }
 6029:     if ($result eq 'ok') {
 6030:        return 'F';
 6031:     } elsif ($result =~ /^[^:]+:guest_/) {
 6032:        return 'A';
 6033:     }
 6034:     return '';
 6035: }
 6036: 
 6037: sub get_portfolio_access {
 6038:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 6039: 
 6040:     if (!ref($access_hash)) {
 6041: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 6042: 	my %access_controls = &get_access_controls($current_perms,$group,
 6043: 						   $file_name);
 6044: 	$access_hash = $access_controls{$file_name};
 6045:     }
 6046: 
 6047:     my ($public,$guest,@domains,@users,@courses,@groups);
 6048:     my $now = time;
 6049:     if (ref($access_hash) eq 'HASH') {
 6050:         foreach my $key (keys(%{$access_hash})) {
 6051:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 6052:             if ($start > $now) {
 6053:                 next;
 6054:             }
 6055:             if ($end && $end<$now) {
 6056:                 next;
 6057:             }
 6058:             if ($scope eq 'public') {
 6059:                 $public = $key;
 6060:                 last;
 6061:             } elsif ($scope eq 'guest') {
 6062:                 $guest = $key;
 6063:             } elsif ($scope eq 'domains') {
 6064:                 push(@domains,$key);
 6065:             } elsif ($scope eq 'users') {
 6066:                 push(@users,$key);
 6067:             } elsif ($scope eq 'course') {
 6068:                 push(@courses,$key);
 6069:             } elsif ($scope eq 'group') {
 6070:                 push(@groups,$key);
 6071:             }
 6072:         }
 6073:         if ($public) {
 6074:             return 'ok';
 6075:         }
 6076:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 6077:             if ($guest) {
 6078:                 return $guest;
 6079:             }
 6080:         } else {
 6081:             if (@domains > 0) {
 6082:                 foreach my $domkey (@domains) {
 6083:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 6084:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 6085:                             return 'ok';
 6086:                         }
 6087:                     }
 6088:                 }
 6089:             }
 6090:             if (@users > 0) {
 6091:                 foreach my $userkey (@users) {
 6092:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 6093:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 6094:                             if (ref($item) eq 'HASH') {
 6095:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 6096:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 6097:                                     return 'ok';
 6098:                                 }
 6099:                             }
 6100:                         }
 6101:                     } 
 6102:                 }
 6103:             }
 6104:             my %roleshash;
 6105:             my @courses_and_groups = @courses;
 6106:             push(@courses_and_groups,@groups); 
 6107:             if (@courses_and_groups > 0) {
 6108:                 my (%allgroups,%allroles); 
 6109:                 my ($start,$end,$role,$sec,$group);
 6110:                 foreach my $envkey (%env) {
 6111:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 6112:                         my $cid = $2.'_'.$3; 
 6113:                         if ($1 eq 'gr') {
 6114:                             $group = $4;
 6115:                             $allgroups{$cid}{$group} = $env{$envkey};
 6116:                         } else {
 6117:                             if ($4 eq '') {
 6118:                                 $sec = 'none';
 6119:                             } else {
 6120:                                 $sec = $4;
 6121:                             }
 6122:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 6123:                         }
 6124:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 6125:                         my $cid = $2.'_'.$3;
 6126:                         if ($4 eq '') {
 6127:                             $sec = 'none';
 6128:                         } else {
 6129:                             $sec = $4;
 6130:                         }
 6131:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 6132:                     }
 6133:                 }
 6134:                 if (keys(%allroles) == 0) {
 6135:                     return;
 6136:                 }
 6137:                 foreach my $key (@courses_and_groups) {
 6138:                     my %content = %{$$access_hash{$key}};
 6139:                     my $cnum = $content{'number'};
 6140:                     my $cdom = $content{'domain'};
 6141:                     my $cid = $cdom.'_'.$cnum;
 6142:                     if (!exists($allroles{$cid})) {
 6143:                         next;
 6144:                     }    
 6145:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 6146:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 6147:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 6148:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 6149:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 6150:                         foreach my $role (keys(%{$allroles{$cid}})) {
 6151:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 6152:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 6153:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 6154:                                         if (grep/^all$/,@sections) {
 6155:                                             return 'ok';
 6156:                                         } else {
 6157:                                             if (grep/^$sec$/,@sections) {
 6158:                                                 return 'ok';
 6159:                                             }
 6160:                                         }
 6161:                                     }
 6162:                                 }
 6163:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 6164:                                     if (grep/^none$/,@groups) {
 6165:                                         return 'ok';
 6166:                                     }
 6167:                                 } else {
 6168:                                     if (grep/^all$/,@groups) {
 6169:                                         return 'ok';
 6170:                                     } 
 6171:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 6172:                                         if (grep/^$group$/,@groups) {
 6173:                                             return 'ok';
 6174:                                         }
 6175:                                     }
 6176:                                 } 
 6177:                             }
 6178:                         }
 6179:                     }
 6180:                 }
 6181:             }
 6182:             if ($guest) {
 6183:                 return $guest;
 6184:             }
 6185:         }
 6186:     }
 6187:     return;
 6188: }
 6189: 
 6190: sub course_group_datechecker {
 6191:     my ($dates,$now,$status) = @_;
 6192:     my ($start,$end) = split(/\./,$dates);
 6193:     if (!$start && !$end) {
 6194:         return 'ok';
 6195:     }
 6196:     if (grep/^active$/,@{$status}) {
 6197:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 6198:             return 'ok';
 6199:         }
 6200:     }
 6201:     if (grep/^previous$/,@{$status}) {
 6202:         if ($end > $now ) {
 6203:             return 'ok';
 6204:         }
 6205:     }
 6206:     if (grep/^future$/,@{$status}) {
 6207:         if ($start > $now) {
 6208:             return 'ok';
 6209:         }
 6210:     }
 6211:     return; 
 6212: }
 6213: 
 6214: sub parse_portfolio_url {
 6215:     my ($url) = @_;
 6216: 
 6217:     my ($type,$udom,$unum,$group,$file_name);
 6218:     
 6219:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 6220: 	$type = 1;
 6221:         $udom = $1;
 6222:         $unum = $2;
 6223:         $file_name = $3;
 6224:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 6225: 	$type = 2;
 6226:         $udom = $1;
 6227:         $unum = $2;
 6228:         $group = $3;
 6229:         $file_name = $3.'/'.$4;
 6230:     }
 6231:     if (wantarray) {
 6232: 	return ($type,$udom,$unum,$file_name,$group);
 6233:     }
 6234:     return $type;
 6235: }
 6236: 
 6237: sub is_portfolio_url {
 6238:     my ($url) = @_;
 6239:     return scalar(&parse_portfolio_url($url));
 6240: }
 6241: 
 6242: sub is_portfolio_file {
 6243:     my ($file) = @_;
 6244:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 6245:         return 1;
 6246:     }
 6247:     return;
 6248: }
 6249: 
 6250: sub usertools_access {
 6251:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 6252:     my ($access,%tools);
 6253:     if ($context eq '') {
 6254:         $context = 'tools';
 6255:     }
 6256:     if ($context eq 'requestcourses') {
 6257:         %tools = (
 6258:                       official   => 1,
 6259:                       unofficial => 1,
 6260:                       community  => 1,
 6261:                       textbook   => 1,
 6262:                  );
 6263:     } elsif ($context eq 'requestauthor') {
 6264:         %tools = (
 6265:                       requestauthor => 1,
 6266:                  );
 6267:     } else {
 6268:         %tools = (
 6269:                       aboutme   => 1,
 6270:                       blog      => 1,
 6271:                       webdav    => 1,
 6272:                       portfolio => 1,
 6273:                  );
 6274:     }
 6275:     return if (!defined($tools{$tool}));
 6276: 
 6277:     if (($udom eq '') || ($uname eq '')) {
 6278:         $udom = $env{'user.domain'};
 6279:         $uname = $env{'user.name'};
 6280:     }
 6281: 
 6282:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6283:         if ($action ne 'reload') {
 6284:             if ($context eq 'requestcourses') {
 6285:                 return $env{'environment.canrequest.'.$tool};
 6286:             } elsif ($context eq 'requestauthor') {
 6287:                 return $env{'environment.canrequest.author'};
 6288:             } else {
 6289:                 return $env{'environment.availabletools.'.$tool};
 6290:             }
 6291:         }
 6292:     }
 6293: 
 6294:     my ($toolstatus,$inststatus,$envkey);
 6295:     if ($context eq 'requestauthor') {
 6296:         $envkey = $context; 
 6297:     } else {
 6298:         $envkey = $context.'.'.$tool;
 6299:     }
 6300: 
 6301:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 6302:          ($action ne 'reload')) {
 6303:         $toolstatus = $env{'environment.'.$envkey};
 6304:         $inststatus = $env{'environment.inststatus'};
 6305:     } else {
 6306:         if (ref($userenvref) eq 'HASH') {
 6307:             $toolstatus = $userenvref->{$envkey};
 6308:             $inststatus = $userenvref->{'inststatus'};
 6309:         } else {
 6310:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 6311:             $toolstatus = $userenv{$envkey};
 6312:             $inststatus = $userenv{'inststatus'};
 6313:         }
 6314:     }
 6315: 
 6316:     if ($toolstatus ne '') {
 6317:         if ($toolstatus) {
 6318:             $access = 1;
 6319:         } else {
 6320:             $access = 0;
 6321:         }
 6322:         return $access;
 6323:     }
 6324: 
 6325:     my ($is_adv,%domdef);
 6326:     if (ref($is_advref) eq 'HASH') {
 6327:         $is_adv = $is_advref->{'is_adv'};
 6328:     } else {
 6329:         $is_adv = &is_advanced_user($udom,$uname);
 6330:     }
 6331:     if (ref($domdefref) eq 'HASH') {
 6332:         %domdef = %{$domdefref};
 6333:     } else {
 6334:         %domdef = &get_domain_defaults($udom);
 6335:     }
 6336:     if (ref($domdef{$tool}) eq 'HASH') {
 6337:         if ($is_adv) {
 6338:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 6339:                 if ($domdef{$tool}{'_LC_adv'}) { 
 6340:                     $access = 1;
 6341:                 } else {
 6342:                     $access = 0;
 6343:                 }
 6344:                 return $access;
 6345:             }
 6346:         }
 6347:         if ($inststatus ne '') {
 6348:             my ($hasaccess,$hasnoaccess);
 6349:             foreach my $affiliation (split(/:/,$inststatus)) {
 6350:                 if ($domdef{$tool}{$affiliation} ne '') { 
 6351:                     if ($domdef{$tool}{$affiliation}) {
 6352:                         $hasaccess = 1;
 6353:                     } else {
 6354:                         $hasnoaccess = 1;
 6355:                     }
 6356:                 }
 6357:             }
 6358:             if ($hasaccess || $hasnoaccess) {
 6359:                 if ($hasaccess) {
 6360:                     $access = 1;
 6361:                 } elsif ($hasnoaccess) {
 6362:                     $access = 0; 
 6363:                 }
 6364:                 return $access;
 6365:             }
 6366:         } else {
 6367:             if ($domdef{$tool}{'default'} ne '') {
 6368:                 if ($domdef{$tool}{'default'}) {
 6369:                     $access = 1;
 6370:                 } elsif ($domdef{$tool}{'default'} == 0) {
 6371:                     $access = 0;
 6372:                 }
 6373:                 return $access;
 6374:             }
 6375:         }
 6376:     } else {
 6377:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 6378:             $access = 1;
 6379:         } else {
 6380:             $access = 0;
 6381:         }
 6382:         return $access;
 6383:     }
 6384: }
 6385: 
 6386: sub is_course_owner {
 6387:     my ($cdom,$cnum,$udom,$uname) = @_;
 6388:     if (($udom eq '') || ($uname eq '')) {
 6389:         $udom = $env{'user.domain'};
 6390:         $uname = $env{'user.name'};
 6391:     }
 6392:     unless (($udom eq '') || ($uname eq '')) {
 6393:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 6394:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 6395:                 return 1;
 6396:             } else {
 6397:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 6398:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 6399:                     return 1;
 6400:                 }
 6401:             }
 6402:         }
 6403:     }
 6404:     return;
 6405: }
 6406: 
 6407: sub is_advanced_user {
 6408:     my ($udom,$uname) = @_;
 6409:     if ($udom ne '' && $uname ne '') {
 6410:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6411:             if (wantarray) {
 6412:                 return ($env{'user.adv'},$env{'user.author'});
 6413:             } else {
 6414:                 return $env{'user.adv'};
 6415:             }
 6416:         }
 6417:     }
 6418:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 6419:     my %allroles;
 6420:     my ($is_adv,$is_author);
 6421:     foreach my $role (keys(%roleshash)) {
 6422:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 6423:         my $area = '/'.$tdomain.'/'.$trest;
 6424:         if ($sec ne '') {
 6425:             $area .= '/'.$sec;
 6426:         }
 6427:         if (($area ne '') && ($trole ne '')) {
 6428:             my $spec=$trole.'.'.$area;
 6429:             if ($trole =~ /^cr\//) {
 6430:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6431:             } elsif ($trole ne 'gr') {
 6432:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6433:             }
 6434:             if ($trole eq 'au') {
 6435:                 $is_author = 1;
 6436:             }
 6437:         }
 6438:     }
 6439:     foreach my $role (keys(%allroles)) {
 6440:         last if ($is_adv);
 6441:         foreach my $item (split(/:/,$allroles{$role})) {
 6442:             if ($item ne '') {
 6443:                 my ($privilege,$restrictions)=split(/&/,$item);
 6444:                 if ($privilege eq 'adv') {
 6445:                     $is_adv = 1;
 6446:                     last;
 6447:                 }
 6448:             }
 6449:         }
 6450:     }
 6451:     if (wantarray) {
 6452:         return ($is_adv,$is_author);
 6453:     }
 6454:     return $is_adv;
 6455: }
 6456: 
 6457: sub check_can_request {
 6458:     my ($dom,$can_request,$request_domains) = @_;
 6459:     my $canreq = 0;
 6460:     my ($types,$typename) = &Apache::loncommon::course_types();
 6461:     my @options = ('approval','validate','autolimit');
 6462:     my $optregex = join('|',@options);
 6463:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 6464:         foreach my $type (@{$types}) {
 6465:             if (&usertools_access($env{'user.name'},
 6466:                                   $env{'user.domain'},
 6467:                                   $type,undef,'requestcourses')) {
 6468:                 $canreq ++;
 6469:                 if (ref($request_domains) eq 'HASH') {
 6470:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 6471:                 }
 6472:                 if ($dom eq $env{'user.domain'}) {
 6473:                     $can_request->{$type} = 1;
 6474:                 }
 6475:             }
 6476:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 6477:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 6478:                 if (@curr > 0) {
 6479:                     foreach my $item (@curr) {
 6480:                         if (ref($request_domains) eq 'HASH') {
 6481:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 6482:                             if ($otherdom ne '') {
 6483:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 6484:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 6485:                                         push(@{$request_domains->{$type}},$otherdom);
 6486:                                     }
 6487:                                 } else {
 6488:                                     push(@{$request_domains->{$type}},$otherdom);
 6489:                                 }
 6490:                             }
 6491:                         }
 6492:                     }
 6493:                     unless($dom eq $env{'user.domain'}) {
 6494:                         $canreq ++;
 6495:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 6496:                             $can_request->{$type} = 1;
 6497:                         }
 6498:                     }
 6499:                 }
 6500:             }
 6501:         }
 6502:     }
 6503:     return $canreq;
 6504: }
 6505: 
 6506: # ---------------------------------------------- Custom access rule evaluation
 6507: 
 6508: sub customaccess {
 6509:     my ($priv,$uri)=@_;
 6510:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 6511:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 6512:     $udom = &LONCAPA::clean_domain($udom);
 6513:     $ucrs = &LONCAPA::clean_username($ucrs);
 6514:     my $access=0;
 6515:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 6516: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 6517: 	if ($type eq 'user') {
 6518: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 6519: 		my ($tdom,$tuname)=split(m{/},$scope);
 6520: 		if ($tdom) {
 6521: 		    if ($tdom ne $env{'user.domain'}) { next; }
 6522: 		}
 6523: 		if ($tuname) {
 6524: 		    if ($tuname ne $env{'user.name'}) { next; }
 6525: 		}
 6526: 		$access=($effect eq 'allow');
 6527: 		last;
 6528: 	    }
 6529: 	} else {
 6530: 	    if ($role) {
 6531: 		if ($role ne $urole) { next; }
 6532: 	    }
 6533: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 6534: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 6535: 		if ($tdom) {
 6536: 		    if ($tdom ne $udom) { next; }
 6537: 		}
 6538: 		if ($tcrs) {
 6539: 		    if ($tcrs ne $ucrs) { next; }
 6540: 		}
 6541: 		if ($tsec) {
 6542: 		    if ($tsec ne $usec) { next; }
 6543: 		}
 6544: 		$access=($effect eq 'allow');
 6545: 		last;
 6546: 	    }
 6547: 	    if ($realm eq '' && $role eq '') {
 6548: 		$access=($effect eq 'allow');
 6549: 	    }
 6550: 	}
 6551:     }
 6552:     return $access;
 6553: }
 6554: 
 6555: # ------------------------------------------------- Check for a user privilege
 6556: 
 6557: sub allowed {
 6558:     my ($priv,$uri,$symb,$role)=@_;
 6559:     my $ver_orguri=$uri;
 6560:     $uri=&deversion($uri);
 6561:     my $orguri=$uri;
 6562:     $uri=&declutter($uri);
 6563: 
 6564:     if ($priv eq 'evb') {
 6565: # Evade communication block restrictions for specified role in a course
 6566:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 6567:             return $1;
 6568:         } else {
 6569:             return;
 6570:         }
 6571:     }
 6572: 
 6573:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 6574: # Free bre access to adm and meta resources
 6575:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 6576: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 6577: 	&& ($priv eq 'bre')) {
 6578: 	return 'F';
 6579:     }
 6580: 
 6581: # Free bre access to user's own portfolio contents
 6582:     my ($space,$domain,$name,@dir)=split('/',$uri);
 6583:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 6584: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 6585:         my %setters;
 6586:         my ($startblock,$endblock) = 
 6587:             &Apache::loncommon::blockcheck(\%setters,'port');
 6588:         if ($startblock && $endblock) {
 6589:             return 'B';
 6590:         } else {
 6591:             return 'F';
 6592:         }
 6593:     }
 6594: 
 6595: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 6596:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 6597:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 6598:         if (exists($env{'request.course.id'})) {
 6599:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6600:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6601:             if (($domain eq $cdom) && ($name eq $cnum)) {
 6602:                 my $courseprivid=$env{'request.course.id'};
 6603:                 $courseprivid=~s/\_/\//;
 6604:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 6605:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 6606:                     return $1; 
 6607:                 } else {
 6608:                     if ($env{'request.course.sec'}) {
 6609:                         $courseprivid.='/'.$env{'request.course.sec'};
 6610:                     }
 6611:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 6612:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 6613:                         return $2;
 6614:                     }
 6615:                 }
 6616:             }
 6617:         }
 6618:     }
 6619: 
 6620: # Free bre to public access
 6621: 
 6622:     if ($priv eq 'bre') {
 6623:         my $copyright=&metadata($uri,'copyright');
 6624: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 6625:            return 'F'; 
 6626:         }
 6627:         if ($copyright eq 'priv') {
 6628:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6629: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 6630: 		return '';
 6631:             }
 6632:         }
 6633:         if ($copyright eq 'domain') {
 6634:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6635: 	    unless (($env{'user.domain'} eq $1) ||
 6636:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 6637: 		return '';
 6638:             }
 6639:         }
 6640:         if ($env{'request.role'}=~ /li\.\//) {
 6641:             # Library role, so allow browsing of resources in this domain.
 6642:             return 'F';
 6643:         }
 6644:         if ($copyright eq 'custom') {
 6645: 	    unless (&customaccess($priv,$uri)) { return ''; }
 6646:         }
 6647:     }
 6648:     # Domain coordinator is trying to create a course
 6649:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 6650:         # uri is the requested domain in this case.
 6651:         # comparison to 'request.role.domain' shows if the user has selected
 6652:         # a role of dc for the domain in question.
 6653:         return 'F' if ($uri eq $env{'request.role.domain'});
 6654:     }
 6655: 
 6656:     my $thisallowed='';
 6657:     my $statecond=0;
 6658:     my $courseprivid='';
 6659: 
 6660:     my $ownaccess;
 6661:     # Community Coordinator or Assistant Co-author browsing resource space.
 6662:     if (($priv eq 'bro') && ($env{'user.author'})) {
 6663:         if ($uri eq '') {
 6664:             $ownaccess = 1;
 6665:         } else {
 6666:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 6667:                 my $udom = $env{'user.domain'};
 6668:                 my $uname = $env{'user.name'};
 6669:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 6670:                     $ownaccess = 1;
 6671:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 6672:                     unless ($uri =~ m{\.\./}) {
 6673:                         $ownaccess = 1;
 6674:                     }
 6675:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 6676:                     my $now = time;
 6677:                     if ($uri =~ m{^([^/]+)/?$}) {
 6678:                         my $adom = $1;
 6679:                         foreach my $key (keys(%env)) {
 6680:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 6681:                                 my ($start,$end) = split('.',$env{$key});
 6682:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6683:                                     $ownaccess = 1;
 6684:                                     last;
 6685:                                 }
 6686:                             }
 6687:                         }
 6688:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 6689:                         my $adom = $1;
 6690:                         my $aname = $2;
 6691:                         foreach my $role ('ca','aa') { 
 6692:                             if ($env{"user.role.$role./$adom/$aname"}) {
 6693:                                 my ($start,$end) =
 6694:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 6695:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6696:                                     $ownaccess = 1;
 6697:                                     last;
 6698:                                 }
 6699:                             }
 6700:                         }
 6701:                     }
 6702:                 }
 6703:             }
 6704:         }
 6705:     }
 6706: 
 6707: # Course
 6708: 
 6709:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 6710:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6711:             $thisallowed.=$1;
 6712:         }
 6713:     }
 6714: 
 6715: # Domain
 6716: 
 6717:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 6718:        =~/\Q$priv\E\&([^\:]*)/) {
 6719:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6720:             $thisallowed.=$1;
 6721:         }
 6722:     }
 6723: 
 6724: # User who is not author or co-author might still be able to edit
 6725: # resource of an author in the domain (e.g., if Domain Coordinator).
 6726:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 6727:         (&allowed('mdc',$env{'request.course.id'}))) {
 6728:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 6729:             $thisallowed.=$1;
 6730:         }
 6731:     }
 6732: 
 6733: # Course: uri itself is a course
 6734:     my $courseuri=$uri;
 6735:     $courseuri=~s/\_(\d)/\/$1/;
 6736:     $courseuri=~s/^([^\/])/\/$1/;
 6737: 
 6738:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 6739:        =~/\Q$priv\E\&([^\:]*)/) {
 6740:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6741:             $thisallowed.=$1;
 6742:         }
 6743:     }
 6744: 
 6745: # URI is an uploaded document for this course, default permissions don't matter
 6746: # not allowing 'edit' access (editupload) to uploaded course docs
 6747:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 6748: 	$thisallowed='';
 6749:         my ($match)=&is_on_map($uri);
 6750:         if ($match) {
 6751:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 6752:                   =~/\Q$priv\E\&([^\:]*)/) {
 6753:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6754:                 if (@blockers > 0) {
 6755:                     $thisallowed = 'B';
 6756:                 } else {
 6757:                     $thisallowed.=$1;
 6758:                 }
 6759:             }
 6760:         } else {
 6761:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 6762:             if ($refuri) {
 6763:                 if ($refuri =~ m|^/adm/|) {
 6764:                     $thisallowed='F';
 6765:                 } else {
 6766:                     $refuri=&declutter($refuri);
 6767:                     my ($match) = &is_on_map($refuri);
 6768:                     if ($match) {
 6769:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6770:                         if (@blockers > 0) {
 6771:                             $thisallowed = 'B';
 6772:                         } else {
 6773:                             $thisallowed='F';
 6774:                         }
 6775:                     }
 6776:                 }
 6777:             }
 6778:         }
 6779:     }
 6780: 
 6781:     if ($priv eq 'bre'
 6782: 	&& $thisallowed ne 'F' 
 6783: 	&& $thisallowed ne '2'
 6784: 	&& &is_portfolio_url($uri)) {
 6785: 	$thisallowed = &portfolio_access($uri);
 6786:     }
 6787: 
 6788: # Full access at system, domain or course-wide level? Exit.
 6789:     if ($thisallowed=~/F/) {
 6790: 	return 'F';
 6791:     }
 6792: 
 6793: # If this is generating or modifying users, exit with special codes
 6794: 
 6795:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 6796: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 6797: 	    my ($audom,$auname)=split('/',$uri);
 6798: # no author name given, so this just checks on the general right to make a co-author in this domain
 6799: 	    unless ($auname) { return $thisallowed; }
 6800: # an author name is given, so we are about to actually make a co-author for a certain account
 6801: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 6802: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 6803: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 6804: 	}
 6805: 	return $thisallowed;
 6806:     }
 6807: #
 6808: # Gathered so far: system, domain and course wide privileges
 6809: #
 6810: # Course: See if uri or referer is an individual resource that is part of 
 6811: # the course
 6812: 
 6813:     if ($env{'request.course.id'}) {
 6814: 
 6815:        $courseprivid=$env{'request.course.id'};
 6816:        if ($env{'request.course.sec'}) {
 6817:           $courseprivid.='/'.$env{'request.course.sec'};
 6818:        }
 6819:        $courseprivid=~s/\_/\//;
 6820:        my $checkreferer=1;
 6821:        my ($match,$cond)=&is_on_map($uri);
 6822:        if ($match) {
 6823:            $statecond=$cond;
 6824:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6825:                =~/\Q$priv\E\&([^\:]*)/) {
 6826:                my $value = $1;
 6827:                if ($priv eq 'bre') {
 6828:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6829:                    if (@blockers > 0) {
 6830:                        $thisallowed = 'B';
 6831:                    } else {
 6832:                        $thisallowed.=$value;
 6833:                    }
 6834:                } else {
 6835:                    $thisallowed.=$value;
 6836:                }
 6837:                $checkreferer=0;
 6838:            }
 6839:        }
 6840:        
 6841:        if ($checkreferer) {
 6842: 	  my $refuri=$env{'httpref.'.$orguri};
 6843:             unless ($refuri) {
 6844:                 foreach my $key (keys(%env)) {
 6845: 		    if ($key=~/^httpref\..*\*/) {
 6846: 			my $pattern=$key;
 6847:                         $pattern=~s/^httpref\.\/res\///;
 6848:                         $pattern=~s/\*/\[\^\/\]\+/g;
 6849:                         $pattern=~s/\//\\\//g;
 6850:                         if ($orguri=~/$pattern/) {
 6851: 			    $refuri=$env{$key};
 6852:                         }
 6853:                     }
 6854:                 }
 6855:             }
 6856: 
 6857:          if ($refuri) { 
 6858: 	  $refuri=&declutter($refuri);
 6859:           my ($match,$cond)=&is_on_map($refuri);
 6860:             if ($match) {
 6861:               my $refstatecond=$cond;
 6862:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6863:                   =~/\Q$priv\E\&([^\:]*)/) {
 6864:                   my $value = $1;
 6865:                   if ($priv eq 'bre') {
 6866:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6867:                       if (@blockers > 0) {
 6868:                           $thisallowed = 'B';
 6869:                       } else {
 6870:                           $thisallowed.=$value;
 6871:                       }
 6872:                   } else {
 6873:                       $thisallowed.=$value;
 6874:                   }
 6875:                   $uri=$refuri;
 6876:                   $statecond=$refstatecond;
 6877:               }
 6878:           }
 6879:         }
 6880:        }
 6881:    }
 6882: 
 6883: #
 6884: # Gathered now: all privileges that could apply, and condition number
 6885: # 
 6886: #
 6887: # Full or no access?
 6888: #
 6889: 
 6890:     if ($thisallowed=~/F/) {
 6891: 	return 'F';
 6892:     }
 6893: 
 6894:     unless ($thisallowed) {
 6895:         return '';
 6896:     }
 6897: 
 6898: # Restrictions exist, deal with them
 6899: #
 6900: #   C:according to course preferences
 6901: #   R:according to resource settings
 6902: #   L:unless locked
 6903: #   X:according to user session state
 6904: #
 6905: 
 6906: # Possibly locked functionality, check all courses
 6907: # Locks might take effect only after 10 minutes cache expiration for other
 6908: # courses, and 2 minutes for current course
 6909: 
 6910:     my $envkey;
 6911:     if ($thisallowed=~/L/) {
 6912:         foreach $envkey (keys(%env)) {
 6913:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 6914:                my $courseid=$2;
 6915:                my $roleid=$1.'.'.$2;
 6916:                $courseid=~s/^\///;
 6917:                my $expiretime=600;
 6918:                if ($env{'request.role'} eq $roleid) {
 6919: 		  $expiretime=120;
 6920:                }
 6921: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 6922:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 6923:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 6924: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 6925:                }
 6926:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6927:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 6928: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 6929:                        &log($env{'user.domain'},$env{'user.name'},
 6930:                             $env{'user.home'},
 6931:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 6932:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6933:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6934: 		       return '';
 6935:                    }
 6936:                }
 6937:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6938:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 6939: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 6940:                        &log($env{'user.domain'},$env{'user.name'},
 6941:                             $env{'user.home'},
 6942:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 6943:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6944:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6945: 		       return '';
 6946:                    }
 6947:                }
 6948: 	   }
 6949:        }
 6950:     }
 6951:    
 6952: #
 6953: # Rest of the restrictions depend on selected course
 6954: #
 6955: 
 6956:     unless ($env{'request.course.id'}) {
 6957: 	if ($thisallowed eq 'A') {
 6958: 	    return 'A';
 6959:         } elsif ($thisallowed eq 'B') {
 6960:             return 'B';
 6961: 	} else {
 6962: 	    return '1';
 6963: 	}
 6964:     }
 6965: 
 6966: #
 6967: # Now user is definitely in a course
 6968: #
 6969: 
 6970: 
 6971: # Course preferences
 6972: 
 6973:    if ($thisallowed=~/C/) {
 6974:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6975:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 6976:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 6977: 	   =~/\Q$rolecode\E/) {
 6978: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6979: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6980: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 6981: 			$env{'request.course.id'});
 6982: 	   }
 6983:            return '';
 6984:        }
 6985: 
 6986:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 6987: 	   =~/\Q$unamedom\E/) {
 6988: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6989: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 6990: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 6991: 			$env{'request.course.id'});
 6992: 	   }
 6993:            return '';
 6994:        }
 6995:    }
 6996: 
 6997: # Resource preferences
 6998: 
 6999:    if ($thisallowed=~/R/) {
 7000:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 7001:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 7002: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 7003: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 7004: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 7005: 	   }
 7006: 	   return '';
 7007:        }
 7008:    }
 7009: 
 7010: # Restricted by state or randomout?
 7011: 
 7012:    if ($thisallowed=~/X/) {
 7013:       if ($env{'acc.randomout'}) {
 7014: 	 if (!$symb) { $symb=&symbread($uri,1); }
 7015:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 7016:             return ''; 
 7017:          }
 7018:       }
 7019:       if (&condval($statecond)) {
 7020: 	 return '2';
 7021:       } else {
 7022:          return '';
 7023:       }
 7024:    }
 7025: 
 7026:     if ($thisallowed eq 'A') {
 7027: 	return 'A';
 7028:     } elsif ($thisallowed eq 'B') {
 7029:         return 'B';
 7030:     }
 7031:    return 'F';
 7032: }
 7033: 
 7034: # ------------------------------------------- Check construction space access
 7035: 
 7036: sub constructaccess {
 7037:     my ($url,$setpriv)=@_;
 7038: 
 7039: # We do not allow editing of previous versions of files
 7040:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 7041: 
 7042: # Get username and domain from URL
 7043:     my ($ownername,$ownerdomain,$ownerhome);
 7044: 
 7045:     ($ownerdomain,$ownername) =
 7046:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
 7047: 
 7048: # The URL does not really point to any authorspace, forget it
 7049:     unless (($ownername) && ($ownerdomain)) { return ''; }
 7050: 
 7051: # Now we need to see if the user has access to the authorspace of
 7052: # $ownername at $ownerdomain
 7053: 
 7054:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 7055: # Real author for this?
 7056:        $ownerhome = $env{'user.home'};
 7057:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 7058:           return ($ownername,$ownerdomain,$ownerhome);
 7059:        }
 7060:     } else {
 7061: # Co-author for this?
 7062:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 7063:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 7064:             $ownerhome = &homeserver($ownername,$ownerdomain);
 7065:             return ($ownername,$ownerdomain,$ownerhome);
 7066:         }
 7067:     }
 7068: 
 7069: # We don't have any access right now. If we are not possibly going to do anything about this,
 7070: # we might as well leave
 7071:    unless ($setpriv) { return ''; }
 7072: 
 7073: # Backdoor access?
 7074:     my $allowed=&allowed('eco',$ownerdomain);
 7075: # Nope
 7076:     unless ($allowed) { return ''; }
 7077: # Looks like we may have access, but could be locked by the owner of the construction space
 7078:     if ($allowed eq 'U') {
 7079:         my %blocked=&get('environment',['domcoord.author'],
 7080:                          $ownerdomain,$ownername);
 7081: # Is blocked by owner
 7082:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 7083:     }
 7084:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 7085: # Grant temporary access
 7086:         my $then=$env{'user.login.time'};
 7087:         my $update=$env{'user.update.time'};
 7088:         if (!$update) { $update = $then; }
 7089:         my $refresh=$env{'user.refresh.time'};
 7090:         if (!$refresh) { $refresh = $update; }
 7091:         my $now = time;
 7092:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 7093:                            $now,'ca','constructaccess');
 7094:         $ownerhome = &homeserver($ownername,$ownerdomain);
 7095:         return($ownername,$ownerdomain,$ownerhome);
 7096:     }
 7097: # No business here
 7098:     return '';
 7099: }
 7100: 
 7101: sub get_comm_blocks {
 7102:     my ($cdom,$cnum) = @_;
 7103:     if ($cdom eq '' || $cnum eq '') {
 7104:         return unless ($env{'request.course.id'});
 7105:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7106:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7107:     }
 7108:     my %commblocks;
 7109:     my $hashid=$cdom.'_'.$cnum;
 7110:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 7111:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 7112:         %commblocks = %{$blocksref};
 7113:     } else {
 7114:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 7115:         my $cachetime = 600;
 7116:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 7117:     }
 7118:     return %commblocks;
 7119: }
 7120: 
 7121: sub has_comm_blocking {
 7122:     my ($priv,$symb,$uri,$blocks) = @_;
 7123:     return unless ($env{'request.course.id'});
 7124:     return unless ($priv eq 'bre');
 7125:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 7126:     my %commblocks;
 7127:     if (ref($blocks) eq 'HASH') {
 7128:         %commblocks = %{$blocks};
 7129:     } else {
 7130:         %commblocks = &get_comm_blocks();
 7131:     }
 7132:     return unless (keys(%commblocks) > 0);
 7133:     if (!$symb) { $symb=&symbread($uri,1); }
 7134:     my ($map,$resid,undef)=&decode_symb($symb);
 7135:     my %tocheck = (
 7136:                     maps      => $map,
 7137:                     resources => $symb,
 7138:                   );
 7139:     my @blockers;
 7140:     my $now = time;
 7141:     my $navmap = Apache::lonnavmaps::navmap->new();
 7142:     foreach my $block (keys(%commblocks)) {
 7143:         if ($block =~ /^(\d+)____(\d+)$/) {
 7144:             my ($start,$end) = ($1,$2);
 7145:             if ($start <= $now && $end >= $now) {
 7146:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 7147:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 7148:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 7149:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
 7150:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 7151:                                     push(@blockers,$block);
 7152:                                 }
 7153:                             }
 7154:                         }
 7155:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 7156:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
 7157:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
 7158:                                     push(@blockers,$block);
 7159:                                 }
 7160:                             }
 7161:                         }
 7162:                     }
 7163:                 }
 7164:             }
 7165:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 7166:             my $item = $1;
 7167:             my @to_test;
 7168:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 7169:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 7170:                     my $check_interval;
 7171:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
 7172:                         my @interval;
 7173:                         my $type = 'map';
 7174:                         if ($item eq 'course') {
 7175:                             $type = 'course';
 7176:                             @interval=&EXT("resource.0.interval");
 7177:                         } else {
 7178:                             if ($item =~ /___\d+___/) {
 7179:                                 $type = 'resource';
 7180:                                 @interval=&EXT("resource.0.interval",$item);
 7181:                                 if (ref($navmap)) {                        
 7182:                                     my $res = $navmap->getBySymb($item); 
 7183:                                     push(@to_test,$res);
 7184:                                 }
 7185:                             } else {
 7186:                                 my $mapsymb = &symbread($item,1);
 7187:                                 if ($mapsymb) {
 7188:                                     if (ref($navmap)) {
 7189:                                         my $mapres = $navmap->getBySymb($mapsymb);
 7190:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
 7191:                                         foreach my $res (@to_test) {
 7192:                                             my $symb = $res->symb();
 7193:                                             next if ($symb eq $mapsymb);
 7194:                                             if ($symb ne '') {
 7195:                                                 @interval=&EXT("resource.0.interval",$symb);
 7196:                                                 last;
 7197:                                             }
 7198:                                         }
 7199:                                     }
 7200:                                 }
 7201:                             }
 7202:                         }
 7203:                         if ($interval[0] =~ /\d+/) {
 7204:                             my $first_access;
 7205:                             if ($type eq 'resource') {
 7206:                                 $first_access=&get_first_access($interval[1],$item);
 7207:                             } elsif ($type eq 'map') {
 7208:                                 $first_access=&get_first_access($interval[1],undef,$item);
 7209:                             } else {
 7210:                                 $first_access=&get_first_access($interval[1]);
 7211:                             }
 7212:                             if ($first_access) {
 7213:                                 my $timesup = $first_access+$interval[0];
 7214:                                 if ($timesup > $now) {
 7215:                                     foreach my $res (@to_test) {
 7216:                                         if ($res->is_problem()) {
 7217:                                             if ($res->completable()) {
 7218:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 7219:                                                     push(@blockers,$block);
 7220:                                                 }
 7221:                                                 last;
 7222:                                             }
 7223:                                         }
 7224:                                     }
 7225:                                 }
 7226:                             }
 7227:                         }
 7228:                     }
 7229:                 }
 7230:             }
 7231:         }
 7232:     }
 7233:     return @blockers;
 7234: }
 7235: 
 7236: sub check_docs_block {
 7237:     my ($docsblock,$tocheck) =@_;
 7238:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
 7239:         return;
 7240:     }
 7241:     if (ref($docsblock->{'maps'}) eq 'HASH') {
 7242:         if ($tocheck->{'maps'}) {
 7243:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
 7244:                 return 1;
 7245:             }
 7246:         }
 7247:     }
 7248:     if (ref($docsblock->{'resources'}) eq 'HASH') {
 7249:         if ($tocheck->{'resources'}) {
 7250:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
 7251:                 return 1;
 7252:             }
 7253:         }
 7254:     }
 7255:     return;
 7256: }
 7257: 
 7258: #
 7259: #   Removes the versino from a URI and
 7260: #   splits it in to its filename and path to the filename.
 7261: #   Seems like File::Basename could have done this more clearly.
 7262: #   Parameters:
 7263: #      $uri   - input URI
 7264: #   Returns:
 7265: #     Two element list consisting of 
 7266: #     $pathname  - the URI up to and excluding the trailing /
 7267: #     $filename  - The part of the URI following the last /
 7268: #  NOTE:
 7269: #    Another realization of this is simply:
 7270: #    use File::Basename;
 7271: #    ...
 7272: #    $uri = shift;
 7273: #    $filename = basename($uri);
 7274: #    $path     = dirname($uri);
 7275: #    return ($filename, $path);
 7276: #
 7277: #     The implementation below is probably faster however.
 7278: #
 7279: sub split_uri_for_cond {
 7280:     my $uri=&deversion(&declutter(shift));
 7281:     my @uriparts=split(/\//,$uri);
 7282:     my $filename=pop(@uriparts);
 7283:     my $pathname=join('/',@uriparts);
 7284:     return ($pathname,$filename);
 7285: }
 7286: # --------------------------------------------------- Is a resource on the map?
 7287: 
 7288: sub is_on_map {
 7289:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 7290:     #Trying to find the conditional for the file
 7291:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 7292: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 7293:     if ($match) {
 7294: 	return (1,$1);
 7295:     } else {
 7296: 	return (0,0);
 7297:     }
 7298: }
 7299: 
 7300: # --------------------------------------------------------- Get symb from alias
 7301: 
 7302: sub get_symb_from_alias {
 7303:     my $symb=shift;
 7304:     my ($map,$resid,$url)=&decode_symb($symb);
 7305: # Already is a symb
 7306:     if ($url) { return $symb; }
 7307: # Must be an alias
 7308:     my $aliassymb='';
 7309:     my %bighash;
 7310:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7311:                             &GDBM_READER(),0640)) {
 7312:         my $rid=$bighash{'mapalias_'.$symb};
 7313: 	if ($rid) {
 7314: 	    my ($mapid,$resid)=split(/\./,$rid);
 7315: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 7316: 				    $resid,$bighash{'src_'.$rid});
 7317: 	}
 7318:         untie %bighash;
 7319:     }
 7320:     return $aliassymb;
 7321: }
 7322: 
 7323: # ----------------------------------------------------------------- Define Role
 7324: 
 7325: sub definerole {
 7326:   if (allowed('mcr','/')) {
 7327:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 7328:     foreach my $role (split(':',$sysrole)) {
 7329: 	my ($crole,$cqual)=split(/\&/,$role);
 7330:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 7331:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 7332: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 7333:                return "refused:s:$crole&$cqual"; 
 7334:             }
 7335:         }
 7336:     }
 7337:     foreach my $role (split(':',$domrole)) {
 7338: 	my ($crole,$cqual)=split(/\&/,$role);
 7339:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 7340:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 7341: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 7342:                return "refused:d:$crole&$cqual"; 
 7343:             }
 7344:         }
 7345:     }
 7346:     foreach my $role (split(':',$courole)) {
 7347: 	my ($crole,$cqual)=split(/\&/,$role);
 7348:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 7349:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 7350: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 7351:                return "refused:c:$crole&$cqual"; 
 7352:             }
 7353:         }
 7354:     }
 7355:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 7356:                 "$env{'user.domain'}:$env{'user.name'}:".
 7357: 	        "rolesdef_$rolename=".
 7358:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 7359:     return reply($command,$env{'user.home'});
 7360:   } else {
 7361:     return 'refused';
 7362:   }
 7363: }
 7364: 
 7365: # ---------------- Make a metadata query against the network of library servers
 7366: 
 7367: sub metadata_query {
 7368:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 7369:     my %rhash;
 7370:     my %libserv = &all_library();
 7371:     my @server_list = (defined($server_array) ? @$server_array
 7372:                                               : keys(%libserv) );
 7373:     for my $server (@server_list) {
 7374:         my $domains = ''; 
 7375:         if (ref($domains_hash) eq 'HASH') {
 7376:             $domains = $domains_hash->{$server}; 
 7377:         }
 7378: 	unless ($custom or $customshow) {
 7379: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 7380: 	    $rhash{$server}=$reply;
 7381: 	}
 7382: 	else {
 7383: 	    my $reply=&reply("querysend:".&escape($query).':'.
 7384: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 7385: 			     $server);
 7386: 	    $rhash{$server}=$reply;
 7387: 	}
 7388:     }
 7389:     return \%rhash;
 7390: }
 7391: 
 7392: # ----------------------------------------- Send log queries and wait for reply
 7393: 
 7394: sub log_query {
 7395:     my ($uname,$udom,$query,%filters)=@_;
 7396:     my $uhome=&homeserver($uname,$udom);
 7397:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 7398:     my $uhost=&hostname($uhome);
 7399:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 7400:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 7401:                        $uhome);
 7402:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 7403:     return get_query_reply($queryid);
 7404: }
 7405: 
 7406: # -------------------------- Update MySQL table for portfolio file
 7407: 
 7408: sub update_portfolio_table {
 7409:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 7410:     if ($group ne '') {
 7411:         $file_name =~s /^\Q$group\E//;
 7412:     }
 7413:     my $homeserver = &homeserver($uname,$udom);
 7414:     my $queryid=
 7415:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 7416:                ':'.&escape($file_name).':'.$action,$homeserver);
 7417:     my $reply = &get_query_reply($queryid);
 7418:     return $reply;
 7419: }
 7420: 
 7421: # -------------------------- Update MySQL allusers table
 7422: 
 7423: sub update_allusers_table {
 7424:     my ($uname,$udom,$names) = @_;
 7425:     my $homeserver = &homeserver($uname,$udom);
 7426:     my $queryid=
 7427:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 7428:                'lastname='.&escape($names->{'lastname'}).'%%'.
 7429:                'firstname='.&escape($names->{'firstname'}).'%%'.
 7430:                'middlename='.&escape($names->{'middlename'}).'%%'.
 7431:                'generation='.&escape($names->{'generation'}).'%%'.
 7432:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 7433:                'id='.&escape($names->{'id'}),$homeserver);
 7434:     return;
 7435: }
 7436: 
 7437: # ------- Request retrieval of institutional classlists for course(s)
 7438: 
 7439: sub fetch_enrollment_query {
 7440:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 7441:     my $homeserver;
 7442:     my $maxtries = 1;
 7443:     if ($context eq 'automated') {
 7444:         $homeserver = $perlvar{'lonHostID'};
 7445:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 7446:     } else {
 7447:         $homeserver = &homeserver($cnum,$dom);
 7448:     }
 7449:     my $host=&hostname($homeserver);
 7450:     my $cmd = '';
 7451:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7452:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7453:     }
 7454:     $cmd =~ s/%%$//;
 7455:     $cmd = &escape($cmd);
 7456:     my $query = 'fetchenrollment';
 7457:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 7458:     unless ($queryid=~/^\Q$host\E\_/) { 
 7459:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 7460:         return 'error: '.$queryid;
 7461:     }
 7462:     my $reply = &get_query_reply($queryid);
 7463:     my $tries = 1;
 7464:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7465:         $reply = &get_query_reply($queryid);
 7466:         $tries ++;
 7467:     }
 7468:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7469:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7470:     } else {
 7471:         my @responses = split(/:/,$reply);
 7472:         if ($homeserver eq $perlvar{'lonHostID'}) {
 7473:             foreach my $line (@responses) {
 7474:                 my ($key,$value) = split(/=/,$line,2);
 7475:                 $$replyref{$key} = $value;
 7476:             }
 7477:         } else {
 7478:             my $pathname = LONCAPA::tempdir();
 7479:             foreach my $line (@responses) {
 7480:                 my ($key,$value) = split(/=/,$line);
 7481:                 $$replyref{$key} = $value;
 7482:                 if ($value > 0) {
 7483:                     foreach my $item (@{$$affiliatesref{$key}}) {
 7484:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 7485:                         my $destname = $pathname.'/'.$filename;
 7486:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 7487:                         if ($xml_classlist =~ /^error/) {
 7488:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 7489:                         } else {
 7490:                             if ( open(FILE,">$destname") ) {
 7491:                                 print FILE &unescape($xml_classlist);
 7492:                                 close(FILE);
 7493:                             } else {
 7494:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 7495:                             }
 7496:                         }
 7497:                     }
 7498:                 }
 7499:             }
 7500:         }
 7501:         return 'ok';
 7502:     }
 7503:     return 'error';
 7504: }
 7505: 
 7506: sub get_query_reply {
 7507:     my $queryid=shift;
 7508:     my $replyfile=LONCAPA::tempdir().$queryid;
 7509:     my $reply='';
 7510:     for (1..100) {
 7511: 	sleep 2;
 7512:         if (-e $replyfile.'.end') {
 7513: 	    if (open(my $fh,$replyfile)) {
 7514: 		$reply = join('',<$fh>);
 7515: 		close($fh);
 7516: 	   } else { return 'error: reply_file_error'; }
 7517:            return &unescape($reply);
 7518: 	}
 7519:     }
 7520:     return 'timeout:'.$queryid;
 7521: }
 7522: 
 7523: sub courselog_query {
 7524: #
 7525: # possible filters:
 7526: # url: url or symb
 7527: # username
 7528: # domain
 7529: # action: view, submit, grade
 7530: # start: timestamp
 7531: # end: timestamp
 7532: #
 7533:     my (%filters)=@_;
 7534:     unless ($env{'request.course.id'}) { return 'no_course'; }
 7535:     if ($filters{'url'}) {
 7536: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 7537:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 7538:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 7539:     }
 7540:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7541:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7542:     return &log_query($cname,$cdom,'courselog',%filters);
 7543: }
 7544: 
 7545: sub userlog_query {
 7546: #
 7547: # possible filters:
 7548: # action: log check role
 7549: # start: timestamp
 7550: # end: timestamp
 7551: #
 7552:     my ($uname,$udom,%filters)=@_;
 7553:     return &log_query($uname,$udom,'userlog',%filters);
 7554: }
 7555: 
 7556: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 7557: 
 7558: sub auto_run {
 7559:     my ($cnum,$cdom) = @_;
 7560:     my $response = 0;
 7561:     my $settings;
 7562:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 7563:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 7564:         $settings = $domconfig{'autoenroll'};
 7565:         if ($settings->{'run'} eq '1') {
 7566:             $response = 1;
 7567:         }
 7568:     } else {
 7569:         my $homeserver;
 7570:         if (&is_course($cdom,$cnum)) {
 7571:             $homeserver = &homeserver($cnum,$cdom);
 7572:         } else {
 7573:             $homeserver = &domain($cdom,'primary');
 7574:         }
 7575:         if ($homeserver ne 'no_host') {
 7576:             $response = &reply('autorun:'.$cdom,$homeserver);
 7577:         }
 7578:     }
 7579:     return $response;
 7580: }
 7581: 
 7582: sub auto_get_sections {
 7583:     my ($cnum,$cdom,$inst_coursecode) = @_;
 7584:     my $homeserver;
 7585:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 7586:         $homeserver = &homeserver($cnum,$cdom);
 7587:     }
 7588:     if (!defined($homeserver)) { 
 7589:         if ($cdom =~ /^$match_domain$/) {
 7590:             $homeserver = &domain($cdom,'primary');
 7591:         }
 7592:     }
 7593:     my @secs;
 7594:     if (defined($homeserver)) {
 7595:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 7596:         unless ($response eq 'refused') {
 7597:             @secs = split(/:/,$response);
 7598:         }
 7599:     }
 7600:     return @secs;
 7601: }
 7602: 
 7603: sub auto_new_course {
 7604:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 7605:     my $homeserver = &homeserver($cnum,$cdom);
 7606:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 7607:     return $response;
 7608: }
 7609: 
 7610: sub auto_validate_courseID {
 7611:     my ($cnum,$cdom,$inst_course_id) = @_;
 7612:     my $homeserver = &homeserver($cnum,$cdom);
 7613:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 7614:     return $response;
 7615: }
 7616: 
 7617: sub auto_validate_instcode {
 7618:     my ($cnum,$cdom,$instcode,$owner) = @_;
 7619:     my ($homeserver,$response);
 7620:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7621:         $homeserver = &homeserver($cnum,$cdom);
 7622:     }
 7623:     if (!defined($homeserver)) {
 7624:         if ($cdom =~ /^$match_domain$/) {
 7625:             $homeserver = &domain($cdom,'primary');
 7626:         }
 7627:     }
 7628:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 7629:                         &escape($instcode).':'.&escape($owner),$homeserver));
 7630:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 7631:     return ($outcome,$description,$defaultcredits);
 7632: }
 7633: 
 7634: sub auto_create_password {
 7635:     my ($cnum,$cdom,$authparam,$udom) = @_;
 7636:     my ($homeserver,$response);
 7637:     my $create_passwd = 0;
 7638:     my $authchk = '';
 7639:     if ($udom =~ /^$match_domain$/) {
 7640:         $homeserver = &domain($udom,'primary');
 7641:     }
 7642:     if ($homeserver eq '') {
 7643:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7644:             $homeserver = &homeserver($cnum,$cdom);
 7645:         }
 7646:     }
 7647:     if ($homeserver eq '') {
 7648:         $authchk = 'nodomain';
 7649:     } else {
 7650:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 7651:         if ($response eq 'refused') {
 7652:             $authchk = 'refused';
 7653:         } else {
 7654:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 7655:         }
 7656:     }
 7657:     return ($authparam,$create_passwd,$authchk);
 7658: }
 7659: 
 7660: sub auto_photo_permission {
 7661:     my ($cnum,$cdom,$students) = @_;
 7662:     my $homeserver = &homeserver($cnum,$cdom);
 7663:     my ($outcome,$perm_reqd,$conditions) = 
 7664: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 7665:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7666: 	return (undef,undef);
 7667:     }
 7668:     return ($outcome,$perm_reqd,$conditions);
 7669: }
 7670: 
 7671: sub auto_checkphotos {
 7672:     my ($uname,$udom,$pid) = @_;
 7673:     my $homeserver = &homeserver($uname,$udom);
 7674:     my ($result,$resulttype);
 7675:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 7676: 				   &escape($uname).':'.&escape($pid),
 7677: 				   $homeserver));
 7678:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7679: 	return (undef,undef);
 7680:     }
 7681:     if ($outcome) {
 7682:         ($result,$resulttype) = split(/:/,$outcome);
 7683:     } 
 7684:     return ($result,$resulttype);
 7685: }
 7686: 
 7687: sub auto_photochoice {
 7688:     my ($cnum,$cdom) = @_;
 7689:     my $homeserver = &homeserver($cnum,$cdom);
 7690:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 7691: 						       &escape($cdom),
 7692: 						       $homeserver)));
 7693:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7694: 	return (undef,undef);
 7695:     }
 7696:     return ($update,$comment);
 7697: }
 7698: 
 7699: sub auto_photoupdate {
 7700:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 7701:     my $homeserver = &homeserver($cnum,$dom);
 7702:     my $host=&hostname($homeserver);
 7703:     my $cmd = '';
 7704:     my $maxtries = 1;
 7705:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7706:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7707:     }
 7708:     $cmd =~ s/%%$//;
 7709:     $cmd = &escape($cmd);
 7710:     my $query = 'institutionalphotos';
 7711:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 7712:     unless ($queryid=~/^\Q$host\E\_/) {
 7713:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 7714:         return 'error: '.$queryid;
 7715:     }
 7716:     my $reply = &get_query_reply($queryid);
 7717:     my $tries = 1;
 7718:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7719:         $reply = &get_query_reply($queryid);
 7720:         $tries ++;
 7721:     }
 7722:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7723:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7724:     } else {
 7725:         my @responses = split(/:/,$reply);
 7726:         my $outcome = shift(@responses); 
 7727:         foreach my $item (@responses) {
 7728:             my ($key,$value) = split(/=/,$item);
 7729:             $$photo{$key} = $value;
 7730:         }
 7731:         return $outcome;
 7732:     }
 7733:     return 'error';
 7734: }
 7735: 
 7736: sub auto_instcode_format {
 7737:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 7738: 	$cat_order) = @_;
 7739:     my $courses = '';
 7740:     my @homeservers;
 7741:     if ($caller eq 'global') {
 7742: 	my %servers = &get_servers($codedom,'library');
 7743: 	foreach my $tryserver (keys(%servers)) {
 7744: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7745: 		push(@homeservers,$tryserver);
 7746: 	    }
 7747:         }
 7748:     } elsif ($caller eq 'requests') {
 7749:         if ($codedom =~ /^$match_domain$/) {
 7750:             my $chome = &domain($codedom,'primary');
 7751:             unless ($chome eq 'no_host') {
 7752:                 push(@homeservers,$chome);
 7753:             }
 7754:         }
 7755:     } else {
 7756:         push(@homeservers,&homeserver($caller,$codedom));
 7757:     }
 7758:     foreach my $code (keys(%{$instcodes})) {
 7759:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 7760:     }
 7761:     chop($courses);
 7762:     my $ok_response = 0;
 7763:     my $response;
 7764:     while (@homeservers > 0 && $ok_response == 0) {
 7765:         my $server = shift(@homeservers); 
 7766:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 7767:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 7768:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 7769: 		split(/:/,$response);
 7770:             %{$codes} = (%{$codes},&str2hash($codes_str));
 7771:             push(@{$codetitles},&str2array($codetitles_str));
 7772:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 7773:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 7774:             $ok_response = 1;
 7775:         }
 7776:     }
 7777:     if ($ok_response) {
 7778:         return 'ok';
 7779:     } else {
 7780:         return $response;
 7781:     }
 7782: }
 7783: 
 7784: sub auto_instcode_defaults {
 7785:     my ($domain,$returnhash,$code_order) = @_;
 7786:     my @homeservers;
 7787: 
 7788:     my %servers = &get_servers($domain,'library');
 7789:     foreach my $tryserver (keys(%servers)) {
 7790: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7791: 	    push(@homeservers,$tryserver);
 7792: 	}
 7793:     }
 7794: 
 7795:     my $response;
 7796:     foreach my $server (@homeservers) {
 7797:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 7798:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7799: 	
 7800: 	foreach my $pair (split(/\&/,$response)) {
 7801: 	    my ($name,$value)=split(/\=/,$pair);
 7802: 	    if ($name eq 'code_order') {
 7803: 		@{$code_order} = split(/\&/,&unescape($value));
 7804: 	    } else {
 7805: 		$returnhash->{&unescape($name)}=&unescape($value);
 7806: 	    }
 7807: 	}
 7808: 	return 'ok';
 7809:     }
 7810: 
 7811:     return $response;
 7812: }
 7813: 
 7814: sub auto_possible_instcodes {
 7815:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 7816:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 7817:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 7818:         return;
 7819:     }
 7820:     my (@homeservers,$uhome);
 7821:     if (defined(&domain($domain,'primary'))) {
 7822:         $uhome=&domain($domain,'primary');
 7823:         push(@homeservers,&domain($domain,'primary'));
 7824:     } else {
 7825:         my %servers = &get_servers($domain,'library');
 7826:         foreach my $tryserver (keys(%servers)) {
 7827:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7828:                 push(@homeservers,$tryserver);
 7829:             }
 7830:         }
 7831:     }
 7832:     my $response;
 7833:     foreach my $server (@homeservers) {
 7834:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 7835:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7836:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 7837:             split(':',$response);
 7838:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 7839:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 7840:         foreach my $item (split('&',$cat_title)) {   
 7841:             my ($name,$value)=split('=',$item);
 7842:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 7843:         }
 7844:         foreach my $item (split('&',$cat_order)) {
 7845:             my ($name,$value)=split('=',$item);
 7846:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 7847:         }
 7848:         return 'ok';
 7849:     }
 7850:     return $response;
 7851: }
 7852: 
 7853: sub auto_courserequest_checks {
 7854:     my ($dom) = @_;
 7855:     my ($homeserver,%validations);
 7856:     if ($dom =~ /^$match_domain$/) {
 7857:         $homeserver = &domain($dom,'primary');
 7858:     }
 7859:     unless ($homeserver eq 'no_host') {
 7860:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 7861:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 7862:             my @items = split(/&/,$response);
 7863:             foreach my $item (@items) {
 7864:                 my ($key,$value) = split('=',$item);
 7865:                 $validations{&unescape($key)} = &thaw_unescape($value);
 7866:             }
 7867:         }
 7868:     }
 7869:     return %validations; 
 7870: }
 7871: 
 7872: sub auto_courserequest_validation {
 7873:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
 7874:     my ($homeserver,$response);
 7875:     if ($dom =~ /^$match_domain$/) {
 7876:         $homeserver = &domain($dom,'primary');
 7877:     }
 7878:     unless ($homeserver eq 'no_host') {
 7879:         my $customdata;
 7880:         if (ref($custominfo) eq 'HASH') {
 7881:             $customdata = &freeze_escape($custominfo);
 7882:         }
 7883:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 7884:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 7885:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
 7886:                                     $customdata,$homeserver));
 7887:     }
 7888:     return $response;
 7889: }
 7890: 
 7891: sub auto_validate_class_sec {
 7892:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 7893:     my $homeserver = &homeserver($cnum,$cdom);
 7894:     my $ownerlist;
 7895:     if (ref($owners) eq 'ARRAY') {
 7896:         $ownerlist = join(',',@{$owners});
 7897:     } else {
 7898:         $ownerlist = $owners;
 7899:     }
 7900:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 7901:                         &escape($ownerlist).':'.$cdom,$homeserver);
 7902:     return $response;
 7903: }
 7904: 
 7905: sub auto_crsreq_update {
 7906:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
 7907:         $code,$accessstart,$accessend,$inbound) = @_;
 7908:     my ($homeserver,%crsreqresponse);
 7909:     if ($cdom =~ /^$match_domain$/) {
 7910:         $homeserver = &domain($cdom,'primary');
 7911:     }
 7912:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 7913:         my $info;
 7914:         if (ref($inbound) eq 'HASH') {
 7915:             $info = &freeze_escape($inbound);
 7916:         }
 7917:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
 7918:                             ':'.&escape($action).':'.&escape($ownername).':'.
 7919:                             &escape($ownerdomain).':'.&escape($fullname).':'.
 7920:                             &escape($title).':'.&escape($code).':'.
 7921:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
 7922:                             $homeserver);
 7923:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 7924:             my @items = split(/&/,$response);
 7925:             foreach my $item (@items) {
 7926:                 my ($key,$value) = split('=',$item);
 7927:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
 7928:             }
 7929:         }
 7930:     }
 7931:     return \%crsreqresponse;
 7932: }
 7933: 
 7934: # ------------------------------------------------------- Course Group routines
 7935: 
 7936: sub get_coursegroups {
 7937:     my ($cdom,$cnum,$group,$namespace) = @_;
 7938:     return(&dump($namespace,$cdom,$cnum,$group));
 7939: }
 7940: 
 7941: sub modify_coursegroup {
 7942:     my ($cdom,$cnum,$groupsettings) = @_;
 7943:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 7944: }
 7945: 
 7946: sub toggle_coursegroup_status {
 7947:     my ($cdom,$cnum,$group,$action) = @_;
 7948:     my ($from_namespace,$to_namespace);
 7949:     if ($action eq 'delete') {
 7950:         $from_namespace = 'coursegroups';
 7951:         $to_namespace = 'deleted_groups';
 7952:     } else {
 7953:         $from_namespace = 'deleted_groups';
 7954:         $to_namespace = 'coursegroups';
 7955:     }
 7956:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 7957:     if (my $tmp = &error(%curr_group)) {
 7958:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 7959:         return ('read error',$tmp);
 7960:     } else {
 7961:         my %savedsettings = %curr_group; 
 7962:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 7963:         my $deloutcome;
 7964:         if ($result eq 'ok') {
 7965:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 7966:         } else {
 7967:             return ('write error',$result);
 7968:         }
 7969:         if ($deloutcome eq 'ok') {
 7970:             return 'ok';
 7971:         } else {
 7972:             return ('delete error',$deloutcome);
 7973:         }
 7974:     }
 7975: }
 7976: 
 7977: sub modify_group_roles {
 7978:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 7979:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 7980:     my $role = 'gr/'.&escape($userprivs);
 7981:     my ($uname,$udom) = split(/:/,$user);
 7982:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 7983:     if ($result eq 'ok') {
 7984:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 7985:     }
 7986:     return $result;
 7987: }
 7988: 
 7989: sub modify_coursegroup_membership {
 7990:     my ($cdom,$cnum,$membership) = @_;
 7991:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 7992:     return $result;
 7993: }
 7994: 
 7995: sub get_active_groups {
 7996:     my ($udom,$uname,$cdom,$cnum) = @_;
 7997:     my $now = time;
 7998:     my %groups = ();
 7999:     foreach my $key (keys(%env)) {
 8000:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 8001:             my ($start,$end) = split(/\./,$env{$key});
 8002:             if (($end!=0) && ($end<$now)) { next; }
 8003:             if (($start!=0) && ($start>$now)) { next; }
 8004:             if ($1 eq $cdom && $2 eq $cnum) {
 8005:                 $groups{$3} = $env{$key} ;
 8006:             }
 8007:         }
 8008:     }
 8009:     return %groups;
 8010: }
 8011: 
 8012: sub get_group_membership {
 8013:     my ($cdom,$cnum,$group) = @_;
 8014:     return(&dump('groupmembership',$cdom,$cnum,$group));
 8015: }
 8016: 
 8017: sub get_users_groups {
 8018:     my ($udom,$uname,$courseid) = @_;
 8019:     my @usersgroups;
 8020:     my $cachetime=1800;
 8021: 
 8022:     my $hashid="$udom:$uname:$courseid";
 8023:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 8024:     if (defined($cached)) {
 8025:         @usersgroups = split(/:/,$grouplist);
 8026:     } else {  
 8027:         $grouplist = '';
 8028:         my $courseurl = &courseid_to_courseurl($courseid);
 8029:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 8030:         my $access_end = $env{'course.'.$courseid.
 8031:                               '.default_enrollment_end_date'};
 8032:         my $now = time;
 8033:         foreach my $key (keys(%roleshash)) {
 8034:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 8035:                 my $group = $1;
 8036:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 8037:                     my $start = $2;
 8038:                     my $end = $1;
 8039:                     if ($start == -1) { next; } # deleted from group
 8040:                     if (($start!=0) && ($start>$now)) { next; }
 8041:                     if (($end!=0) && ($end<$now)) {
 8042:                         if ($access_end && $access_end < $now) {
 8043:                             if ($access_end - $end < 86400) {
 8044:                                 push(@usersgroups,$group);
 8045:                             }
 8046:                         }
 8047:                         next;
 8048:                     }
 8049:                     push(@usersgroups,$group);
 8050:                 }
 8051:             }
 8052:         }
 8053:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 8054:         $grouplist = join(':',@usersgroups);
 8055:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 8056:     }
 8057:     return @usersgroups;
 8058: }
 8059: 
 8060: sub devalidate_getgroups_cache {
 8061:     my ($udom,$uname,$cdom,$cnum)=@_;
 8062:     my $courseid = $cdom.'_'.$cnum;
 8063: 
 8064:     my $hashid="$udom:$uname:$courseid";
 8065:     &devalidate_cache_new('getgroups',$hashid);
 8066: }
 8067: 
 8068: # ------------------------------------------------------------------ Plain Text
 8069: 
 8070: sub plaintext {
 8071:     my ($short,$type,$cid,$forcedefault) = @_;
 8072:     if ($short =~ m{^cr/}) {
 8073: 	return (split('/',$short))[-1];
 8074:     }
 8075:     if (!defined($cid)) {
 8076:         $cid = $env{'request.course.id'};
 8077:     }
 8078:     my %rolenames = (
 8079:                       Course    => 'std',
 8080:                       Community => 'alt1',
 8081:                     );
 8082:     if ($cid ne '') {
 8083:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 8084:             unless ($forcedefault) {
 8085:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 8086:                 &Apache::lonlocal::mt_escape(\$roletext);
 8087:                 return &Apache::lonlocal::mt($roletext);
 8088:             }
 8089:         }
 8090:     }
 8091:     if ((defined($type)) && (defined($rolenames{$type})) &&
 8092:         (defined($rolenames{$type})) && 
 8093:         (defined($prp{$short}{$rolenames{$type}}))) {
 8094:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 8095:     } elsif ($cid ne '') {
 8096:         my $crstype = $env{'course.'.$cid.'.type'};
 8097:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 8098:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 8099:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 8100:         }
 8101:     }
 8102:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 8103: }
 8104: 
 8105: # ----------------------------------------------------------------- Assign Role
 8106: 
 8107: sub assignrole {
 8108:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 8109:         $context)=@_;
 8110:     my $mrole;
 8111:     if ($role =~ /^cr\//) {
 8112:         my $cwosec=$url;
 8113:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 8114: 	unless (&allowed('ccr',$cwosec)) {
 8115:            my $refused = 1;
 8116:            if ($context eq 'requestcourses') {
 8117:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 8118:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 8119:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 8120:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 8121:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8122:                            if ($crsenv{'internal.courseowner'} eq
 8123:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 8124:                                $refused = '';
 8125:                            }
 8126:                        }
 8127:                    }
 8128:                }
 8129:            }
 8130:            if ($refused) {
 8131:                &logthis('Refused custom assignrole: '.
 8132:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 8133:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 8134:                return 'refused';
 8135:            }
 8136:         }
 8137:         $mrole='cr';
 8138:     } elsif ($role =~ /^gr\//) {
 8139:         my $cwogrp=$url;
 8140:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 8141:         unless (&allowed('mdg',$cwogrp)) {
 8142:             &logthis('Refused group assignrole: '.
 8143:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 8144:                     $env{'user.name'}.' at '.$env{'user.domain'});
 8145:             return 'refused';
 8146:         }
 8147:         $mrole='gr';
 8148:     } else {
 8149:         my $cwosec=$url;
 8150:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 8151:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 8152:             my $refused;
 8153:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 8154:                 if (!(&allowed('c'.$role,$url))) {
 8155:                     $refused = 1;
 8156:                 }
 8157:             } else {
 8158:                 $refused = 1;
 8159:             }
 8160:             if ($refused) {
 8161:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 8162:                 if (!$selfenroll && $context eq 'course') {
 8163:                     my %crsenv;
 8164:                     if ($role eq 'cc' || $role eq 'co') {
 8165:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8166:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 8167:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 8168:                                 if ($crsenv{'internal.courseowner'} eq 
 8169:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 8170:                                     $refused = '';
 8171:                                 }
 8172:                             }
 8173:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 8174:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 8175:                                 if ($crsenv{'internal.courseowner'} eq 
 8176:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 8177:                                     $refused = '';
 8178:                                 }
 8179:                             }
 8180:                         }
 8181:                     }
 8182:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 8183:                     $refused = '';
 8184:                 } elsif ($context eq 'requestcourses') {
 8185:                     my @possroles = ('st','ta','ep','in','cc','co');
 8186:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 8187:                         my $wrongcc;
 8188:                         if ($cnum =~ /^$match_community$/) {
 8189:                             $wrongcc = 1 if ($role eq 'cc');
 8190:                         } else {
 8191:                             $wrongcc = 1 if ($role eq 'co');
 8192:                         }
 8193:                         unless ($wrongcc) {
 8194:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8195:                             if ($crsenv{'internal.courseowner'} eq 
 8196:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 8197:                                 $refused = '';
 8198:                             }
 8199:                         }
 8200:                     }
 8201:                 } elsif ($context eq 'requestauthor') {
 8202:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
 8203:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 8204:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 8205:                             $refused = '';
 8206:                         } else {
 8207:                             my %domdefaults = &get_domain_defaults($udom);
 8208:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 8209:                                 my $checkbystatus;
 8210:                                 if ($env{'user.adv'}) { 
 8211:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 8212:                                     if ($disposition eq 'automatic') {
 8213:                                         $refused = '';
 8214:                                     } elsif ($disposition eq '') {
 8215:                                         $checkbystatus = 1;
 8216:                                     } 
 8217:                                 } else {
 8218:                                     $checkbystatus = 1;
 8219:                                 }
 8220:                                 if ($checkbystatus) {
 8221:                                     if ($env{'environment.inststatus'}) {
 8222:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 8223:                                         foreach my $type (@inststatuses) {
 8224:                                             if (($type ne '') &&
 8225:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 8226:                                                 $refused = '';
 8227:                                             }
 8228:                                         }
 8229:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 8230:                                         $refused = '';
 8231:                                     }
 8232:                                 }
 8233:                             }
 8234:                         }
 8235:                     }
 8236:                 }
 8237:                 if ($refused) {
 8238:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 8239:                              ' '.$role.' '.$end.' '.$start.' by '.
 8240: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 8241:                     return 'refused';
 8242:                 }
 8243:             }
 8244:         } elsif ($role eq 'au') {
 8245:             if ($url ne '/'.$udom.'/') {
 8246:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 8247:                          ' to assign author role for '.$uname.':'.$udom.
 8248:                          ' in domain: '.$url.' refused (wrong domain).');
 8249:                 return 'refused';
 8250:             }
 8251:         }
 8252:         $mrole=$role;
 8253:     }
 8254:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 8255:                 "$udom:$uname:$url".'_'."$mrole=$role";
 8256:     if ($end) { $command.='_'.$end; }
 8257:     if ($start) {
 8258: 	if ($end) { 
 8259:            $command.='_'.$start; 
 8260:         } else {
 8261:            $command.='_0_'.$start;
 8262:         }
 8263:     }
 8264:     my $origstart = $start;
 8265:     my $origend = $end;
 8266:     my $delflag;
 8267: # actually delete
 8268:     if ($deleteflag) {
 8269: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 8270: # modify command to delete the role
 8271:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 8272:                 "$udom:$uname:$url".'_'."$mrole";
 8273: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 8274: # set start and finish to negative values for userrolelog
 8275:            $start=-1;
 8276:            $end=-1;
 8277:            $delflag = 1;
 8278:         }
 8279:     }
 8280: # send command
 8281:     my $answer=&reply($command,&homeserver($uname,$udom));
 8282: # log new user role if status is ok
 8283:     if ($answer eq 'ok') {
 8284: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 8285:         if (($role eq 'cc') || ($role eq 'in') ||
 8286:             ($role eq 'ep') || ($role eq 'ad') ||
 8287:             ($role eq 'ta') || ($role eq 'st') ||
 8288:             ($role=~/^cr/) || ($role eq 'gr') ||
 8289:             ($role eq 'co')) {
 8290: # for course roles, perform group memberships changes triggered by role change.
 8291:             unless ($role =~ /^gr/) {
 8292:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 8293:                                                  $origstart,$selfenroll,$context);
 8294:             }
 8295:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8296:                            $selfenroll,$context);
 8297:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
 8298:                  ($role eq 'au') || ($role eq 'dc')) {
 8299:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8300:                            $context);
 8301:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
 8302:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8303:                              $context); 
 8304:         }
 8305:         if ($role eq 'cc') {
 8306:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 8307:         }
 8308:     }
 8309:     return $answer;
 8310: }
 8311: 
 8312: sub autoupdate_coowners {
 8313:     my ($url,$end,$start,$uname,$udom) = @_;
 8314:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 8315:     if (($cdom ne '') && ($cnum ne '')) {
 8316:         my $now = time;
 8317:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 8318:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 8319:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 8320:             my $instcode = $coursehash{'internal.coursecode'};
 8321:             if ($instcode ne '') {
 8322:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 8323:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 8324:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 8325:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 8326:                         if ($result eq 'valid') {
 8327:                             if ($coursehash{'internal.co-owners'}) {
 8328:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 8329:                                     push(@newcoowners,$coowner);
 8330:                                 }
 8331:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 8332:                                     push(@newcoowners,$uname.':'.$udom);
 8333:                                 }
 8334:                                 @newcoowners = sort(@newcoowners);
 8335:                             } else {
 8336:                                 push(@newcoowners,$uname.':'.$udom);
 8337:                             }
 8338:                         } else {
 8339:                             if ($coursehash{'internal.co-owners'}) {
 8340:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 8341:                                     unless ($coowner eq $uname.':'.$udom) {
 8342:                                         push(@newcoowners,$coowner);
 8343:                                     }
 8344:                                 }
 8345:                                 unless (@newcoowners > 0) {
 8346:                                     $delcoowners = 1;
 8347:                                     $coowners = '';
 8348:                                 }
 8349:                             }
 8350:                         }
 8351:                         if (@newcoowners || $delcoowners) {
 8352:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 8353:                                             $delcoowners,@newcoowners);
 8354:                         }
 8355:                     }
 8356:                 }
 8357:             }
 8358:         }
 8359:     }
 8360: }
 8361: 
 8362: sub store_coowners {
 8363:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 8364:     my $cid = $cdom.'_'.$cnum;
 8365:     my ($coowners,$delresult,$putresult);
 8366:     if (@newcoowners) {
 8367:         $coowners = join(',',@newcoowners);
 8368:         my %coownershash = (
 8369:                             'internal.co-owners' => $coowners,
 8370:                            );
 8371:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 8372:         if ($putresult eq 'ok') {
 8373:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 8374:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 8375:             }
 8376:         }
 8377:     }
 8378:     if ($delcoowners) {
 8379:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 8380:         if ($delresult eq 'ok') {
 8381:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 8382:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 8383:             }
 8384:         }
 8385:     }
 8386:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 8387:         my %crsinfo =
 8388:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 8389:         if (ref($crsinfo{$cid}) eq 'HASH') {
 8390:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 8391:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 8392:         }
 8393:     }
 8394: }
 8395: 
 8396: # -------------------------------------------------- Modify user authentication
 8397: # Overrides without validation
 8398: 
 8399: sub modifyuserauth {
 8400:     my ($udom,$uname,$umode,$upass)=@_;
 8401:     my $uhome=&homeserver($uname,$udom);
 8402:     unless (&allowed('mau',$udom)) { return 'refused'; }
 8403:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 8404:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 8405:              ' in domain '.$env{'request.role.domain'});  
 8406:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 8407: 		     &escape($upass),$uhome);
 8408:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 8409:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 8410:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 8411:     &log($udom,,$uname,$uhome,
 8412:         'Authentication changed by '.$env{'user.domain'}.', '.
 8413:                                      $env{'user.name'}.', '.$umode.
 8414:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 8415:     unless ($reply eq 'ok') {
 8416:         &logthis('Authentication mode error: '.$reply);
 8417: 	return 'error: '.$reply;
 8418:     }   
 8419:     return 'ok';
 8420: }
 8421: 
 8422: # --------------------------------------------------------------- Modify a user
 8423: 
 8424: sub modifyuser {
 8425:     my ($udom,    $uname, $uid,
 8426:         $umode,   $upass, $first,
 8427:         $middle,  $last,  $gene,
 8428:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 8429:     $udom= &LONCAPA::clean_domain($udom);
 8430:     $uname=&LONCAPA::clean_username($uname);
 8431:     my $showcandelete = 'none';
 8432:     if (ref($candelete) eq 'ARRAY') {
 8433:         if (@{$candelete} > 0) {
 8434:             $showcandelete = join(', ',@{$candelete});
 8435:         }
 8436:     }
 8437:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 8438:              $umode.', '.$first.', '.$middle.', '.
 8439: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 8440:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 8441:                                      ' desiredhome not specified'). 
 8442:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 8443:              ' in domain '.$env{'request.role.domain'});
 8444:     my $uhome=&homeserver($uname,$udom,'true');
 8445:     my $newuser;
 8446:     if ($uhome eq 'no_host') {
 8447:         $newuser = 1;
 8448:     }
 8449: # ----------------------------------------------------------------- Create User
 8450:     if (($uhome eq 'no_host') && 
 8451: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 8452:         my $unhome='';
 8453:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 8454:             $unhome = $desiredhome;
 8455: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 8456: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 8457:         } else { # load balancing routine for determining $unhome
 8458:             my $loadm=10000000;
 8459: 	    my %servers = &get_servers($udom,'library');
 8460: 	    foreach my $tryserver (keys(%servers)) {
 8461: 		my $answer=reply('load',$tryserver);
 8462: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 8463: 		    $loadm=$answer;
 8464: 		    $unhome=$tryserver;
 8465: 		}
 8466: 	    }
 8467:         }
 8468:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 8469: 	    return 'error: unable to find a home server for '.$uname.
 8470:                    ' in domain '.$udom;
 8471:         }
 8472:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 8473:                          &escape($upass),$unhome);
 8474: 	unless ($reply eq 'ok') {
 8475:             return 'error: '.$reply;
 8476:         }   
 8477:         $uhome=&homeserver($uname,$udom,'true');
 8478:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 8479: 	    return 'error: unable verify users home machine.';
 8480:         }
 8481:     }   # End of creation of new user
 8482: # ---------------------------------------------------------------------- Add ID
 8483:     if ($uid) {
 8484:        $uid=~tr/A-Z/a-z/;
 8485:        my %uidhash=&idrget($udom,$uname);
 8486:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 8487:          && (!$forceid)) {
 8488: 	  unless ($uid eq $uidhash{$uname}) {
 8489: 	      return 'error: user id "'.$uid.'" does not match '.
 8490:                   'current user id "'.$uidhash{$uname}.'".';
 8491:           }
 8492:        } else {
 8493: 	  &idput($udom,($uname => $uid));
 8494:        }
 8495:     }
 8496: # -------------------------------------------------------------- Add names, etc
 8497:     my @tmp=&get('environment',
 8498: 		   ['firstname','middlename','lastname','generation','id',
 8499:                     'permanentemail','inststatus'],
 8500: 		   $udom,$uname);
 8501:     my (%names,%oldnames);
 8502:     if ($tmp[0] =~ m/^error:.*/) { 
 8503:         %names=(); 
 8504:     } else {
 8505:         %names = @tmp;
 8506:         %oldnames = %names;
 8507:     }
 8508: #
 8509: # If name, email and/or uid are blank (e.g., because an uploaded file
 8510: # of users did not contain them), do not overwrite existing values
 8511: # unless field is in $candelete array ref.  
 8512: #
 8513: 
 8514:     my @fields = ('firstname','middlename','lastname','generation',
 8515:                   'permanentemail','id');
 8516:     my %newvalues;
 8517:     if (ref($candelete) eq 'ARRAY') {
 8518:         foreach my $field (@fields) {
 8519:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 8520:                 if ($field eq 'firstname') {
 8521:                     $names{$field} = $first;
 8522:                 } elsif ($field eq 'middlename') {
 8523:                     $names{$field} = $middle;
 8524:                 } elsif ($field eq 'lastname') {
 8525:                     $names{$field} = $last;
 8526:                 } elsif ($field eq 'generation') { 
 8527:                     $names{$field} = $gene;
 8528:                 } elsif ($field eq 'permanentemail') {
 8529:                     $names{$field} = $email;
 8530:                 } elsif ($field eq 'id') {
 8531:                     $names{$field}  = $uid;
 8532:                 }
 8533:             }
 8534:         }
 8535:     }
 8536:     if ($first)  { $names{'firstname'}  = $first; }
 8537:     if (defined($middle)) { $names{'middlename'} = $middle; }
 8538:     if ($last)   { $names{'lastname'}   = $last; }
 8539:     if (defined($gene))   { $names{'generation'} = $gene; }
 8540:     if ($email) {
 8541:        $email=~s/[^\w\@\.\-\,]//gs;
 8542:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 8543:     }
 8544:     if ($uid) { $names{'id'}  = $uid; }
 8545:     if (defined($inststatus)) {
 8546:         $names{'inststatus'} = '';
 8547:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 8548:         if (ref($usertypes) eq 'HASH') {
 8549:             my @okstatuses; 
 8550:             foreach my $item (split(/:/,$inststatus)) {
 8551:                 if (defined($usertypes->{$item})) {
 8552:                     push(@okstatuses,$item);  
 8553:                 }
 8554:             }
 8555:             if (@okstatuses) {
 8556:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 8557:             }
 8558:         }
 8559:     }
 8560:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 8561:                  $umode.', '.$first.', '.$middle.', '.
 8562:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 8563:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 8564:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 8565:     } else {
 8566:         $logmsg .= ' during self creation';
 8567:     }
 8568:     my $changed;
 8569:     if ($newuser) {
 8570:         $changed = 1;
 8571:     } else {
 8572:         foreach my $field (@fields) {
 8573:             if ($names{$field} ne $oldnames{$field}) {
 8574:                 $changed = 1;
 8575:                 last;
 8576:             }
 8577:         }
 8578:     }
 8579:     unless ($changed) {
 8580:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 8581:         &logthis($logmsg);
 8582:         return 'ok';
 8583:     }
 8584:     my $reply = &put('environment', \%names, $udom,$uname);
 8585:     if ($reply ne 'ok') { 
 8586:         return 'error: '.$reply;
 8587:     }
 8588:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
 8589:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
 8590:     }
 8591:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 8592:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 8593:     $logmsg = 'Success modifying user '.$logmsg;
 8594:     &logthis($logmsg);
 8595:     return 'ok';
 8596: }
 8597: 
 8598: # -------------------------------------------------------------- Modify student
 8599: 
 8600: sub modifystudent {
 8601:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 8602:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 8603:         $selfenroll,$context,$inststatus,$credits)=@_;
 8604:     if (!$cid) {
 8605: 	unless ($cid=$env{'request.course.id'}) {
 8606: 	    return 'not_in_class';
 8607: 	}
 8608:     }
 8609: # --------------------------------------------------------------- Make the user
 8610:     my $reply=&modifyuser
 8611: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 8612:          $desiredhome,$email,$inststatus);
 8613:     unless ($reply eq 'ok') { return $reply; }
 8614:     # This will cause &modify_student_enrollment to get the uid from the
 8615:     # student's environment
 8616:     $uid = undef if (!$forceid);
 8617:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 8618:                                         $gene,$usec,$end,$start,$type,$locktype,
 8619:                                         $cid,$selfenroll,$context,$credits);
 8620:     return $reply;
 8621: }
 8622: 
 8623: sub modify_student_enrollment {
 8624:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
 8625:         $locktype,$cid,$selfenroll,$context,$credits) = @_;
 8626:     my ($cdom,$cnum,$chome);
 8627:     if (!$cid) {
 8628: 	unless ($cid=$env{'request.course.id'}) {
 8629: 	    return 'not_in_class';
 8630: 	}
 8631: 	$cdom=$env{'course.'.$cid.'.domain'};
 8632: 	$cnum=$env{'course.'.$cid.'.num'};
 8633:     } else {
 8634: 	($cdom,$cnum)=split(/_/,$cid);
 8635:     }
 8636:     $chome=$env{'course.'.$cid.'.home'};
 8637:     if (!$chome) {
 8638: 	$chome=&homeserver($cnum,$cdom);
 8639:     }
 8640:     if (!$chome) { return 'unknown_course'; }
 8641:     # Make sure the user exists
 8642:     my $uhome=&homeserver($uname,$udom);
 8643:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8644: 	return 'error: no such user';
 8645:     }
 8646:     # Get student data if we were not given enough information
 8647:     if (!defined($first)  || $first  eq '' || 
 8648:         !defined($last)   || $last   eq '' || 
 8649:         !defined($uid)    || $uid    eq '' || 
 8650:         !defined($middle) || $middle eq '' || 
 8651:         !defined($gene)   || $gene   eq '') {
 8652:         # They did not supply us with enough data to enroll the student, so
 8653:         # we need to pick up more information.
 8654:         my %tmp = &get('environment',
 8655:                        ['firstname','middlename','lastname', 'generation','id']
 8656:                        ,$udom,$uname);
 8657: 
 8658:         #foreach my $key (keys(%tmp)) {
 8659:         #    &logthis("key $key = ".$tmp{$key});
 8660:         #}
 8661:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 8662:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 8663:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 8664:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 8665:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 8666:     }
 8667:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 8668:     my $user = "$uname:$udom";
 8669:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
 8670:     my $reply=cput('classlist',
 8671: 		   {$user => 
 8672: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
 8673: 		   $cdom,$cnum);
 8674:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
 8675:         &devalidate_getsection_cache($udom,$uname,$cid);
 8676:     } else { 
 8677: 	return 'error: '.$reply;
 8678:     }
 8679:     # Add student role to user
 8680:     my $uurl='/'.$cid;
 8681:     $uurl=~s/\_/\//g;
 8682:     if ($usec) {
 8683: 	$uurl.='/'.$usec;
 8684:     }
 8685:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
 8686:                              $selfenroll,$context);
 8687:     if ($result ne 'ok') {
 8688:         if ($old_entry{$user} ne '') {
 8689:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
 8690:         } else {
 8691:             $reply = &del('classlist',[$user],$cdom,$cnum);
 8692:         }
 8693:     }
 8694:     return $result; 
 8695: }
 8696: 
 8697: sub format_name {
 8698:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 8699:     my $name;
 8700:     if ($first ne 'lastname') {
 8701: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 8702:     } else {
 8703: 	if ($lastname=~/\S/) {
 8704: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 8705: 	    $name=~s/\s+,/,/;
 8706: 	} else {
 8707: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 8708: 	}
 8709:     }
 8710:     $name=~s/^\s+//;
 8711:     $name=~s/\s+$//;
 8712:     $name=~s/\s+/ /g;
 8713:     return $name;
 8714: }
 8715: 
 8716: # ------------------------------------------------- Write to course preferences
 8717: 
 8718: sub writecoursepref {
 8719:     my ($courseid,%prefs)=@_;
 8720:     $courseid=~s/^\///;
 8721:     $courseid=~s/\_/\//g;
 8722:     my ($cdomain,$cnum)=split(/\//,$courseid);
 8723:     my $chome=homeserver($cnum,$cdomain);
 8724:     if (($chome eq '') || ($chome eq 'no_host')) { 
 8725: 	return 'error: no such course';
 8726:     }
 8727:     my $cstring='';
 8728:     foreach my $pref (keys(%prefs)) {
 8729: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 8730:     }
 8731:     $cstring=~s/\&$//;
 8732:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 8733: }
 8734: 
 8735: # ---------------------------------------------------------- Make/modify course
 8736: 
 8737: sub createcourse {
 8738:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 8739:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 8740:     $url=&declutter($url);
 8741:     my $cid='';
 8742:     if ($context eq 'requestcourses') {
 8743:         my $can_create = 0;
 8744:         my ($ownername,$ownerdom) = split(':',$course_owner);
 8745:         if ($udom eq $ownerdom) {
 8746:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 8747:                                   $context)) {
 8748:                 $can_create = 1;
 8749:             }
 8750:         } else {
 8751:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 8752:                                            $category);
 8753:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 8754:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 8755:                 if (@curr > 0) {
 8756:                     my @options = qw(approval validate autolimit);
 8757:                     my $optregex = join('|',@options);
 8758:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 8759:                         $can_create = 1;
 8760:                     }
 8761:                 }
 8762:             }
 8763:         }
 8764:         if ($can_create) {
 8765:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 8766:                 unless (&allowed('ccc',$udom)) {
 8767:                     return 'refused'; 
 8768:                 }
 8769:             }
 8770:         } else {
 8771:             return 'refused';
 8772:         }
 8773:     } elsif (!&allowed('ccc',$udom)) {
 8774:         return 'refused';
 8775:     }
 8776: # --------------------------------------------------------------- Get Unique ID
 8777:     my $uname;
 8778:     if ($cnum =~ /^$match_courseid$/) {
 8779:         my $chome=&homeserver($cnum,$udom,'true');
 8780:         if (($chome eq '') || ($chome eq 'no_host')) {
 8781:             $uname = $cnum;
 8782:         } else {
 8783:             $uname = &generate_coursenum($udom,$crstype);
 8784:         }
 8785:     } else {
 8786:         $uname = &generate_coursenum($udom,$crstype);
 8787:     }
 8788:     return $uname if ($uname =~ /^error/);
 8789: # -------------------------------------------------- Check supplied server name
 8790:     if (!defined($course_server)) {
 8791:         if (defined(&domain($udom,'primary'))) {
 8792:             $course_server = &domain($udom,'primary');
 8793:         } else {
 8794:             $course_server = $env{'user.home'}; 
 8795:         }
 8796:     }
 8797:     my %host_servers =
 8798:         &Apache::lonnet::get_servers($udom,'library');
 8799:     unless ($host_servers{$course_server}) {
 8800:         return 'error: invalid home server for course: '.$course_server;
 8801:     }
 8802: # ------------------------------------------------------------- Make the course
 8803:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 8804:                       $course_server);
 8805:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 8806:     my $uhome=&homeserver($uname,$udom,'true');
 8807:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8808: 	return 'error: no such course';
 8809:     }
 8810: # ----------------------------------------------------------------- Course made
 8811: # log existence
 8812:     my $now = time;
 8813:     my $newcourse = {
 8814:                     $udom.'_'.$uname => {
 8815:                                      description => $description,
 8816:                                      inst_code   => $inst_code,
 8817:                                      owner       => $course_owner,
 8818:                                      type        => $crstype,
 8819:                                      creator     => $env{'user.name'}.':'.
 8820:                                                     $env{'user.domain'},
 8821:                                      created     => $now,
 8822:                                      context     => $context,
 8823:                                                 },
 8824:                     };
 8825:     &courseidput($udom,$newcourse,$uhome,'notime');
 8826: # set toplevel url
 8827:     my $topurl=$url;
 8828:     unless ($nonstandard) {
 8829: # ------------------------------------------ For standard courses, make top url
 8830:         my $mapurl=&clutter($url);
 8831:         if ($mapurl eq '/res/') { $mapurl=''; }
 8832:         $env{'form.initmap'}=(<<ENDINITMAP);
 8833: <map>
 8834: <resource id="1" type="start"></resource>
 8835: <resource id="2" src="$mapurl"></resource>
 8836: <resource id="3" type="finish"></resource>
 8837: <link index="1" from="1" to="2"></link>
 8838: <link index="2" from="2" to="3"></link>
 8839: </map>
 8840: ENDINITMAP
 8841:         $topurl=&declutter(
 8842:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 8843:                           );
 8844:     }
 8845: # ----------------------------------------------------------- Write preferences
 8846:     &writecoursepref($udom.'_'.$uname,
 8847:                      ('description'              => $description,
 8848:                       'url'                      => $topurl,
 8849:                       'internal.creator'         => $env{'user.name'}.':'.
 8850:                                                     $env{'user.domain'},
 8851:                       'internal.created'         => $now,
 8852:                       'internal.creationcontext' => $context)
 8853:                     );
 8854:     return '/'.$udom.'/'.$uname;
 8855: }
 8856: 
 8857: # ------------------------------------------------------------------- Create ID
 8858: sub generate_coursenum {
 8859:     my ($udom,$crstype) = @_;
 8860:     my $domdesc = &domain($udom);
 8861:     return 'error: invalid domain' if ($domdesc eq '');
 8862:     my $first;
 8863:     if ($crstype eq 'Community') {
 8864:         $first = '0';
 8865:     } else {
 8866:         $first = int(1+rand(9)); 
 8867:     } 
 8868:     my $uname=$first.
 8869:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8870:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8871:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8872: # ----------------------------------------------- Make sure that does not exist
 8873:     my $uhome=&homeserver($uname,$udom,'true');
 8874:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8875:         if ($crstype eq 'Community') {
 8876:             $first = '0';
 8877:         } else {
 8878:             $first = int(1+rand(9));
 8879:         }
 8880:         $uname=$first.
 8881:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8882:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8883:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8884:         $uhome=&homeserver($uname,$udom,'true');
 8885:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8886:             return 'error: unable to generate unique course-ID';
 8887:         }
 8888:     }
 8889:     return $uname;
 8890: }
 8891: 
 8892: sub is_course {
 8893:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
 8894:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
 8895: 
 8896:     return unless $cdom and $cnum;
 8897: 
 8898:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
 8899:         '.');
 8900: 
 8901:     return unless(exists($courses{$cdom.'_'.$cnum}));
 8902:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
 8903: }
 8904: 
 8905: sub store_userdata {
 8906:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
 8907:     my $result;
 8908:     if ($datakey ne '') {
 8909:         if (ref($storehash) eq 'HASH') {
 8910:             if ($udom eq '' || $uname eq '') {
 8911:                 $udom = $env{'user.domain'};
 8912:                 $uname = $env{'user.name'};
 8913:             }
 8914:             my $uhome=&homeserver($uname,$udom);
 8915:             if (($uhome eq '') || ($uhome eq 'no_host')) {
 8916:                 $result = 'error: no_host';
 8917:             } else {
 8918:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
 8919:                 $storehash->{'host'} = $perlvar{'lonHostID'};
 8920: 
 8921:                 my $namevalue='';
 8922:                 foreach my $key (keys(%{$storehash})) {
 8923:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 8924:                 }
 8925:                 $namevalue=~s/\&$//;
 8926:                 unless ($namespace eq 'courserequests') {
 8927:                     $datakey = &escape($datakey);
 8928:                 }
 8929:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
 8930:                                   $namevalue,$uhome);
 8931:             }
 8932:         } else {
 8933:             $result = 'error: data to store was not a hash reference'; 
 8934:         }
 8935:     } else {
 8936:         $result= 'error: invalid requestkey'; 
 8937:     }
 8938:     return $result;
 8939: }
 8940: 
 8941: # ---------------------------------------------------------- Assign Custom Role
 8942: 
 8943: sub assigncustomrole {
 8944:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 8945:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 8946:                        $end,$start,$deleteflag,$selfenroll,$context);
 8947: }
 8948: 
 8949: # ----------------------------------------------------------------- Revoke Role
 8950: 
 8951: sub revokerole {
 8952:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 8953:     my $now=time;
 8954:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 8955: }
 8956: 
 8957: # ---------------------------------------------------------- Revoke Custom Role
 8958: 
 8959: sub revokecustomrole {
 8960:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 8961:     my $now=time;
 8962:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 8963:            $deleteflag,$selfenroll,$context);
 8964: }
 8965: 
 8966: # ------------------------------------------------------------ Disk usage
 8967: sub diskusage {
 8968:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 8969:     $directorypath =~ s/\/$//;
 8970:     my $listing=&reply('du2:'.&escape($directorypath).':'
 8971:                        .&escape($getpropath).':'.&escape($uname).':'
 8972:                        .&escape($udom),homeserver($uname,$udom));
 8973:     if ($listing eq 'unknown_cmd') {
 8974:         if ($getpropath) {
 8975:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 8976:         }
 8977:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 8978:     }
 8979:     return $listing;
 8980: }
 8981: 
 8982: sub is_locked {
 8983:     my ($file_name, $domain, $user, $which) = @_;
 8984:     my @check;
 8985:     my $is_locked;
 8986:     push (@check,$file_name);
 8987:     my %locked = &get('file_permissions',\@check,
 8988: 		      $env{'user.domain'},$env{'user.name'});
 8989:     my ($tmp)=keys(%locked);
 8990:     if ($tmp=~/^error:/) { undef(%locked); }
 8991:     
 8992:     if (ref($locked{$file_name}) eq 'ARRAY') {
 8993:         $is_locked = 'false';
 8994:         foreach my $entry (@{$locked{$file_name}}) {
 8995:            if (ref($entry) eq 'ARRAY') {
 8996:                $is_locked = 'true';
 8997:                if (ref($which) eq 'ARRAY') {
 8998:                    push(@{$which},$entry);
 8999:                } else {
 9000:                    last;
 9001:                }
 9002:            }
 9003:        }
 9004:     } else {
 9005:         $is_locked = 'false';
 9006:     }
 9007:     return $is_locked;
 9008: }
 9009: 
 9010: sub declutter_portfile {
 9011:     my ($file) = @_;
 9012:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 9013:     return $file;
 9014: }
 9015: 
 9016: # ------------------------------------------------------------- Mark as Read Only
 9017: 
 9018: sub mark_as_readonly {
 9019:     my ($domain,$user,$files,$what) = @_;
 9020:     my %current_permissions = &dump('file_permissions',$domain,$user);
 9021:     my ($tmp)=keys(%current_permissions);
 9022:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9023:     foreach my $file (@{$files}) {
 9024: 	$file = &declutter_portfile($file);
 9025:         push(@{$current_permissions{$file}},$what);
 9026:     }
 9027:     &put('file_permissions',\%current_permissions,$domain,$user);
 9028:     return;
 9029: }
 9030: 
 9031: # ------------------------------------------------------------Save Selected Files
 9032: 
 9033: sub save_selected_files {
 9034:     my ($user, $path, @files) = @_;
 9035:     my $filename = $user."savedfiles";
 9036:     my @other_files = &files_not_in_path($user, $path);
 9037:     open (OUT, '>'.$tmpdir.$filename);
 9038:     foreach my $file (@files) {
 9039:         print (OUT $env{'form.currentpath'}.$file."\n");
 9040:     }
 9041:     foreach my $file (@other_files) {
 9042:         print (OUT $file."\n");
 9043:     }
 9044:     close (OUT);
 9045:     return 'ok';
 9046: }
 9047: 
 9048: sub clear_selected_files {
 9049:     my ($user) = @_;
 9050:     my $filename = $user."savedfiles";
 9051:     open (OUT, '>'.LONCAPA::tempdir().$filename);
 9052:     print (OUT undef);
 9053:     close (OUT);
 9054:     return ("ok");    
 9055: }
 9056: 
 9057: sub files_in_path {
 9058:     my ($user, $path) = @_;
 9059:     my $filename = $user."savedfiles";
 9060:     my %return_files;
 9061:     open (IN, '<'.LONCAPA::tempdir().$filename);
 9062:     while (my $line_in = <IN>) {
 9063:         chomp ($line_in);
 9064:         my @paths_and_file = split (m!/!, $line_in);
 9065:         my $file_part = pop (@paths_and_file);
 9066:         my $path_part = join ('/', @paths_and_file);
 9067:         $path_part.='/';
 9068:         my $path_and_file = $path_part.$file_part;
 9069:         if ($path_part eq $path) {
 9070:             $return_files{$file_part}= 'selected';
 9071:         }
 9072:     }
 9073:     close (IN);
 9074:     return (\%return_files);
 9075: }
 9076: 
 9077: # called in portfolio select mode, to show files selected NOT in current directory
 9078: sub files_not_in_path {
 9079:     my ($user, $path) = @_;
 9080:     my $filename = $user."savedfiles";
 9081:     my @return_files;
 9082:     my $path_part;
 9083:     open(IN, '<'.LONCAPA::.$filename);
 9084:     while (my $line = <IN>) {
 9085:         #ok, I know it's clunky, but I want it to work
 9086:         my @paths_and_file = split(m|/|, $line);
 9087:         my $file_part = pop(@paths_and_file);
 9088:         chomp($file_part);
 9089:         my $path_part = join('/', @paths_and_file);
 9090:         $path_part .= '/';
 9091:         my $path_and_file = $path_part.$file_part;
 9092:         if ($path_part ne $path) {
 9093:             push(@return_files, ($path_and_file));
 9094:         }
 9095:     }
 9096:     close(OUT);
 9097:     return (@return_files);
 9098: }
 9099: 
 9100: #----------------------------------------------Get portfolio file permissions
 9101: 
 9102: sub get_portfile_permissions {
 9103:     my ($domain,$user) = @_;
 9104:     my %current_permissions = &dump('file_permissions',$domain,$user);
 9105:     my ($tmp)=keys(%current_permissions);
 9106:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9107:     return \%current_permissions;
 9108: }
 9109: 
 9110: #---------------------------------------------Get portfolio file access controls
 9111: 
 9112: sub get_access_controls {
 9113:     my ($current_permissions,$group,$file) = @_;
 9114:     my %access;
 9115:     my $real_file = $file;
 9116:     $file =~ s/\.meta$//;
 9117:     if (defined($file)) {
 9118:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 9119:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 9120:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 9121:             }
 9122:         }
 9123:     } else {
 9124:         foreach my $key (keys(%{$current_permissions})) {
 9125:             if ($key =~ /\0accesscontrol$/) {
 9126:                 if (defined($group)) {
 9127:                     if ($key !~ m-^\Q$group\E/-) {
 9128:                         next;
 9129:                     }
 9130:                 }
 9131:                 my ($fullpath) = split(/\0/,$key);
 9132:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 9133:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 9134:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 9135:                     }
 9136:                 }
 9137:             }
 9138:         }
 9139:     }
 9140:     return %access;
 9141: }
 9142: 
 9143: sub modify_access_controls {
 9144:     my ($file_name,$changes,$domain,$user)=@_;
 9145:     my ($outcome,$deloutcome);
 9146:     my %store_permissions;
 9147:     my %new_values;
 9148:     my %new_control;
 9149:     my %translation;
 9150:     my @deletions = ();
 9151:     my $now = time;
 9152:     if (exists($$changes{'activate'})) {
 9153:         if (ref($$changes{'activate'}) eq 'HASH') {
 9154:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 9155:             my $numnew = scalar(@newitems);
 9156:             for (my $i=0; $i<$numnew; $i++) {
 9157:                 my $newkey = $newitems[$i];
 9158:                 my $newid = &Apache::loncommon::get_cgi_id();
 9159:                 if ($newkey =~ /^\d+:/) { 
 9160:                     $newkey =~ s/^(\d+)/$newid/;
 9161:                     $translation{$1} = $newid;
 9162:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 9163:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 9164:                     $translation{$1} = $newid;
 9165:                 }
 9166:                 $new_values{$file_name."\0".$newkey} = 
 9167:                                           $$changes{'activate'}{$newitems[$i]};
 9168:                 $new_control{$newkey} = $now;
 9169:             }
 9170:         }
 9171:     }
 9172:     my %todelete;
 9173:     my %changed_items;
 9174:     foreach my $action ('delete','update') {
 9175:         if (exists($$changes{$action})) {
 9176:             if (ref($$changes{$action}) eq 'HASH') {
 9177:                 foreach my $key (keys(%{$$changes{$action}})) {
 9178:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 9179:                     if ($action eq 'delete') { 
 9180:                         $todelete{$itemnum} = 1;
 9181:                     } else {
 9182:                         $changed_items{$itemnum} = $key;
 9183:                     }
 9184:                 }
 9185:             }
 9186:         }
 9187:     }
 9188:     # get lock on access controls for file.
 9189:     my $lockhash = {
 9190:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 9191:                                                        ':'.$env{'user.domain'},
 9192:                    }; 
 9193:     my $tries = 0;
 9194:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 9195:    
 9196:     while (($gotlock ne 'ok') && $tries <3) {
 9197:         $tries ++;
 9198:         sleep 1;
 9199:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 9200:     }
 9201:     if ($gotlock eq 'ok') {
 9202:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 9203:         my ($tmp)=keys(%curr_permissions);
 9204:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 9205:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 9206:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 9207:             if (ref($curr_controls) eq 'HASH') {
 9208:                 foreach my $control_item (keys(%{$curr_controls})) {
 9209:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 9210:                     if (defined($todelete{$itemnum})) {
 9211:                         push(@deletions,$file_name."\0".$control_item);
 9212:                     } else {
 9213:                         if (defined($changed_items{$itemnum})) {
 9214:                             $new_control{$changed_items{$itemnum}} = $now;
 9215:                             push(@deletions,$file_name."\0".$control_item);
 9216:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 9217:                         } else {
 9218:                             $new_control{$control_item} = $$curr_controls{$control_item};
 9219:                         }
 9220:                     }
 9221:                 }
 9222:             }
 9223:         }
 9224:         my ($group);
 9225:         if (&is_course($domain,$user)) {
 9226:             ($group,my $file) = split(/\//,$file_name,2);
 9227:         }
 9228:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 9229:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 9230:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 9231:         #  remove lock
 9232:         my @del_lock = ($file_name."\0".'locked_access_records');
 9233:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 9234:         my $sqlresult =
 9235:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 9236:                                     $group);
 9237:     } else {
 9238:         $outcome = "error: could not obtain lockfile\n";  
 9239:     }
 9240:     return ($outcome,$deloutcome,\%new_values,\%translation);
 9241: }
 9242: 
 9243: sub make_public_indefinitely {
 9244:     my ($requrl) = @_;
 9245:     my $now = time;
 9246:     my $action = 'activate';
 9247:     my $aclnum = 0;
 9248:     if (&is_portfolio_url($requrl)) {
 9249:         my (undef,$udom,$unum,$file_name,$group) =
 9250:             &parse_portfolio_url($requrl);
 9251:         my $current_perms = &get_portfile_permissions($udom,$unum);
 9252:         my %access_controls = &get_access_controls($current_perms,
 9253:                                                    $group,$file_name);
 9254:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 9255:             my ($num,$scope,$end,$start) = 
 9256:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 9257:             if ($scope eq 'public') {
 9258:                 if ($start <= $now && $end == 0) {
 9259:                     $action = 'none';
 9260:                 } else {
 9261:                     $action = 'update';
 9262:                     $aclnum = $num;
 9263:                 }
 9264:                 last;
 9265:             }
 9266:         }
 9267:         if ($action eq 'none') {
 9268:              return 'ok';
 9269:         } else {
 9270:             my %changes;
 9271:             my $newend = 0;
 9272:             my $newstart = $now;
 9273:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 9274:             $changes{$action}{$newkey} = {
 9275:                 type => 'public',
 9276:                 time => {
 9277:                     start => $newstart,
 9278:                     end   => $newend,
 9279:                 },
 9280:             };
 9281:             my ($outcome,$deloutcome,$new_values,$translation) =
 9282:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 9283:             return $outcome;
 9284:         }
 9285:     } else {
 9286:         return 'invalid';
 9287:     }
 9288: }
 9289: 
 9290: #------------------------------------------------------Get Marked as Read Only
 9291: 
 9292: sub get_marked_as_readonly {
 9293:     my ($domain,$user,$what,$group) = @_;
 9294:     my $current_permissions = &get_portfile_permissions($domain,$user);
 9295:     my @readonly_files;
 9296:     my $cmp1=$what;
 9297:     if (ref($what)) { $cmp1=join('',@{$what}) };
 9298:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 9299:         if (defined($group)) {
 9300:             if ($file_name !~ m-^\Q$group\E/-) {
 9301:                 next;
 9302:             }
 9303:         }
 9304:         if (ref($value) eq "ARRAY"){
 9305:             foreach my $stored_what (@{$value}) {
 9306:                 my $cmp2=$stored_what;
 9307:                 if (ref($stored_what) eq 'ARRAY') {
 9308:                     $cmp2=join('',@{$stored_what});
 9309:                 }
 9310:                 if ($cmp1 eq $cmp2) {
 9311:                     push(@readonly_files, $file_name);
 9312:                     last;
 9313:                 } elsif (!defined($what)) {
 9314:                     push(@readonly_files, $file_name);
 9315:                     last;
 9316:                 }
 9317:             }
 9318:         }
 9319:     }
 9320:     return @readonly_files;
 9321: }
 9322: #-----------------------------------------------------------Get Marked as Read Only Hash
 9323: 
 9324: sub get_marked_as_readonly_hash {
 9325:     my ($current_permissions,$group,$what) = @_;
 9326:     my %readonly_files;
 9327:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 9328:         if (defined($group)) {
 9329:             if ($file_name !~ m-^\Q$group\E/-) {
 9330:                 next;
 9331:             }
 9332:         }
 9333:         if (ref($value) eq "ARRAY"){
 9334:             foreach my $stored_what (@{$value}) {
 9335:                 if (ref($stored_what) eq 'ARRAY') {
 9336:                     foreach my $lock_descriptor(@{$stored_what}) {
 9337:                         if ($lock_descriptor eq 'graded') {
 9338:                             $readonly_files{$file_name} = 'graded';
 9339:                         } elsif ($lock_descriptor eq 'handback') {
 9340:                             $readonly_files{$file_name} = 'handback';
 9341:                         } else {
 9342:                             if (!exists($readonly_files{$file_name})) {
 9343:                                 $readonly_files{$file_name} = 'locked';
 9344:                             }
 9345:                         }
 9346:                     }
 9347:                 } 
 9348:             }
 9349:         } 
 9350:     }
 9351:     return %readonly_files;
 9352: }
 9353: # ------------------------------------------------------------ Unmark as Read Only
 9354: 
 9355: sub unmark_as_readonly {
 9356:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 9357:     # for portfolio submissions, $what contains [$symb,$crsid] 
 9358:     my ($domain,$user,$what,$file_name,$group) = @_;
 9359:     $file_name = &declutter_portfile($file_name);
 9360:     my $symb_crs = $what;
 9361:     if (ref($what)) { $symb_crs=join('',@$what); }
 9362:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 9363:     my ($tmp)=keys(%current_permissions);
 9364:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9365:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 9366:     foreach my $file (@readonly_files) {
 9367: 	my $clean_file = &declutter_portfile($file);
 9368: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 9369: 	my $current_locks = $current_permissions{$file};
 9370:         my @new_locks;
 9371:         my @del_keys;
 9372:         if (ref($current_locks) eq "ARRAY"){
 9373:             foreach my $locker (@{$current_locks}) {
 9374:                 my $compare=$locker;
 9375:                 if (ref($locker) eq 'ARRAY') {
 9376:                     $compare=join('',@{$locker});
 9377:                     if ($compare ne $symb_crs) {
 9378:                         push(@new_locks, $locker);
 9379:                     }
 9380:                 }
 9381:             }
 9382:             if (scalar(@new_locks) > 0) {
 9383:                 $current_permissions{$file} = \@new_locks;
 9384:             } else {
 9385:                 push(@del_keys, $file);
 9386:                 &del('file_permissions',\@del_keys, $domain, $user);
 9387:                 delete($current_permissions{$file});
 9388:             }
 9389:         }
 9390:     }
 9391:     &put('file_permissions',\%current_permissions,$domain,$user);
 9392:     return;
 9393: }
 9394: 
 9395: # ------------------------------------------------------------ Directory lister
 9396: 
 9397: sub dirlist {
 9398:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 9399:     $uri=~s/^\///;
 9400:     $uri=~s/\/$//;
 9401:     my ($udom, $uname);
 9402:     if ($getuserdir) {
 9403:         $udom = $userdomain;
 9404:         $uname = $username;
 9405:     } else {
 9406:         (undef,$udom,$uname)=split(/\//,$uri);
 9407:         if(defined($userdomain)) {
 9408:             $udom = $userdomain;
 9409:         }
 9410:         if(defined($username)) {
 9411:             $uname = $username;
 9412:         }
 9413:     }
 9414:     my ($dirRoot,$listing,@listing_results);
 9415: 
 9416:     $dirRoot = $perlvar{'lonDocRoot'};
 9417:     if (defined($getpropath)) {
 9418:         $dirRoot = &propath($udom,$uname);
 9419:         $dirRoot =~ s/\/$//;
 9420:     } elsif (defined($getuserdir)) {
 9421:         my $subdir=$uname.'__';
 9422:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 9423:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 9424:                    ."/$udom/$subdir/$uname";
 9425:     } elsif (defined($alternateRoot)) {
 9426:         $dirRoot = $alternateRoot;
 9427:     }
 9428: 
 9429:     if($udom) {
 9430:         if($uname) {
 9431:             my $uhome = &homeserver($uname,$udom);
 9432:             if ($uhome eq 'no_host') {
 9433:                 return ([],'no_host');
 9434:             }
 9435:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 9436:                               .$getuserdir.':'.&escape($dirRoot)
 9437:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
 9438:             if ($listing eq 'unknown_cmd') {
 9439:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
 9440:             } else {
 9441:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 9442:             }
 9443:             if ($listing eq 'unknown_cmd') {
 9444:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
 9445:                 @listing_results = split(/:/,$listing);
 9446:             } else {
 9447:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 9448:             }
 9449:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
 9450:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
 9451:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 9452:                 return ([],$listing);
 9453:             } else {
 9454:                 return (\@listing_results);
 9455:             }
 9456:         } elsif(!$alternateRoot) {
 9457:             my (%allusers,%listerror);
 9458: 	    my %servers = &get_servers($udom,'library');
 9459:  	    foreach my $tryserver (keys(%servers)) {
 9460:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 9461:                                   &escape($udom),$tryserver);
 9462:                 if ($listing eq 'unknown_cmd') {
 9463: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 9464: 				      $udom, $tryserver);
 9465:                 } else {
 9466:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 9467:                 }
 9468: 		if ($listing eq 'unknown_cmd') {
 9469: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 9470: 				      $udom, $tryserver);
 9471: 		    @listing_results = split(/:/,$listing);
 9472: 		} else {
 9473: 		    @listing_results =
 9474: 			map { &unescape($_); } split(/:/,$listing);
 9475: 		}
 9476:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
 9477:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
 9478:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 9479:                     $listerror{$tryserver} = $listing;
 9480:                 } else {
 9481: 		    foreach my $line (@listing_results) {
 9482: 			my ($entry) = split(/&/,$line,2);
 9483: 			$allusers{$entry} = 1;
 9484: 		    }
 9485: 		}
 9486:             }
 9487:             my @alluserslist=();
 9488:             foreach my $user (sort(keys(%allusers))) {
 9489:                 push(@alluserslist,$user.'&user');
 9490:             }
 9491:             return (\@alluserslist);
 9492:         } else {
 9493:             return ([],'missing username');
 9494:         }
 9495:     } elsif(!defined($getpropath)) {
 9496:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
 9497:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
 9498:         return (\@all_domains);
 9499:     } else {
 9500:         return ([],'missing domain');
 9501:     }
 9502: }
 9503: 
 9504: # --------------------------------------------- GetFileTimestamp
 9505: # This function utilizes dirlist and returns the date stamp for
 9506: # when it was last modified.  It will also return an error of -1
 9507: # if an error occurs
 9508: 
 9509: sub GetFileTimestamp {
 9510:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 9511:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 9512:     $studentName   = &LONCAPA::clean_username($studentName);
 9513:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
 9514:                                     undef,$getuserdir);
 9515:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 9516:         return -1;
 9517:     }
 9518:     if (ref($fileref) eq 'ARRAY') {
 9519:         my @stats = split('&',$fileref->[0]);
 9520:         # @stats contains first the filename, then the stat output
 9521:         return $stats[10]; # so this is 10 instead of 9.
 9522:     } else {
 9523:         return -1;
 9524:     }
 9525: }
 9526: 
 9527: sub stat_file {
 9528:     my ($uri) = @_;
 9529:     $uri = &clutter_with_no_wrapper($uri);
 9530: 
 9531:     my ($udom,$uname,$file);
 9532:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 9533: 	($udom,$uname,$file) =
 9534: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 9535: 	$file = 'userfiles/'.$file;
 9536:     }
 9537:     if ($uri =~ m-^/res/-) {
 9538: 	($udom,$uname) = 
 9539: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 9540: 	$file = $uri;
 9541:     }
 9542: 
 9543:     if (!$udom || !$uname || !$file) {
 9544: 	# unable to handle the uri
 9545: 	return ();
 9546:     }
 9547:     my $getpropath;
 9548:     if ($file =~ /^userfiles\//) {
 9549:         $getpropath = 1;
 9550:     }
 9551:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
 9552:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 9553:         return ();
 9554:     } else {
 9555:         if (ref($listref) eq 'ARRAY') {
 9556:             my @stats = split('&',$listref->[0]);
 9557: 	    shift(@stats); #filename is first
 9558: 	    return @stats;
 9559:         }
 9560:     }
 9561:     return ();
 9562: }
 9563: 
 9564: # -------------------------------------------------------- Value of a Condition
 9565: 
 9566: # gets the value of a specific preevaluated condition
 9567: #    stored in the string  $env{user.state.<cid>}
 9568: # or looks up a condition reference in the bighash and if if hasn't
 9569: # already been evaluated recurses into docondval to get the value of
 9570: # the condition, then memoizing it to 
 9571: #   $env{user.state.<cid>.<condition>}
 9572: sub directcondval {
 9573:     my $number=shift;
 9574:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 9575: 	&Apache::lonuserstate::evalstate();
 9576:     }
 9577:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 9578: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 9579:     } elsif ($number =~ /^_/) {
 9580: 	my $sub_condition;
 9581: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9582: 		&GDBM_READER(),0640)) {
 9583: 	    $sub_condition=$bighash{'conditions'.$number};
 9584: 	    untie(%bighash);
 9585: 	}
 9586: 	my $value = &docondval($sub_condition);
 9587: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 9588: 	return $value;
 9589:     }
 9590:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 9591:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 9592:     } else {
 9593:        return 2;
 9594:     }
 9595: }
 9596: 
 9597: # get the collection of conditions for this resource
 9598: sub condval {
 9599:     my $condidx=shift;
 9600:     my $allpathcond='';
 9601:     foreach my $cond (split(/\|/,$condidx)) {
 9602: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 9603: 	    $allpathcond.=
 9604: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 9605: 	}
 9606:     }
 9607:     $allpathcond=~s/\|$//;
 9608:     return &docondval($allpathcond);
 9609: }
 9610: 
 9611: #evaluates an expression of conditions
 9612: sub docondval {
 9613:     my ($allpathcond) = @_;
 9614:     my $result=0;
 9615:     if ($env{'request.course.id'}
 9616: 	&& defined($allpathcond)) {
 9617: 	my $operand='|';
 9618: 	my @stack;
 9619: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 9620: 	    if ($chunk eq '(') {
 9621: 		push @stack,($operand,$result);
 9622: 	    } elsif ($chunk eq ')') {
 9623: 		my $before=pop @stack;
 9624: 		if (pop @stack eq '&') {
 9625: 		    $result=$result>$before?$before:$result;
 9626: 		} else {
 9627: 		    $result=$result>$before?$result:$before;
 9628: 		}
 9629: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 9630: 		$operand=$chunk;
 9631: 	    } else {
 9632: 		my $new=directcondval($chunk);
 9633: 		if ($operand eq '&') {
 9634: 		    $result=$result>$new?$new:$result;
 9635: 		} else {
 9636: 		    $result=$result>$new?$result:$new;
 9637: 		}
 9638: 	    }
 9639: 	}
 9640:     }
 9641:     return $result;
 9642: }
 9643: 
 9644: # ---------------------------------------------------- Devalidate courseresdata
 9645: 
 9646: sub devalidatecourseresdata {
 9647:     my ($coursenum,$coursedomain)=@_;
 9648:     my $hashid=$coursenum.':'.$coursedomain;
 9649:     &devalidate_cache_new('courseres',$hashid);
 9650: }
 9651: 
 9652: 
 9653: # --------------------------------------------------- Course Resourcedata Query
 9654: #
 9655: #  Parameters:
 9656: #      $coursenum    - Number of the course.
 9657: #      $coursedomain - Domain at which the course was created.
 9658: #  Returns:
 9659: #     A hash of the course parameters along (I think) with timestamps
 9660: #     and version info.
 9661: 
 9662: sub get_courseresdata {
 9663:     my ($coursenum,$coursedomain)=@_;
 9664:     my $coursehom=&homeserver($coursenum,$coursedomain);
 9665:     my $hashid=$coursenum.':'.$coursedomain;
 9666:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 9667:     my %dumpreply;
 9668:     unless (defined($cached)) {
 9669: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 9670: 	$result=\%dumpreply;
 9671: 	my ($tmp) = keys(%dumpreply);
 9672: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9673: 	    &do_cache_new('courseres',$hashid,$result,600);
 9674: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 9675: 	    return $tmp;
 9676: 	} elsif ($tmp =~ /^(error)/) {
 9677: 	    $result=undef;
 9678: 	    &do_cache_new('courseres',$hashid,$result,600);
 9679: 	}
 9680:     }
 9681:     return $result;
 9682: }
 9683: 
 9684: sub devalidateuserresdata {
 9685:     my ($uname,$udom)=@_;
 9686:     my $hashid="$udom:$uname";
 9687:     &devalidate_cache_new('userres',$hashid);
 9688: }
 9689: 
 9690: sub get_userresdata {
 9691:     my ($uname,$udom)=@_;
 9692:     #most student don\'t have any data set, check if there is some data
 9693:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 9694: 
 9695:     my $hashid="$udom:$uname";
 9696:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 9697:     if (!defined($cached)) {
 9698: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 9699: 	$result=\%resourcedata;
 9700: 	&do_cache_new('userres',$hashid,$result,600);
 9701:     }
 9702:     my ($tmp)=keys(%$result);
 9703:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 9704: 	return $result;
 9705:     }
 9706:     #error 2 occurs when the .db doesn't exist
 9707:     if ($tmp!~/error: 2 /) {
 9708: 	&logthis("<font color=\"blue\">WARNING:".
 9709: 		 " Trying to get resource data for ".
 9710: 		 $uname." at ".$udom.": ".
 9711: 		 $tmp."</font>");
 9712:     } elsif ($tmp=~/error: 2 /) {
 9713: 	#&EXT_cache_set($udom,$uname);
 9714: 	&do_cache_new('userres',$hashid,undef,600);
 9715: 	undef($tmp); # not really an error so don't send it back
 9716:     }
 9717:     return $tmp;
 9718: }
 9719: #----------------------------------------------- resdata - return resource data
 9720: #  Purpose:
 9721: #    Return resource data for either users or for a course.
 9722: #  Parameters:
 9723: #     $name      - Course/user name.
 9724: #     $domain    - Name of the domain the user/course is registered on.
 9725: #     $type      - Type of thing $name is (must be 'course' or 'user'
 9726: #     @which     - Array of names of resources desired.
 9727: #  Returns:
 9728: #     The value of the first reasource in @which that is found in the
 9729: #     resource hash.
 9730: #  Exceptional Conditions:
 9731: #     If the $type passed in is not valid (not the string 'course' or 
 9732: #     'user', an undefined  reference is returned.
 9733: #     If none of the resources are found, an undef is returned
 9734: sub resdata {
 9735:     my ($name,$domain,$type,@which)=@_;
 9736:     my $result;
 9737:     if ($type eq 'course') {
 9738: 	$result=&get_courseresdata($name,$domain);
 9739:     } elsif ($type eq 'user') {
 9740: 	$result=&get_userresdata($name,$domain);
 9741:     }
 9742:     if (!ref($result)) { return $result; }    
 9743:     foreach my $item (@which) {
 9744: 	if (defined($result->{$item->[0]})) {
 9745: 	    return [$result->{$item->[0]},$item->[1]];
 9746: 	}
 9747:     }
 9748:     return undef;
 9749: }
 9750: 
 9751: sub get_numsuppfiles {
 9752:     my ($cnum,$cdom,$ignorecache)=@_;
 9753:     my $hashid=$cnum.':'.$cdom;
 9754:     my ($suppcount,$cached);
 9755:     unless ($ignorecache) {
 9756:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
 9757:     }
 9758:     unless (defined($cached)) {
 9759:         my $chome=&homeserver($cnum,$cdom);
 9760:         unless ($chome eq 'no_host') {
 9761:             ($suppcount,my $errors) = (0,0);
 9762:             my $suppmap = 'supplemental.sequence';
 9763:             ($suppcount,$errors) = 
 9764:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
 9765:         }
 9766:         &do_cache_new('suppcount',$hashid,$suppcount,600);
 9767:     }
 9768:     return $suppcount;
 9769: }
 9770: 
 9771: #
 9772: # EXT resource caching routines
 9773: #
 9774: 
 9775: sub clear_EXT_cache_status {
 9776:     &delenv('cache.EXT.');
 9777: }
 9778: 
 9779: sub EXT_cache_status {
 9780:     my ($target_domain,$target_user) = @_;
 9781:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 9782:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 9783:         # We know already the user has no data
 9784:         return 1;
 9785:     } else {
 9786:         return 0;
 9787:     }
 9788: }
 9789: 
 9790: sub EXT_cache_set {
 9791:     my ($target_domain,$target_user) = @_;
 9792:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 9793:     #&appenv({$cachename => time});
 9794: }
 9795: 
 9796: # --------------------------------------------------------- Value of a Variable
 9797: sub EXT {
 9798: 
 9799:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
 9800:     unless ($varname) { return ''; }
 9801:     #get real user name/domain, courseid and symb
 9802:     my $courseid;
 9803:     my $publicuser;
 9804:     if ($symbparm) {
 9805: 	$symbparm=&get_symb_from_alias($symbparm);
 9806:     }
 9807:     if (!($uname && $udom)) {
 9808:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 9809:       if (!$symbparm) {	$symbparm=$cursymb; }
 9810:     } else {
 9811: 	$courseid=$env{'request.course.id'};
 9812:     }
 9813:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 9814:     my $rest;
 9815:     if (defined($therest[0])) {
 9816:        $rest=join('.',@therest);
 9817:     } else {
 9818:        $rest='';
 9819:     }
 9820: 
 9821:     my $qualifierrest=$qualifier;
 9822:     if ($rest) { $qualifierrest.='.'.$rest; }
 9823:     my $spacequalifierrest=$space;
 9824:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 9825:     if ($realm eq 'user') {
 9826: # --------------------------------------------------------------- user.resource
 9827: 	if ($space eq 'resource') {
 9828: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 9829: 		  || defined($Apache::lonhomework::parsing_a_task))
 9830: 		 &&
 9831: 		 ($symbparm eq &symbread()) ) {	
 9832: 		# if we are in the middle of processing the resource the
 9833: 		# get the value we are planning on committing
 9834:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 9835:                     return $Apache::lonhomework::results{$qualifierrest};
 9836:                 } else {
 9837:                     return $Apache::lonhomework::history{$qualifierrest};
 9838:                 }
 9839: 	    } else {
 9840: 		my %restored;
 9841: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 9842: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 9843: 		} else {
 9844: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 9845: 		}
 9846: 		return $restored{$qualifierrest};
 9847: 	    }
 9848: # ----------------------------------------------------------------- user.access
 9849:         } elsif ($space eq 'access') {
 9850: 	    # FIXME - not supporting calls for a specific user
 9851:             return &allowed($qualifier,$rest);
 9852: # ------------------------------------------ user.preferences, user.environment
 9853:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 9854: 	    if (($uname eq $env{'user.name'}) &&
 9855: 		($udom eq $env{'user.domain'})) {
 9856: 		return $env{join('.',('environment',$qualifierrest))};
 9857: 	    } else {
 9858: 		my %returnhash;
 9859: 		if (!$publicuser) {
 9860: 		    %returnhash=&userenvironment($udom,$uname,
 9861: 						 $qualifierrest);
 9862: 		}
 9863: 		return $returnhash{$qualifierrest};
 9864: 	    }
 9865: # ----------------------------------------------------------------- user.course
 9866:         } elsif ($space eq 'course') {
 9867: 	    # FIXME - not supporting calls for a specific user
 9868:             return $env{join('.',('request.course',$qualifier))};
 9869: # ------------------------------------------------------------------- user.role
 9870:         } elsif ($space eq 'role') {
 9871: 	    # FIXME - not supporting calls for a specific user
 9872:             my ($role,$where)=split(/\./,$env{'request.role'});
 9873:             if ($qualifier eq 'value') {
 9874: 		return $role;
 9875:             } elsif ($qualifier eq 'extent') {
 9876:                 return $where;
 9877:             }
 9878: # ----------------------------------------------------------------- user.domain
 9879:         } elsif ($space eq 'domain') {
 9880:             return $udom;
 9881: # ------------------------------------------------------------------- user.name
 9882:         } elsif ($space eq 'name') {
 9883:             return $uname;
 9884: # ---------------------------------------------------- Any other user namespace
 9885:         } else {
 9886: 	    my %reply;
 9887: 	    if (!$publicuser) {
 9888: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 9889: 	    }
 9890: 	    return $reply{$qualifierrest};
 9891:         }
 9892:     } elsif ($realm eq 'query') {
 9893: # ---------------------------------------------- pull stuff out of query string
 9894:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 9895: 						[$spacequalifierrest]);
 9896: 	return $env{'form.'.$spacequalifierrest}; 
 9897:    } elsif ($realm eq 'request') {
 9898: # ------------------------------------------------------------- request.browser
 9899:         if ($space eq 'browser') {
 9900:             return $env{'browser.'.$qualifier};
 9901: # ------------------------------------------------------------ request.filename
 9902:         } else {
 9903:             return $env{'request.'.$spacequalifierrest};
 9904:         }
 9905:     } elsif ($realm eq 'course') {
 9906: # ---------------------------------------------------------- course.description
 9907:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 9908:     } elsif ($realm eq 'resource') {
 9909: 
 9910: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 9911: 	    if (!$symbparm) { $symbparm=&symbread(); }
 9912: 	}
 9913: 
 9914:         if ($qualifier eq '') {
 9915: 	    if ($space eq 'title') {
 9916: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 9917: 	        return &gettitle($symbparm);
 9918: 	    }
 9919: 	
 9920: 	    if ($space eq 'map') {
 9921: 	        my ($map) = &decode_symb($symbparm);
 9922: 	        return &symbread($map);
 9923: 	    }
 9924:             if ($space eq 'maptitle') {
 9925:                 my ($map) = &decode_symb($symbparm);
 9926:                 return &gettitle($map);
 9927:             }
 9928: 	    if ($space eq 'filename') {
 9929: 	        if ($symbparm) {
 9930: 		    return &clutter((&decode_symb($symbparm))[2]);
 9931: 	        }
 9932: 	        return &hreflocation('',$env{'request.filename'});
 9933: 	    }
 9934: 
 9935:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
 9936:                 if ($space eq 'visibleparts') {
 9937:                     my $navmap = Apache::lonnavmaps::navmap->new();
 9938:                     my $item;
 9939:                     if (ref($navmap)) {
 9940:                         my $res = $navmap->getBySymb($symbparm);
 9941:                         my $parts = $res->parts();
 9942:                         if (ref($parts) eq 'ARRAY') {
 9943:                             $item = join(',',@{$parts});
 9944:                         }
 9945:                         undef($navmap);
 9946:                     }
 9947:                     return $item;
 9948:                 }
 9949:             }
 9950:         }
 9951: 
 9952: 	my ($section, $group, @groups);
 9953: 	my ($courselevelm,$courselevel);
 9954:         if (($courseid eq '') && ($cid)) {
 9955:             $courseid = $cid;
 9956:         }
 9957: 	if (($symbparm && $courseid) && 
 9958: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
 9959: 
 9960: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 9961: 
 9962: # ----------------------------------------------------- Cascading lookup scheme
 9963: 	    my $symbp=$symbparm;
 9964: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 9965: 
 9966: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 9967: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 9968: 
 9969: 	    if (($env{'user.name'} eq $uname) &&
 9970: 		($env{'user.domain'} eq $udom)) {
 9971: 		$section=$env{'request.course.sec'};
 9972:                 @groups = split(/:/,$env{'request.course.groups'});  
 9973:                 @groups=&sort_course_groups($courseid,@groups); 
 9974: 	    } else {
 9975: 		if (! defined($usection)) {
 9976: 		    $section=&getsection($udom,$uname,$courseid);
 9977: 		} else {
 9978: 		    $section = $usection;
 9979: 		}
 9980:                 @groups = &get_users_groups($udom,$uname,$courseid);
 9981: 	    }
 9982: 
 9983: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 9984: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 9985: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 9986: 
 9987: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 9988: 	    my $courselevelr=$courseid.'.'.$symbparm;
 9989: 	    $courselevelm=$courseid.'.'.$mapparm;
 9990: 
 9991: # ----------------------------------------------------------- first, check user
 9992: 
 9993: 	    my $userreply=&resdata($uname,$udom,'user',
 9994: 				       ([$courselevelr,'resource'],
 9995: 					[$courselevelm,'map'     ],
 9996: 					[$courselevel, 'course'  ]));
 9997: 	    if (defined($userreply)) { return &get_reply($userreply); }
 9998: 
 9999: # ------------------------------------------------ second, check some of course
10000:             my $coursereply;
10001:             if (@groups > 0) {
10002:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
10003:                                        $mapparm,$spacequalifierrest);
10004:                 if (defined($coursereply)) { return &get_reply($coursereply); }
10005:             }
10006: 
10007: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10008: 				  $env{'course.'.$courseid.'.domain'},
10009: 				  'course',
10010: 				  ([$seclevelr,   'resource'],
10011: 				   [$seclevelm,   'map'     ],
10012: 				   [$seclevel,    'course'  ],
10013: 				   [$courselevelr,'resource']));
10014: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
10015: 
10016: # ------------------------------------------------------ third, check map parms
10017: 	    my %parmhash=();
10018: 	    my $thisparm='';
10019: 	    if (tie(%parmhash,'GDBM_File',
10020: 		    $env{'request.course.fn'}.'_parms.db',
10021: 		    &GDBM_READER(),0640)) {
10022: 		$thisparm=$parmhash{$symbparm};
10023: 		untie(%parmhash);
10024: 	    }
10025: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
10026: 	}
10027: # ------------------------------------------ fourth, look in resource metadata
10028: 
10029: 	$spacequalifierrest=~s/\./\_/;
10030: 	my $filename;
10031: 	if (!$symbparm) { $symbparm=&symbread(); }
10032: 	if ($symbparm) {
10033: 	    $filename=(&decode_symb($symbparm))[2];
10034: 	} else {
10035: 	    $filename=$env{'request.filename'};
10036: 	}
10037: 	my $metadata=&metadata($filename,$spacequalifierrest);
10038: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
10039: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
10040: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
10041: 
10042: # ---------------------------------------------- fourth, look in rest of course
10043: 	if ($symbparm && defined($courseid) && 
10044: 	    $courseid eq $env{'request.course.id'}) {
10045: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10046: 				     $env{'course.'.$courseid.'.domain'},
10047: 				     'course',
10048: 				     ([$courselevelm,'map'   ],
10049: 				      [$courselevel, 'course']));
10050: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
10051: 	}
10052: # ------------------------------------------------------------------ Cascade up
10053: 	unless ($space eq '0') {
10054: 	    my @parts=split(/_/,$space);
10055: 	    my $id=pop(@parts);
10056: 	    my $part=join('_',@parts);
10057: 	    if ($part eq '') { $part='0'; }
10058: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
10059: 				 $symbparm,$udom,$uname,$section,1);
10060: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
10061: 	}
10062: 	if ($recurse) { return undef; }
10063: 	my $pack_def=&packages_tab_default($filename,$varname);
10064: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
10065: # ---------------------------------------------------- Any other user namespace
10066:     } elsif ($realm eq 'environment') {
10067: # ----------------------------------------------------------------- environment
10068: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
10069: 	    return $env{'environment.'.$spacequalifierrest};
10070: 	} else {
10071: 	    if ($uname eq 'anonymous' && $udom eq '') {
10072: 		return '';
10073: 	    }
10074: 	    my %returnhash=&userenvironment($udom,$uname,
10075: 					    $spacequalifierrest);
10076: 	    return $returnhash{$spacequalifierrest};
10077: 	}
10078:     } elsif ($realm eq 'system') {
10079: # ----------------------------------------------------------------- system.time
10080: 	if ($space eq 'time') {
10081: 	    return time;
10082:         }
10083:     } elsif ($realm eq 'server') {
10084: # ----------------------------------------------------------------- system.time
10085: 	if ($space eq 'name') {
10086: 	    return $ENV{'SERVER_NAME'};
10087:         }
10088:     }
10089:     return '';
10090: }
10091: 
10092: sub get_reply {
10093:     my ($reply_value) = @_;
10094:     if (ref($reply_value) eq 'ARRAY') {
10095:         if (wantarray) {
10096: 	    return @$reply_value;
10097:         }
10098:         return $reply_value->[0];
10099:     } else {
10100:         return $reply_value;
10101:     }
10102: }
10103: 
10104: sub check_group_parms {
10105:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10106:     my @groupitems = ();
10107:     my $resultitem;
10108:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
10109:     foreach my $group (@{$groups}) {
10110:         foreach my $level (@levels) {
10111:              my $item = $courseid.'.['.$group.'].'.$level->[0];
10112:              push(@groupitems,[$item,$level->[1]]);
10113:         }
10114:     }
10115:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10116:                             $env{'course.'.$courseid.'.domain'},
10117:                                      'course',@groupitems);
10118:     return $coursereply;
10119: }
10120: 
10121: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
10122:     my ($courseid,@groups) = @_;
10123:     @groups = sort(@groups);
10124:     return @groups;
10125: }
10126: 
10127: sub packages_tab_default {
10128:     my ($uri,$varname)=@_;
10129:     my (undef,$part,$name)=split(/\./,$varname);
10130: 
10131:     my (@extension,@specifics,$do_default);
10132:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
10133: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
10134: 	if ($pack_type eq 'default') {
10135: 	    $do_default=1;
10136: 	} elsif ($pack_type eq 'extension') {
10137: 	    push(@extension,[$package,$pack_type,$pack_part]);
10138: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
10139: 	    # only look at packages defaults for packages that this id is
10140: 	    push(@specifics,[$package,$pack_type,$pack_part]);
10141: 	}
10142:     }
10143:     # first look for a package that matches the requested part id
10144:     foreach my $package (@specifics) {
10145: 	my (undef,$pack_type,$pack_part)=@{$package};
10146: 	next if ($pack_part ne $part);
10147: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10148: 	    return $packagetab{"$pack_type&$name&default"};
10149: 	}
10150:     }
10151:     # look for any possible matching non extension_ package
10152:     foreach my $package (@specifics) {
10153: 	my (undef,$pack_type,$pack_part)=@{$package};
10154: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10155: 	    return $packagetab{"$pack_type&$name&default"};
10156: 	}
10157: 	if ($pack_type eq 'part') { $pack_part='0'; }
10158: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10159: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
10160: 	}
10161:     }
10162:     # look for any posible extension_ match
10163:     foreach my $package (@extension) {
10164: 	my ($package,$pack_type)=@{$package};
10165: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10166: 	    return $packagetab{"$pack_type&$name&default"};
10167: 	}
10168: 	if (defined($packagetab{$package."&$name&default"})) {
10169: 	    return $packagetab{$package."&$name&default"};
10170: 	}
10171:     }
10172:     # look for a global default setting
10173:     if ($do_default && defined($packagetab{"default&$name&default"})) {
10174: 	return $packagetab{"default&$name&default"};
10175:     }
10176:     return undef;
10177: }
10178: 
10179: sub add_prefix_and_part {
10180:     my ($prefix,$part)=@_;
10181:     my $keyroot;
10182:     if (defined($prefix) && $prefix !~ /^__/) {
10183: 	# prefix that has a part already
10184: 	$keyroot=$prefix;
10185:     } elsif (defined($prefix)) {
10186: 	# prefix that is missing a part
10187: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10188:     } else {
10189: 	# no prefix at all
10190: 	if (defined($part)) { $keyroot='_'.$part; }
10191:     }
10192:     return $keyroot;
10193: }
10194: 
10195: # ---------------------------------------------------------------- Get metadata
10196: 
10197: my %metaentry;
10198: my %importedpartids;
10199: sub metadata {
10200:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
10201:     $uri=&declutter($uri);
10202:     # if it is a non metadata possible uri return quickly
10203:     if (($uri eq '') || 
10204: 	(($uri =~ m|^/*adm/|) && 
10205: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
10206:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
10207: 	return undef;
10208:     }
10209:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
10210: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
10211: 	return undef;
10212:     }
10213:     my $filename=$uri;
10214:     $uri=~s/\.meta$//;
10215: #
10216: # Is the metadata already cached?
10217: # Look at timestamp of caching
10218: # Everything is cached by the main uri, libraries are never directly cached
10219: #
10220:     if (!defined($liburi)) {
10221: 	my ($result,$cached)=&is_cached_new('meta',$uri);
10222: 	if (defined($cached)) { return $result->{':'.$what}; }
10223:     }
10224:     {
10225: # Imported parts would go here
10226:         my %importedids=();
10227:         my @origfileimportpartids=();
10228:         my $importedparts=0;
10229: #
10230: # Is this a recursive call for a library?
10231: #
10232: #	if (! exists($metacache{$uri})) {
10233: #	    $metacache{$uri}={};
10234: #	}
10235: 	my $cachetime = 60*60;
10236:         if ($liburi) {
10237: 	    $liburi=&declutter($liburi);
10238:             $filename=$liburi;
10239:         } else {
10240: 	    &devalidate_cache_new('meta',$uri);
10241: 	    undef(%metaentry);
10242: 	}
10243:         my %metathesekeys=();
10244:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
10245: 	my $metastring;
10246: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
10247: 	    my $which = &hreflocation('','/'.($liburi || $uri));
10248: 	    $metastring = 
10249: 		&Apache::lonnet::ssi_body($which,
10250: 					  ('grade_target' => 'meta'));
10251: 	    $cachetime = 1; # only want this cached in the child not long term
10252: 	} elsif (($uri !~ m -^(editupload)/-) && 
10253:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
10254: 	    my $file=&filelocation('',&clutter($filename));
10255: 	    #push(@{$metaentry{$uri.'.file'}},$file);
10256: 	    $metastring=&getfile($file);
10257: 	}
10258:         my $parser=HTML::LCParser->new(\$metastring);
10259:         my $token;
10260:         undef %metathesekeys;
10261:         while ($token=$parser->get_token) {
10262: 	    if ($token->[0] eq 'S') {
10263: 		if (defined($token->[2]->{'package'})) {
10264: #
10265: # This is a package - get package info
10266: #
10267: 		    my $package=$token->[2]->{'package'};
10268: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10269: 		    if (defined($token->[2]->{'id'})) { 
10270: 			$keyroot.='_'.$token->[2]->{'id'}; 
10271: 		    }
10272: 		    if ($metaentry{':packages'}) {
10273: 			$metaentry{':packages'}.=','.$package.$keyroot;
10274: 		    } else {
10275: 			$metaentry{':packages'}=$package.$keyroot;
10276: 		    }
10277: 		    foreach my $pack_entry (keys(%packagetab)) {
10278: 			my $part=$keyroot;
10279: 			$part=~s/^\_//;
10280: 			if ($pack_entry=~/^\Q$package\E\&/ || 
10281: 			    $pack_entry=~/^\Q$package\E_0\&/) {
10282: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
10283: 			    # ignore package.tab specified default values
10284:                             # here &package_tab_default() will fetch those
10285: 			    if ($subp eq 'default') { next; }
10286: 			    my $value=$packagetab{$pack_entry};
10287: 			    my $unikey;
10288: 			    if ($pack =~ /_0$/) {
10289: 				$unikey='parameter_0_'.$name;
10290: 				$part=0;
10291: 			    } else {
10292: 				$unikey='parameter'.$keyroot.'_'.$name;
10293: 			    }
10294: 			    if ($subp eq 'display') {
10295: 				$value.=' [Part: '.$part.']';
10296: 			    }
10297: 			    $metaentry{':'.$unikey.'.part'}=$part;
10298: 			    $metathesekeys{$unikey}=1;
10299: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10300: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
10301: 			    }
10302: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
10303: 				$metaentry{':'.$unikey}=
10304: 				    $metaentry{':'.$unikey.'.default'};
10305: 			    }
10306: 			}
10307: 		    }
10308: 		} else {
10309: #
10310: # This is not a package - some other kind of start tag
10311: #
10312: 		    my $entry=$token->[1];
10313: 		    my $unikey='';
10314: 
10315: 		    if ($entry eq 'import') {
10316: #
10317: # Importing a library here
10318: #
10319:                         my $location=$parser->get_text('/import');
10320:                         my $dir=$filename;
10321:                         $dir=~s|[^/]*$||;
10322:                         $location=&filelocation($dir,$location);
10323:                        
10324:                         my $importmode=$token->[2]->{'importmode'};
10325:                         if ($importmode eq 'problem') {
10326: # Import as problem/response
10327:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10328:                         } elsif ($importmode eq 'part') {
10329: # Import as part(s)
10330:                            $importedparts=1;
10331: # We need to get the original file and the imported file to get the part order correct
10332: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10333: # Load and inspect original file
10334:                            if ($#origfileimportpartids<0) {
10335:                               undef(%importedpartids);
10336:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10337:                               my $origfile=&getfile($origfilelocation);
10338:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10339:                            }
10340: 
10341: # Load and inspect imported file
10342:                            my $impfile=&getfile($location);
10343:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10344:                            if ($#impfilepartids>=0) {
10345: # This problem had parts
10346:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
10347:                            } else {
10348: # Importing by turning a single problem into a problem part
10349: # It gets the import-tags ID as part-ID
10350:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
10351:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
10352:                            }
10353:                         } else {
10354: # Normal import
10355:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10356:                            if (defined($token->[2]->{'id'})) {
10357:                               $unikey.='_'.$token->[2]->{'id'};
10358:                            }
10359:                         }
10360: 
10361: 			if ($depthcount<20) {
10362: 			    my $metadata = 
10363: 				&metadata($uri,'keys', $location,$unikey,
10364: 					  $depthcount+1);
10365: 			    foreach my $meta (split(',',$metadata)) {
10366: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
10367: 				$metathesekeys{$meta}=1;
10368: 			    }
10369: 			
10370:                         }
10371: 		    } else {
10372: #
10373: # Not importing, some other kind of non-package, non-library start tag
10374: # 
10375:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10376:                         if (defined($token->[2]->{'id'})) {
10377:                             $unikey.='_'.$token->[2]->{'id'};
10378:                         }
10379: 			if (defined($token->[2]->{'name'})) { 
10380: 			    $unikey.='_'.$token->[2]->{'name'}; 
10381: 			}
10382: 			$metathesekeys{$unikey}=1;
10383: 			foreach my $param (@{$token->[3]}) {
10384: 			    $metaentry{':'.$unikey.'.'.$param} =
10385: 				$token->[2]->{$param};
10386: 			}
10387: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
10388: 			my $default=$metaentry{':'.$unikey.'.default'};
10389: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10390: 		 # only ws inside the tag, and not in default, so use default
10391: 		 # as value
10392: 			    $metaentry{':'.$unikey}=$default;
10393: 			} elsif ( $internaltext =~ /\S/ ) {
10394: 		  # something interesting inside the tag
10395: 			    $metaentry{':'.$unikey}=$internaltext;
10396: 			} else {
10397: 		  # no interesting values, don't set a default
10398: 			}
10399: # end of not-a-package not-a-library import
10400: 		    }
10401: # end of not-a-package start tag
10402: 		}
10403: # the next is the end of "start tag"
10404: 	    }
10405: 	}
10406: 	my ($extension) = ($uri =~ /\.(\w+)$/);
10407: 	$extension = lc($extension);
10408: 	if ($extension eq 'htm') { $extension='html'; }
10409: 
10410: 	foreach my $key (keys(%packagetab)) {
10411: 	    #no specific packages #how's our extension
10412: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
10413: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
10414: 					 \%metathesekeys);
10415: 	}
10416: 
10417: 	if (!exists($metaentry{':packages'})
10418: 	    || $packagetab{"import_defaults&extension_$extension"}) {
10419: 	    foreach my $key (keys(%packagetab)) {
10420: 		#no specific packages well let's get default then
10421: 		if ($key!~/^default&/) { next; }
10422: 		&metadata_create_package_def($uri,$key,'default',
10423: 					     \%metathesekeys);
10424: 	    }
10425: 	}
10426: # are there custom rights to evaluate
10427: 	if ($metaentry{':copyright'} eq 'custom') {
10428: 
10429:     #
10430:     # Importing a rights file here
10431:     #
10432: 	    unless ($depthcount) {
10433: 		my $location=$metaentry{':customdistributionfile'};
10434: 		my $dir=$filename;
10435: 		$dir=~s|[^/]*$||;
10436: 		$location=&filelocation($dir,$location);
10437: 		my $rights_metadata =
10438: 		    &metadata($uri,'keys',$location,'_rights',
10439: 			      $depthcount+1);
10440: 		foreach my $rights (split(',',$rights_metadata)) {
10441: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10442: 		    $metathesekeys{$rights}=1;
10443: 		}
10444: 	    }
10445: 	}
10446: 	# uniqifiy package listing
10447: 	my %seen;
10448: 	my @uniq_packages =
10449: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10450: 	$metaentry{':packages'} = join(',',@uniq_packages);
10451: 
10452:         if ($importedparts) {
10453: # We had imported parts and need to rebuild partorder
10454:            $metaentry{':partorder'}='';
10455:            $metathesekeys{'partorder'}=1;
10456:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10457:                if ($origfileimportpartids[$index] eq 'part') {
10458: # original part, part of the problem
10459:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10460:                } else {
10461: # we have imported parts at this position
10462:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10463:                }
10464:            }
10465:            $metaentry{':partorder'}=~s/^\,//;
10466:         }
10467: 
10468: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
10469: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
10470: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
10471: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
10472: # this is the end of "was not already recently cached
10473:     }
10474:     return $metaentry{':'.$what};
10475: }
10476: 
10477: sub metadata_create_package_def {
10478:     my ($uri,$key,$package,$metathesekeys)=@_;
10479:     my ($pack,$name,$subp)=split(/\&/,$key);
10480:     if ($subp eq 'default') { next; }
10481:     
10482:     if (defined($metaentry{':packages'})) {
10483: 	$metaentry{':packages'}.=','.$package;
10484:     } else {
10485: 	$metaentry{':packages'}=$package;
10486:     }
10487:     my $value=$packagetab{$key};
10488:     my $unikey;
10489:     $unikey='parameter_0_'.$name;
10490:     $metaentry{':'.$unikey.'.part'}=0;
10491:     $$metathesekeys{$unikey}=1;
10492:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10493: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
10494:     }
10495:     if (defined($metaentry{':'.$unikey.'.default'})) {
10496: 	$metaentry{':'.$unikey}=
10497: 	    $metaentry{':'.$unikey.'.default'};
10498:     }
10499: }
10500: 
10501: sub metadata_generate_part0 {
10502:     my ($metadata,$metacache,$uri) = @_;
10503:     my %allnames;
10504:     foreach my $metakey (keys(%$metadata)) {
10505: 	if ($metakey=~/^parameter\_(.*)/) {
10506: 	  my $part=$$metacache{':'.$metakey.'.part'};
10507: 	  my $name=$$metacache{':'.$metakey.'.name'};
10508: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
10509: 	    $allnames{$name}=$part;
10510: 	  }
10511: 	}
10512:     }
10513:     foreach my $name (keys(%allnames)) {
10514:       $$metadata{"parameter_0_$name"}=1;
10515:       my $key=":parameter_0_$name";
10516:       $$metacache{"$key.part"}='0';
10517:       $$metacache{"$key.name"}=$name;
10518:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
10519: 					   $allnames{$name}.'_'.$name.
10520: 					   '.type'};
10521:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
10522: 			     '.display'};
10523:       my $expr='[Part: '.$allnames{$name}.']';
10524:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
10525:       $$metacache{"$key.display"}=$olddis;
10526:     }
10527: }
10528: 
10529: # ------------------------------------------------------ Devalidate title cache
10530: 
10531: sub devalidate_title_cache {
10532:     my ($url)=@_;
10533:     if (!$env{'request.course.id'}) { return; }
10534:     my $symb=&symbread($url);
10535:     if (!$symb) { return; }
10536:     my $key=$env{'request.course.id'}."\0".$symb;
10537:     &devalidate_cache_new('title',$key);
10538: }
10539: 
10540: # ------------------------------------------------- Get the title of a course
10541: 
10542: sub current_course_title {
10543:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10544: }
10545: # ------------------------------------------------- Get the title of a resource
10546: 
10547: sub gettitle {
10548:     my $urlsymb=shift;
10549:     my $symb=&symbread($urlsymb);
10550:     if ($symb) {
10551: 	my $key=$env{'request.course.id'}."\0".$symb;
10552: 	my ($result,$cached)=&is_cached_new('title',$key);
10553: 	if (defined($cached)) { 
10554: 	    return $result;
10555: 	}
10556: 	my ($map,$resid,$url)=&decode_symb($symb);
10557: 	my $title='';
10558: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10559: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10560: 	} else {
10561: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10562: 		    &GDBM_READER(),0640)) {
10563: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
10564: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
10565: 		untie(%bighash);
10566: 	    }
10567: 	}
10568: 	$title=~s/\&colon\;/\:/gs;
10569: 	if ($title) {
10570: # Remember both $symb and $title for dynamic metadata
10571:             $accesshash{$symb.'___crstitle'}=$title;
10572:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
10573: # Cache this title and then return it
10574: 	    return &do_cache_new('title',$key,$title,600);
10575: 	}
10576: 	$urlsymb=$url;
10577:     }
10578:     my $title=&metadata($urlsymb,'title');
10579:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
10580:     return $title;
10581: }
10582: 
10583: sub get_slot {
10584:     my ($which,$cnum,$cdom)=@_;
10585:     if (!$cnum || !$cdom) {
10586: 	(undef,my $courseid)=&whichuser();
10587: 	$cdom=$env{'course.'.$courseid.'.domain'};
10588: 	$cnum=$env{'course.'.$courseid.'.num'};
10589:     }
10590:     my $key=join("\0",'slots',$cdom,$cnum,$which);
10591:     my %slotinfo;
10592:     if (exists($remembered{$key})) {
10593: 	$slotinfo{$which} = $remembered{$key};
10594:     } else {
10595: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
10596: 	&Apache::lonhomework::showhash(%slotinfo);
10597: 	my ($tmp)=keys(%slotinfo);
10598: 	if ($tmp=~/^error:/) { return (); }
10599: 	$remembered{$key} = $slotinfo{$which};
10600:     }
10601:     if (ref($slotinfo{$which}) eq 'HASH') {
10602: 	return %{$slotinfo{$which}};
10603:     }
10604:     return $slotinfo{$which};
10605: }
10606: 
10607: sub get_reservable_slots {
10608:     my ($cnum,$cdom,$uname,$udom) = @_;
10609:     my $now = time;
10610:     my $reservable_info;
10611:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10612:     if (exists($remembered{$key})) {
10613:         $reservable_info = $remembered{$key};
10614:     } else {
10615:         my %resv;
10616:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10617:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10618:         $reservable_info = \%resv;
10619:         $remembered{$key} = $reservable_info;
10620:     }
10621:     return $reservable_info;
10622: }
10623: 
10624: sub get_course_slots {
10625:     my ($cnum,$cdom) = @_;
10626:     my $hashid=$cnum.':'.$cdom;
10627:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10628:     if (defined($cached)) {
10629:         if (ref($result) eq 'HASH') {
10630:             return %{$result};
10631:         }
10632:     } else {
10633:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10634:         my ($tmp) = keys(%slots);
10635:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10636:             &do_cache_new('allslots',$hashid,\%slots,600);
10637:             return %slots;
10638:         }
10639:     }
10640:     return;
10641: }
10642: 
10643: sub devalidate_slots_cache {
10644:     my ($cnum,$cdom)=@_;
10645:     my $hashid=$cnum.':'.$cdom;
10646:     &devalidate_cache_new('allslots',$hashid);
10647: }
10648: 
10649: sub get_coursechange {
10650:     my ($cdom,$cnum) = @_;
10651:     if ($cdom eq '' || $cnum eq '') {
10652:         return unless ($env{'request.course.id'});
10653:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10654:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10655:     }
10656:     my $hashid=$cdom.'_'.$cnum;
10657:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
10658:     if ((defined($cached)) && ($change ne '')) {
10659:         return $change;
10660:     } else {
10661:         my %crshash;
10662:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10663:         if ($crshash{'internal.contentchange'} eq '') {
10664:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
10665:             if ($change eq '') {
10666:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
10667:                 $change = $crshash{'internal.created'};
10668:             }
10669:         } else {
10670:             $change = $crshash{'internal.contentchange'};
10671:         }
10672:         my $cachetime = 600;
10673:         &do_cache_new('crschange',$hashid,$change,$cachetime);
10674:     }
10675:     return $change;
10676: }
10677: 
10678: sub devalidate_coursechange_cache {
10679:     my ($cnum,$cdom)=@_;
10680:     my $hashid=$cnum.':'.$cdom;
10681:     &devalidate_cache_new('crschange',$hashid);
10682: }
10683: 
10684: # ------------------------------------------------- Update symbolic store links
10685: 
10686: sub symblist {
10687:     my ($mapname,%newhash)=@_;
10688:     $mapname=&deversion(&declutter($mapname));
10689:     my %hash;
10690:     if (($env{'request.course.fn'}) && (%newhash)) {
10691:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10692:                       &GDBM_WRCREAT(),0640)) {
10693: 	    foreach my $url (keys(%newhash)) {
10694: 		next if ($url eq 'last_known'
10695: 			 && $env{'form.no_update_last_known'});
10696: 		$hash{declutter($url)}=&encode_symb($mapname,
10697: 						    $newhash{$url}->[1],
10698: 						    $newhash{$url}->[0]);
10699:             }
10700:             if (untie(%hash)) {
10701: 		return 'ok';
10702:             }
10703:         }
10704:     }
10705:     return 'error';
10706: }
10707: 
10708: # --------------------------------------------------------------- Verify a symb
10709: 
10710: sub symbverify {
10711:     my ($symb,$thisurl,$encstate)=@_;
10712:     my $thisfn=$thisurl;
10713:     $thisfn=&declutter($thisfn);
10714: # direct jump to resource in page or to a sequence - will construct own symbs
10715:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10716: # check URL part
10717:     my ($map,$resid,$url)=&decode_symb($symb);
10718: 
10719:     unless ($url eq $thisfn) { return 0; }
10720: 
10721:     $symb=&symbclean($symb);
10722:     $thisurl=&deversion($thisurl);
10723:     $thisfn=&deversion($thisfn);
10724: 
10725:     my %bighash;
10726:     my $okay=0;
10727: 
10728:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10729:                             &GDBM_READER(),0640)) {
10730:         my $noclutter;
10731:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10732:             $thisurl =~ s/\?.+$//;
10733:             if ($map =~ m{^uploaded/.+\.page$}) {
10734:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
10735:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
10736:                 $noclutter = 1;
10737:             }
10738:         }
10739:         my $ids;
10740:         if ($noclutter) {
10741:             $ids=$bighash{'ids_'.$thisurl};
10742:         } else {
10743:             $ids=$bighash{'ids_'.&clutter($thisurl)};
10744:         }
10745:         unless ($ids) {
10746:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
10747:             $ids=$bighash{$idkey};
10748:         }
10749:         if ($ids) {
10750: # ------------------------------------------------------------------- Has ID(s)
10751:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
10752:                 $symb =~ s/\?.+$//;
10753:             }
10754: 	    foreach my $id (split(/\,/,$ids)) {
10755: 	       my ($mapid,$resid)=split(/\./,$id);
10756:                if (
10757:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
10758:    eq $symb) {
10759:                    if (ref($encstate)) {
10760:                        $$encstate = $bighash{'encrypted_'.$id};
10761:                    }
10762: 		   if (($env{'request.role.adv'}) ||
10763: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
10764:                        ($thisurl eq '/adm/navmaps')) {
10765: 		       $okay=1;
10766:                        last;
10767: 		   }
10768: 	       }
10769: 	   }
10770:         }
10771: 	untie(%bighash);
10772:     }
10773:     return $okay;
10774: }
10775: 
10776: # --------------------------------------------------------------- Clean-up symb
10777: 
10778: sub symbclean {
10779:     my $symb=shift;
10780:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10781: # remove version from map
10782:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
10783: 
10784: # remove version from URL
10785:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
10786: 
10787: # remove wrapper
10788: 
10789:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
10790:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
10791:     return $symb;
10792: }
10793: 
10794: # ---------------------------------------------- Split symb to find map and url
10795: 
10796: sub encode_symb {
10797:     my ($map,$resid,$url)=@_;
10798:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
10799: }
10800: 
10801: sub decode_symb {
10802:     my $symb=shift;
10803:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10804:     my ($map,$resid,$url)=split(/___/,$symb);
10805:     return (&fixversion($map),$resid,&fixversion($url));
10806: }
10807: 
10808: sub fixversion {
10809:     my $fn=shift;
10810:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
10811:     my %bighash;
10812:     my $uri=&clutter($fn);
10813:     my $key=$env{'request.course.id'}.'_'.$uri;
10814: # is this cached?
10815:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
10816:     if (defined($cached)) { return $result; }
10817: # unfortunately not cached, or expired
10818:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10819: 	    &GDBM_READER(),0640)) {
10820:  	if ($bighash{'version_'.$uri}) {
10821:  	    my $version=$bighash{'version_'.$uri};
10822:  	    unless (($version eq 'mostrecent') || 
10823: 		    ($version==&getversion($uri))) {
10824:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
10825:  	    }
10826:  	}
10827:  	untie %bighash;
10828:     }
10829:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
10830: }
10831: 
10832: sub deversion {
10833:     my $url=shift;
10834:     $url=~s/\.\d+\.(\w+)$/\.$1/;
10835:     return $url;
10836: }
10837: 
10838: # ------------------------------------------------------ Return symb list entry
10839: 
10840: sub symbread {
10841:     my ($thisfn,$donotrecurse)=@_;
10842:     my $cache_str;
10843:     if ($thisfn ne '') {
10844:         $cache_str='request.symbread.cached.'.$thisfn;
10845:         if ($env{$cache_str} ne '') {
10846:             return $env{$cache_str};
10847:         }
10848:     } else {
10849: # no filename provided? try from environment
10850:         if ($env{'request.symb'}) {
10851: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
10852: 	}
10853: 	$thisfn=$env{'request.filename'};
10854:     }
10855:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
10856: # is that filename actually a symb? Verify, clean, and return
10857:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
10858: 	if (&symbverify($thisfn,$1)) {
10859: 	    return $env{$cache_str}=&symbclean($thisfn);
10860: 	}
10861:     }
10862:     $thisfn=declutter($thisfn);
10863:     my %hash;
10864:     my %bighash;
10865:     my $syval='';
10866:     if (($env{'request.course.fn'}) && ($thisfn)) {
10867:         my $targetfn = $thisfn;
10868:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
10869:             $targetfn = 'adm/wrapper/'.$thisfn;
10870:         }
10871: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
10872: 	    $targetfn=$1;
10873: 	}
10874:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10875:                       &GDBM_READER(),0640)) {
10876: 	    $syval=$hash{$targetfn};
10877:             untie(%hash);
10878:         }
10879: # ---------------------------------------------------------- There was an entry
10880:         if ($syval) {
10881: 	    #unless ($syval=~/\_\d+$/) {
10882: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
10883: 		    #&appenv({'request.ambiguous' => $thisfn});
10884: 		    #return $env{$cache_str}='';
10885: 		#}    
10886: 		#$syval.=$1;
10887: 	    #}
10888:         } else {
10889: # ------------------------------------------------------- Was not in symb table
10890:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10891:                             &GDBM_READER(),0640)) {
10892: # ---------------------------------------------- Get ID(s) for current resource
10893:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
10894:               unless ($ids) { 
10895:                  $ids=$bighash{'ids_/'.$thisfn};
10896:               }
10897:               unless ($ids) {
10898: # alias?
10899: 		  $ids=$bighash{'mapalias_'.$thisfn};
10900:               }
10901:               if ($ids) {
10902: # ------------------------------------------------------------------- Has ID(s)
10903:                  my @possibilities=split(/\,/,$ids);
10904:                  if ($#possibilities==0) {
10905: # ----------------------------------------------- There is only one possibility
10906: 		     my ($mapid,$resid)=split(/\./,$ids);
10907: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
10908: 						    $resid,$thisfn);
10909:                  } elsif (!$donotrecurse) {
10910: # ------------------------------------------ There is more than one possibility
10911:                      my $realpossible=0;
10912:                      foreach my $id (@possibilities) {
10913: 			 my $file=$bighash{'src_'.$id};
10914:                          if (&allowed('bre',$file)) {
10915:          		    my ($mapid,$resid)=split(/\./,$id);
10916:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
10917: 				$realpossible++;
10918:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
10919: 						    $resid,$thisfn);
10920:                             }
10921: 			 }
10922:                      }
10923: 		     if ($realpossible!=1) { $syval=''; }
10924:                  } else {
10925:                      $syval='';
10926:                  }
10927: 	      }
10928:               untie(%bighash)
10929:            }
10930:         }
10931:         if ($syval) {
10932: 	    return $env{$cache_str}=$syval;
10933:         }
10934:     }
10935:     &appenv({'request.ambiguous' => $thisfn});
10936:     return $env{$cache_str}='';
10937: }
10938: 
10939: # ---------------------------------------------------------- Return random seed
10940: 
10941: sub numval {
10942:     my $txt=shift;
10943:     $txt=~tr/A-J/0-9/;
10944:     $txt=~tr/a-j/0-9/;
10945:     $txt=~tr/K-T/0-9/;
10946:     $txt=~tr/k-t/0-9/;
10947:     $txt=~tr/U-Z/0-5/;
10948:     $txt=~tr/u-z/0-5/;
10949:     $txt=~s/\D//g;
10950:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
10951:     return int($txt);
10952: }
10953: 
10954: sub numval2 {
10955:     my $txt=shift;
10956:     $txt=~tr/A-J/0-9/;
10957:     $txt=~tr/a-j/0-9/;
10958:     $txt=~tr/K-T/0-9/;
10959:     $txt=~tr/k-t/0-9/;
10960:     $txt=~tr/U-Z/0-5/;
10961:     $txt=~tr/u-z/0-5/;
10962:     $txt=~s/\D//g;
10963:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10964:     my $total;
10965:     foreach my $val (@txts) { $total+=$val; }
10966:     if ($_64bit) { if ($total > 2**32) { return -1; } }
10967:     return int($total);
10968: }
10969: 
10970: sub numval3 {
10971:     use integer;
10972:     my $txt=shift;
10973:     $txt=~tr/A-J/0-9/;
10974:     $txt=~tr/a-j/0-9/;
10975:     $txt=~tr/K-T/0-9/;
10976:     $txt=~tr/k-t/0-9/;
10977:     $txt=~tr/U-Z/0-5/;
10978:     $txt=~tr/u-z/0-5/;
10979:     $txt=~s/\D//g;
10980:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10981:     my $total;
10982:     foreach my $val (@txts) { $total+=$val; }
10983:     if ($_64bit) { $total=(($total<<32)>>32); }
10984:     return $total;
10985: }
10986: 
10987: sub digest {
10988:     my ($data)=@_;
10989:     my $digest=&Digest::MD5::md5($data);
10990:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
10991:     my ($e,$f);
10992:     {
10993:         use integer;
10994:         $e=($a+$b);
10995:         $f=($c+$d);
10996:         if ($_64bit) {
10997:             $e=(($e<<32)>>32);
10998:             $f=(($f<<32)>>32);
10999:         }
11000:     }
11001:     if (wantarray) {
11002: 	return ($e,$f);
11003:     } else {
11004: 	my $g;
11005: 	{
11006: 	    use integer;
11007: 	    $g=($e+$f);
11008: 	    if ($_64bit) {
11009: 		$g=(($g<<32)>>32);
11010: 	    }
11011: 	}
11012: 	return $g;
11013:     }
11014: }
11015: 
11016: sub latest_rnd_algorithm_id {
11017:     return '64bit5';
11018: }
11019: 
11020: sub get_rand_alg {
11021:     my ($courseid)=@_;
11022:     if (!$courseid) { $courseid=(&whichuser())[1]; }
11023:     if ($courseid) {
11024: 	return $env{"course.$courseid.rndseed"};
11025:     }
11026:     return &latest_rnd_algorithm_id();
11027: }
11028: 
11029: sub validCODE {
11030:     my ($CODE)=@_;
11031:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
11032:     return 0;
11033: }
11034: 
11035: sub getCODE {
11036:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
11037:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
11038: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
11039: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
11040: 	return $Apache::lonhomework::history{'resource.CODE'};
11041:     }
11042:     return undef;
11043: }
11044: #
11045: #  Determines the random seed for a specific context:
11046: #
11047: # parameters:
11048: #   symb      - in course context the symb for the seed.
11049: #   course_id - The course id of the form domain_coursenum.
11050: #   domain    - Domain for the user.
11051: #   course    - Course for the user.
11052: #   cenv      - environment of the course.
11053: #
11054: # NOTE:
11055: #   All parameters are picked out of the environment if missing
11056: #   or not defined.
11057: #   If a symb cannot be determined the current time is used instead.
11058: #
11059: #  For a given well defined symb, courside, domain, username,
11060: #  and course environment, the seed is reproducible.
11061: #
11062: sub rndseed {
11063:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
11064:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
11065:     if (!defined($symb)) {
11066: 	unless ($symb=$wsymb) { return time; }
11067:     }
11068:     if (!defined $courseid) { 
11069: 	$courseid=$wcourseid; 
11070:     }
11071:     if (!defined $domain) { $domain=$wdomain; }
11072:     if (!defined $username) { $username=$wusername }
11073: 
11074:     my $which;
11075:     if (defined($cenv->{'rndseed'})) {
11076: 	$which = $cenv->{'rndseed'};
11077:     } else {
11078: 	$which =&get_rand_alg($courseid);
11079:     }
11080:     if (defined(&getCODE())) {
11081: 
11082: 	if ($which eq '64bit5') {
11083: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
11084: 	} elsif ($which eq '64bit4') {
11085: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
11086: 	} else {
11087: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
11088: 	}
11089:     } elsif ($which eq '64bit5') {
11090: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
11091:     } elsif ($which eq '64bit4') {
11092: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
11093:     } elsif ($which eq '64bit3') {
11094: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
11095:     } elsif ($which eq '64bit2') {
11096: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
11097:     } elsif ($which eq '64bit') {
11098: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
11099:     }
11100:     return &rndseed_32bit($symb,$courseid,$domain,$username);
11101: }
11102: 
11103: sub rndseed_32bit {
11104:     my ($symb,$courseid,$domain,$username)=@_;
11105:     {
11106: 	use integer;
11107: 	my $symbchck=unpack("%32C*",$symb) << 27;
11108: 	my $symbseed=numval($symb) << 22;
11109: 	my $namechck=unpack("%32C*",$username) << 17;
11110: 	my $nameseed=numval($username) << 12;
11111: 	my $domainseed=unpack("%32C*",$domain) << 7;
11112: 	my $courseseed=unpack("%32C*",$courseid);
11113: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
11114: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11115: 	#&logthis("rndseed :$num:$symb");
11116: 	if ($_64bit) { $num=(($num<<32)>>32); }
11117: 	return $num;
11118:     }
11119: }
11120: 
11121: sub rndseed_64bit {
11122:     my ($symb,$courseid,$domain,$username)=@_;
11123:     {
11124: 	use integer;
11125: 	my $symbchck=unpack("%32S*",$symb) << 21;
11126: 	my $symbseed=numval($symb) << 10;
11127: 	my $namechck=unpack("%32S*",$username);
11128: 	
11129: 	my $nameseed=numval($username) << 21;
11130: 	my $domainseed=unpack("%32S*",$domain) << 10;
11131: 	my $courseseed=unpack("%32S*",$courseid);
11132: 	
11133: 	my $num1=$symbchck+$symbseed+$namechck;
11134: 	my $num2=$nameseed+$domainseed+$courseseed;
11135: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11136: 	#&logthis("rndseed :$num:$symb");
11137: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11138: 	return "$num1,$num2";
11139:     }
11140: }
11141: 
11142: sub rndseed_64bit2 {
11143:     my ($symb,$courseid,$domain,$username)=@_;
11144:     {
11145: 	use integer;
11146: 	# strings need to be an even # of cahracters long, it it is odd the
11147:         # last characters gets thrown away
11148: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11149: 	my $symbseed=numval($symb) << 10;
11150: 	my $namechck=unpack("%32S*",$username.' ');
11151: 	
11152: 	my $nameseed=numval($username) << 21;
11153: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11154: 	my $courseseed=unpack("%32S*",$courseid.' ');
11155: 	
11156: 	my $num1=$symbchck+$symbseed+$namechck;
11157: 	my $num2=$nameseed+$domainseed+$courseseed;
11158: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11159: 	#&logthis("rndseed :$num:$symb");
11160: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11161: 	return "$num1,$num2";
11162:     }
11163: }
11164: 
11165: sub rndseed_64bit3 {
11166:     my ($symb,$courseid,$domain,$username)=@_;
11167:     {
11168: 	use integer;
11169: 	# strings need to be an even # of cahracters long, it it is odd the
11170:         # last characters gets thrown away
11171: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11172: 	my $symbseed=numval2($symb) << 10;
11173: 	my $namechck=unpack("%32S*",$username.' ');
11174: 	
11175: 	my $nameseed=numval2($username) << 21;
11176: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11177: 	my $courseseed=unpack("%32S*",$courseid.' ');
11178: 	
11179: 	my $num1=$symbchck+$symbseed+$namechck;
11180: 	my $num2=$nameseed+$domainseed+$courseseed;
11181: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11182: 	#&logthis("rndseed :$num1:$num2:$_64bit");
11183: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11184: 	
11185: 	return "$num1:$num2";
11186:     }
11187: }
11188: 
11189: sub rndseed_64bit4 {
11190:     my ($symb,$courseid,$domain,$username)=@_;
11191:     {
11192: 	use integer;
11193: 	# strings need to be an even # of cahracters long, it it is odd the
11194:         # last characters gets thrown away
11195: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11196: 	my $symbseed=numval3($symb) << 10;
11197: 	my $namechck=unpack("%32S*",$username.' ');
11198: 	
11199: 	my $nameseed=numval3($username) << 21;
11200: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11201: 	my $courseseed=unpack("%32S*",$courseid.' ');
11202: 	
11203: 	my $num1=$symbchck+$symbseed+$namechck;
11204: 	my $num2=$nameseed+$domainseed+$courseseed;
11205: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11206: 	#&logthis("rndseed :$num1:$num2:$_64bit");
11207: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11208: 	
11209: 	return "$num1:$num2";
11210:     }
11211: }
11212: 
11213: sub rndseed_64bit5 {
11214:     my ($symb,$courseid,$domain,$username)=@_;
11215:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11216:     return "$num1:$num2";
11217: }
11218: 
11219: sub rndseed_CODE_64bit {
11220:     my ($symb,$courseid,$domain,$username)=@_;
11221:     {
11222: 	use integer;
11223: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
11224: 	my $symbseed=numval2($symb);
11225: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11226: 	my $CODEseed=numval(&getCODE());
11227: 	my $courseseed=unpack("%32S*",$courseid.' ');
11228: 	my $num1=$symbseed+$CODEchck;
11229: 	my $num2=$CODEseed+$courseseed+$symbchck;
11230: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11231: 	#&logthis("rndseed :$num1:$num2:$symb");
11232: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
11233: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
11234: 	return "$num1:$num2";
11235:     }
11236: }
11237: 
11238: sub rndseed_CODE_64bit4 {
11239:     my ($symb,$courseid,$domain,$username)=@_;
11240:     {
11241: 	use integer;
11242: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
11243: 	my $symbseed=numval3($symb);
11244: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11245: 	my $CODEseed=numval3(&getCODE());
11246: 	my $courseseed=unpack("%32S*",$courseid.' ');
11247: 	my $num1=$symbseed+$CODEchck;
11248: 	my $num2=$CODEseed+$courseseed+$symbchck;
11249: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11250: 	#&logthis("rndseed :$num1:$num2:$symb");
11251: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
11252: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
11253: 	return "$num1:$num2";
11254:     }
11255: }
11256: 
11257: sub rndseed_CODE_64bit5 {
11258:     my ($symb,$courseid,$domain,$username)=@_;
11259:     my $code = &getCODE();
11260:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
11261:     return "$num1:$num2";
11262: }
11263: 
11264: sub setup_random_from_rndseed {
11265:     my ($rndseed)=@_;
11266:     if ($rndseed =~/([,:])/) {
11267: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
11268: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
11269:     } else {
11270: 	&Math::Random::random_set_seed_from_phrase($rndseed);
11271:     }
11272: }
11273: 
11274: sub latest_receipt_algorithm_id {
11275:     return 'receipt3';
11276: }
11277: 
11278: sub recunique {
11279:     my $fucourseid=shift;
11280:     my $unique;
11281:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11282: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11283: 	$unique=$env{"course.$fucourseid.internal.encseed"};
11284:     } else {
11285: 	$unique=$perlvar{'lonReceipt'};
11286:     }
11287:     return unpack("%32C*",$unique);
11288: }
11289: 
11290: sub recprefix {
11291:     my $fucourseid=shift;
11292:     my $prefix;
11293:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11294: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11295: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
11296:     } else {
11297: 	$prefix=$perlvar{'lonHostID'};
11298:     }
11299:     return unpack("%32C*",$prefix);
11300: }
11301: 
11302: sub ireceipt {
11303:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
11304: 
11305:     my $return =&recprefix($fucourseid).'-';
11306: 
11307:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11308: 	$env{'request.state'} eq 'construct') {
11309: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11310: 	return $return;
11311:     }
11312: 
11313:     my $cuname=unpack("%32C*",$funame);
11314:     my $cudom=unpack("%32C*",$fudom);
11315:     my $cucourseid=unpack("%32C*",$fucourseid);
11316:     my $cusymb=unpack("%32C*",$fusymb);
11317:     my $cunique=&recunique($fucourseid);
11318:     my $cpart=unpack("%32S*",$part);
11319:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11320: 
11321: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
11322: 			       
11323: 	$return.= ($cunique%$cuname+
11324: 		   $cunique%$cudom+
11325: 		   $cusymb%$cuname+
11326: 		   $cusymb%$cudom+
11327: 		   $cucourseid%$cuname+
11328: 		   $cucourseid%$cudom+
11329: 		   $cpart%$cuname+
11330: 		   $cpart%$cudom);
11331:     } else {
11332: 	$return.= ($cunique%$cuname+
11333: 		   $cunique%$cudom+
11334: 		   $cusymb%$cuname+
11335: 		   $cusymb%$cudom+
11336: 		   $cucourseid%$cuname+
11337: 		   $cucourseid%$cudom);
11338:     }
11339:     return $return;
11340: }
11341: 
11342: sub receipt {
11343:     my ($part)=@_;
11344:     my ($symb,$courseid,$domain,$name) = &whichuser();
11345:     return &ireceipt($name,$domain,$courseid,$symb,$part);
11346: }
11347: 
11348: sub whichuser {
11349:     my ($passedsymb)=@_;
11350:     my ($symb,$courseid,$domain,$name,$publicuser);
11351:     if (defined($env{'form.grade_symb'})) {
11352: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11353: 	my $allowed=&allowed('vgr',$tmp_courseid);
11354: 	if (!$allowed &&
11355: 	    exists($env{'request.course.sec'}) &&
11356: 	    $env{'request.course.sec'} !~ /^\s*$/) {
11357: 	    $allowed=&allowed('vgr',$tmp_courseid.
11358: 			      '/'.$env{'request.course.sec'});
11359: 	}
11360: 	if ($allowed) {
11361: 	    ($symb)=&get_env_multiple('form.grade_symb');
11362: 	    $courseid=$tmp_courseid;
11363: 	    ($domain)=&get_env_multiple('form.grade_domain');
11364: 	    ($name)=&get_env_multiple('form.grade_username');
11365: 	    return ($symb,$courseid,$domain,$name,$publicuser);
11366: 	}
11367:     }
11368:     if (!$passedsymb) {
11369: 	$symb=&symbread();
11370:     } else {
11371: 	$symb=$passedsymb;
11372:     }
11373:     $courseid=$env{'request.course.id'};
11374:     $domain=$env{'user.domain'};
11375:     $name=$env{'user.name'};
11376:     if ($name eq 'public' && $domain eq 'public') {
11377: 	if (!defined($env{'form.username'})) {
11378: 	    $env{'form.username'}.=time.rand(10000000);
11379: 	}
11380: 	$name.=$env{'form.username'};
11381:     }
11382:     return ($symb,$courseid,$domain,$name,$publicuser);
11383: 
11384: }
11385: 
11386: # ------------------------------------------------------------ Serves up a file
11387: # returns either the contents of the file or 
11388: # -1 if the file doesn't exist
11389: #
11390: # if the target is a file that was uploaded via DOCS, 
11391: # a check will be made to see if a current copy exists on the local server,
11392: # if it does this will be served, otherwise a copy will be retrieved from
11393: # the home server for the course and stored in /home/httpd/html/userfiles on
11394: # the local server.   
11395: 
11396: sub getfile {
11397:     my ($file) = @_;
11398:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
11399:     &repcopy($file);
11400:     return &readfile($file);
11401: }
11402: 
11403: sub repcopy_userfile {
11404:     my ($file)=@_;
11405:     my $londocroot = $perlvar{'lonDocRoot'};
11406:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
11407:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
11408:     my ($cdom,$cnum,$filename) = 
11409: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
11410:     my $uri="/uploaded/$cdom/$cnum/$filename";
11411:     if (-e "$file") {
11412: # we already have a local copy, check it out
11413: 	my @fileinfo = stat($file);
11414: 	my $rtncode;
11415: 	my $info;
11416: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
11417: 	if ($lwpresp ne 'ok') {
11418: # there is no such file anymore, even though we had a local copy
11419: 	    if ($rtncode eq '404') {
11420: 		unlink($file);
11421: 	    }
11422: 	    return -1;
11423: 	}
11424: 	if ($info < $fileinfo[9]) {
11425: # nice, the file we have is up-to-date, just say okay
11426: 	    return 'ok';
11427: 	} else {
11428: # the file is outdated, get rid of it
11429: 	    unlink($file);
11430: 	}
11431:     }
11432: # one way or the other, at this point, we don't have the file
11433: # construct the correct path for the file
11434:     my @parts = ($cdom,$cnum); 
11435:     if ($filename =~ m|^(.+)/[^/]+$|) {
11436: 	push @parts, split(/\//,$1);
11437:     }
11438:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11439:     foreach my $part (@parts) {
11440: 	$path .= '/'.$part;
11441: 	if (!-e $path) {
11442: 	    mkdir($path,0770);
11443: 	}
11444:     }
11445: # now the path exists for sure
11446: # get a user agent
11447:     my $ua=new LWP::UserAgent;
11448:     my $transferfile=$file.'.in.transfer';
11449: # FIXME: this should flock
11450:     if (-e $transferfile) { return 'ok'; }
11451:     my $request;
11452:     $uri=~s/^\///;
11453:     my $homeserver = &homeserver($cnum,$cdom);
11454:     my $protocol = $protocol{$homeserver};
11455:     $protocol = 'http' if ($protocol ne 'https');
11456:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
11457:     my $response=$ua->request($request,$transferfile);
11458: # did it work?
11459:     if ($response->is_error()) {
11460: 	unlink($transferfile);
11461: 	&logthis("Userfile repcopy failed for $uri");
11462: 	return -1;
11463:     }
11464: # worked, rename the transfer file
11465:     rename($transferfile,$file);
11466:     return 'ok';
11467: }
11468: 
11469: sub tokenwrapper {
11470:     my $uri=shift;
11471:     $uri=~s|^https?\://([^/]+)||;
11472:     $uri=~s|^/||;
11473:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
11474:     my $token=$1;
11475:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
11476:     if ($udom && $uname && $file) {
11477: 	$file=~s|(\?\.*)*$||;
11478:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
11479:         my $homeserver = &homeserver($uname,$udom);
11480:         my $protocol = $protocol{$homeserver};
11481:         $protocol = 'http' if ($protocol ne 'https');
11482:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
11483:                (($uri=~/\?/)?'&':'?').'token='.$token.
11484:                                '&tokenissued='.$perlvar{'lonHostID'};
11485:     } else {
11486:         return '/adm/notfound.html';
11487:     }
11488: }
11489: 
11490: # call with reqtype HEAD: get last modification time
11491: # call with reqtype GET: get the file contents
11492: # Do not call this with reqtype GET for large files! It loads everything into memory
11493: #
11494: sub getuploaded {
11495:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11496:     $uri=~s/^\///;
11497:     my $homeserver = &homeserver($cnum,$cdom);
11498:     my $protocol = $protocol{$homeserver};
11499:     $protocol = 'http' if ($protocol ne 'https');
11500:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
11501:     my $ua=new LWP::UserAgent;
11502:     my $request=new HTTP::Request($reqtype,$uri);
11503:     my $response=$ua->request($request);
11504:     $$rtncode = $response->code;
11505:     if (! $response->is_success()) {
11506: 	return 'failed';
11507:     }      
11508:     if ($reqtype eq 'HEAD') {
11509: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
11510:     } elsif ($reqtype eq 'GET') {
11511: 	$$info = $response->content;
11512:     }
11513:     return 'ok';
11514: }
11515: 
11516: sub readfile {
11517:     my $file = shift;
11518:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
11519:     my $fh;
11520:     open($fh,"<$file");
11521:     my $a='';
11522:     while (my $line = <$fh>) { $a .= $line; }
11523:     return $a;
11524: }
11525: 
11526: sub filelocation {
11527:     my ($dir,$file) = @_;
11528:     my $location;
11529:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
11530: 
11531:     if ($file =~ m-^/adm/-) {
11532: 	$file=~s-^/adm/wrapper/-/-;
11533: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
11534:     }
11535: 
11536:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
11537:         $location = $file;
11538:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
11539:         my ($udom,$uname,$filename)=
11540:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
11541:         my $home=&homeserver($uname,$udom);
11542:         my $is_me=0;
11543:         my @ids=&current_machine_ids();
11544:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11545:         if ($is_me) {
11546:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
11547:         } else {
11548:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11549:   	      $udom.'/'.$uname.'/'.$filename;
11550:         }
11551:     } elsif ($file =~ m-^/adm/-) {
11552: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
11553:     } else {
11554:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
11555:         $file=~s:^/(res|priv)/:/:;
11556:         my $space=$1;
11557:         if ( !( $file =~ m:^/:) ) {
11558:             $location = $dir. '/'.$file;
11559:         } else {
11560:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
11561:         }
11562:     }
11563:     $location=~s://+:/:g; # remove duplicate /
11564:     while ($location=~m{/\.\./}) {
11565: 	if ($location =~ m{/[^/]+/\.\./}) {
11566: 	    $location=~ s{/[^/]+/\.\./}{/}g;
11567: 	} else {
11568: 	    $location=~ s{/\.\./}{/}g;
11569: 	}
11570:     } #remove dir/..
11571:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11572:     return $location;
11573: }
11574: 
11575: sub hreflocation {
11576:     my ($dir,$file)=@_;
11577:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
11578: 	$file=filelocation($dir,$file);
11579:     } elsif ($file=~m-^/adm/-) {
11580: 	$file=~s-^/adm/wrapper/-/-;
11581: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
11582:     }
11583:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11584: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11585:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
11586: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11587: 	        {/uploaded/$1/$2/}x;
11588:     }
11589:     if ($file=~ m{^/userfiles/}) {
11590: 	$file =~ s{^/userfiles/}{/uploaded/};
11591:     }
11592:     return $file;
11593: }
11594: 
11595: 
11596: 
11597: 
11598: 
11599: sub current_machine_domains {
11600:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
11601: }
11602: 
11603: sub machine_domains {
11604:     my ($hostname) = @_;
11605:     my @domains;
11606:     my %hostname = &all_hostnames();
11607:     while( my($id, $name) = each(%hostname)) {
11608: #	&logthis("-$id-$name-$hostname-");
11609: 	if ($hostname eq $name) {
11610: 	    push(@domains,&host_domain($id));
11611: 	}
11612:     }
11613:     return @domains;
11614: }
11615: 
11616: sub current_machine_ids {
11617:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
11618: }
11619: 
11620: sub machine_ids {
11621:     my ($hostname) = @_;
11622:     $hostname ||= &hostname($perlvar{'lonHostID'});
11623:     my @ids;
11624:     my %name_to_host = &all_names();
11625:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11626: 	return @{ $name_to_host{$hostname} };
11627:     }
11628:     return;
11629: }
11630: 
11631: sub additional_machine_domains {
11632:     my @domains;
11633:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
11634:     while( my $line = <$fh>) {
11635:         $line =~ s/\s//g;
11636:         push(@domains,$line);
11637:     }
11638:     return @domains;
11639: }
11640: 
11641: sub default_login_domain {
11642:     my $domain = $perlvar{'lonDefDomain'};
11643:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
11644:     foreach my $posdom (&current_machine_domains(),
11645:                         &additional_machine_domains()) {
11646:         if (lc($posdom) eq lc($testdomain)) {
11647:             $domain=$posdom;
11648:             last;
11649:         }
11650:     }
11651:     return $domain;
11652: }
11653: 
11654: # ------------------------------------------------------------- Declutters URLs
11655: 
11656: sub declutter {
11657:     my $thisfn=shift;
11658:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
11659:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
11660:     $thisfn=~s/^\///;
11661:     $thisfn=~s|^adm/wrapper/||;
11662:     $thisfn=~s|^adm/coursedocs/showdoc/||;
11663:     $thisfn=~s/^res\///;
11664:     $thisfn=~s/^priv\///;
11665:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
11666:         $thisfn=~s/\?.+$//;
11667:     }
11668:     return $thisfn;
11669: }
11670: 
11671: # ------------------------------------------------------------- Clutter up URLs
11672: 
11673: sub clutter {
11674:     my $thisfn='/'.&declutter(shift);
11675:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
11676: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
11677:        $thisfn='/res'.$thisfn; 
11678:     }
11679:     if ($thisfn !~m|^/adm|) {
11680: 	if ($thisfn =~ m|^/ext/|) {
11681: 	    $thisfn='/adm/wrapper'.$thisfn;
11682: 	} else {
11683: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
11684: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
11685: 	    if ($embstyle eq 'ssi'
11686: 		|| ($embstyle eq 'hdn')
11687: 		|| ($embstyle eq 'rat')
11688: 		|| ($embstyle eq 'prv')
11689: 		|| ($embstyle eq 'ign')) {
11690: 		#do nothing with these
11691: 	    } elsif (($embstyle eq 'img') 
11692: 		|| ($embstyle eq 'emb')
11693: 		|| ($embstyle eq 'wrp')) {
11694: 		$thisfn='/adm/wrapper'.$thisfn;
11695: 	    } elsif ($embstyle eq 'unk'
11696: 		     && $thisfn!~/\.(sequence|page)$/) {
11697: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
11698: 	    } else {
11699: #		&logthis("Got a blank emb style");
11700: 	    }
11701: 	}
11702:     }
11703:     return $thisfn;
11704: }
11705: 
11706: sub clutter_with_no_wrapper {
11707:     my $uri = &clutter(shift);
11708:     if ($uri =~ m-^/adm/-) {
11709: 	$uri =~ s-^/adm/wrapper/-/-;
11710: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
11711:     }
11712:     return $uri;
11713: }
11714: 
11715: sub freeze_escape {
11716:     my ($value)=@_;
11717:     if (ref($value)) {
11718: 	$value=&nfreeze($value);
11719: 	return '__FROZEN__'.&escape($value);
11720:     }
11721:     return &escape($value);
11722: }
11723: 
11724: 
11725: sub thaw_unescape {
11726:     my ($value)=@_;
11727:     if ($value =~ /^__FROZEN__/) {
11728: 	substr($value,0,10,undef);
11729: 	$value=&unescape($value);
11730: 	return &thaw($value);
11731:     }
11732:     return &unescape($value);
11733: }
11734: 
11735: sub correct_line_ends {
11736:     my ($result)=@_;
11737:     $$result =~s/\r\n/\n/mg;
11738:     $$result =~s/\r/\n/mg;
11739: }
11740: # ================================================================ Main Program
11741: 
11742: sub goodbye {
11743:    &logthis("Starting Shut down");
11744: #not converted to using infrastruture and probably shouldn't be
11745:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
11746: #converted
11747: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
11748:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
11749: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
11750: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
11751: #1.1 only
11752: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
11753: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
11754: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
11755: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
11756:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
11757:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
11758:    &logthis(sprintf("%-20s is %s",'hits',$hits));
11759:    &flushcourselogs();
11760:    &logthis("Shutting down");
11761: }
11762: 
11763: sub get_dns {
11764:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
11765:     if (!$ignore_cache) {
11766: 	my ($content,$cached)=
11767: 	    &Apache::lonnet::is_cached_new('dns',$url);
11768: 	if ($cached) {
11769: 	    &$func($content,$hashref);
11770: 	    return;
11771: 	}
11772:     }
11773: 
11774:     my %alldns;
11775:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11776:     foreach my $dns (<$config>) {
11777: 	next if ($dns !~ /^\^(\S*)/x);
11778:         my $line = $1;
11779:         my ($host,$protocol) = split(/:/,$line);
11780:         if ($protocol ne 'https') {
11781:             $protocol = 'http';
11782:         }
11783: 	$alldns{$host} = $protocol;
11784:     }
11785:     while (%alldns) {
11786: 	my ($dns) = keys(%alldns);
11787: 	my $ua=new LWP::UserAgent;
11788:         $ua->timeout(30);
11789: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
11790: 	my $response=$ua->request($request);
11791:         delete($alldns{$dns});
11792: 	next if ($response->is_error());
11793: 	my @content = split("\n",$response->content);
11794: 	unless ($nocache) {
11795: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
11796: 	}
11797: 	&$func(\@content,$hashref);
11798: 	return;
11799:     }
11800:     close($config);
11801:     my $which = (split('/',$url))[3];
11802:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
11803:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
11804:     my @content = <$config>;
11805:     &$func(\@content,$hashref);
11806:     return;
11807: }
11808: 
11809: # ------------------------------------------------------Get DNS checksums file
11810: sub parse_dns_checksums_tab {
11811:     my ($lines,$hashref) = @_;
11812:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11813:     my $loncaparev = &get_server_loncaparev($machine_dom);
11814:     my ($release,$timestamp) = split(/\-/,$loncaparev);
11815:     my (%chksum,%revnum);
11816:     if (ref($lines) eq 'ARRAY') {
11817:         chomp(@{$lines});
11818:         my $version = shift(@{$lines});
11819:         if ($version eq $release) {  
11820:             foreach my $line (@{$lines}) {
11821:                 my ($file,$version,$shasum) = split(/,/,$line);
11822:                 $chksum{$file} = $shasum;
11823:                 $revnum{$file} = $version;
11824:             }
11825:             if (ref($hashref) eq 'HASH') {
11826:                 %{$hashref} = (
11827:                                 sums     => \%chksum,
11828:                                 versions => \%revnum,
11829:                               );
11830:             }
11831:         }
11832:     }
11833:     return;
11834: }
11835: 
11836: sub fetch_dns_checksums {
11837:     my %checksums;
11838:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
11839:     my $loncaparev = &get_server_loncaparev($machine_dom);
11840:     my ($release,$timestamp) = split(/\-/,$loncaparev);
11841:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
11842:              \%checksums);
11843:     return \%checksums;
11844: }
11845: 
11846: # ------------------------------------------------------------ Read domain file
11847: {
11848:     my $loaded;
11849:     my %domain;
11850: 
11851:     sub parse_domain_tab {
11852: 	my ($lines) = @_;
11853: 	foreach my $line (@$lines) {
11854: 	    next if ($line =~ /^(\#|\s*$ )/x);
11855: 
11856: 	    chomp($line);
11857: 	    my ($name,@elements) = split(/:/,$line,9);
11858: 	    my %this_domain;
11859: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
11860: 			       'lang_def', 'city', 'longi', 'lati',
11861: 			       'primary') {
11862: 		$this_domain{$field} = shift(@elements);
11863: 	    }
11864: 	    $domain{$name} = \%this_domain;
11865: 	}
11866:     }
11867: 
11868:     sub reset_domain_info {
11869: 	undef($loaded);
11870: 	undef(%domain);
11871:     }
11872: 
11873:     sub load_domain_tab {
11874: 	my ($ignore_cache) = @_;
11875: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
11876: 	my $fh;
11877: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
11878: 	    my @lines = <$fh>;
11879: 	    &parse_domain_tab(\@lines);
11880: 	}
11881: 	close($fh);
11882: 	$loaded = 1;
11883:     }
11884: 
11885:     sub domain {
11886: 	&load_domain_tab() if (!$loaded);
11887: 
11888: 	my ($name,$what) = @_;
11889: 	return if ( !exists($domain{$name}) );
11890: 
11891: 	if (!$what) {
11892: 	    return $domain{$name}{'description'};
11893: 	}
11894: 	return $domain{$name}{$what};
11895:     }
11896: 
11897:     sub domain_info {
11898:         &load_domain_tab() if (!$loaded);
11899:         return %domain;
11900:     }
11901: 
11902: }
11903: 
11904: 
11905: # ------------------------------------------------------------- Read hosts file
11906: {
11907:     my %hostname;
11908:     my %hostdom;
11909:     my %libserv;
11910:     my $loaded;
11911:     my %name_to_host;
11912:     my %internetdom;
11913:     my %LC_dns_serv;
11914: 
11915:     sub parse_hosts_tab {
11916: 	my ($file) = @_;
11917: 	foreach my $configline (@$file) {
11918: 	    next if ($configline =~ /^(\#|\s*$ )/x);
11919:             chomp($configline);
11920: 	    if ($configline =~ /^\^/) {
11921:                 if ($configline =~ /^\^([\w.\-]+)/) {
11922:                     $LC_dns_serv{$1} = 1;
11923:                 }
11924:                 next;
11925:             }
11926: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
11927: 	    $name=~s/\s//g;
11928: 	    if ($id && $domain && $role && $name) {
11929: 		$hostname{$id}=$name;
11930: 		push(@{$name_to_host{$name}}, $id);
11931: 		$hostdom{$id}=$domain;
11932: 		if ($role eq 'library') { $libserv{$id}=$name; }
11933:                 if (defined($protocol)) {
11934:                     if ($protocol eq 'https') {
11935:                         $protocol{$id} = $protocol;
11936:                     } else {
11937:                         $protocol{$id} = 'http'; 
11938:                     }
11939:                 } else {
11940:                     $protocol{$id} = 'http';
11941:                 }
11942:                 if (defined($intdom)) {
11943:                     $internetdom{$id} = $intdom;
11944:                 }
11945: 	    }
11946: 	}
11947:     }
11948:     
11949:     sub reset_hosts_info {
11950: 	&purge_remembered();
11951: 	&reset_domain_info();
11952: 	&reset_hosts_ip_info();
11953: 	undef(%name_to_host);
11954: 	undef(%hostname);
11955: 	undef(%hostdom);
11956: 	undef(%libserv);
11957: 	undef($loaded);
11958:     }
11959: 
11960:     sub load_hosts_tab {
11961: 	my ($ignore_cache) = @_;
11962: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
11963: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11964: 	my @config = <$config>;
11965: 	&parse_hosts_tab(\@config);
11966: 	close($config);
11967: 	$loaded=1;
11968:     }
11969: 
11970:     sub hostname {
11971: 	&load_hosts_tab() if (!$loaded);
11972: 
11973: 	my ($lonid) = @_;
11974: 	return $hostname{$lonid};
11975:     }
11976: 
11977:     sub all_hostnames {
11978: 	&load_hosts_tab() if (!$loaded);
11979: 
11980: 	return %hostname;
11981:     }
11982: 
11983:     sub all_names {
11984: 	&load_hosts_tab() if (!$loaded);
11985: 
11986: 	return %name_to_host;
11987:     }
11988: 
11989:     sub all_host_domain {
11990:         &load_hosts_tab() if (!$loaded);
11991:         return %hostdom;
11992:     }
11993: 
11994:     sub is_library {
11995: 	&load_hosts_tab() if (!$loaded);
11996: 
11997: 	return exists($libserv{$_[0]});
11998:     }
11999: 
12000:     sub all_library {
12001: 	&load_hosts_tab() if (!$loaded);
12002: 
12003: 	return %libserv;
12004:     }
12005: 
12006:     sub unique_library {
12007: 	#2x reverse removes all hostnames that appear more than once
12008:         my %unique = reverse &all_library();
12009:         return reverse %unique;
12010:     }
12011: 
12012:     sub get_servers {
12013: 	&load_hosts_tab() if (!$loaded);
12014: 
12015: 	my ($domain,$type) = @_;
12016: 	my %possible_hosts = ($type eq 'library') ? %libserv
12017: 	                                          : %hostname;
12018: 	my %result;
12019: 	if (ref($domain) eq 'ARRAY') {
12020: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
12021: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
12022: 		    $result{$host} = $hostname;
12023: 		}
12024: 	    }
12025: 	} else {
12026: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
12027: 		if ($hostdom{$host} eq $domain) {
12028: 		    $result{$host} = $hostname;
12029: 		}
12030: 	    }
12031: 	}
12032: 	return %result;
12033:     }
12034: 
12035:     sub get_unique_servers {
12036:         my %unique = reverse &get_servers(@_);
12037: 	return reverse %unique;
12038:     }
12039: 
12040:     sub host_domain {
12041: 	&load_hosts_tab() if (!$loaded);
12042: 
12043: 	my ($lonid) = @_;
12044: 	return $hostdom{$lonid};
12045:     }
12046: 
12047:     sub all_domains {
12048: 	&load_hosts_tab() if (!$loaded);
12049: 
12050: 	my %seen;
12051: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
12052: 	return @uniq;
12053:     }
12054: 
12055:     sub internet_dom {
12056:         &load_hosts_tab() if (!$loaded);
12057: 
12058:         my ($lonid) = @_;
12059:         return $internetdom{$lonid};
12060:     }
12061: 
12062:     sub is_LC_dns {
12063:         &load_hosts_tab() if (!$loaded);
12064: 
12065:         my ($hostname) = @_;
12066:         return exists($LC_dns_serv{$hostname});
12067:     }
12068: 
12069: }
12070: 
12071: { 
12072:     my %iphost;
12073:     my %name_to_ip;
12074:     my %lonid_to_ip;
12075: 
12076:     sub get_hosts_from_ip {
12077: 	my ($ip) = @_;
12078: 	my %iphosts = &get_iphost();
12079: 	if (ref($iphosts{$ip})) {
12080: 	    return @{$iphosts{$ip}};
12081: 	}
12082: 	return;
12083:     }
12084:     
12085:     sub reset_hosts_ip_info {
12086: 	undef(%iphost);
12087: 	undef(%name_to_ip);
12088: 	undef(%lonid_to_ip);
12089:     }
12090: 
12091:     sub get_host_ip {
12092: 	my ($lonid) = @_;
12093: 	if (exists($lonid_to_ip{$lonid})) {
12094: 	    return $lonid_to_ip{$lonid};
12095: 	}
12096: 	my $name=&hostname($lonid);
12097:    	my $ip = gethostbyname($name);
12098: 	return if (!$ip || length($ip) ne 4);
12099: 	$ip=inet_ntoa($ip);
12100: 	$name_to_ip{$name}   = $ip;
12101: 	$lonid_to_ip{$lonid} = $ip;
12102: 	return $ip;
12103:     }
12104:     
12105:     sub get_iphost {
12106: 	my ($ignore_cache) = @_;
12107: 
12108: 	if (!$ignore_cache) {
12109: 	    if (%iphost) {
12110: 		return %iphost;
12111: 	    }
12112: 	    my ($ip_info,$cached)=
12113: 		&Apache::lonnet::is_cached_new('iphost','iphost');
12114: 	    if ($cached) {
12115: 		%iphost      = %{$ip_info->[0]};
12116: 		%name_to_ip  = %{$ip_info->[1]};
12117: 		%lonid_to_ip = %{$ip_info->[2]};
12118: 		return %iphost;
12119: 	    }
12120: 	}
12121: 
12122: 	# get yesterday's info for fallback
12123: 	my %old_name_to_ip;
12124: 	my ($ip_info,$cached)=
12125: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
12126: 	if ($cached) {
12127: 	    %old_name_to_ip = %{$ip_info->[1]};
12128: 	}
12129: 
12130: 	my %name_to_host = &all_names();
12131: 	foreach my $name (keys(%name_to_host)) {
12132: 	    my $ip;
12133: 	    if (!exists($name_to_ip{$name})) {
12134: 		$ip = gethostbyname($name);
12135: 		if (!$ip || length($ip) ne 4) {
12136: 		    if (defined($old_name_to_ip{$name})) {
12137: 			$ip = $old_name_to_ip{$name};
12138: 			&logthis("Can't find $name defaulting to old $ip");
12139: 		    } else {
12140: 			&logthis("Name $name no IP found");
12141: 			next;
12142: 		    }
12143: 		} else {
12144: 		    $ip=inet_ntoa($ip);
12145: 		}
12146: 		$name_to_ip{$name} = $ip;
12147: 	    } else {
12148: 		$ip = $name_to_ip{$name};
12149: 	    }
12150: 	    foreach my $id (@{ $name_to_host{$name} }) {
12151: 		$lonid_to_ip{$id} = $ip;
12152: 	    }
12153: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
12154: 	}
12155: 	&do_cache_new('iphost','iphost',
12156: 		      [\%iphost,\%name_to_ip,\%lonid_to_ip],
12157: 		      48*60*60);
12158: 
12159: 	return %iphost;
12160:     }
12161: 
12162:     #
12163:     #  Given a DNS returns the loncapa host name for that DNS 
12164:     # 
12165:     sub host_from_dns {
12166:         my ($dns) = @_;
12167:         my @hosts;
12168:         my $ip;
12169: 
12170:         if (exists($name_to_ip{$dns})) {
12171:             $ip = $name_to_ip{$dns};
12172:         }
12173:         if (!$ip) {
12174:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12175:             if (length($ip) == 4) { 
12176: 	        $ip   = &IO::Socket::inet_ntoa($ip);
12177:             }
12178:         }
12179:         if ($ip) {
12180: 	    @hosts = get_hosts_from_ip($ip);
12181: 	    return $hosts[0];
12182:         }
12183:         return undef;
12184:     }
12185: 
12186:     sub get_internet_names {
12187:         my ($lonid) = @_;
12188:         return if ($lonid eq '');
12189:         my ($idnref,$cached)=
12190:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
12191:         if ($cached) {
12192:             return $idnref;
12193:         }
12194:         my $ip = &get_host_ip($lonid);
12195:         my @hosts = &get_hosts_from_ip($ip);
12196:         my %iphost = &get_iphost();
12197:         my (@idns,%seen);
12198:         foreach my $id (@hosts) {
12199:             my $dom = &host_domain($id);
12200:             my $prim_id = &domain($dom,'primary');
12201:             my $prim_ip = &get_host_ip($prim_id);
12202:             next if ($seen{$prim_ip});
12203:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12204:                 foreach my $id (@{$iphost{$prim_ip}}) {
12205:                     my $intdom = &internet_dom($id);
12206:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
12207:                         push(@idns,$intdom);
12208:                     }
12209:                 }
12210:             }
12211:             $seen{$prim_ip} = 1;
12212:         }
12213:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
12214:     }
12215: 
12216: }
12217: 
12218: sub all_loncaparevs {
12219:     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);
12220: }
12221: 
12222: # ---------------------------------------------------------- Read loncaparev table
12223: {
12224:     sub load_loncaparevs { 
12225:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12226:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12227:                 while (my $configline=<$config>) {
12228:                     chomp($configline);
12229:                     my ($hostid,$loncaparev)=split(/:/,$configline);
12230:                     $loncaparevs{$hostid}=$loncaparev;
12231:                 }
12232:                 close($config);
12233:             }
12234:         }
12235:     }
12236: }
12237: 
12238: # ---------------------------------------------------------- Read serverhostID table
12239: {
12240:     sub load_serverhomeIDs {
12241:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12242:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12243:                 while (my $configline=<$config>) {
12244:                     chomp($configline);
12245:                     my ($name,$id)=split(/:/,$configline);
12246:                     $serverhomeIDs{$name}=$id;
12247:                 }
12248:                 close($config);
12249:             }
12250:         }
12251:     }
12252: }
12253: 
12254: 
12255: BEGIN {
12256: 
12257: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12258:     unless ($readit) {
12259: {
12260:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12261:     %perlvar = (%perlvar,%{$configvars});
12262: }
12263: 
12264: 
12265: # ------------------------------------------------------ Read spare server file
12266: {
12267:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
12268: 
12269:     while (my $configline=<$config>) {
12270:        chomp($configline);
12271:        if ($configline) {
12272: 	   my ($host,$type) = split(':',$configline,2);
12273: 	   if (!defined($type) || $type eq '') { $type = 'default' };
12274: 	   push(@{ $spareid{$type} }, $host);
12275:        }
12276:     }
12277:     close($config);
12278: }
12279: # ------------------------------------------------------------ Read permissions
12280: {
12281:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
12282: 
12283:     while (my $configline=<$config>) {
12284: 	chomp($configline);
12285: 	if ($configline) {
12286: 	    my ($role,$perm)=split(/ /,$configline);
12287: 	    if ($perm ne '') { $pr{$role}=$perm; }
12288: 	}
12289:     }
12290:     close($config);
12291: }
12292: 
12293: # -------------------------------------------- Read plain texts for permissions
12294: {
12295:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
12296: 
12297:     while (my $configline=<$config>) {
12298: 	chomp($configline);
12299: 	if ($configline) {
12300: 	    my ($short,@plain)=split(/:/,$configline);
12301:             %{$prp{$short}} = ();
12302: 	    if (@plain > 0) {
12303:                 $prp{$short}{'std'} = $plain[0];
12304:                 for (my $i=1; $i<@plain; $i++) {
12305:                     $prp{$short}{'alt'.$i} = $plain[$i];  
12306:                 }
12307:             }
12308: 	}
12309:     }
12310:     close($config);
12311: }
12312: 
12313: # ---------------------------------------------------------- Read package table
12314: {
12315:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
12316: 
12317:     while (my $configline=<$config>) {
12318: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
12319: 	chomp($configline);
12320: 	my ($short,$plain)=split(/:/,$configline);
12321: 	my ($pack,$name)=split(/\&/,$short);
12322: 	if ($plain ne '') {
12323: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
12324: 	    $packagetab{$short}=$plain; 
12325: 	}
12326:     }
12327:     close($config);
12328: }
12329: 
12330: # ---------------------------------------------------------- Read loncaparev table
12331: 
12332: &load_loncaparevs();
12333: 
12334: # ---------------------------------------------------------- Read serverhostID table
12335: 
12336: &load_serverhomeIDs();
12337: 
12338: # ---------------------------------------------------------- Read releaseslist XML
12339: {
12340:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12341:     if (-e $file) {
12342:         my $parser = HTML::LCParser->new($file);
12343:         while (my $token = $parser->get_token()) {
12344:             if ($token->[0] eq 'S') {
12345:                 my $item = $token->[1];
12346:                 my $name = $token->[2]{'name'};
12347:                 my $value = $token->[2]{'value'};
12348:                 if ($item ne '' && $name ne '' && $value ne '') {
12349:                     my $release = $parser->get_text();
12350:                     $release =~ s/(^\s*|\s*$ )//gx;
12351:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
12352:                 }
12353:             }
12354:         }
12355:     }
12356: }
12357: 
12358: # ---------------------------------------------------------- Read managers table
12359: {
12360:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12361:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12362:             while (my $configline=<$config>) {
12363:                 chomp($configline);
12364:                 next if ($configline =~ /^\#/);
12365:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12366:                     $managerstab{$configline} = 1;
12367:                 }
12368:             }
12369:             close($config);
12370:         }
12371:     }
12372: }
12373: 
12374: # ------------- set up temporary directory
12375: {
12376:     $tmpdir = LONCAPA::tempdir();
12377: 
12378: }
12379: 
12380: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
12381: 				'compress_threshold'=> 20_000,
12382:  			        });
12383: 
12384: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
12385: $dumpcount=0;
12386: $locknum=0;
12387: 
12388: &logtouch();
12389: &logthis('<font color="yellow">INFO: Read configuration</font>');
12390: $readit=1;
12391:     {
12392: 	use integer;
12393: 	my $test=(2**32)+1;
12394: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
12395: 	&logthis(" Detected 64bit platform ($_64bit)");
12396:     }
12397: }
12398: }
12399: 
12400: 1;
12401: __END__
12402: 
12403: =pod
12404: 
12405: =head1 NAME
12406: 
12407: Apache::lonnet - Subroutines to ask questions about things in the network.
12408: 
12409: =head1 SYNOPSIS
12410: 
12411: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
12412: 
12413:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12414: 
12415: Common parameters:
12416: 
12417: =over 4
12418: 
12419: =item *
12420: 
12421: $uname : an internal username (if $cname expecting a course Id specifically)
12422: 
12423: =item *
12424: 
12425: $udom : a domain (if $cdom expecting a course's domain specifically)
12426: 
12427: =item *
12428: 
12429: $symb : a resource instance identifier
12430: 
12431: =item *
12432: 
12433: $namespace : the name of a .db file that contains the data needed or
12434: being set.
12435: 
12436: =back
12437: 
12438: =head1 OVERVIEW
12439: 
12440: lonnet provides subroutines which interact with the
12441: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12442: about classes, users, and resources.
12443: 
12444: For many of these objects you can also use this to store data about
12445: them or modify them in various ways.
12446: 
12447: =head2 Symbs
12448: 
12449: To identify a specific instance of a resource, LON-CAPA uses symbols
12450: or "symbs"X<symb>. These identifiers are built from the URL of the
12451: map, the resource number of the resource in the map, and the URL of
12452: the resource itself. The latter is somewhat redundant, but might help
12453: if maps change.
12454: 
12455: An example is
12456: 
12457:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12458: 
12459: The respective map entry is
12460: 
12461:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
12462:   title="Problem 2">
12463:  </resource>
12464: 
12465: Symbs are used by the random number generator, as well as to store and
12466: restore data specific to a certain instance of for example a problem.
12467: 
12468: =head2 Storing And Retrieving Data
12469: 
12470: X<store()>X<cstore()>X<restore()>Three of the most important functions
12471: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12472: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12473: is is the non-critical message twin of cstore. These functions are for
12474: handlers to store a perl hash to a user's permanent data space in an
12475: easy manner, and to retrieve it again on another call. It is expected
12476: that a handler would use this once at the beginning to retrieve data,
12477: and then again once at the end to send only the new data back.
12478: 
12479: The data is stored in the user's data directory on the user's
12480: homeserver under the ID of the course.
12481: 
12482: The hash that is returned by restore will have all of the previous
12483: value for all of the elements of the hash.
12484: 
12485: Example:
12486: 
12487:  #creating a hash
12488:  my %hash;
12489:  $hash{'foo'}='bar';
12490: 
12491:  #storing it
12492:  &Apache::lonnet::cstore(\%hash);
12493: 
12494:  #changing a value
12495:  $hash{'foo'}='notbar';
12496: 
12497:  #adding a new value
12498:  $hash{'bar'}='foo';
12499:  &Apache::lonnet::cstore(\%hash);
12500: 
12501:  #retrieving the hash
12502:  my %history=&Apache::lonnet::restore();
12503: 
12504:  #print the hash
12505:  foreach my $key (sort(keys(%history))) {
12506:    print("\%history{$key} = $history{$key}");
12507:  }
12508: 
12509: Will print out:
12510: 
12511:  %history{1:foo} = bar
12512:  %history{1:keys} = foo:timestamp
12513:  %history{1:timestamp} = 990455579
12514:  %history{2:bar} = foo
12515:  %history{2:foo} = notbar
12516:  %history{2:keys} = foo:bar:timestamp
12517:  %history{2:timestamp} = 990455580
12518:  %history{bar} = foo
12519:  %history{foo} = notbar
12520:  %history{timestamp} = 990455580
12521:  %history{version} = 2
12522: 
12523: Note that the special hash entries C<keys>, C<version> and
12524: C<timestamp> were added to the hash. C<version> will be equal to the
12525: total number of versions of the data that have been stored. The
12526: C<timestamp> attribute will be the UNIX time the hash was
12527: stored. C<keys> is available in every historical section to list which
12528: keys were added or changed at a specific historical revision of a
12529: hash.
12530: 
12531: B<Warning>: do not store the hash that restore returns directly. This
12532: will cause a mess since it will restore the historical keys as if the
12533: were new keys. I.E. 1:foo will become 1:1:foo etc.
12534: 
12535: Calling convention:
12536: 
12537:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
12538:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname);
12539: 
12540: For more detailed information, see lonnet specific documentation.
12541: 
12542: =head1 RETURN MESSAGES
12543: 
12544: =over 4
12545: 
12546: =item * B<con_lost>: unable to contact remote host
12547: 
12548: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12549: when the connection is brought back up
12550: 
12551: =item * B<con_failed>: unable to contact remote host and unable to save message
12552: for later delivery
12553: 
12554: =item * B<error:>: an error a occurred, a description of the error follows the :
12555: 
12556: =item * B<no_such_host>: unable to fund a host associated with the user/domain
12557: that was requested
12558: 
12559: =back
12560: 
12561: =head1 PUBLIC SUBROUTINES
12562: 
12563: =head2 Session Environment Functions
12564: 
12565: =over 4
12566: 
12567: =item * 
12568: X<appenv()>
12569: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
12570: the user envirnoment file, and will be restored for each access this
12571: user makes during this session, also modifies the %env for the current
12572: process. Optional rolesarrayref - if defined contains a reference to an array
12573: of roles which are exempt from the restriction on modifying user.role entries 
12574: in the user's environment.db and in %env.    
12575: 
12576: =item *
12577: X<delenv()>
12578: B<delenv($delthis,$regexp)>: removes all items from the session
12579: environment file that begin with $delthis. If the 
12580: optional second arg - $regexp - is true, $delthis is treated as a 
12581: regular expression, otherwise \Q$delthis\E is used. 
12582: The values are also deleted from the current processes %env.
12583: 
12584: =item * get_env_multiple($name) 
12585: 
12586: gets $name from the %env hash, it seemlessly handles the cases where multiple
12587: values may be defined and end up as an array ref.
12588: 
12589: returns an array of values
12590: 
12591: =back
12592: 
12593: =head2 User Information
12594: 
12595: =over 4
12596: 
12597: =item *
12598: X<queryauthenticate()>
12599: B<queryauthenticate($uname,$udom)>: try to determine user's current 
12600: authentication scheme
12601: 
12602: =item *
12603: X<authenticate()>
12604: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
12605: authenticate user from domain's lib servers (first use the current
12606: one). C<$upass> should be the users password.
12607: $checkdefauth is optional (value is 1 if a check should be made to
12608:    authenticate user using default authentication method, and allow
12609:    account creation if username does not have account in the domain).
12610: $clientcancheckhost is optional (value is 1 if checking whether the
12611:    server can host will occur on the client side in lonauth.pm).   
12612: 
12613: =item *
12614: X<homeserver()>
12615: B<homeserver($uname,$udom)>: find the server which has
12616: the user's directory and files (there must be only one), this caches
12617: the answer, and also caches if there is a borken connection.
12618: 
12619: =item *
12620: X<idget()>
12621: B<idget($udom,@ids)>: find the usernames behind a list of IDs
12622: (IDs are a unique resource in a domain, there must be only 1 ID per
12623: username, and only 1 username per ID in a specific domain) (returns
12624: hash: id=>name,id=>name)
12625: 
12626: =item *
12627: X<idrget()>
12628: B<idrget($udom,@unames)>: find the IDs behind a list of
12629: usernames (returns hash: name=>id,name=>id)
12630: 
12631: =item *
12632: X<idput()>
12633: B<idput($udom,%ids)>: store away a list of names and associated IDs
12634: 
12635: =item *
12636: X<rolesinit()>
12637: B<rolesinit($udom,$username)>: get user privileges.
12638: returns user role, first access and timer interval hashes
12639: 
12640: =item *
12641: X<privileged()>
12642: B<privileged($username,$domain)>: returns a true if user has a
12643: privileged and active role (i.e. su or dc), false otherwise.
12644: 
12645: =item *
12646: X<getsection()>
12647: B<getsection($udom,$uname,$cname)>: finds the section of student in the
12648: course $cname, return section name/number or '' for "not in course"
12649: and '-1' for "no section"
12650: 
12651: =item *
12652: X<userenvironment()>
12653: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
12654: passed in @what from the requested user's environment, returns a hash
12655: 
12656: =item * 
12657: X<userlog_query()>
12658: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
12659: activity.log file. %filters defines filters applied when parsing the
12660: log file. These can be start or end timestamps, or the type of action
12661: - log to look for Login or Logout events, check for Checkin or
12662: Checkout, role for role selection. The response is in the form
12663: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
12664: escaped strings of the action recorded in the activity.log file.
12665: 
12666: =back
12667: 
12668: =head2 User Roles
12669: 
12670: =over 4
12671: 
12672: =item *
12673: 
12674: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
12675:  F: full access
12676:  U,I,K: authentication modes (cxx only)
12677:  '': forbidden
12678:  1: user needs to choose course
12679:  2: browse allowed
12680:  A: passphrase authentication needed
12681: 
12682: =item *
12683: 
12684: constructaccess($url,$setpriv) : check for access to construction space URL
12685: 
12686: See if the owner domain and name in the URL match those in the
12687: expected environment.  If so, return three element list
12688: ($ownername,$ownerdomain,$ownerhome).
12689: 
12690: Otherwise return the null string.
12691: 
12692: If second argument 'setpriv' is true, it assigns the privileges,
12693: and returns the same three element list, unless the owner has
12694: blocked "ad hoc" Domain Coordinator access to the Author Space,
12695: in which case the null string is returned.
12696: 
12697: =item *
12698: 
12699: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
12700: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
12701: and course level
12702: 
12703: =item *
12704: 
12705: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
12706: (rolesplain.tab); plain text explanation of a user role term.
12707: $type is Course (default) or Community.
12708: If $forcedefault evaluates to true, text returned will be default 
12709: text for $type. Otherwise, if this is a course, the text returned 
12710: will be a custom name for the role (if defined in the course's 
12711: environment).  If no custom name is defined the default is returned.
12712:    
12713: =item *
12714: 
12715: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
12716: All arguments are optional. Returns a hash of a roles, either for
12717: co-author/assistant author roles for a user's Construction Space
12718: (default), or if $context is 'userroles', roles for the user himself,
12719: In the hash, keys are set to colon-separated $uname,$udom,$role, and
12720: (optionally) if $withsec is true, a fourth colon-separated item - $section.
12721: For each key, value is set to colon-separated start and end times for
12722: the role.  If no username and domain are specified, will default to
12723: current user/domain. Types, roles, and roledoms are references to arrays
12724: of role statuses (active, future or previous), roles 
12725: (e.g., cc,in, st etc.) and domains of the roles which can be used
12726: to restrict the list of roles reported. If no array ref is 
12727: provided for types, will default to return only active roles.
12728: 
12729: =item *
12730: 
12731: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
12732: user: $uname:$udom has a role in the course: $cdom_$cnum. 
12733: 
12734: Additional optional arguments are: $type (if role checking is to be restricted 
12735: to certain user status types -- previous (expired roles), active (currently
12736: available roles) or future (roles available in the future), and
12737: $hideprivileged -- if true will not report course roles for users who
12738: have active Domain Coordinator role in course's domain or in additional
12739: domains (specified in 'Domains to check for privileged users' in course
12740: environment -- set via:  Course Settings -> Classlists and staff listing).
12741: 
12742: =item *
12743: 
12744: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
12745: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
12746: $possdomains and $possroles are optional array refs -- to domains to check and
12747: roles to check.  If $possdomains is not specified, a dump will be done of the
12748: users' roles.db to check for a dc or su role in any domain. This can be
12749: time consuming if &privileged is called repeatedly (e.g., when displaying a
12750: classlist), so in such cases, supplying a $possdomains array is preferred, as
12751: this then allows &privileged_by_domain() to be used, which caches the identity
12752: of privileged users, eliminating the need for repeated calls to &dump().
12753: 
12754: =item *
12755: 
12756: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
12757: where the outer hash keys are domains specified in the $possdomains array ref,
12758: next inner hash keys are privileged roles specified in the $roles array ref,
12759: and the innermost hash contains key = value pairs for username:domain = end:start
12760: for active or future "privileged" users with that role in that domain. To avoid
12761: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
12762: innerhash are cached using priv_$role and $dom as the identifiers.
12763: 
12764: =back
12765: 
12766: =head2 User Modification
12767: 
12768: =over 4
12769: 
12770: =item *
12771: 
12772: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
12773: user for the level given by URL.  Optional start and end dates (leave empty
12774: string or zero for "no date")
12775: 
12776: =item *
12777: 
12778: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
12779: change a users, password, possible return values are: ok,
12780: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
12781: refused
12782: 
12783: =item *
12784: 
12785: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
12786: 
12787: =item *
12788: 
12789: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
12790:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
12791: 
12792: will update user information (firstname,middlename,lastname,generation,
12793: permanentemail), and if forceid is true, student/employee ID also.
12794: A user's institutional affiliation(s) can also be updated.
12795: User information fields will not be overwritten with empty entries 
12796: unless the field is included in the $candelete array reference.
12797: This array is included when a single user is modified via "Manage Users",
12798: or when Autoupdate.pl is run by cron in a domain.
12799: 
12800: =item *
12801: 
12802: modifystudent
12803: 
12804: modify a student's enrollment and identification information.
12805: The course id is resolved based on the current user's environment.  
12806: This means the invoking user must be a course coordinator or otherwise
12807: associated with a course.
12808: 
12809: This call is essentially a wrapper for lonnet::modifyuser and
12810: lonnet::modify_student_enrollment
12811: 
12812: Inputs: 
12813: 
12814: =over 4
12815: 
12816: =item B<$udom> Student's loncapa domain
12817: 
12818: =item B<$uname> Student's loncapa login name
12819: 
12820: =item B<$uid> Student/Employee ID
12821: 
12822: =item B<$umode> Student's authentication mode
12823: 
12824: =item B<$upass> Student's password
12825: 
12826: =item B<$first> Student's first name
12827: 
12828: =item B<$middle> Student's middle name
12829: 
12830: =item B<$last> Student's last name
12831: 
12832: =item B<$gene> Student's generation
12833: 
12834: =item B<$usec> Student's section in course
12835: 
12836: =item B<$end> Unix time of the roles expiration
12837: 
12838: =item B<$start> Unix time of the roles start date
12839: 
12840: =item B<$forceid> If defined, allow $uid to be changed
12841: 
12842: =item B<$desiredhome> server to use as home server for student
12843: 
12844: =item B<$email> Student's permanent e-mail address
12845: 
12846: =item B<$type> Type of enrollment (auto or manual)
12847: 
12848: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
12849: 
12850: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
12851: 
12852: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
12853: 
12854: =item B<$context> role change context (shown in User Management Logs display in a course)
12855: 
12856: =item B<$inststatus> institutional status of user - : separated string of escaped status types
12857: 
12858: =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.
12859: 
12860: =back
12861: 
12862: =item *
12863: 
12864: modify_student_enrollment
12865: 
12866: Change a student's enrollment status in a class.  The environment variable
12867: 'role.request.course' must be defined for this function to proceed.
12868: 
12869: Inputs:
12870: 
12871: =over 4
12872: 
12873: =item $udom, student's domain
12874: 
12875: =item $uname, student's name
12876: 
12877: =item $uid, student's user id
12878: 
12879: =item $first, student's first name
12880: 
12881: =item $middle
12882: 
12883: =item $last
12884: 
12885: =item $gene
12886: 
12887: =item $usec
12888: 
12889: =item $end
12890: 
12891: =item $start
12892: 
12893: =item $type
12894: 
12895: =item $locktype
12896: 
12897: =item $cid
12898: 
12899: =item $selfenroll
12900: 
12901: =item $context
12902: 
12903: =item $credits, number of credits student will earn from this class
12904: 
12905: =back
12906: 
12907: 
12908: =item *
12909: 
12910: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
12911: custom role; give a custom role to a user for the level given by URL.  Specify
12912: name and domain of role author, and role name
12913: 
12914: =item *
12915: 
12916: revokerole($udom,$uname,$url,$role) : revoke a role for url
12917: 
12918: =item *
12919: 
12920: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
12921: 
12922: =back
12923: 
12924: =head2 Course Infomation
12925: 
12926: =over 4
12927: 
12928: =item *
12929: 
12930: coursedescription($courseid,$options) : returns a hash of information about the
12931: specified course id, including all environment settings for the
12932: course, the description of the course will be in the hash under the
12933: key 'description'
12934: 
12935: $options is an optional parameter that if supplied is a hash reference that controls
12936: what how this function works.  It has the following key/values:
12937: 
12938: =over 4
12939: 
12940: =item freshen_cache
12941: 
12942: If defined, and the environment cache for the course is valid, it is 
12943: returned in the returned hash.
12944: 
12945: =item one_time
12946: 
12947: If defined, the last cache time is set to _now_
12948: 
12949: =item user
12950: 
12951: If defined, the supplied username is used instead of the current user.
12952: 
12953: 
12954: =back
12955: 
12956: =item *
12957: 
12958: resdata($name,$domain,$type,@which) : request for current parameter
12959: setting for a specific $type, where $type is either 'course' or 'user',
12960: @what should be a list of parameters to ask about. This routine caches
12961: answers for 10 minutes.
12962: 
12963: =item *
12964: 
12965: get_courseresdata($courseid, $domain) : dump the entire course resource
12966: data base, returning a hash that is keyed by the resource name and has
12967: values that are the resource value.  I believe that the timestamps and
12968: versions are also returned.
12969: 
12970: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
12971: supplemental content area. This routine caches the number of files for 
12972: 10 minutes.
12973: 
12974: =back
12975: 
12976: =head2 Course Modification
12977: 
12978: =over 4
12979: 
12980: =item *
12981: 
12982: writecoursepref($courseid,%prefs) : write preferences (environment
12983: database) for a course
12984: 
12985: =item *
12986: 
12987: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
12988: 
12989: =item *
12990: 
12991: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
12992: 
12993: =item *
12994: 
12995: is_course($courseid), is_course($cdom, $cnum)
12996: 
12997: Accepts either a combined $courseid (in the form of domain_courseid) or the
12998: two component version $cdom, $cnum. It checks if the specified course exists.
12999: 
13000: Returns:
13001:     undef if the course doesn't exist, otherwise
13002:     in scalar context the combined courseid.
13003:     in list context the two components of the course identifier, domain and 
13004:     courseid.    
13005: 
13006: =back
13007: 
13008: =head2 Resource Subroutines
13009: 
13010: =over 4
13011: 
13012: =item *
13013: 
13014: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
13015: 
13016: =item *
13017: 
13018: repcopy($filename) : subscribes to the requested file, and attempts to
13019: replicate from the owning library server, Might return
13020: 'unavailable', 'not_found', 'forbidden', 'ok', or
13021: 'bad_request', also attempts to grab the metadata for the
13022: resource. Expects the local filesystem pathname
13023: (/home/httpd/html/res/....)
13024: 
13025: =back
13026: 
13027: =head2 Resource Information
13028: 
13029: =over 4
13030: 
13031: =item *
13032: 
13033: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
13034: and returns the value of a variety of different possible values,
13035: $varname should be a request string, and the other parameters can be
13036: used to specify who and what one is asking about. Ordinarily, $cid 
13037: does not need to be specified, as it is retrived from 
13038: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
13039: within lonuserstate::loadmap() when initializing a course, before
13040: $env{'request.course.id'} has been set, so it needs to be provided
13041: in that one case.
13042: 
13043: Possible values for $varname are environment.lastname (or other item
13044: from the envirnment hash), user.name (or someother aspect about the
13045: user), resource.0.maxtries (or some other part and parameter of a
13046: resource)
13047: 
13048: =item *
13049: 
13050: directcondval($number) : get current value of a condition; reads from a state
13051: string
13052: 
13053: =item *
13054: 
13055: condval($condidx) : value of condition index based on state
13056: 
13057: =item *
13058: 
13059: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
13060: resource's metadata, $what should be either a specific key, or either
13061: 'keys' (to get a list of possible keys) or 'packages' to get a list of
13062: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
13063: 
13064: this function automatically caches all requests
13065: 
13066: =item *
13067: 
13068: metadata_query($query,$custom,$customshow) : make a metadata query against the
13069: network of library servers; returns file handle of where SQL and regex results
13070: will be stored for query
13071: 
13072: =item *
13073: 
13074: symbread($filename) : return symbolic list entry (filename argument optional);
13075: returns the data handle
13076: 
13077: =item *
13078: 
13079: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
13080: and is a possible symb for the URL in $thisfn, and if is an encrypted
13081: resource that the user accessed using /enc/ returns a 1 on success, 0
13082: on failure, user must be in a course, as it assumes the existence of
13083: the course initial hash, and uses $env('request.course.id'}.  The third
13084: arg is an optional reference to a scalar.  If this arg is passed in the 
13085: call to symbverify, it will be set to 1 if the symb has been set to be 
13086: encrypted; otherwise it will be null.  
13087: 
13088: =item *
13089: 
13090: symbclean($symb) : removes versions numbers from a symb, returns the
13091: cleaned symb
13092: 
13093: =item *
13094: 
13095: is_on_map($uri) : checks if the $uri is somewhere on the current
13096: course map, user must be in a course for it to work.
13097: 
13098: =item *
13099: 
13100: numval($salt) : return random seed value (addend for rndseed)
13101: 
13102: =item *
13103: 
13104: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13105: a random seed, all arguments are optional, if they aren't sent it uses the
13106: environment to derive them. Note: if symb isn't sent and it can't get one
13107: from &symbread it will use the current time as its return value
13108: 
13109: =item *
13110: 
13111: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13112: unfakeable, receipt
13113: 
13114: =item *
13115: 
13116: receipt() : API to ireceipt working off of env values; given out to users
13117: 
13118: =item *
13119: 
13120: countacc($url) : count the number of accesses to a given URL
13121: 
13122: =item *
13123: 
13124: 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
13125: 
13126: =item *
13127: 
13128: 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)
13129: 
13130: =item *
13131: 
13132: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
13133: 
13134: =item *
13135: 
13136: devalidate($symb) : devalidate temporary spreadsheet calculations,
13137: forcing spreadsheet to reevaluate the resource scores next time.
13138: 
13139: =item * 
13140: 
13141: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13142: when viewing in course context.
13143: 
13144:  input: six args -- filename (decluttered), course number, course domain,
13145:                     url, symb (if registered) and group (if this is a 
13146:                     group item -- e.g., bulletin board, group page etc.).
13147: 
13148:  output: array of five scalars --
13149:          $cfile -- url for file editing if editable on current server
13150:          $home -- homeserver of resource (i.e., for author if published,
13151:                                           or course if uploaded.).
13152:          $switchserver --  1 if server switch will be needed.
13153:          $forceedit -- 1 if icon/link should be to go to edit mode 
13154:          $forceview -- 1 if icon/link should be to go to view mode
13155: 
13156: =item *
13157: 
13158: is_course_upload($file,$cnum,$cdom)
13159: 
13160: Used in course context to determine if current file was uploaded to 
13161: the course (i.e., would be found in /userfiles/docs on the course's 
13162: homeserver.
13163: 
13164:   input: 3 args -- filename (decluttered), course number and course domain.
13165:   output: boolean -- 1 if file was uploaded.
13166: 
13167: =back
13168: 
13169: =head2 Storing/Retreiving Data
13170: 
13171: =over 4
13172: 
13173: =item *
13174: 
13175: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
13176: for this url; hashref needs to be given and should be a \%hashname; the
13177: remaining args aren't required and if they aren't passed or are '' they will
13178: be derived from the env
13179: 
13180: =item *
13181: 
13182: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
13183: uses critical subroutine
13184: 
13185: =item *
13186: 
13187: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13188: all args are optional
13189: 
13190: =item *
13191: 
13192: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
13193: dumps the complete (or key matching regexp) namespace into a hash
13194: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13195: normally &store()ed into
13196: 
13197: $range should be either an integer '100' (give me the first 100
13198:                                            matching records)
13199:               or be  two integers sperated by a - with no spaces
13200:                  '30-50' (give me the 30th through the 50th matching
13201:                           records)
13202: 
13203: 
13204: =item *
13205: 
13206: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
13207: replaces a &store() version of data with a replacement set of data
13208: for a particular resource in a namespace passed in the $storehash hash 
13209: reference
13210: 
13211: =item *
13212: 
13213: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13214: works very similar to store/cstore, but all data is stored in a
13215: temporary location and can be reset using tmpreset, $storehash should
13216: be a hash reference, returns nothing on success
13217: 
13218: =item *
13219: 
13220: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13221: similar to restore, but all data is stored in a temporary location and
13222: can be reset using tmpreset. Returns a hash of values on success,
13223: error string otherwise.
13224: 
13225: =item *
13226: 
13227: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13228: deltes all keys for $symb form the temporary storage hash.
13229: 
13230: =item *
13231: 
13232: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13233: reference filled in from namesp ($udom and $uname are optional)
13234: 
13235: =item *
13236: 
13237: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13238: namesp ($udom and $uname are optional)
13239: 
13240: =item *
13241: 
13242: dump($namespace,$udom,$uname,$regexp,$range) : 
13243: dumps the complete (or key matching regexp) namespace into a hash
13244: ($udom, $uname, $regexp, $range are optional)
13245: 
13246: $range should be either an integer '100' (give me the first 100
13247:                                            matching records)
13248:               or be  two integers sperated by a - with no spaces
13249:                  '30-50' (give me the 30th through the 50th matching
13250:                           records)
13251: =item *
13252: 
13253: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13254: $store can be a scalar, an array reference, or if the amount to be 
13255: incremented is > 1, a hash reference.
13256: 
13257: ($udom and $uname are optional)
13258: 
13259: =item *
13260: 
13261: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13262: ($udom and $uname are optional)
13263: 
13264: =item *
13265: 
13266: cput($namespace,$storehash,$udom,$uname) : critical put
13267: ($udom and $uname are optional)
13268: 
13269: =item *
13270: 
13271: newput($namespace,$storehash,$udom,$uname) :
13272: 
13273: Attempts to store the items in the $storehash, but only if they don't
13274: currently exist, if this succeeds you can be certain that you have 
13275: successfully created a new key value pair in the $namespace db.
13276: 
13277: 
13278: Args:
13279:  $namespace: name of database to store values to
13280:  $storehash: hashref to store to the db
13281:  $udom: (optional) domain of user containing the db
13282:  $uname: (optional) name of user caontaining the db
13283: 
13284: Returns:
13285:  'ok' -> succeeded in storing all keys of $storehash
13286:  'key_exists: <key>' -> failed to anything out of $storehash, as at
13287:                         least <key> already existed in the db (other
13288:                         requested keys may also already exist)
13289:  'error: <msg>' -> unable to tie the DB or other error occurred
13290:  'con_lost' -> unable to contact request server
13291:  'refused' -> action was not allowed by remote machine
13292: 
13293: 
13294: =item *
13295: 
13296: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13297: reference filled in from namesp (encrypts the return communication)
13298: ($udom and $uname are optional)
13299: 
13300: =item *
13301: 
13302: log($udom,$name,$home,$message) : write to permanent log for user; use
13303: critical subroutine
13304: 
13305: =item *
13306: 
13307: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13308: array reference filled in from namespace found in domain level on either
13309: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
13310: 
13311: =item *
13312: 
13313: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
13314: domain level either on specified domain server ($uhome) or primary domain 
13315: server ($udom and $uhome are optional)
13316: 
13317: =item * 
13318: 
13319: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
13320: for: authentication, language, quotas, timezone, date locale, and portal URL in
13321: the target domain.
13322: 
13323: May also include additional key => value pairs for the following groups:
13324: 
13325: =over
13326: 
13327: =item
13328: disk quotas (MB allocated by default to portfolios and authoring spaces).
13329: 
13330: =over
13331: 
13332: =item defaultquota, authorquota
13333: 
13334: =back
13335: 
13336: =item
13337: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
13338: portfolio for users).
13339: 
13340: =over
13341: 
13342: =item
13343: aboutme, blog, webdav, portfolio
13344: 
13345: =back
13346: 
13347: =item
13348: requestcourses: ability to request courses, and how requests are processed.
13349: 
13350: =over
13351: 
13352: =item
13353: official, unofficial, community, textbook
13354: 
13355: =back
13356: 
13357: =item
13358: inststatus: types of institutional affiliation, and order in which they are displayed.
13359: 
13360: =over
13361: 
13362: =item
13363: inststatustypes, inststatusorder, inststatusguest
13364: 
13365: =back
13366: 
13367: =item
13368: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
13369: for course's uploaded content.
13370: 
13371: =over
13372: 
13373: =item
13374: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
13375: communityquota, textbookquota
13376: 
13377: =back
13378: 
13379: =item
13380: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
13381: on your servers.
13382: 
13383: =over
13384: 
13385: =item 
13386: remotesessions, hostedsessions
13387: 
13388: =back
13389: 
13390: =back
13391: 
13392: In cases where a domain coordinator has never used the "Set Domain Configuration"
13393: utility to create a configuration.db file on a domain's primary library server 
13394: only the following domain defaults: auth_def, auth_arg_def, lang_def
13395: -- corresponding values are authentication type (internal, krb4, krb5,
13396: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
13397: will be available. Values are retrieved from cache (if current), unless the
13398: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
13399: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
13400: 
13401: Typical usage:
13402: 
13403: %domdefaults = &get_domain_defaults($target_domain);
13404: 
13405: =back
13406: 
13407: =head2 Network Status Functions
13408: 
13409: =over 4
13410: 
13411: =item *
13412: 
13413: dirlist() : return directory list based on URI (first arg).
13414: 
13415: Inputs: 1 required, 5 optional.
13416: 
13417: =over
13418: 
13419: =item 
13420: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13421: 
13422: =item
13423: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
13424: 
13425: =item
13426: $username -  username of user/course to be listed. Extracted from $uri if absent. 
13427: 
13428: =item
13429: $getpropath - boolean: 1 if prepend path using &propath(). 
13430: 
13431: =item
13432: $getuserdir - boolean: 1 if prepend path for "userfiles".
13433: 
13434: =item 
13435: $alternateRoot - path to prepend in place of path from $uri.
13436: 
13437: =back
13438: 
13439: Returns: Array of up to two items.
13440: 
13441: =over
13442: 
13443: a reference to an array of files/subdirectories
13444: 
13445: =over
13446: 
13447: Each element in the array of files/subdirectories is a & separated list of
13448: item name and the result of running stat on the item.  If dirlist was requested
13449: for a file instead of a directory, the item name will be ''. For a directory 
13450: listing, if the item is a metadata file, the element will end &N&M 
13451: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13452: default copyright set (1).  
13453: 
13454: =back
13455: 
13456: a scalar containing error condition (if encountered).
13457: 
13458: =over
13459: 
13460: =item 
13461: no_host (no homeserver identified for $username:$domain).
13462: 
13463: =item 
13464: no_such_host (server contacted for listing not identified as valid host).
13465: 
13466: =item 
13467: con_lost (connection to remote server failed).
13468: 
13469: =item 
13470: refused (invalid $username:$domain received on lond side).
13471: 
13472: =item 
13473: no_such_dir (directory at specified path on lond side does not exist). 
13474: 
13475: =item 
13476: empty (directory at specified path on lond side is empty).
13477: 
13478: =over
13479: 
13480: This is currently not encountered because the &ls3, &ls2, 
13481: &ls (_handler) routines on the lond side do not filter out
13482: . and .. from a directory listing. 
13483: 
13484: =back
13485: 
13486: =back
13487: 
13488: =back
13489: 
13490: =item *
13491: 
13492: spareserver() : find server with least workload from spare.tab
13493: 
13494: 
13495: =item *
13496: 
13497: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13498: if there is no corresponding loncapa host.
13499: 
13500: =back
13501: 
13502: 
13503: =head2 Apache Request
13504: 
13505: =over 4
13506: 
13507: =item *
13508: 
13509: ssi($url,%hash) : server side include, does a complete request cycle on url to
13510: localhost, posts hash
13511: 
13512: =back
13513: 
13514: =head2 Data to String to Data
13515: 
13516: =over 4
13517: 
13518: =item *
13519: 
13520: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13521: and '&' separators, supports elements that are arrayrefs and hashrefs
13522: 
13523: =item *
13524: 
13525: hashref2str($hashref) : convert a hashref into a string complete with
13526: escaping and '=' and '&' separators, supports elements that are
13527: arrayrefs and hashrefs
13528: 
13529: =item *
13530: 
13531: arrayref2str($arrayref) : convert an arrayref into a string complete
13532: with escaping and '&' separators, supports elements that are arrayrefs
13533: and hashrefs
13534: 
13535: =item *
13536: 
13537: str2hash($string) : convert string to hash using unescaping and
13538: splitting on '=' and '&', supports elements that are arrayrefs and
13539: hashrefs
13540: 
13541: =item *
13542: 
13543: str2array($string) : convert string to hash using unescaping and
13544: splitting on '&', supports elements that are arrayrefs and hashrefs
13545: 
13546: =back
13547: 
13548: =head2 Logging Routines
13549: 
13550: 
13551: These routines allow one to make log messages in the lonnet.log and
13552: lonnet.perm logfiles.
13553: 
13554: =over 4
13555: 
13556: =item *
13557: 
13558: logtouch() : make sure the logfile, lonnet.log, exists
13559: 
13560: =item *
13561: 
13562: logthis() : append message to the normal lonnet.log file, it gets
13563: preiodically rolled over and deleted.
13564: 
13565: =item *
13566: 
13567: logperm() : append a permanent message to lonnet.perm.log, this log
13568: file never gets deleted by any automated portion of the system, only
13569: messages of critical importance should go in here.
13570: 
13571: 
13572: =back
13573: 
13574: =head2 General File Helper Routines
13575: 
13576: =over 4
13577: 
13578: =item *
13579: 
13580: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
13581: (a) files in /uploaded
13582:   (i) If a local copy of the file exists - 
13583:       compares modification date of local copy with last-modified date for 
13584:       definitive version stored on home server for course. If local copy is 
13585:       stale, requests a new version from the home server and stores it. 
13586:       If the original has been removed from the home server, then local copy 
13587:       is unlinked.
13588:   (ii) If local copy does not exist -
13589:       requests the file from the home server and stores it. 
13590:   
13591:   If $caller is 'uploadrep':  
13592:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
13593:     for request for files originally uploaded via DOCS. 
13594:      - returns 'ok' if fresh local copy now available, -1 otherwise.
13595:   
13596:   Otherwise:
13597:      This indicates a call from the content generation phase of the request.
13598:      -  returns the entire contents of the file or -1.
13599:      
13600: (b) files in /res
13601:    - returns the entire contents of a file or -1; 
13602:    it properly subscribes to and replicates the file if neccessary.
13603: 
13604: 
13605: =item *
13606: 
13607: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
13608:                   reference
13609: 
13610: returns either a stat() list of data about the file or an empty list
13611: if the file doesn't exist or couldn't find out about it (connection
13612: problems or user unknown)
13613: 
13614: =item *
13615: 
13616: filelocation($dir,$file) : returns file system location of a file
13617: based on URI; meant to be "fairly clean" absolute reference, $dir is a
13618: directory that relative $file lookups are to looked in ($dir of /a/dir
13619: and a file of ../bob will become /a/bob)
13620: 
13621: =item *
13622: 
13623: hreflocation($dir,$file) : returns file system location or a URL; same as
13624: filelocation except for hrefs
13625: 
13626: =item *
13627: 
13628: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
13629: 
13630: =back
13631: 
13632: =head2 Usererfile file routines (/uploaded*)
13633: 
13634: =over 4
13635: 
13636: =item *
13637: 
13638: userfileupload(): main rotine for putting a file in a user or course's
13639:                   filespace, arguments are,
13640: 
13641:  formname - required - this is the name of the element in $env where the
13642:            filename, and the contents of the file to create/modifed exist
13643:            the filename is in $env{'form.'.$formname.'.filename'} and the
13644:            contents of the file is located in $env{'form.'.$formname}
13645:  context - if coursedoc, store the file in the course of the active role
13646:              of the current user; 
13647:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
13648:            if 'canceloverwrite': delete file in tmp/overwrites directory
13649:  subdir - required - subdirectory to put the file in under ../userfiles/
13650:          if undefined, it will be placed in "unknown"
13651: 
13652:  (This routine calls clean_filename() to remove any dangerous
13653:  characters from the filename, and then calls finuserfileupload() to
13654:  complete the transaction)
13655: 
13656:  returns either the url of the uploaded file (/uploaded/....) if successful
13657:  and /adm/notfound.html if unsuccessful
13658: 
13659: =item *
13660: 
13661: clean_filename(): routine for cleaing a filename up for storage in
13662:                  userfile space, argument is:
13663: 
13664:  filename - proposed filename
13665: 
13666: returns: the new clean filename
13667: 
13668: =item *
13669: 
13670: finishuserfileupload(): routine that creates and sends the file to
13671: userspace, probably shouldn't be called directly
13672: 
13673:   docuname: username or courseid of destination for the file
13674:   docudom: domain of user/course of destination for the file
13675:   formname: same as for userfileupload()
13676:   fname: filename (including subdirectories) for the file
13677:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
13678:   allfiles: reference to hash used to store objects found by parser
13679:   codebase: reference to hash used for codebases of java objects found by parser
13680:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
13681:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
13682:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
13683:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
13684:   context: if 'overwrite', will move the uploaded file from its temporary location to
13685:             userfiles to facilitate overwriting a previously uploaded file with same name.
13686:   mimetype: reference to scalar to accommodate mime type determined
13687:             from File::MMagic if $parser = parse.
13688: 
13689:  returns either the url of the uploaded file (/uploaded/....) if successful
13690:  and /adm/notfound.html if unsuccessful (or an error message if context 
13691:  was 'overwrite').
13692:  
13693: 
13694: =item *
13695: 
13696: renameuserfile(): renames an existing userfile to a new name
13697: 
13698:   Args:
13699:    docuname: username or courseid of destination for the file
13700:    docudom: domain of user/course of destination for the file
13701:    old: current file name (including any subdirs under userfiles)
13702:    new: desired file name (including any subdirs under userfiles)
13703: 
13704: =item *
13705: 
13706: mkdiruserfile(): creates a directory is a userfiles dir
13707: 
13708:   Args:
13709:    docuname: username or courseid of destination for the file
13710:    docudom: domain of user/course of destination for the file
13711:    dir: dir to create (including any subdirs under userfiles)
13712: 
13713: =item *
13714: 
13715: removeuserfile(): removes a file that exists in userfiles
13716: 
13717:   Args:
13718:    docuname: username or courseid of destination for the file
13719:    docudom: domain of user/course of destination for the file
13720:    fname: filname to delete (including any subdirs under userfiles)
13721: 
13722: =item *
13723: 
13724: removeuploadedurl(): convience function for removeuserfile()
13725: 
13726:   Args:
13727:    url:  a full /uploaded/... url to delete
13728: 
13729: =item * 
13730: 
13731: get_portfile_permissions():
13732:   Args:
13733:     domain: domain of user or course contain the portfolio files
13734:     user: name of user or num of course contain the portfolio files
13735:   Returns:
13736:     hashref of a dump of the proper file_permissions.db
13737:    
13738: 
13739: =item * 
13740: 
13741: get_access_controls():
13742: 
13743: Args:
13744:   current_permissions: the hash ref returned from get_portfile_permissions()
13745:   group: (optional) the group you want the files associated with
13746:   file: (optional) the file you want access info on
13747: 
13748: Returns:
13749:     a hash (keys are file names) of hashes containing
13750:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
13751:         values are XML containing access control settings (see below) 
13752: 
13753: Internal notes:
13754: 
13755:  access controls are stored in file_permissions.db as key=value pairs.
13756:     key -> path to file/file_name\0uniqueID:scope_end_start
13757:         where scope -> public,guest,course,group,domains or users.
13758:               end -> UNIX time for end of access (0 -> no end date)
13759:               start -> UNIX time for start of access
13760: 
13761:     value -> XML description of access control
13762:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
13763:             <start></start>
13764:             <end></end>
13765: 
13766:             <password></password>  for scope type = guest
13767: 
13768:             <domain></domain>     for scope type = course or group
13769:             <number></number>
13770:             <roles id="">
13771:              <role></role>
13772:              <access></access>
13773:              <section></section>
13774:              <group></group>
13775:             </roles>
13776: 
13777:             <dom></dom>         for scope type = domains
13778: 
13779:             <users>             for scope type = users
13780:              <user>
13781:               <uname></uname>
13782:               <udom></udom>
13783:              </user>
13784:             </users>
13785:            </scope> 
13786:               
13787:  Access data is also aggregated for each file in an additional key=value pair:
13788:  key -> path to file/file_name\0accesscontrol 
13789:  value -> reference to hash
13790:           hash contains key = value pairs
13791:           where key = uniqueID:scope_end_start
13792:                 value = UNIX time record was last updated
13793: 
13794:           Used to improve speed of look-ups of access controls for each file.  
13795:  
13796:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
13797: 
13798: =item *
13799: 
13800: modify_access_controls():
13801: 
13802: Modifies access controls for a portfolio file
13803: Args
13804: 1. file name
13805: 2. reference to hash of required changes,
13806: 3. domain
13807: 4. username
13808:   where domain,username are the domain of the portfolio owner 
13809:   (either a user or a course) 
13810: 
13811: Returns:
13812: 1. result of additions or updates ('ok' or 'error', with error message). 
13813: 2. result of deletions ('ok' or 'error', with error message).
13814: 3. reference to hash of any new or updated access controls.
13815: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
13816:    key = integer (inbound ID)
13817:    value = uniqueID
13818: 
13819: =item *
13820: 
13821: get_timebased_id():
13822: 
13823: Attempts to get a unique timestamp-based suffix for use with items added to a 
13824: course via the Course Editor (e.g., folders, composite pages, 
13825: group bulletin boards).
13826: 
13827: Args: (first three required; six others optional)
13828: 
13829: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
13830:    docssequence, or name of group
13831: 
13832: 2. keyid (alphanumeric): name of temporary locking key in hash,
13833:    e.g., num, boardids
13834: 
13835: 3. namespace: name of gdbm file used to store suffixes already assigned;  
13836:    file will be named nohist_namespace.db
13837: 
13838: 4. cdom: domain of course; default is current course domain from %env
13839: 
13840: 5. cnum: course number; default is current course number from %env
13841: 
13842: 6. idtype: set to concat if an additional digit is to be appended to the 
13843:    unix timestamp to form the suffix, if the plain timestamp is already
13844:    in use.  Default is to not do this, but simply increment the unix 
13845:    timestamp by 1 until a unique key is obtained.
13846: 
13847: 7. who: holder of locking key; defaults to user:domain for user.
13848: 
13849: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
13850:    retrying); default is 3.
13851: 
13852: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
13853: 
13854: Returns:
13855: 
13856: 1. suffix obtained (numeric)
13857: 
13858: 2. result of deleting locking key (ok if deleted, or lock never obtained)
13859: 
13860: 3. error: contains (localized) error message if an error occurred.
13861: 
13862: 
13863: =back
13864: 
13865: =head2 HTTP Helper Routines
13866: 
13867: =over 4
13868: 
13869: =item *
13870: 
13871: escape() : unpack non-word characters into CGI-compatible hex codes
13872: 
13873: =item *
13874: 
13875: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
13876: 
13877: =back
13878: 
13879: =head1 PRIVATE SUBROUTINES
13880: 
13881: =head2 Underlying communication routines (Shouldn't call)
13882: 
13883: =over 4
13884: 
13885: =item *
13886: 
13887: subreply() : tries to pass a message to lonc, returns con_lost if incapable
13888: 
13889: =item *
13890: 
13891: reply() : uses subreply to send a message to remote machine, logs all failures
13892: 
13893: =item *
13894: 
13895: critical() : passes a critical message to another server; if cannot
13896: get through then place message in connection buffer directory and
13897: returns con_delayed, if incapable of saving message, returns
13898: con_failed
13899: 
13900: =item *
13901: 
13902: reconlonc() : tries to reconnect lonc client processes.
13903: 
13904: =back
13905: 
13906: =head2 Resource Access Logging
13907: 
13908: =over 4
13909: 
13910: =item *
13911: 
13912: flushcourselogs() : flush (save) buffer logs and access logs
13913: 
13914: =item *
13915: 
13916: courselog($what) : save message for course in hash
13917: 
13918: =item *
13919: 
13920: courseacclog($what) : save message for course using &courselog().  Perform
13921: special processing for specific resource types (problems, exams, quizzes, etc).
13922: 
13923: =item *
13924: 
13925: goodbye() : flush course logs and log shutting down; it is called in srm.conf
13926: as a PerlChildExitHandler
13927: 
13928: =back
13929: 
13930: =head2 Other
13931: 
13932: =over 4
13933: 
13934: =item *
13935: 
13936: symblist($mapname,%newhash) : update symbolic storage links
13937: 
13938: =back
13939: 
13940: =cut
13941: 

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