File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1192: download - view: text, annotated - select for diffs
Mon Oct 29 17:39:02 2012 UTC (11 years, 9 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- &constructaccess() moved from loncacc.pm to lonnet.pm
  - to facilitate re-use, and separate from handler,
  - for use in lonnet.pm (use Apache::Constants() not supported there.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1192 2012/10/29 17:39:02 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,$name,$id) = @_;
  360:     my $response = &reply('devalidatecache:'.&escape($name).':'.&escape($id),$lonhost);
  361:     return $response;
  362: }
  363: 
  364: # -------------------------------------------------- Non-critical communication
  365: sub subreply {
  366:     my ($cmd,$server)=@_;
  367:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  368:     #
  369:     #  With loncnew process trimming, there's a timing hole between lonc server
  370:     #  process exit and the master server picking up the listen on the AF_UNIX
  371:     #  socket.  In that time interval, a lock file will exist:
  372: 
  373:     my $lockfile=$peerfile.".lock";
  374:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  375: 	sleep(1);
  376:     }
  377:     # At this point, either a loncnew parent is listening or an old lonc
  378:     # or loncnew child is listening so we can connect or everything's dead.
  379:     #
  380:     #   We'll give the connection a few tries before abandoning it.  If
  381:     #   connection is not possible, we'll con_lost back to the client.
  382:     #   
  383:     my $client;
  384:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  385: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  386: 				      Type    => SOCK_STREAM,
  387: 				      Timeout => 10);
  388: 	if ($client) {
  389: 	    last;		# Connected!
  390: 	} else {
  391: 	    &create_connection(&hostname($server),$server);
  392: 	}
  393:         sleep(1);		# Try again later if failed connection.
  394:     }
  395:     my $answer;
  396:     if ($client) {
  397: 	print $client "sethost:$server:$cmd\n";
  398: 	$answer=<$client>;
  399: 	if (!$answer) { $answer="con_lost"; }
  400: 	chomp($answer);
  401:     } else {
  402: 	$answer = 'con_lost';	# Failed connection.
  403:     }
  404:     return $answer;
  405: }
  406: 
  407: sub reply {
  408:     my ($cmd,$server)=@_;
  409:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  410:     my $answer=subreply($cmd,$server);
  411:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  412:        &logthis("<font color=\"blue\">WARNING:".
  413:                 " $cmd to $server returned $answer</font>");
  414:     }
  415:     return $answer;
  416: }
  417: 
  418: # ----------------------------------------------------------- Send USR1 to lonc
  419: 
  420: sub reconlonc {
  421:     my ($lonid) = @_;
  422:     my $hostname = &hostname($lonid);
  423:     if ($lonid) {
  424: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  425: 	if ($hostname && -e $peerfile) {
  426: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  427: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  428: 					     Type    => SOCK_STREAM,
  429: 					     Timeout => 10);
  430: 	    if ($client) {
  431: 		print $client ("reset_retries\n");
  432: 		my $answer=<$client>;
  433: 		#reset just this one.
  434: 	    }
  435: 	}
  436: 	return;
  437:     }
  438: 
  439:     &logthis("Trying to reconnect lonc");
  440:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  441:     if (open(my $fh,"<$loncfile")) {
  442: 	my $loncpid=<$fh>;
  443:         chomp($loncpid);
  444:         if (kill 0 => $loncpid) {
  445: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  446:             kill USR1 => $loncpid;
  447:             sleep 1;
  448:          } else {
  449: 	    &logthis(
  450:                "<font color=\"blue\">WARNING:".
  451:                " lonc at pid $loncpid not responding, giving up</font>");
  452:         }
  453:     } else {
  454: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  455:     }
  456: }
  457: 
  458: # ------------------------------------------------------ Critical communication
  459: 
  460: sub critical {
  461:     my ($cmd,$server)=@_;
  462:     unless (&hostname($server)) {
  463:         &logthis("<font color=\"blue\">WARNING:".
  464:                " Critical message to unknown server ($server)</font>");
  465:         return 'no_such_host';
  466:     }
  467:     my $answer=reply($cmd,$server);
  468:     if ($answer eq 'con_lost') {
  469: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  470: 	my $answer=reply($cmd,$server);
  471:         if ($answer eq 'con_lost') {
  472:             my $now=time;
  473:             my $middlename=$cmd;
  474:             $middlename=substr($middlename,0,16);
  475:             $middlename=~s/\W//g;
  476:             my $dfilename=
  477:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  478:             $dumpcount++;
  479:             {
  480: 		my $dfh;
  481: 		if (open($dfh,">$dfilename")) {
  482: 		    print $dfh "$cmd\n"; 
  483: 		    close($dfh);
  484: 		}
  485:             }
  486:             sleep 2;
  487:             my $wcmd='';
  488:             {
  489: 		my $dfh;
  490: 		if (open($dfh,"<$dfilename")) {
  491: 		    $wcmd=<$dfh>; 
  492: 		    close($dfh);
  493: 		}
  494:             }
  495:             chomp($wcmd);
  496:             if ($wcmd eq $cmd) {
  497: 		&logthis("<font color=\"blue\">WARNING: ".
  498:                          "Connection buffer $dfilename: $cmd</font>");
  499:                 &logperm("D:$server:$cmd");
  500: 	        return 'con_delayed';
  501:             } else {
  502:                 &logthis("<font color=\"red\">CRITICAL:"
  503:                         ." Critical connection failed: $server $cmd</font>");
  504:                 &logperm("F:$server:$cmd");
  505:                 return 'con_failed';
  506:             }
  507:         }
  508:     }
  509:     return $answer;
  510: }
  511: 
  512: # ------------------------------------------- check if return value is an error
  513: 
  514: sub error {
  515:     my ($result) = @_;
  516:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  517: 	if ($2 == 2) { return undef; }
  518: 	return $1;
  519:     }
  520:     return undef;
  521: }
  522: 
  523: sub convert_and_load_session_env {
  524:     my ($lonidsdir,$handle)=@_;
  525:     my @profile;
  526:     {
  527: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  528: 	if (!$opened) {
  529: 	    return 0;
  530: 	}
  531: 	flock($idf,LOCK_SH);
  532: 	@profile=<$idf>;
  533: 	close($idf);
  534:     }
  535:     my %temp_env;
  536:     foreach my $line (@profile) {
  537: 	if ($line !~ m/=/) {
  538: 	    return 0;
  539: 	}
  540: 	chomp($line);
  541: 	my ($envname,$envvalue)=split(/=/,$line,2);
  542: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  543:     }
  544:     unlink("$lonidsdir/$handle.id");
  545:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  546: 	    0640)) {
  547: 	%disk_env = %temp_env;
  548: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  549: 	untie(%disk_env);
  550:     }
  551:     return 1;
  552: }
  553: 
  554: # ------------------------------------------- Transfer profile into environment
  555: my $env_loaded;
  556: sub transfer_profile_to_env {
  557:     my ($lonidsdir,$handle,$force_transfer) = @_;
  558:     if (!$force_transfer && $env_loaded) { return; } 
  559: 
  560:     if (!defined($lonidsdir)) {
  561: 	$lonidsdir = $perlvar{'lonIDsDir'};
  562:     }
  563:     if (!defined($handle)) {
  564:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  565:     }
  566: 
  567:     my $convert;
  568:     {
  569:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  570: 	if (!$opened) {
  571: 	    return;
  572: 	}
  573: 	flock($idf,LOCK_SH);
  574: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  575: 		&GDBM_READER(),0640)) {
  576: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  577: 	    untie(%disk_env);
  578: 	} else {
  579: 	    $convert = 1;
  580: 	}
  581:     }
  582:     if ($convert) {
  583: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  584: 	    &logthis("Failed to load session, or convert session.");
  585: 	}
  586:     }
  587: 
  588:     my %remove;
  589:     while ( my $envname = each(%env) ) {
  590:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  591:             if ($time < time-300) {
  592:                 $remove{$key}++;
  593:             }
  594:         }
  595:     }
  596: 
  597:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  598:     $env_loaded=1;
  599:     foreach my $expired_key (keys(%remove)) {
  600:         &delenv($expired_key);
  601:     }
  602: }
  603: 
  604: # ---------------------------------------------------- Check for valid session 
  605: sub check_for_valid_session {
  606:     my ($r,$name) = @_;
  607:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  608:     if ($name eq '') {
  609:         $name = 'lonID';
  610:     }
  611:     my $lonid=$cookies{$name};
  612:     return undef if (!$lonid);
  613: 
  614:     my $handle=&LONCAPA::clean_handle($lonid->value);
  615:     my $lonidsdir;
  616:     if ($name eq 'lonDAV') {
  617:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  618:     } else {
  619:         $lonidsdir=$r->dir_config('lonIDsDir');
  620:     }
  621:     return undef if (!-e "$lonidsdir/$handle.id");
  622: 
  623:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  624:     return undef if (!$opened);
  625: 
  626:     flock($idf,LOCK_SH);
  627:     my %disk_env;
  628:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  629: 	    &GDBM_READER(),0640)) {
  630: 	return undef;	
  631:     }
  632: 
  633:     if (!defined($disk_env{'user.name'})
  634: 	|| !defined($disk_env{'user.domain'})) {
  635: 	return undef;
  636:     }
  637:     return $handle;
  638: }
  639: 
  640: sub timed_flock {
  641:     my ($file,$lock_type) = @_;
  642:     my $failed=0;
  643:     eval {
  644: 	local $SIG{__DIE__}='DEFAULT';
  645: 	local $SIG{ALRM}=sub {
  646: 	    $failed=1;
  647: 	    die("failed lock");
  648: 	};
  649: 	alarm(13);
  650: 	flock($file,$lock_type);
  651: 	alarm(0);
  652:     };
  653:     if ($failed) {
  654: 	return undef;
  655:     } else {
  656: 	return 1;
  657:     }
  658: }
  659: 
  660: # ---------------------------------------------------------- Append Environment
  661: 
  662: sub appenv {
  663:     my ($newenv,$roles) = @_;
  664:     if (ref($newenv) eq 'HASH') {
  665:         foreach my $key (keys(%{$newenv})) {
  666:             my $refused = 0;
  667: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  668:                 $refused = 1;
  669:                 if (ref($roles) eq 'ARRAY') {
  670:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
  671:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  672:                         $refused = 0;
  673:                     }
  674:                 }
  675:             }
  676:             if ($refused) {
  677:                 &logthis("<font color=\"blue\">WARNING: ".
  678:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  679:                          .'</font>');
  680: 	        delete($newenv->{$key});
  681:             } else {
  682:                 $env{$key}=$newenv->{$key};
  683:             }
  684:         }
  685:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  686:         if ($opened
  687: 	    && &timed_flock($env_file,LOCK_EX)
  688: 	    &&
  689: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  690: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  691: 	    while (my ($key,$value) = each(%{$newenv})) {
  692: 	        $disk_env{$key} = $value;
  693: 	    }
  694: 	    untie(%disk_env);
  695:         }
  696:     }
  697:     return 'ok';
  698: }
  699: # ----------------------------------------------------- Delete from Environment
  700: 
  701: sub delenv {
  702:     my ($delthis,$regexp,$roles) = @_;
  703:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  704:         my $refused = 1;
  705:         if (ref($roles) eq 'ARRAY') {
  706:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  707:             if (grep(/^\Q$role\E$/,@{$roles})) {
  708:                 $refused = 0;
  709:             }
  710:         }
  711:         if ($refused) {
  712:             &logthis("<font color=\"blue\">WARNING: ".
  713:                      "Attempt to delete from environment ".$delthis);
  714:             return 'error';
  715:         }
  716:     }
  717:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  718:     if ($opened
  719: 	&& &timed_flock($env_file,LOCK_EX)
  720: 	&&
  721: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  722: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  723: 	foreach my $key (keys(%disk_env)) {
  724: 	    if ($regexp) {
  725:                 if ($key=~/^$delthis/) {
  726:                     delete($env{$key});
  727:                     delete($disk_env{$key});
  728:                 } 
  729:             } else {
  730:                 if ($key=~/^\Q$delthis\E/) {
  731: 		    delete($env{$key});
  732: 		    delete($disk_env{$key});
  733: 	        }
  734:             }
  735: 	}
  736: 	untie(%disk_env);
  737:     }
  738:     return 'ok';
  739: }
  740: 
  741: sub get_env_multiple {
  742:     my ($name) = @_;
  743:     my @values;
  744:     if (defined($env{$name})) {
  745:         # exists is it an array
  746:         if (ref($env{$name})) {
  747:             @values=@{ $env{$name} };
  748:         } else {
  749:             $values[0]=$env{$name};
  750:         }
  751:     }
  752:     return(@values);
  753: }
  754: 
  755: # ------------------------------------------------------------------- Locking
  756: 
  757: sub set_lock {
  758:     my ($text)=@_;
  759:     $locknum++;
  760:     my $id=$$.'-'.$locknum;
  761:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  762:              'session.lock.'.$id => $text});
  763:     return $id;
  764: }
  765: 
  766: sub get_locks {
  767:     my $num=0;
  768:     my %texts=();
  769:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  770:        if ($lock=~/\w/) {
  771:           $num++;
  772:           $texts{$lock}=$env{'session.lock.'.$lock};
  773:        }
  774:    }
  775:    return ($num,%texts);
  776: }
  777: 
  778: sub remove_lock {
  779:     my ($id)=@_;
  780:     my $newlocks='';
  781:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  782:        if (($lock=~/\w/) && ($lock ne $id)) {
  783:           $newlocks.=','.$lock;
  784:        }
  785:     }
  786:     &appenv({'session.locks' => $newlocks});
  787:     &delenv('session.lock.'.$id);
  788: }
  789: 
  790: sub remove_all_locks {
  791:     my $activelocks=$env{'session.locks'};
  792:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  793:        if ($lock=~/\w/) {
  794:           &remove_lock($lock);
  795:        }
  796:     }
  797: }
  798: 
  799: 
  800: # ------------------------------------------ Find out current server userload
  801: sub userload {
  802:     my $numusers=0;
  803:     {
  804: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  805: 	my $filename;
  806: 	my $curtime=time;
  807: 	while ($filename=readdir(LONIDS)) {
  808: 	    next if ($filename eq '.' || $filename eq '..');
  809: 	    next if ($filename =~ /publicuser_\d+\.id/);
  810: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  811: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  812: 	}
  813: 	closedir(LONIDS);
  814:     }
  815:     my $userloadpercent=0;
  816:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  817:     if ($maxuserload) {
  818: 	$userloadpercent=100*$numusers/$maxuserload;
  819:     }
  820:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  821:     return $userloadpercent;
  822: }
  823: 
  824: # ------------------------------ Find server with least workload from spare.tab
  825: 
  826: sub spareserver {
  827:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  828:     my $spare_server;
  829:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  830:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  831:                                                      :  $userloadpercent;
  832:     my ($uint_dom,$remotesessions);
  833:     if (($udom ne '') && (&domain($udom) ne '')) {
  834:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  835:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  836:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  837:         $remotesessions = $udomdefaults{'remotesessions'};
  838:     }
  839:     my $spareshash = &this_host_spares($udom);
  840:     if (ref($spareshash) eq 'HASH') {
  841:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  842:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  843:                 if ($uint_dom) {
  844:                     next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  845:                                                  $try_server));
  846:                 }
  847: 	        ($spare_server, $lowest_load) =
  848: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  849:             }
  850:         }
  851: 
  852:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
  853: 
  854:         if (!$found_server) {
  855:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
  856: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
  857:                     if ($uint_dom) {
  858:                         next unless (&spare_can_host($udom,$uint_dom,
  859:                                                      $remotesessions,$try_server));
  860:                     }
  861: 	            ($spare_server, $lowest_load) =
  862: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
  863:                 }
  864: 	    }
  865:         }
  866:     }
  867: 
  868:     if (!$want_server_name) {
  869:         my $protocol = 'http';
  870:         if ($protocol{$spare_server} eq 'https') {
  871:             $protocol = $protocol{$spare_server};
  872:         }
  873:         if (defined($spare_server)) {
  874:             my $hostname = &hostname($spare_server);
  875:             if (defined($hostname)) {
  876: 	        $spare_server = $protocol.'://'.$hostname;
  877:             }
  878:         }
  879:     }
  880:     return $spare_server;
  881: }
  882: 
  883: sub compare_server_load {
  884:     my ($try_server, $spare_server, $lowest_load) = @_;
  885: 
  886:     my $loadans     = &reply('load',    $try_server);
  887:     my $userloadans = &reply('userload',$try_server);
  888: 
  889:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  890: 	return ($spare_server, $lowest_load); #didn't get a number from the server
  891:     }
  892: 
  893:     my $load;
  894:     if ($loadans =~ /\d/) {
  895: 	if ($userloadans =~ /\d/) {
  896: 	    #both are numbers, pick the bigger one
  897: 	    $load = ($loadans > $userloadans) ? $loadans 
  898: 		                              : $userloadans;
  899: 	} else {
  900: 	    $load = $loadans;
  901: 	}
  902:     } else {
  903: 	$load = $userloadans;
  904:     }
  905: 
  906:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  907: 	$spare_server = $try_server;
  908: 	$lowest_load  = $load;
  909:     }
  910:     return ($spare_server,$lowest_load);
  911: }
  912: 
  913: # --------------------------- ask offload servers if user already has a session
  914: sub find_existing_session {
  915:     my ($udom,$uname) = @_;
  916:     my $spareshash = &this_host_spares($udom);
  917:     if (ref($spareshash) eq 'HASH') {
  918:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  919:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  920:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  921:             }
  922:         }
  923:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
  924:             foreach my $try_server (@{ $spareshash->{'default'} }) {
  925:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  926:             }
  927:         }
  928:     }
  929:     return;
  930: }
  931: 
  932: # -------------------------------- ask if server already has a session for user
  933: sub has_user_session {
  934:     my ($lonid,$udom,$uname) = @_;
  935:     my $result = &reply(join(':','userhassession',
  936: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  937:     return 1 if ($result eq 'ok');
  938: 
  939:     return 0;
  940: }
  941: 
  942: # --------- determine least loaded server in a user's domain which allows login
  943: 
  944: sub choose_server {
  945:     my ($udom,$checkloginvia) = @_;
  946:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
  947:     my %servers = &get_servers($udom);
  948:     my $lowest_load = 30000;
  949:     my ($login_host,$hostname,$portal_path,$isredirect);
  950:     foreach my $lonhost (keys(%servers)) {
  951:         my $loginvia;
  952:         if ($checkloginvia) {
  953:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
  954:             if ($loginvia) {
  955:                 my ($server,$path) = split(/:/,$loginvia);
  956:                 ($login_host, $lowest_load) =
  957:                     &compare_server_load($server, $login_host, $lowest_load);
  958:                 if ($login_host eq $server) {
  959:                     $portal_path = $path;
  960:                     $isredirect = 1;
  961:                 }
  962:             } else {
  963:                 ($login_host, $lowest_load) =
  964:                     &compare_server_load($lonhost, $login_host, $lowest_load);
  965:                 if ($login_host eq $lonhost) {
  966:                     $portal_path = '';
  967:                     $isredirect = ''; 
  968:                 }
  969:             }
  970:         } else {
  971:             ($login_host, $lowest_load) =
  972:                 &compare_server_load($lonhost, $login_host, $lowest_load);
  973:         }
  974:     }
  975:     if ($login_host ne '') {
  976:         $hostname = &hostname($login_host);
  977:     }
  978:     return ($login_host,$hostname,$portal_path,$isredirect);
  979: }
  980: 
  981: # --------------------------------------------- Try to change a user's password
  982: 
  983: sub changepass {
  984:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  985:     $currentpass = &escape($currentpass);
  986:     $newpass     = &escape($newpass);
  987:     my $lonhost = $perlvar{'lonHostID'};
  988:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
  989: 		       $server);
  990:     if (! $answer) {
  991: 	&logthis("No reply on password change request to $server ".
  992: 		 "by $uname in domain $udom.");
  993:     } elsif ($answer =~ "^ok") {
  994:         &logthis("$uname in $udom successfully changed their password ".
  995: 		 "on $server.");
  996:     } elsif ($answer =~ "^pwchange_failure") {
  997: 	&logthis("$uname in $udom was unable to change their password ".
  998: 		 "on $server.  The action was blocked by either lcpasswd ".
  999: 		 "or pwchange");
 1000:     } elsif ($answer =~ "^non_authorized") {
 1001:         &logthis("$uname in $udom did not get their password correct when ".
 1002: 		 "attempting to change it on $server.");
 1003:     } elsif ($answer =~ "^auth_mode_error") {
 1004:         &logthis("$uname in $udom attempted to change their password despite ".
 1005: 		 "not being locally or internally authenticated on $server.");
 1006:     } elsif ($answer =~ "^unknown_user") {
 1007:         &logthis("$uname in $udom attempted to change their password ".
 1008: 		 "on $server but were unable to because $server is not ".
 1009: 		 "their home server.");
 1010:     } elsif ($answer =~ "^refused") {
 1011: 	&logthis("$server refused to change $uname in $udom password because ".
 1012: 		 "it was sent an unencrypted request to change the password.");
 1013:     } elsif ($answer =~ "invalid_client") {
 1014:         &logthis("$server refused to change $uname in $udom password because ".
 1015:                  "it was a reset by e-mail originating from an invalid server.");
 1016:     }
 1017:     return $answer;
 1018: }
 1019: 
 1020: # ----------------------- Try to determine user's current authentication scheme
 1021: 
 1022: sub queryauthenticate {
 1023:     my ($uname,$udom)=@_;
 1024:     my $uhome=&homeserver($uname,$udom);
 1025:     if (!$uhome) {
 1026: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1027: 	return 'no_host';
 1028:     }
 1029:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1030:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1031: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1032:     }
 1033:     return $answer;
 1034: }
 1035: 
 1036: # --------- Try to authenticate user from domain's lib servers (first this one)
 1037: 
 1038: sub authenticate {
 1039:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1040:     $upass=&escape($upass);
 1041:     $uname= &LONCAPA::clean_username($uname);
 1042:     my $uhome=&homeserver($uname,$udom,1);
 1043:     my $newhome;
 1044:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1045: # Maybe the machine was offline and only re-appeared again recently?
 1046:         &reconlonc();
 1047: # One more
 1048: 	$uhome=&homeserver($uname,$udom,1);
 1049:         if (($uhome eq 'no_host') && $checkdefauth) {
 1050:             if (defined(&domain($udom,'primary'))) {
 1051:                 $newhome=&domain($udom,'primary');
 1052:             }
 1053:             if ($newhome ne '') {
 1054:                 $uhome = $newhome;
 1055:             }
 1056:         }
 1057: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1058: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1059: 	    return 'no_host';
 1060:         }
 1061:     }
 1062:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1063:     if ($answer eq 'authorized') {
 1064:         if ($newhome) {
 1065:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1066:             return 'no_account_on_host'; 
 1067:         } else {
 1068:             &logthis("User $uname at $udom authorized by $uhome");
 1069:             return $uhome;
 1070:         }
 1071:     }
 1072:     if ($answer eq 'non_authorized') {
 1073: 	&logthis("User $uname at $udom rejected by $uhome");
 1074: 	return 'no_host'; 
 1075:     }
 1076:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1077:     return 'no_host';
 1078: }
 1079: 
 1080: sub can_host_session {
 1081:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1082:     my $canhost = 1;
 1083:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1084:     if (ref($remotesessions) eq 'HASH') {
 1085:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1086:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1087:                 $canhost = 0;
 1088:             } else {
 1089:                 $canhost = 1;
 1090:             }
 1091:         }
 1092:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1093:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1094:                 $canhost = 1;
 1095:             } else {
 1096:                 $canhost = 0;
 1097:             }
 1098:         }
 1099:         if ($canhost) {
 1100:             if ($remotesessions->{'version'} ne '') {
 1101:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1102:                 if ($reqmajor ne '' && $reqminor ne '') {
 1103:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1104:                         my $major = $1;
 1105:                         my $minor = $2;
 1106:                         if (($major < $reqmajor ) ||
 1107:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1108:                             $canhost = 0;
 1109:                         }
 1110:                     } else {
 1111:                         $canhost = 0;
 1112:                     }
 1113:                 }
 1114:             }
 1115:         }
 1116:     }
 1117:     if ($canhost) {
 1118:         if (ref($hostedsessions) eq 'HASH') {
 1119:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1120:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1121:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1122:                 if (($uint_dom ne '') && 
 1123:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1124:                     $canhost = 0;
 1125:                 } else {
 1126:                     $canhost = 1;
 1127:                 }
 1128:             }
 1129:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1130:                 if (($uint_dom ne '') && 
 1131:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1132:                     $canhost = 1;
 1133:                 } else {
 1134:                     $canhost = 0;
 1135:                 }
 1136:             }
 1137:         }
 1138:     }
 1139:     return $canhost;
 1140: }
 1141: 
 1142: sub spare_can_host {
 1143:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1144:     my $canhost=1;
 1145:     my @intdoms;
 1146:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
 1147:     if (ref($internet_names) eq 'ARRAY') {
 1148:         @intdoms = @{$internet_names};
 1149:     }
 1150:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1151:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
 1152:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
 1153:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
 1154:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
 1155:         $canhost = &can_host_session($udom,$try_server,$remoterev,
 1156:                                      $remotesessions,
 1157:                                      $defdomdefaults{'hostedsessions'});
 1158:     }
 1159:     return $canhost;
 1160: }
 1161: 
 1162: sub this_host_spares {
 1163:     my ($dom) = @_;
 1164:     my ($dom_in_use,$lonhost_in_use,$result);
 1165:     my @hosts = &current_machine_ids();
 1166:     foreach my $lonhost (@hosts) {
 1167:         if (&host_domain($lonhost) eq $dom) {
 1168:             $dom_in_use = $dom;
 1169:             $lonhost_in_use = $lonhost;
 1170:             last;
 1171:         }
 1172:     }
 1173:     if ($dom_in_use ne '') {
 1174:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1175:     }
 1176:     if (ref($result) ne 'HASH') {
 1177:         $lonhost_in_use = $perlvar{'lonHostID'};
 1178:         $dom_in_use = &host_domain($lonhost_in_use);
 1179:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1180:         if (ref($result) ne 'HASH') {
 1181:             $result = \%spareid;
 1182:         }
 1183:     }
 1184:     return $result;
 1185: }
 1186: 
 1187: sub spares_for_offload  {
 1188:     my ($dom_in_use,$lonhost_in_use) = @_;
 1189:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1190:     if (defined($cached)) {
 1191:         return $result;
 1192:     } else {
 1193:         my $cachetime = 60*60*24;
 1194:         my %domconfig =
 1195:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1196:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1197:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1198:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1199:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1200:                 }
 1201:             }
 1202:         }
 1203:     }
 1204:     return;
 1205: }
 1206: 
 1207: sub get_lonbalancer_config {
 1208:     my ($servers) = @_;
 1209:     my ($currbalancer,$currtargets);
 1210:     if (ref($servers) eq 'HASH') {
 1211:         foreach my $server (keys(%{$servers})) {
 1212:             my %what = (
 1213:                          spareid => 1,
 1214:                          perlvar => 1,
 1215:                        );
 1216:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1217:             if ($result eq 'ok') {
 1218:                 if (ref($returnhash) eq 'HASH') {
 1219:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1220:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1221:                             $currbalancer = $server;
 1222:                             $currtargets = {};
 1223:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1224:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1225:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1226:                                 }
 1227:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1228:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1229:                                 }
 1230:                             }
 1231:                             last;
 1232:                         }
 1233:                     }
 1234:                 }
 1235:             }
 1236:         }
 1237:     }
 1238:     return ($currbalancer,$currtargets);
 1239: }
 1240: 
 1241: sub check_loadbalancing {
 1242:     my ($uname,$udom) = @_;
 1243:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1244:         $rule_in_effect,$offloadto,$otherserver);
 1245:     my $lonhost = $perlvar{'lonHostID'};
 1246:     my @hosts = &current_machine_ids();
 1247:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1248:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1249:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1250:     my $serverhomedom = &host_domain($lonhost);
 1251: 
 1252:     my $cachetime = 60*60*24;
 1253: 
 1254:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1255:         $dom_in_use = $udom;
 1256:         $homeintdom = 1;
 1257:     } else {
 1258:         $dom_in_use = $serverhomedom;
 1259:     }
 1260:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1261:     unless (defined($cached)) {
 1262:         my %domconfig =
 1263:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1264:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1265:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1266:         }
 1267:     }
 1268:     if (ref($result) eq 'HASH') {
 1269:         ($is_balancer,$currtargets,$currrules) = 
 1270:             &check_balancer_result($result,@hosts);
 1271:         if ($is_balancer) {
 1272:             if (ref($currrules) eq 'HASH') {
 1273:                 if ($homeintdom) {
 1274:                     if ($uname ne '') {
 1275:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1276:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1277:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1278:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1279:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1280:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1281:                             }
 1282:                         }
 1283:                         if ($rule_in_effect eq '') {
 1284:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1285:                             if ($userenv{'inststatus'} ne '') {
 1286:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1287:                                 my ($othertitle,$usertypes,$types) =
 1288:                                     &Apache::loncommon::sorted_inst_types($udom);
 1289:                                 if (ref($types) eq 'ARRAY') {
 1290:                                     foreach my $type (@{$types}) {
 1291:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1292:                                             if (exists($currrules->{$type})) {
 1293:                                                 $rule_in_effect = $currrules->{$type};
 1294:                                             }
 1295:                                         }
 1296:                                     }
 1297:                                 }
 1298:                             } else {
 1299:                                 if (exists($currrules->{'default'})) {
 1300:                                     $rule_in_effect = $currrules->{'default'};
 1301:                                 }
 1302:                             }
 1303:                         }
 1304:                     } else {
 1305:                         if (exists($currrules->{'default'})) {
 1306:                             $rule_in_effect = $currrules->{'default'};
 1307:                         }
 1308:                     }
 1309:                 } else {
 1310:                     if ($currrules->{'_LC_external'} ne '') {
 1311:                         $rule_in_effect = $currrules->{'_LC_external'};
 1312:                     }
 1313:                 }
 1314:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1315:                                                        $uname,$udom);
 1316:             }
 1317:         }
 1318:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1319:         my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1320:         unless (defined($cached)) {
 1321:             my %domconfig =
 1322:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1323:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1324:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1325:             }
 1326:         }
 1327:         if (ref($result) eq 'HASH') {
 1328:             ($is_balancer,$currtargets,$currrules) = 
 1329:                 &check_balancer_result($result,@hosts);
 1330:             if ($is_balancer) {
 1331:                 if (ref($currrules) eq 'HASH') {
 1332:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1333:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1334:                     }
 1335:                 }
 1336:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1337:                                                        $uname,$udom);
 1338:             }
 1339:         } else {
 1340:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1341:                 $is_balancer = 1;
 1342:                 $offloadto = &this_host_spares($dom_in_use);
 1343:             }
 1344:         }
 1345:     } else {
 1346:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1347:             $is_balancer = 1;
 1348:             $offloadto = &this_host_spares($dom_in_use);
 1349:         }
 1350:     }
 1351:     if ($is_balancer) {
 1352:         my $lowest_load = 30000;
 1353:         if (ref($offloadto) eq 'HASH') {
 1354:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1355:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1356:                     ($otherserver,$lowest_load) =
 1357:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1358:                 }
 1359:             }
 1360:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1361: 
 1362:             if (!$found_server) {
 1363:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1364:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1365:                         ($otherserver,$lowest_load) =
 1366:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1367:                     }
 1368:                 }
 1369:             }
 1370:         } elsif (ref($offloadto) eq 'ARRAY') {
 1371:             if (@{$offloadto} == 1) {
 1372:                 $otherserver = $offloadto->[0];
 1373:             } elsif (@{$offloadto} > 1) {
 1374:                 foreach my $try_server (@{$offloadto}) {
 1375:                     ($otherserver,$lowest_load) =
 1376:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1377:                 }
 1378:             }
 1379:         }
 1380:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1381:             $is_balancer = 0;
 1382:             if ($uname ne '' && $udom ne '') {
 1383:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1384:                     
 1385:                     &appenv({'user.loadbalexempt'     => $lonhost,  
 1386:                              'user.loadbalcheck.time' => time});
 1387:                 }
 1388:             }
 1389:         }
 1390:     }
 1391:     return ($is_balancer,$otherserver);
 1392: }
 1393: 
 1394: sub check_balancer_result {
 1395:     my ($result,@hosts) = @_;
 1396:     my ($is_balancer,$currtargets,$currrules);
 1397:     if (ref($result) eq 'HASH') {
 1398:         if ($result->{'lonhost'} ne '') {
 1399:             my $currbalancer = $result->{'lonhost'};
 1400:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1401:                 $is_balancer = 1;
 1402:                 $currtargets = $result->{'targets'};
 1403:                 $currrules = $result->{'rules'};
 1404:             }
 1405:         } else {
 1406:             foreach my $key (keys(%{$result})) {
 1407:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1408:                     (ref($result->{$key}) eq 'HASH')) {
 1409:                     $is_balancer = 1;
 1410:                     $currrules = $result->{$key}{'rules'};
 1411:                     $currtargets = $result->{$key}{'targets'};
 1412:                     last;
 1413:                 }
 1414:             }
 1415:         }
 1416:     }
 1417:     return ($is_balancer,$currtargets,$currrules);
 1418: }
 1419: 
 1420: sub get_loadbalancer_targets {
 1421:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1422:     my $offloadto;
 1423:     if ($rule_in_effect eq 'none') {
 1424:         return [$perlvar{'lonHostID'}];
 1425:     } elsif ($rule_in_effect eq '') {
 1426:         $offloadto = $currtargets;
 1427:     } else {
 1428:         if ($rule_in_effect eq 'homeserver') {
 1429:             my $homeserver = &homeserver($uname,$udom);
 1430:             if ($homeserver ne 'no_host') {
 1431:                 $offloadto = [$homeserver];
 1432:             }
 1433:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1434:             my %domconfig =
 1435:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1436:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1437:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1438:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1439:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1440:                     }
 1441:                 }
 1442:             } else {
 1443:                 my %servers = &internet_dom_servers($udom);
 1444:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1445:                 if (&hostname($remotebalancer) ne '') {
 1446:                     $offloadto = [$remotebalancer];
 1447:                 }
 1448:             }
 1449:         } elsif (&hostname($rule_in_effect) ne '') {
 1450:             $offloadto = [$rule_in_effect];
 1451:         }
 1452:     }
 1453:     return $offloadto;
 1454: }
 1455: 
 1456: sub internet_dom_servers {
 1457:     my ($dom) = @_;
 1458:     my (%uniqservers,%servers);
 1459:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1460:     my @machinedoms = &machine_domains($primaryserver);
 1461:     foreach my $mdom (@machinedoms) {
 1462:         my %currservers = %servers;
 1463:         my %server = &get_servers($mdom);
 1464:         %servers = (%currservers,%server);
 1465:     }
 1466:     my %by_hostname;
 1467:     foreach my $id (keys(%servers)) {
 1468:         push(@{$by_hostname{$servers{$id}}},$id);
 1469:     }
 1470:     foreach my $hostname (sort(keys(%by_hostname))) {
 1471:         if (@{$by_hostname{$hostname}} > 1) {
 1472:             my $match = 0;
 1473:             foreach my $id (@{$by_hostname{$hostname}}) {
 1474:                 if (&host_domain($id) eq $dom) {
 1475:                     $uniqservers{$id} = $hostname;
 1476:                     $match = 1;
 1477:                 }
 1478:             }
 1479:             unless ($match) {
 1480:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1481:             }
 1482:         } else {
 1483:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1484:         }
 1485:     }
 1486:     return %uniqservers;
 1487: }
 1488: 
 1489: # ---------------------- Find the homebase for a user from domain's lib servers
 1490: 
 1491: my %homecache;
 1492: sub homeserver {
 1493:     my ($uname,$udom,$ignoreBadCache)=@_;
 1494:     my $index="$uname:$udom";
 1495: 
 1496:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1497: 
 1498:     my %servers = &get_servers($udom,'library');
 1499:     foreach my $tryserver (keys(%servers)) {
 1500:         next if ($ignoreBadCache ne 'true' && 
 1501: 		 exists($badServerCache{$tryserver}));
 1502: 
 1503: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1504: 	if ($answer eq 'found') {
 1505: 	    delete($badServerCache{$tryserver}); 
 1506: 	    return $homecache{$index}=$tryserver;
 1507: 	} elsif ($answer eq 'no_host') {
 1508: 	    $badServerCache{$tryserver}=1;
 1509: 	}
 1510:     }    
 1511:     return 'no_host';
 1512: }
 1513: 
 1514: # ------------------------------------- Find the usernames behind a list of IDs
 1515: 
 1516: sub idget {
 1517:     my ($udom,@ids)=@_;
 1518:     my %returnhash=();
 1519:     
 1520:     my %servers = &get_servers($udom,'library');
 1521:     foreach my $tryserver (keys(%servers)) {
 1522: 	my $idlist=join('&',@ids);
 1523: 	$idlist=~tr/A-Z/a-z/; 
 1524: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1525: 	my @answer=();
 1526: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1527: 	    @answer=split(/\&/,$reply);
 1528: 	}                    ;
 1529: 	my $i;
 1530: 	for ($i=0;$i<=$#ids;$i++) {
 1531: 	    if ($answer[$i]) {
 1532: 		$returnhash{$ids[$i]}=$answer[$i];
 1533: 	    } 
 1534: 	}
 1535:     } 
 1536:     return %returnhash;
 1537: }
 1538: 
 1539: # ------------------------------------- Find the IDs behind a list of usernames
 1540: 
 1541: sub idrget {
 1542:     my ($udom,@unames)=@_;
 1543:     my %returnhash=();
 1544:     foreach my $uname (@unames) {
 1545:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1546:     }
 1547:     return %returnhash;
 1548: }
 1549: 
 1550: # ------------------------------- Store away a list of names and associated IDs
 1551: 
 1552: sub idput {
 1553:     my ($udom,%ids)=@_;
 1554:     my %servers=();
 1555:     foreach my $uname (keys(%ids)) {
 1556: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1557:         my $uhom=&homeserver($uname,$udom);
 1558:         if ($uhom ne 'no_host') {
 1559:             my $id=&escape($ids{$uname});
 1560:             $id=~tr/A-Z/a-z/;
 1561:             my $esc_unam=&escape($uname);
 1562: 	    if ($servers{$uhom}) {
 1563: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
 1564:             } else {
 1565:                 $servers{$uhom}=$id.'='.$esc_unam;
 1566:             }
 1567:         }
 1568:     }
 1569:     foreach my $server (keys(%servers)) {
 1570:         &critical('idput:'.$udom.':'.$servers{$server},$server);
 1571:     }
 1572: }
 1573: 
 1574: # ------------------------------dump from db file owned by domainconfig user
 1575: sub dump_dom {
 1576:     my ($namespace, $udom, $regexp) = @_;
 1577: 
 1578:     $udom ||= $env{'user.domain'};
 1579: 
 1580:     return () unless $udom;
 1581: 
 1582:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 1583: }
 1584: 
 1585: # ------------------------------------------ get items from domain db files   
 1586: 
 1587: sub get_dom {
 1588:     my ($namespace,$storearr,$udom,$uhome)=@_;
 1589:     my $items='';
 1590:     foreach my $item (@$storearr) {
 1591:         $items.=&escape($item).'&';
 1592:     }
 1593:     $items=~s/\&$//;
 1594:     if (!$udom) {
 1595:         $udom=$env{'user.domain'};
 1596:         if (defined(&domain($udom,'primary'))) {
 1597:             $uhome=&domain($udom,'primary');
 1598:         } else {
 1599:             undef($uhome);
 1600:         }
 1601:     } else {
 1602:         if (!$uhome) {
 1603:             if (defined(&domain($udom,'primary'))) {
 1604:                 $uhome=&domain($udom,'primary');
 1605:             }
 1606:         }
 1607:     }
 1608:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1609:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 1610:         my %returnhash;
 1611:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 1612:             return %returnhash;
 1613:         }
 1614:         my @pairs=split(/\&/,$rep);
 1615:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1616:             return @pairs;
 1617:         }
 1618:         my $i=0;
 1619:         foreach my $item (@$storearr) {
 1620:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 1621:             $i++;
 1622:         }
 1623:         return %returnhash;
 1624:     } else {
 1625:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1626:     }
 1627: }
 1628: 
 1629: # -------------------------------------------- put items in domain db files 
 1630: 
 1631: sub put_dom {
 1632:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1633:     if (!$udom) {
 1634:         $udom=$env{'user.domain'};
 1635:         if (defined(&domain($udom,'primary'))) {
 1636:             $uhome=&domain($udom,'primary');
 1637:         } else {
 1638:             undef($uhome);
 1639:         }
 1640:     } else {
 1641:         if (!$uhome) {
 1642:             if (defined(&domain($udom,'primary'))) {
 1643:                 $uhome=&domain($udom,'primary');
 1644:             }
 1645:         }
 1646:     } 
 1647:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1648:         my $items='';
 1649:         foreach my $item (keys(%$storehash)) {
 1650:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 1651:         }
 1652:         $items=~s/\&$//;
 1653:         return &reply("putdom:$udom:$namespace:$items",$uhome);
 1654:     } else {
 1655:         &logthis("put_dom failed - no homeserver and/or domain");
 1656:     }
 1657: }
 1658: 
 1659: # --------------------- newput for items in db file owned by domainconfig user
 1660: sub newput_dom {
 1661:     my ($namespace,$storehash,$udom) = @_;
 1662:     my $result;
 1663:     if (!$udom) {
 1664:         $udom=$env{'user.domain'};
 1665:     }
 1666:     if ($udom) {
 1667:         my $uname = &get_domainconfiguser($udom);
 1668:         $result = &newput($namespace,$storehash,$udom,$uname);
 1669:     }
 1670:     return $result;
 1671: }
 1672: 
 1673: # --------------------- delete for items in db file owned by domainconfig user
 1674: sub del_dom {
 1675:     my ($namespace,$storearr,$udom)=@_;
 1676:     if (ref($storearr) eq 'ARRAY') {
 1677:         if (!$udom) {
 1678:             $udom=$env{'user.domain'};
 1679:         }
 1680:         if ($udom) {
 1681:             my $uname = &get_domainconfiguser($udom); 
 1682:             return &del($namespace,$storearr,$udom,$uname);
 1683:         }
 1684:     }
 1685: }
 1686: 
 1687: # ----------------------------------construct domainconfig user for a domain 
 1688: sub get_domainconfiguser {
 1689:     my ($udom) = @_;
 1690:     return $udom.'-domainconfig';
 1691: }
 1692: 
 1693: sub retrieve_inst_usertypes {
 1694:     my ($udom) = @_;
 1695:     my (%returnhash,@order);
 1696:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 1697:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 1698:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 1699:         %returnhash = %{$domdefs{'inststatustypes'}};
 1700:         @order = @{$domdefs{'inststatusorder'}};
 1701:     } else {
 1702:         if (defined(&domain($udom,'primary'))) {
 1703:             my $uhome=&domain($udom,'primary');
 1704:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 1705:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 1706:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
 1707:                 return (\%returnhash,\@order);
 1708:             }
 1709:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 1710:             my @pairs=split(/\&/,$hashitems);
 1711:             foreach my $item (@pairs) {
 1712:                 my ($key,$value)=split(/=/,$item,2);
 1713:                 $key = &unescape($key);
 1714:                 next if ($key =~ /^error: 2 /);
 1715:                 $returnhash{$key}=&thaw_unescape($value);
 1716:             }
 1717:             my @esc_order = split(/\&/,$orderitems);
 1718:             foreach my $item (@esc_order) {
 1719:                 push(@order,&unescape($item));
 1720:             }
 1721:         } else {
 1722:             &logthis("get_dom failed - no primary domain server for $udom");
 1723:         }
 1724:     }
 1725:     return (\%returnhash,\@order);
 1726: }
 1727: 
 1728: sub is_domainimage {
 1729:     my ($url) = @_;
 1730:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1731:         if (&domain($1) ne '') {
 1732:             return '1';
 1733:         }
 1734:     }
 1735:     return;
 1736: }
 1737: 
 1738: sub inst_directory_query {
 1739:     my ($srch) = @_;
 1740:     my $udom = $srch->{'srchdomain'};
 1741:     my %results;
 1742:     my $homeserver = &domain($udom,'primary');
 1743:     my $outcome;
 1744:     if ($homeserver ne '') {
 1745: 	my $queryid=&reply("querysend:instdirsearch:".
 1746: 			   &escape($srch->{'srchby'}).':'.
 1747: 			   &escape($srch->{'srchterm'}).':'.
 1748: 			   &escape($srch->{'srchtype'}),$homeserver);
 1749: 	my $host=&hostname($homeserver);
 1750: 	if ($queryid !~/^\Q$host\E\_/) {
 1751: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1752: 	    return;
 1753: 	}
 1754: 	my $response = &get_query_reply($queryid);
 1755: 	my $maxtries = 5;
 1756: 	my $tries = 1;
 1757: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1758: 	    $response = &get_query_reply($queryid);
 1759: 	    $tries ++;
 1760: 	}
 1761: 
 1762:         if (!&error($response) && $response ne 'refused') {
 1763:             if ($response eq 'unavailable') {
 1764:                 $outcome = $response;
 1765:             } else {
 1766:                 $outcome = 'ok';
 1767:                 my @matches = split(/\n/,$response);
 1768:                 foreach my $match (@matches) {
 1769:                     my ($key,$value) = split(/=/,$match);
 1770:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1771:                 }
 1772:             }
 1773:         }
 1774:     }
 1775:     return ($outcome,%results);
 1776: }
 1777: 
 1778: sub usersearch {
 1779:     my ($srch) = @_;
 1780:     my $dom = $srch->{'srchdomain'};
 1781:     my %results;
 1782:     my %libserv = &all_library();
 1783:     my $query = 'usersearch';
 1784:     foreach my $tryserver (keys(%libserv)) {
 1785:         if (&host_domain($tryserver) eq $dom) {
 1786:             my $host=&hostname($tryserver);
 1787:             my $queryid=
 1788:                 &reply("querysend:".&escape($query).':'.
 1789:                        &escape($srch->{'srchby'}).':'.
 1790:                        &escape($srch->{'srchtype'}).':'.
 1791:                        &escape($srch->{'srchterm'}),$tryserver);
 1792:             if ($queryid !~/^\Q$host\E\_/) {
 1793:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1794:                 next;
 1795:             }
 1796:             my $reply = &get_query_reply($queryid);
 1797:             my $maxtries = 1;
 1798:             my $tries = 1;
 1799:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1800:                 $reply = &get_query_reply($queryid);
 1801:                 $tries ++;
 1802:             }
 1803:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1804:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1805:             } else {
 1806:                 my @matches;
 1807:                 if ($reply =~ /\n/) {
 1808:                     @matches = split(/\n/,$reply);
 1809:                 } else {
 1810:                     @matches = split(/\&/,$reply);
 1811:                 }
 1812:                 foreach my $match (@matches) {
 1813:                     my ($uname,$udom,%userhash);
 1814:                     foreach my $entry (split(/:/,$match)) {
 1815:                         my ($key,$value) =
 1816:                             map {&unescape($_);} split(/=/,$entry);
 1817:                         $userhash{$key} = $value;
 1818:                         if ($key eq 'username') {
 1819:                             $uname = $value;
 1820:                         } elsif ($key eq 'domain') {
 1821:                             $udom = $value;
 1822:                         }
 1823:                     }
 1824:                     $results{$uname.':'.$udom} = \%userhash;
 1825:                 }
 1826:             }
 1827:         }
 1828:     }
 1829:     return %results;
 1830: }
 1831: 
 1832: sub get_instuser {
 1833:     my ($udom,$uname,$id) = @_;
 1834:     my $homeserver = &domain($udom,'primary');
 1835:     my ($outcome,%results);
 1836:     if ($homeserver ne '') {
 1837:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1838:                            &escape($id).':'.&escape($udom),$homeserver);
 1839:         my $host=&hostname($homeserver);
 1840:         if ($queryid !~/^\Q$host\E\_/) {
 1841:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1842:             return;
 1843:         }
 1844:         my $response = &get_query_reply($queryid);
 1845:         my $maxtries = 5;
 1846:         my $tries = 1;
 1847:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1848:             $response = &get_query_reply($queryid);
 1849:             $tries ++;
 1850:         }
 1851:         if (!&error($response) && $response ne 'refused') {
 1852:             if ($response eq 'unavailable') {
 1853:                 $outcome = $response;
 1854:             } else {
 1855:                 $outcome = 'ok';
 1856:                 my @matches = split(/\n/,$response);
 1857:                 foreach my $match (@matches) {
 1858:                     my ($key,$value) = split(/=/,$match);
 1859:                     $results{&unescape($key)} = &thaw_unescape($value);
 1860:                 }
 1861:             }
 1862:         }
 1863:     }
 1864:     my %userinfo;
 1865:     if (ref($results{$uname}) eq 'HASH') {
 1866:         %userinfo = %{$results{$uname}};
 1867:     } 
 1868:     return ($outcome,%userinfo);
 1869: }
 1870: 
 1871: sub inst_rulecheck {
 1872:     my ($udom,$uname,$id,$item,$rules) = @_;
 1873:     my %returnhash;
 1874:     if ($udom ne '') {
 1875:         if (ref($rules) eq 'ARRAY') {
 1876:             @{$rules} = map {&escape($_);} (@{$rules});
 1877:             my $rulestr = join(':',@{$rules});
 1878:             my $homeserver=&domain($udom,'primary');
 1879:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1880:                 my $response;
 1881:                 if ($item eq 'username') {                
 1882:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1883:                                               ':'.&escape($uname).':'.$rulestr,
 1884:                                               $homeserver));
 1885:                 } elsif ($item eq 'id') {
 1886:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1887:                                               ':'.&escape($id).':'.$rulestr,
 1888:                                               $homeserver));
 1889:                 } elsif ($item eq 'selfcreate') {
 1890:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1891:                                                &escape($udom).':'.&escape($uname).
 1892:                                               ':'.$rulestr,$homeserver));
 1893:                 }
 1894:                 if ($response ne 'refused') {
 1895:                     my @pairs=split(/\&/,$response);
 1896:                     foreach my $item (@pairs) {
 1897:                         my ($key,$value)=split(/=/,$item,2);
 1898:                         $key = &unescape($key);
 1899:                         next if ($key =~ /^error: 2 /);
 1900:                         $returnhash{$key}=&thaw_unescape($value);
 1901:                     }
 1902:                 }
 1903:             }
 1904:         }
 1905:     }
 1906:     return %returnhash;
 1907: }
 1908: 
 1909: sub inst_userrules {
 1910:     my ($udom,$check) = @_;
 1911:     my (%ruleshash,@ruleorder);
 1912:     if ($udom ne '') {
 1913:         my $homeserver=&domain($udom,'primary');
 1914:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1915:             my $response;
 1916:             if ($check eq 'id') {
 1917:                 $response=&reply('instidrules:'.&escape($udom),
 1918:                                  $homeserver);
 1919:             } elsif ($check eq 'email') {
 1920:                 $response=&reply('instemailrules:'.&escape($udom),
 1921:                                  $homeserver);
 1922:             } else {
 1923:                 $response=&reply('instuserrules:'.&escape($udom),
 1924:                                  $homeserver);
 1925:             }
 1926:             if (($response ne 'refused') && ($response ne 'error') && 
 1927:                 ($response ne 'unknown_cmd') && 
 1928:                 ($response ne 'no_such_host')) {
 1929:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1930:                 my @pairs=split(/\&/,$hashitems);
 1931:                 foreach my $item (@pairs) {
 1932:                     my ($key,$value)=split(/=/,$item,2);
 1933:                     $key = &unescape($key);
 1934:                     next if ($key =~ /^error: 2 /);
 1935:                     $ruleshash{$key}=&thaw_unescape($value);
 1936:                 }
 1937:                 my @esc_order = split(/\&/,$orderitems);
 1938:                 foreach my $item (@esc_order) {
 1939:                     push(@ruleorder,&unescape($item));
 1940:                 }
 1941:             }
 1942:         }
 1943:     }
 1944:     return (\%ruleshash,\@ruleorder);
 1945: }
 1946: 
 1947: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 1948: 
 1949: sub get_domain_defaults {
 1950:     my ($domain) = @_;
 1951:     my $cachetime = 60*60*24;
 1952:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 1953:     if (defined($cached)) {
 1954:         if (ref($result) eq 'HASH') {
 1955:             return %{$result};
 1956:         }
 1957:     }
 1958:     my %domdefaults;
 1959:     my %domconfig =
 1960:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 1961:                                   'requestcourses','inststatus',
 1962:                                   'coursedefaults','usersessions',
 1963:                                   'requestauthor'],$domain);
 1964:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 1965:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 1966:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 1967:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 1968:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 1969:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 1970:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 1971:     } else {
 1972:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 1973:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 1974:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 1975:     }
 1976:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 1977:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 1978:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 1979:         } else {
 1980:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 1981:         } 
 1982:         my @usertools = ('aboutme','blog','webdav','portfolio');
 1983:         foreach my $item (@usertools) {
 1984:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 1985:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 1986:             }
 1987:         }
 1988:     }
 1989:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 1990:         foreach my $item ('official','unofficial','community') {
 1991:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 1992:         }
 1993:     }
 1994:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 1995:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 1996:     }
 1997:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 1998:         foreach my $item ('inststatustypes','inststatusorder') {
 1999:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2000:         }
 2001:     }
 2002:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2003:         foreach my $item ('canuse_pdfforms') {
 2004:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
 2005:         }
 2006:     }
 2007:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2008:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2009:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2010:         }
 2011:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2012:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2013:         }
 2014:     }
 2015:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
 2016:                                   $cachetime);
 2017:     return %domdefaults;
 2018: }
 2019: 
 2020: # --------------------------------------------------- Assign a key to a student
 2021: 
 2022: sub assign_access_key {
 2023: #
 2024: # a valid key looks like uname:udom#comments
 2025: # comments are being appended
 2026: #
 2027:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2028:     $kdom=
 2029:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2030:     $knum=
 2031:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2032:     $cdom=
 2033:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2034:     $cnum=
 2035:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2036:     $udom=$env{'user.name'} unless (defined($udom));
 2037:     $uname=$env{'user.domain'} unless (defined($uname));
 2038:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2039:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2040:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2041:                                                   # assigned to this person
 2042:                                                   # - this should not happen,
 2043:                                                   # unless something went wrong
 2044:                                                   # the first time around
 2045: # ready to assign
 2046:         $logentry=$1.'; '.$logentry;
 2047:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2048:                                                  $kdom,$knum) eq 'ok') {
 2049: # key now belongs to user
 2050: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2051:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2052:                 &appenv({'environment.'.$envkey => $ckey});
 2053:                 return 'ok';
 2054:             } else {
 2055:                 return 
 2056:   'error: Count not permanently assign key, will need to be re-entered later.';
 2057: 	    }
 2058:         } else {
 2059:             return 'error: Could not assign key, try again later.';
 2060:         }
 2061:     } elsif (!$existing{$ckey}) {
 2062: # the key does not exist
 2063: 	return 'error: The key does not exist';
 2064:     } else {
 2065: # the key is somebody else's
 2066: 	return 'error: The key is already in use';
 2067:     }
 2068: }
 2069: 
 2070: # ------------------------------------------ put an additional comment on a key
 2071: 
 2072: sub comment_access_key {
 2073: #
 2074: # a valid key looks like uname:udom#comments
 2075: # comments are being appended
 2076: #
 2077:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2078:     $cdom=
 2079:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2080:     $cnum=
 2081:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2082:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2083:     if ($existing{$ckey}) {
 2084:         $existing{$ckey}.='; '.$logentry;
 2085: # ready to assign
 2086:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2087:                                                  $cdom,$cnum) eq 'ok') {
 2088: 	    return 'ok';
 2089:         } else {
 2090: 	    return 'error: Count not store comment.';
 2091:         }
 2092:     } else {
 2093: # the key does not exist
 2094: 	return 'error: The key does not exist';
 2095:     }
 2096: }
 2097: 
 2098: # ------------------------------------------------------ Generate a set of keys
 2099: 
 2100: sub generate_access_keys {
 2101:     my ($number,$cdom,$cnum,$logentry)=@_;
 2102:     $cdom=
 2103:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2104:     $cnum=
 2105:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2106:     unless (&allowed('mky',$cdom)) { return 0; }
 2107:     unless (($cdom) && ($cnum)) { return 0; }
 2108:     if ($number>10000) { return 0; }
 2109:     sleep(2); # make sure don't get same seed twice
 2110:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2111:     my $total=0;
 2112:     for (my $i=1;$i<=$number;$i++) {
 2113:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2114:                   sprintf("%lx",int(100000*rand)).'-'.
 2115:                   sprintf("%lx",int(100000*rand));
 2116:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2117:        $newkey=~s/0/h/g; # and also 0 and O
 2118:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2119:        if ($existing{$newkey}) {
 2120:            $i--;
 2121:        } else {
 2122: 	  if (&put('accesskeys',
 2123:               { $newkey => '# generated '.localtime().
 2124:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2125:                            '; '.$logentry },
 2126: 		   $cdom,$cnum) eq 'ok') {
 2127:               $total++;
 2128: 	  }
 2129:        }
 2130:     }
 2131:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2132:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2133:     return $total;
 2134: }
 2135: 
 2136: # ------------------------------------------------------- Validate an accesskey
 2137: 
 2138: sub validate_access_key {
 2139:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2140:     $cdom=
 2141:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2142:     $cnum=
 2143:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2144:     $udom=$env{'user.domain'} unless (defined($udom));
 2145:     $uname=$env{'user.name'} unless (defined($uname));
 2146:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2147:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2148: }
 2149: 
 2150: # ------------------------------------- Find the section of student in a course
 2151: sub devalidate_getsection_cache {
 2152:     my ($udom,$unam,$courseid)=@_;
 2153:     my $hashid="$udom:$unam:$courseid";
 2154:     &devalidate_cache_new('getsection',$hashid);
 2155: }
 2156: 
 2157: sub courseid_to_courseurl {
 2158:     my ($courseid) = @_;
 2159:     #already url style courseid
 2160:     return $courseid if ($courseid =~ m{^/});
 2161: 
 2162:     if (exists($env{'course.'.$courseid.'.num'})) {
 2163: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2164: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2165: 	return "/$cdom/$cnum";
 2166:     }
 2167: 
 2168:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2169:     if (exists($courseinfo{'num'})) {
 2170: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2171:     }
 2172: 
 2173:     return undef;
 2174: }
 2175: 
 2176: sub getsection {
 2177:     my ($udom,$unam,$courseid)=@_;
 2178:     my $cachetime=1800;
 2179: 
 2180:     my $hashid="$udom:$unam:$courseid";
 2181:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2182:     if (defined($cached)) { return $result; }
 2183: 
 2184:     my %Pending; 
 2185:     my %Expired;
 2186:     #
 2187:     # Each role can either have not started yet (pending), be active, 
 2188:     #    or have expired.
 2189:     #
 2190:     # If there is an active role, we are done.
 2191:     #
 2192:     # If there is more than one role which has not started yet, 
 2193:     #     choose the one which will start sooner
 2194:     # If there is one role which has not started yet, return it.
 2195:     #
 2196:     # If there is more than one expired role, choose the one which ended last.
 2197:     # If there is a role which has expired, return it.
 2198:     #
 2199:     $courseid = &courseid_to_courseurl($courseid);
 2200:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 2201:     foreach my $key (keys(%roleshash)) {
 2202:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2203:         my $section=$1;
 2204:         if ($key eq $courseid.'_st') { $section=''; }
 2205:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2206:         my $now=time;
 2207:         if (defined($end) && $end && ($now > $end)) {
 2208:             $Expired{$end}=$section;
 2209:             next;
 2210:         }
 2211:         if (defined($start) && $start && ($now < $start)) {
 2212:             $Pending{$start}=$section;
 2213:             next;
 2214:         }
 2215:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2216:     }
 2217:     #
 2218:     # Presumedly there will be few matching roles from the above
 2219:     # loop and the sorting time will be negligible.
 2220:     if (scalar(keys(%Pending))) {
 2221:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2222:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2223:     } 
 2224:     if (scalar(keys(%Expired))) {
 2225:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2226:         my $time = pop(@sorted);
 2227:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2228:     }
 2229:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2230: }
 2231: 
 2232: sub save_cache {
 2233:     &purge_remembered();
 2234:     #&Apache::loncommon::validate_page();
 2235:     undef(%env);
 2236:     undef($env_loaded);
 2237: }
 2238: 
 2239: my $to_remember=-1;
 2240: my %remembered;
 2241: my %accessed;
 2242: my $kicks=0;
 2243: my $hits=0;
 2244: sub make_key {
 2245:     my ($name,$id) = @_;
 2246:     if (length($id) > 65 
 2247: 	&& length(&escape($id)) > 200) {
 2248: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2249:     }
 2250:     return &escape($name.':'.$id);
 2251: }
 2252: 
 2253: sub devalidate_cache_new {
 2254:     my ($name,$id,$debug) = @_;
 2255:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2256:     $id=&make_key($name,$id);
 2257:     $memcache->delete($id);
 2258:     delete($remembered{$id});
 2259:     delete($accessed{$id});
 2260: }
 2261: 
 2262: sub is_cached_new {
 2263:     my ($name,$id,$debug) = @_;
 2264:     $id=&make_key($name,$id);
 2265:     if (exists($remembered{$id})) {
 2266: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
 2267: 	$accessed{$id}=[&gettimeofday()];
 2268: 	$hits++;
 2269: 	return ($remembered{$id},1);
 2270:     }
 2271:     my $value = $memcache->get($id);
 2272:     if (!(defined($value))) {
 2273: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2274: 	return (undef,undef);
 2275:     }
 2276:     if ($value eq '__undef__') {
 2277: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2278: 	$value=undef;
 2279:     }
 2280:     &make_room($id,$value,$debug);
 2281:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2282:     return ($value,1);
 2283: }
 2284: 
 2285: sub do_cache_new {
 2286:     my ($name,$id,$value,$time,$debug) = @_;
 2287:     $id=&make_key($name,$id);
 2288:     my $setvalue=$value;
 2289:     if (!defined($setvalue)) {
 2290: 	$setvalue='__undef__';
 2291:     }
 2292:     if (!defined($time) ) {
 2293: 	$time=600;
 2294:     }
 2295:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 2296:     my $result = $memcache->set($id,$setvalue,$time);
 2297:     if (! $result) {
 2298: 	&logthis("caching of id -> $id  failed");
 2299: 	$memcache->disconnect_all();
 2300:     }
 2301:     # need to make a copy of $value
 2302:     &make_room($id,$value,$debug);
 2303:     return $value;
 2304: }
 2305: 
 2306: sub make_room {
 2307:     my ($id,$value,$debug)=@_;
 2308: 
 2309:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 2310:                                     : $value;
 2311:     if ($to_remember<0) { return; }
 2312:     $accessed{$id}=[&gettimeofday()];
 2313:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 2314:     my $to_kick;
 2315:     my $max_time=0;
 2316:     foreach my $other (keys(%accessed)) {
 2317: 	if (&tv_interval($accessed{$other}) > $max_time) {
 2318: 	    $to_kick=$other;
 2319: 	    $max_time=&tv_interval($accessed{$other});
 2320: 	}
 2321:     }
 2322:     delete($remembered{$to_kick});
 2323:     delete($accessed{$to_kick});
 2324:     $kicks++;
 2325:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 2326:     return;
 2327: }
 2328: 
 2329: sub purge_remembered {
 2330:     #&logthis("Tossing ".scalar(keys(%remembered)));
 2331:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 2332:     undef(%remembered);
 2333:     undef(%accessed);
 2334: }
 2335: # ------------------------------------- Read an entry from a user's environment
 2336: 
 2337: sub userenvironment {
 2338:     my ($udom,$unam,@what)=@_;
 2339:     my $items;
 2340:     foreach my $item (@what) {
 2341:         $items.=&escape($item).'&';
 2342:     }
 2343:     $items=~s/\&$//;
 2344:     my %returnhash=();
 2345:     my $uhome = &homeserver($unam,$udom);
 2346:     unless ($uhome eq 'no_host') {
 2347:         my @answer=split(/\&/, 
 2348:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 2349:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 2350:             return %returnhash;
 2351:         }
 2352:         my $i;
 2353:         for ($i=0;$i<=$#what;$i++) {
 2354: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 2355:         }
 2356:     }
 2357:     return %returnhash;
 2358: }
 2359: 
 2360: # ---------------------------------------------------------- Get a studentphoto
 2361: sub studentphoto {
 2362:     my ($udom,$unam,$ext) = @_;
 2363:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2364:     if (defined($env{'request.course.id'})) {
 2365:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 2366:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 2367:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 2368:             } else {
 2369:                 my ($result,$perm_reqd)=
 2370: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2371:                 if ($result eq 'ok') {
 2372:                     if (!($perm_reqd eq 'yes')) {
 2373:                         return(&retrievestudentphoto($udom,$unam,$ext));
 2374:                     }
 2375:                 }
 2376:             }
 2377:         }
 2378:     } else {
 2379:         my ($result,$perm_reqd) = 
 2380: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2381:         if ($result eq 'ok') {
 2382:             if (!($perm_reqd eq 'yes')) {
 2383:                 return(&retrievestudentphoto($udom,$unam,$ext));
 2384:             }
 2385:         }
 2386:     }
 2387:     return '/adm/lonKaputt/lonlogo_broken.gif';
 2388: }
 2389: 
 2390: sub retrievestudentphoto {
 2391:     my ($udom,$unam,$ext,$type) = @_;
 2392:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2393:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 2394:     if ($ret eq 'ok') {
 2395:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 2396:         if ($type eq 'thumbnail') {
 2397:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 2398:         }
 2399:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 2400:         return $tokenurl;
 2401:     } else {
 2402:         if ($type eq 'thumbnail') {
 2403:             return '/adm/lonKaputt/genericstudent_tn.gif';
 2404:         } else { 
 2405:             return '/adm/lonKaputt/lonlogo_broken.gif';
 2406:         }
 2407:     }
 2408: }
 2409: 
 2410: # -------------------------------------------------------------------- New chat
 2411: 
 2412: sub chatsend {
 2413:     my ($newentry,$anon,$group)=@_;
 2414:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 2415:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2416:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 2417:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 2418: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 2419: 		   &escape($newentry)).':'.$group,$chome);
 2420: }
 2421: 
 2422: # ------------------------------------------ Find current version of a resource
 2423: 
 2424: sub getversion {
 2425:     my $fname=&clutter(shift);
 2426:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 2427:     return &currentversion(&filelocation('',$fname));
 2428: }
 2429: 
 2430: sub currentversion {
 2431:     my $fname=shift;
 2432:     my $author=$fname;
 2433:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2434:     my ($udom,$uname)=split(/\//,$author);
 2435:     my $home=&homeserver($uname,$udom);
 2436:     if ($home eq 'no_host') { 
 2437:         return -1; 
 2438:     }
 2439:     my $answer=&reply("currentversion:$fname",$home);
 2440:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2441: 	return -1;
 2442:     }
 2443:     return $answer;
 2444: }
 2445: 
 2446: #
 2447: # Return special version number of resource if set by override, empty otherwise
 2448: #
 2449: sub usedversion {
 2450:     my $fname=shift;
 2451:     unless ($fname) { $fname=$env{'request.uri'}; }
 2452:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 2453:     if ($urlversion) { return $urlversion; }
 2454:     return '';
 2455: }
 2456: 
 2457: # ----------------------------- Subscribe to a resource, return URL if possible
 2458: 
 2459: sub subscribe {
 2460:     my $fname=shift;
 2461:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 2462:     $fname=~s/[\n\r]//g;
 2463:     my $author=$fname;
 2464:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2465:     my ($udom,$uname)=split(/\//,$author);
 2466:     my $home=homeserver($uname,$udom);
 2467:     if ($home eq 'no_host') {
 2468:         return 'not_found';
 2469:     }
 2470:     my $answer=reply("sub:$fname",$home);
 2471:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2472: 	$answer.=' by '.$home;
 2473:     }
 2474:     return $answer;
 2475: }
 2476:     
 2477: # -------------------------------------------------------------- Replicate file
 2478: 
 2479: sub repcopy {
 2480:     my $filename=shift;
 2481:     $filename=~s/\/+/\//g;
 2482:     my $londocroot = $perlvar{'lonDocRoot'};
 2483:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 2484:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 2485:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 2486: 	$filename=~m{^/*(uploaded|editupload)/}) {
 2487: 	return &repcopy_userfile($filename);
 2488:     }
 2489:     $filename=~s/[\n\r]//g;
 2490:     my $transname="$filename.in.transfer";
 2491: # FIXME: this should flock
 2492:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 2493:     my $remoteurl=subscribe($filename);
 2494:     if ($remoteurl =~ /^con_lost by/) {
 2495: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2496:            return 'unavailable';
 2497:     } elsif ($remoteurl eq 'not_found') {
 2498: 	   #&logthis("Subscribe returned not_found: $filename");
 2499: 	   return 'not_found';
 2500:     } elsif ($remoteurl =~ /^rejected by/) {
 2501: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2502:            return 'forbidden';
 2503:     } elsif ($remoteurl eq 'directory') {
 2504:            return 'ok';
 2505:     } else {
 2506:         my $author=$filename;
 2507:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2508:         my ($udom,$uname)=split(/\//,$author);
 2509:         my $home=homeserver($uname,$udom);
 2510:         unless ($home eq $perlvar{'lonHostID'}) {
 2511:            my @parts=split(/\//,$filename);
 2512:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 2513:            if ($path ne "$londocroot/res") {
 2514:                &logthis("Malconfiguration for replication: $filename");
 2515: 	       return 'bad_request';
 2516:            }
 2517:            my $count;
 2518:            for ($count=5;$count<$#parts;$count++) {
 2519:                $path.="/$parts[$count]";
 2520:                if ((-e $path)!=1) {
 2521: 		   mkdir($path,0777);
 2522:                }
 2523:            }
 2524:            my $ua=new LWP::UserAgent;
 2525:            my $request=new HTTP::Request('GET',"$remoteurl");
 2526:            my $response=$ua->request($request,$transname);
 2527:            if ($response->is_error()) {
 2528: 	       unlink($transname);
 2529:                my $message=$response->status_line;
 2530:                &logthis("<font color=\"blue\">WARNING:"
 2531:                        ." LWP get: $message: $filename</font>");
 2532:                return 'unavailable';
 2533:            } else {
 2534: 	       if ($remoteurl!~/\.meta$/) {
 2535:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 2536:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 2537:                   if ($mresponse->is_error()) {
 2538: 		      unlink($filename.'.meta');
 2539:                       &logthis(
 2540:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 2541:                   }
 2542: 	       }
 2543:                rename($transname,$filename);
 2544:                return 'ok';
 2545:            }
 2546:        }
 2547:     }
 2548: }
 2549: 
 2550: # ------------------------------------------------ Get server side include body
 2551: sub ssi_body {
 2552:     my ($filelink,%form)=@_;
 2553:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 2554:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 2555:     }
 2556:     my $output='';
 2557:     my $response;
 2558:     if ($filelink=~/^https?\:/) {
 2559:        ($output,$response)=&externalssi($filelink);
 2560:     } else {
 2561:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 2562:        $filelink .= 'inhibitmenu=yes';
 2563:        ($output,$response)=&ssi($filelink,%form);
 2564:     }
 2565:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 2566:     $output=~s/^.*?\<body[^\>]*\>//si;
 2567:     $output=~s/\<\/body\s*\>.*?$//si;
 2568:     if (wantarray) {
 2569:         return ($output, $response);
 2570:     } else {
 2571:         return $output;
 2572:     }
 2573: }
 2574: 
 2575: # --------------------------------------------------------- Server Side Include
 2576: 
 2577: sub absolute_url {
 2578:     my ($host_name) = @_;
 2579:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 2580:     if ($host_name eq '') {
 2581: 	$host_name = $ENV{'SERVER_NAME'};
 2582:     }
 2583:     return $protocol.$host_name;
 2584: }
 2585: 
 2586: #
 2587: #   Server side include.
 2588: # Parameters:
 2589: #  fn     Possibly encrypted resource name/id.
 2590: #  form   Hash that describes how the rendering should be done
 2591: #         and other things.
 2592: # Returns:
 2593: #   Scalar context: The content of the response.
 2594: #   Array context:  2 element list of the content and the full response object.
 2595: #     
 2596: sub ssi {
 2597: 
 2598:     my ($fn,%form)=@_;
 2599:     my $ua=new LWP::UserAgent;
 2600:     my $request;
 2601: 
 2602:     $form{'no_update_last_known'}=1;
 2603:     &Apache::lonenc::check_encrypt(\$fn);
 2604:     if (%form) {
 2605:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 2606:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
 2607:     } else {
 2608:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 2609:     }
 2610: 
 2611:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 2612:     my $response= $ua->request($request);
 2613:     my $content = $response->content;
 2614: 
 2615: 
 2616:     if (wantarray) {
 2617: 	return ($content, $response);
 2618:     } else {
 2619: 	return $content;
 2620:     }
 2621: }
 2622: 
 2623: sub externalssi {
 2624:     my ($url)=@_;
 2625:     my $ua=new LWP::UserAgent;
 2626:     my $request=new HTTP::Request('GET',$url);
 2627:     my $response=$ua->request($request);
 2628:     if (wantarray) {
 2629:         return ($response->content, $response);
 2630:     } else {
 2631:         return $response->content;
 2632:     }
 2633: }
 2634: 
 2635: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 2636: 
 2637: sub allowuploaded {
 2638:     my ($srcurl,$url)=@_;
 2639:     $url=&clutter(&declutter($url));
 2640:     my $dir=$url;
 2641:     $dir=~s/\/[^\/]+$//;
 2642:     my %httpref=();
 2643:     my $httpurl=&hreflocation('',$url);
 2644:     $httpref{'httpref.'.$httpurl}=$srcurl;
 2645:     &Apache::lonnet::appenv(\%httpref);
 2646: }
 2647: 
 2648: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 2649: # input: action, courseID, current domain, intended
 2650: #        path to file, source of file, instruction to parse file for objects,
 2651: #        ref to hash for embedded objects,
 2652: #        ref to hash for codebase of java objects.
 2653: #        reference to scalar to accommodate mime type determined
 2654: #          from File::MMagic if $parser = parse.
 2655: #
 2656: # output: url to file (if action was uploaddoc), 
 2657: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 2658: #
 2659: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 2660: # course.
 2661: #
 2662: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2663: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 2664: #          course's home server.
 2665: #
 2666: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 2667: #          be copied from $source (current location) to 
 2668: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2669: #         and will then be copied to
 2670: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 2671: #         course's home server.
 2672: #
 2673: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2674: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 2675: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2676: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 2677: #         in course's home server.
 2678: #
 2679: 
 2680: sub process_coursefile {
 2681:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 2682:         $mimetype)=@_;
 2683:     my $fetchresult;
 2684:     my $home=&homeserver($docuname,$docudom);
 2685:     if ($action eq 'propagate') {
 2686:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2687: 			     $home);
 2688:     } else {
 2689:         my $fpath = '';
 2690:         my $fname = $file;
 2691:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2692:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2693:         my $filepath = &build_filepath($fpath);
 2694:         if ($action eq 'copy') {
 2695:             if ($source eq '') {
 2696:                 $fetchresult = 'no source file';
 2697:                 return $fetchresult;
 2698:             } else {
 2699:                 my $destination = $filepath.'/'.$fname;
 2700:                 rename($source,$destination);
 2701:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2702:                                  $home);
 2703:             }
 2704:         } elsif ($action eq 'uploaddoc') {
 2705:             open(my $fh,'>'.$filepath.'/'.$fname);
 2706:             print $fh $env{'form.'.$source};
 2707:             close($fh);
 2708:             if ($parser eq 'parse') {
 2709:                 my $mm = new File::MMagic;
 2710:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 2711:                 if ($type eq 'text/html') {
 2712:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 2713:                     unless ($parse_result eq 'ok') {
 2714:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 2715:                     }
 2716:                 }
 2717:                 if (ref($mimetype)) {
 2718:                     $$mimetype = $type;
 2719:                 } 
 2720:             }
 2721:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2722:                                  $home);
 2723:             if ($fetchresult eq 'ok') {
 2724:                 return '/uploaded/'.$fpath.'/'.$fname;
 2725:             } else {
 2726:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2727:                         ' to host '.$home.': '.$fetchresult);
 2728:                 return '/adm/notfound.html';
 2729:             }
 2730:         }
 2731:     }
 2732:     unless ( $fetchresult eq 'ok') {
 2733:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2734:              ' to host '.$home.': '.$fetchresult);
 2735:     }
 2736:     return $fetchresult;
 2737: }
 2738: 
 2739: sub build_filepath {
 2740:     my ($fpath) = @_;
 2741:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 2742:     unless ($fpath eq '') {
 2743:         my @parts=split('/',$fpath);
 2744:         foreach my $part (@parts) {
 2745:             $filepath.= '/'.$part;
 2746:             if ((-e $filepath)!=1) {
 2747:                 mkdir($filepath,0777);
 2748:             }
 2749:         }
 2750:     }
 2751:     return $filepath;
 2752: }
 2753: 
 2754: sub store_edited_file {
 2755:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 2756:     my $file = $primary_url;
 2757:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 2758:     my $fpath = '';
 2759:     my $fname = $file;
 2760:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2761:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2762:     my $filepath = &build_filepath($fpath);
 2763:     open(my $fh,'>'.$filepath.'/'.$fname);
 2764:     print $fh $content;
 2765:     close($fh);
 2766:     my $home=&homeserver($docuname,$docudom);
 2767:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2768: 			  $home);
 2769:     if ($$fetchresult eq 'ok') {
 2770:         return '/uploaded/'.$fpath.'/'.$fname;
 2771:     } else {
 2772:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2773: 		 ' to host '.$home.': '.$$fetchresult);
 2774:         return '/adm/notfound.html';
 2775:     }
 2776: }
 2777: 
 2778: sub clean_filename {
 2779:     my ($fname,$args)=@_;
 2780: # Replace Windows backslashes by forward slashes
 2781:     $fname=~s/\\/\//g;
 2782:     if (!$args->{'keep_path'}) {
 2783:         # Get rid of everything but the actual filename
 2784: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 2785:     }
 2786: # Replace spaces by underscores
 2787:     $fname=~s/\s+/\_/g;
 2788: # Replace all other weird characters by nothing
 2789:     $fname=~s{[^/\w\.\-]}{}g;
 2790: # Replace all .\d. sequences with _\d. so they no longer look like version
 2791: # numbers
 2792:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 2793:     return $fname;
 2794: }
 2795: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 2796: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 2797: # image with the same aspect ratio as the original, but with dimensions which do 
 2798: # not exceed $resizewidth and $resizeheight.
 2799:  
 2800: sub resizeImage {
 2801:     my ($img_path,$resizewidth,$resizeheight) = @_;
 2802:     my $ima = Image::Magick->new;
 2803:     my $resized;
 2804:     if (-e $img_path) {
 2805:         $ima->Read($img_path);
 2806:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 2807:             my $width = $ima->Get('width');
 2808:             my $height = $ima->Get('height');
 2809:             if ($width > $resizewidth) {
 2810: 	        my $factor = $width/$resizewidth;
 2811:                 my $newheight = $height/$factor;
 2812:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 2813:                 $resized = 1;
 2814:             }
 2815:         }
 2816:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 2817:             my $width = $ima->Get('width');
 2818:             my $height = $ima->Get('height');
 2819:             if ($height > $resizeheight) {
 2820:                 my $factor = $height/$resizeheight;
 2821:                 my $newwidth = $width/$factor;
 2822:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 2823:                 $resized = 1;
 2824:             }
 2825:         }
 2826:         if ($resized) {
 2827:             $ima->Write($img_path);
 2828:         }
 2829:     }
 2830:     return;
 2831: }
 2832: 
 2833: # --------------- Take an uploaded file and put it into the userfiles directory
 2834: # input: $formname - the contents of the file are in $env{"form.$formname"}
 2835: #                    the desired filename is in $env{"form.$formname.filename"}
 2836: #        $context - possible values: coursedoc, existingfile, overwrite, 
 2837: #                                    canceloverwrite, or ''. 
 2838: #                   if 'coursedoc': upload to the current course
 2839: #                   if 'existingfile': write file to tmp/overwrites directory 
 2840: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 2841: #                   $context is passed as argument to &finishuserfileupload
 2842: #        $subdir - directory in userfile to store the file into
 2843: #        $parser - instruction to parse file for objects ($parser = parse)    
 2844: #        $allfiles - reference to hash for embedded objects
 2845: #        $codebase - reference to hash for codebase of java objects
 2846: #        $desuname - username for permanent storage of uploaded file
 2847: #        $dsetudom - domain for permanaent storage of uploaded file
 2848: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 2849: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 2850: #        $resizewidth - width (pixels) to which to resize uploaded image
 2851: #        $resizeheight - height (pixels) to which to resize uploaded image
 2852: #        $mimetype - reference to scalar to accommodate mime type determined
 2853: #                    from File::MMagic.
 2854: # 
 2855: # output: url of file in userspace, or error: <message> 
 2856: #             or /adm/notfound.html if failure to upload occurse
 2857: 
 2858: sub userfileupload {
 2859:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 2860:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 2861:     if (!defined($subdir)) { $subdir='unknown'; }
 2862:     my $fname=$env{'form.'.$formname.'.filename'};
 2863:     $fname=&clean_filename($fname);
 2864:     # See if there is anything left
 2865:     unless ($fname) { return 'error: no uploaded file'; }
 2866:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 2867:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 2868:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 2869:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 2870:         my $now = time;
 2871:         my $filepath;
 2872:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 2873:              $filepath = 'tmp/helprequests/'.$now;
 2874:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 2875:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 2876:                          '_'.$env{'user.domain'}.'/pending';
 2877:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 2878:             my ($docuname,$docudom);
 2879:             if ($destudom) {
 2880:                 $docudom = $destudom;
 2881:             } else {
 2882:                 $docudom = $env{'user.domain'};
 2883:             }
 2884:             if ($destuname) {
 2885:                 $docuname = $destuname;
 2886:             } else {
 2887:                 $docuname = $env{'user.name'};
 2888:             }
 2889:             if (exists($env{'form.group'})) {
 2890:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2891:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2892:             }
 2893:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 2894:             if ($context eq 'canceloverwrite') {
 2895:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 2896:                 if (-e  $tempfile) {
 2897:                     my @info = stat($tempfile);
 2898:                     if ($info[9] eq $env{'form.timestamp'}) {
 2899:                         unlink($tempfile);
 2900:                     }
 2901:                 }
 2902:                 return;
 2903:             }
 2904:         }
 2905:         # Create the directory if not present
 2906:         my @parts=split(/\//,$filepath);
 2907:         my $fullpath = $perlvar{'lonDaemons'};
 2908:         for (my $i=0;$i<@parts;$i++) {
 2909:             $fullpath .= '/'.$parts[$i];
 2910:             if ((-e $fullpath)!=1) {
 2911:                 mkdir($fullpath,0777);
 2912:             }
 2913:         }
 2914:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2915:         print $fh $env{'form.'.$formname};
 2916:         close($fh);
 2917:         if ($context eq 'existingfile') {
 2918:             my @info = stat($fullpath.'/'.$fname);
 2919:             return ($fullpath.'/'.$fname,$info[9]);
 2920:         } else {
 2921:             return $fullpath.'/'.$fname;
 2922:         }
 2923:     }
 2924:     if ($subdir eq 'scantron') {
 2925:         $fname = 'scantron_orig_'.$fname;
 2926:     } else {
 2927:         $fname="$subdir/$fname";
 2928:     }
 2929:     if ($context eq 'coursedoc') {
 2930: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2931: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2932:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 2933:             return &finishuserfileupload($docuname,$docudom,
 2934: 					 $formname,$fname,$parser,$allfiles,
 2935: 					 $codebase,$thumbwidth,$thumbheight,
 2936:                                          $resizewidth,$resizeheight,$context,$mimetype);
 2937:         } else {
 2938:             $fname=$env{'form.folder'}.'/'.$fname;
 2939:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 2940: 				       $fname,$formname,$parser,
 2941: 				       $allfiles,$codebase,$mimetype);
 2942:         }
 2943:     } elsif (defined($destuname)) {
 2944:         my $docuname=$destuname;
 2945:         my $docudom=$destudom;
 2946: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2947: 				     $parser,$allfiles,$codebase,
 2948:                                      $thumbwidth,$thumbheight,
 2949:                                      $resizewidth,$resizeheight,$context,$mimetype);
 2950:     } else {
 2951:         my $docuname=$env{'user.name'};
 2952:         my $docudom=$env{'user.domain'};
 2953:         if (exists($env{'form.group'})) {
 2954:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2955:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2956:         }
 2957: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2958: 				     $parser,$allfiles,$codebase,
 2959:                                      $thumbwidth,$thumbheight,
 2960:                                      $resizewidth,$resizeheight,$context,$mimetype);
 2961:     }
 2962: }
 2963: 
 2964: sub finishuserfileupload {
 2965:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 2966:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 2967:     my $path=$docudom.'/'.$docuname.'/';
 2968:     my $filepath=$perlvar{'lonDocRoot'};
 2969:   
 2970:     my ($fnamepath,$file,$fetchthumb);
 2971:     $file=$fname;
 2972:     if ($fname=~m|/|) {
 2973:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 2974: 	$path.=$fnamepath.'/';
 2975:     }
 2976:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 2977:     my $count;
 2978:     for ($count=4;$count<=$#parts;$count++) {
 2979:         $filepath.="/$parts[$count]";
 2980:         if ((-e $filepath)!=1) {
 2981: 	    mkdir($filepath,0777);
 2982:         }
 2983:     }
 2984: 
 2985: # Save the file
 2986:     {
 2987: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 2988: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 2989: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 2990: 	    return '/adm/notfound.html';
 2991: 	}
 2992:         if ($context eq 'overwrite') {
 2993:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 2994:             my $target = $filepath.'/'.$file;
 2995:             if (-e $source) {
 2996:                 my @info = stat($source);
 2997:                 if ($info[9] eq $env{'form.timestamp'}) {   
 2998:                     unless (&File::Copy::move($source,$target)) {
 2999:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 3000:                         return "Moving from $source failed";
 3001:                     }
 3002:                 } else {
 3003:                     return "Temporary file: $source had unexpected date/time for last modification";
 3004:                 }
 3005:             } else {
 3006:                 return "Temporary file: $source missing";
 3007:             }
 3008:         } elsif (!print FH ($env{'form.'.$formname})) {
 3009: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 3010: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 3011: 	    return '/adm/notfound.html';
 3012: 	}
 3013: 	close(FH);
 3014:         if ($resizewidth && $resizeheight) {
 3015:             my $mm = new File::MMagic;
 3016:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 3017:             if ($mime_type =~ m{^image/}) {
 3018: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 3019:             }  
 3020: 	}
 3021:     }
 3022:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 3023:         if (ref($mimetype)) {
 3024:             if ($$mimetype eq '') {
 3025:                 my $mm = new File::MMagic;
 3026:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 3027:                 $$mimetype = $type;
 3028:             }
 3029:         }
 3030:     }
 3031:     if ($parser eq 'parse') {
 3032:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 3033:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 3034:                                                        $allfiles,$codebase);
 3035:             unless ($parse_result eq 'ok') {
 3036:                 &logthis('Failed to parse '.$filepath.$file.
 3037: 	   	         ' for embedded media: '.$parse_result); 
 3038:             }
 3039:         }
 3040:     }
 3041:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 3042:         my $input = $filepath.'/'.$file;
 3043:         my $output = $filepath.'/'.'tn-'.$file;
 3044:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 3045:         system("convert -sample $thumbsize $input $output");
 3046:         if (-e $filepath.'/'.'tn-'.$file) {
 3047:             $fetchthumb  = 1; 
 3048:         }
 3049:     }
 3050:  
 3051: # Notify homeserver to grep it
 3052: #
 3053:     my $docuhome=&homeserver($docuname,$docudom);	
 3054:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 3055:     if ($fetchresult eq 'ok') {
 3056:         if ($fetchthumb) {
 3057:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 3058:             if ($thumbresult ne 'ok') {
 3059:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 3060:                          $docuhome.': '.$thumbresult);
 3061:             }
 3062:         }
 3063: #
 3064: # Return the URL to it
 3065:         return '/uploaded/'.$path.$file;
 3066:     } else {
 3067:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 3068: 		 ': '.$fetchresult);
 3069:         return '/adm/notfound.html';
 3070:     }
 3071: }
 3072: 
 3073: sub extract_embedded_items {
 3074:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 3075:     my @state = ();
 3076:     my (%lastids,%related,%shockwave,%flashvars);
 3077:     my %javafiles = (
 3078:                       codebase => '',
 3079:                       code => '',
 3080:                       archive => ''
 3081:                     );
 3082:     my %mediafiles = (
 3083:                       src => '',
 3084:                       movie => '',
 3085:                      );
 3086:     my $p;
 3087:     if ($content) {
 3088:         $p = HTML::LCParser->new($content);
 3089:     } else {
 3090:         $p = HTML::LCParser->new($fullpath);
 3091:     }
 3092:     while (my $t=$p->get_token()) {
 3093: 	if ($t->[0] eq 'S') {
 3094: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 3095: 	    push(@state, $tagname);
 3096:             if (lc($tagname) eq 'allow') {
 3097:                 &add_filetype($allfiles,$attr->{'src'},'src');
 3098:             }
 3099: 	    if (lc($tagname) eq 'img') {
 3100: 		&add_filetype($allfiles,$attr->{'src'},'src');
 3101: 	    }
 3102: 	    if (lc($tagname) eq 'a') {
 3103: 		&add_filetype($allfiles,$attr->{'href'},'href');
 3104: 	    }
 3105:             if (lc($tagname) eq 'script') {
 3106:                 my $src;
 3107:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 3108:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 3109:                 } else {
 3110:                     if ($attr->{'src'} ne '') {
 3111:                         $src = $attr->{'src'};
 3112:                         &add_filetype($allfiles,$src,'src');
 3113:                     }
 3114:                 }
 3115:                 my $text = $p->get_trimmed_text();
 3116:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 3117:                     my @swfargs = split(/,/,$1);
 3118:                     foreach my $item (@swfargs) {
 3119:                         $item =~ s/["']//g;
 3120:                         $item =~ s/^\s+//;
 3121:                         $item =~ s/\s+$//;
 3122:                     }
 3123:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 3124:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 3125:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 3126:                         } else {
 3127:                             $related{$swfargs[0]} = [$swfargs[2]];
 3128:                         }
 3129:                     }
 3130:                 }
 3131:             }
 3132:             if (lc($tagname) eq 'link') {
 3133:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 3134:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3135:                 }
 3136:             }
 3137: 	    if (lc($tagname) eq 'object' ||
 3138: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 3139: 		foreach my $item (keys(%javafiles)) {
 3140: 		    $javafiles{$item} = '';
 3141: 		}
 3142:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 3143:                     $lastids{lc($tagname)} = $attr->{'id'};
 3144:                 }
 3145: 	    }
 3146: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 3147: 		my $name = lc($attr->{'name'});
 3148: 		foreach my $item (keys(%javafiles)) {
 3149: 		    if ($name eq $item) {
 3150: 			$javafiles{$item} = $attr->{'value'};
 3151: 			last;
 3152: 		    }
 3153: 		}
 3154:                 my $pathfrom;
 3155: 		foreach my $item (keys(%mediafiles)) {
 3156: 		    if ($name eq $item) {
 3157:                         $pathfrom = $attr->{'value'};
 3158:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 3159: 			&add_filetype($allfiles,$pathfrom,$name);
 3160: 			last;
 3161: 		    }
 3162: 		}
 3163:                 if ($name eq 'flashvars') {
 3164:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 3165:                 }
 3166:                 if ($pathfrom ne '') {
 3167:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 3168:                                          $pathfrom);
 3169:                 }
 3170: 	    }
 3171: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 3172: 		foreach my $item (keys(%javafiles)) {
 3173: 		    if ($attr->{$item}) {
 3174: 			$javafiles{$item} = $attr->{$item};
 3175: 			last;
 3176: 		    }
 3177: 		}
 3178: 		foreach my $item (keys(%mediafiles)) {
 3179: 		    if ($attr->{$item}) {
 3180: 			&add_filetype($allfiles,$attr->{$item},$item);
 3181: 			last;
 3182: 		    }
 3183: 		}
 3184:                 if (lc($tagname) eq 'embed') {
 3185:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 3186:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 3187:                                              $attr->{'src'});
 3188:                     }
 3189:                 }
 3190: 	    }
 3191:             if ($t->[4] =~ m{/>$}) {
 3192:                 pop(@state);  
 3193:             }
 3194: 	} elsif ($t->[0] eq 'E') {
 3195: 	    my ($tagname) = ($t->[1]);
 3196: 	    if ($javafiles{'codebase'} ne '') {
 3197: 		$javafiles{'codebase'} .= '/';
 3198: 	    }  
 3199: 	    if (lc($tagname) eq 'applet' ||
 3200: 		lc($tagname) eq 'object' ||
 3201: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 3202: 		) {
 3203: 		foreach my $item (keys(%javafiles)) {
 3204: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 3205: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 3206: 			&add_filetype($allfiles,$file,$item);
 3207: 		    }
 3208: 		}
 3209: 	    } 
 3210: 	    pop @state;
 3211: 	}
 3212:     }
 3213:     foreach my $id (sort(keys(%flashvars))) {
 3214:         if ($shockwave{$id} ne '') {
 3215:             my @pairs = split(/\&/,$flashvars{$id});
 3216:             foreach my $pair (@pairs) {
 3217:                 my ($key,$value) = split(/\=/,$pair);
 3218:                 if ($key eq 'thumb') {
 3219:                     &add_filetype($allfiles,$value,$key);
 3220:                 } elsif ($key eq 'content') {
 3221:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 3222:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 3223:                     if ($ext ne '') {
 3224:                         &add_filetype($allfiles,$path.$value,$ext);
 3225:                     }
 3226:                 }
 3227:             }
 3228:         }
 3229:     }
 3230:     return 'ok';
 3231: }
 3232: 
 3233: sub add_filetype {
 3234:     my ($allfiles,$file,$type)=@_;
 3235:     if (exists($allfiles->{$file})) {
 3236: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 3237: 	    push(@{$allfiles->{$file}}, &escape($type));
 3238: 	}
 3239:     } else {
 3240: 	@{$allfiles->{$file}} = (&escape($type));
 3241:     }
 3242: }
 3243: 
 3244: sub embedded_dependency {
 3245:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 3246:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 3247:         if (($identifier ne '') &&
 3248:             (ref($related->{$identifier}) eq 'ARRAY') &&
 3249:             ($pathfrom ne '')) {
 3250:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 3251:             foreach my $dep (@{$related->{$identifier}}) {
 3252:                 &add_filetype($allfiles,$path.$dep,'object');
 3253:             }
 3254:         }
 3255:     }
 3256:     return;
 3257: }
 3258: 
 3259: sub removeuploadedurl {
 3260:     my ($url)=@_;	
 3261:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 3262:     return &removeuserfile($uname,$udom,$fname);
 3263: }
 3264: 
 3265: sub removeuserfile {
 3266:     my ($docuname,$docudom,$fname)=@_;
 3267:     my $home=&homeserver($docuname,$docudom);    
 3268:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 3269:     if ($result eq 'ok') {	
 3270:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 3271:             my $metafile = $fname.'.meta';
 3272:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 3273: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 3274:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 3275:             my $sqlresult = 
 3276:                 &update_portfolio_table($docuname,$docudom,$file,
 3277:                                         'portfolio_metadata',$group,
 3278:                                         'delete');
 3279:         }
 3280:     }
 3281:     return $result;
 3282: }
 3283: 
 3284: sub mkdiruserfile {
 3285:     my ($docuname,$docudom,$dir)=@_;
 3286:     my $home=&homeserver($docuname,$docudom);
 3287:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 3288: }
 3289: 
 3290: sub renameuserfile {
 3291:     my ($docuname,$docudom,$old,$new)=@_;
 3292:     my $home=&homeserver($docuname,$docudom);
 3293:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 3294:                         &escape("$old").':'.&escape("$new"),$home);
 3295:     if ($result eq 'ok') {
 3296:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 3297:             my $oldmeta = $old.'.meta';
 3298:             my $newmeta = $new.'.meta';
 3299:             my $metaresult = 
 3300:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 3301: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 3302:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 3303:             my $sqlresult = 
 3304:                 &update_portfolio_table($docuname,$docudom,$file,
 3305:                                         'portfolio_metadata',$group,
 3306:                                         'delete');
 3307:         }
 3308:     }
 3309:     return $result;
 3310: }
 3311: 
 3312: # ------------------------------------------------------------------------- Log
 3313: 
 3314: sub log {
 3315:     my ($dom,$nam,$hom,$what)=@_;
 3316:     return critical("log:$dom:$nam:$what",$hom);
 3317: }
 3318: 
 3319: # ------------------------------------------------------------------ Course Log
 3320: #
 3321: # This routine flushes several buffers of non-mission-critical nature
 3322: #
 3323: 
 3324: sub flushcourselogs {
 3325:     &logthis('Flushing log buffers');
 3326: #
 3327: # course logs
 3328: # This is a log of all transactions in a course, which can be used
 3329: # for data mining purposes
 3330: #
 3331: # It also collects the courseid database, which lists last transaction
 3332: # times and course titles for all courseids
 3333: #
 3334:     my %courseidbuffer=();
 3335:     foreach my $crsid (keys(%courselogs)) {
 3336:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 3337: 		          &escape($courselogs{$crsid}),
 3338: 		          $coursehombuf{$crsid}) eq 'ok') {
 3339: 	    delete $courselogs{$crsid};
 3340:         } else {
 3341:             &logthis('Failed to flush log buffer for '.$crsid);
 3342:             if (length($courselogs{$crsid})>40000) {
 3343:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 3344:                         " exceeded maximum size, deleting.</font>");
 3345:                delete $courselogs{$crsid};
 3346:             }
 3347:         }
 3348:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 3349:             'description' => $coursedescrbuf{$crsid},
 3350:             'inst_code'    => $courseinstcodebuf{$crsid},
 3351:             'type'        => $coursetypebuf{$crsid},
 3352:             'owner'       => $courseownerbuf{$crsid},
 3353:         };
 3354:     }
 3355: #
 3356: # Write course id database (reverse lookup) to homeserver of courses 
 3357: # Is used in pickcourse
 3358: #
 3359:     foreach my $crs_home (keys(%courseidbuffer)) {
 3360:         my $response = &courseidput(&host_domain($crs_home),
 3361:                                     $courseidbuffer{$crs_home},
 3362:                                     $crs_home,'timeonly');
 3363:     }
 3364: #
 3365: # File accesses
 3366: # Writes to the dynamic metadata of resources to get hit counts, etc.
 3367: #
 3368:     foreach my $entry (keys(%accesshash)) {
 3369:         if ($entry =~ /___count$/) {
 3370:             my ($dom,$name);
 3371:             ($dom,$name,undef)=
 3372: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 3373:             if (! defined($dom) || $dom eq '' || 
 3374:                 ! defined($name) || $name eq '') {
 3375:                 my $cid = $env{'request.course.id'};
 3376:                 $dom  = $env{'request.'.$cid.'.domain'};
 3377:                 $name = $env{'request.'.$cid.'.num'};
 3378:             }
 3379:             my $value = $accesshash{$entry};
 3380:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 3381:             my %temphash=($url => $value);
 3382:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 3383:             if ($result eq 'ok') {
 3384:                 delete $accesshash{$entry};
 3385:             }
 3386:         } else {
 3387:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 3388:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 3389:             my %temphash=($entry => $accesshash{$entry});
 3390:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 3391:                 delete $accesshash{$entry};
 3392:             }
 3393:         }
 3394:     }
 3395: #
 3396: # Roles
 3397: # Reverse lookup of user roles for course faculty/staff and co-authorship
 3398: #
 3399:     foreach my $entry (keys(%userrolehash)) {
 3400:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 3401: 	    split(/\:/,$entry);
 3402:         if (&Apache::lonnet::put('nohist_userroles',
 3403:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 3404:                 $rudom,$runame) eq 'ok') {
 3405: 	    delete $userrolehash{$entry};
 3406:         }
 3407:     }
 3408: #
 3409: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 3410: #
 3411:     my %domrolebuffer = ();
 3412:     foreach my $entry (keys(%domainrolehash)) {
 3413:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 3414:         if ($domrolebuffer{$rudom}) {
 3415:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 3416:                       '='.&escape($domainrolehash{$entry});
 3417:         } else {
 3418:             $domrolebuffer{$rudom}.=&escape($entry).
 3419:                       '='.&escape($domainrolehash{$entry});
 3420:         }
 3421:         delete $domainrolehash{$entry};
 3422:     }
 3423:     foreach my $dom (keys(%domrolebuffer)) {
 3424: 	my %servers = &get_servers($dom,'library');
 3425: 	foreach my $tryserver (keys(%servers)) {
 3426: 	    unless (&reply('domroleput:'.$dom.':'.
 3427: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 3428: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 3429: 	    }
 3430:         }
 3431:     }
 3432:     $dumpcount++;
 3433: }
 3434: 
 3435: sub courselog {
 3436:     my $what=shift;
 3437:     $what=time.':'.$what;
 3438:     unless ($env{'request.course.id'}) { return ''; }
 3439:     $coursedombuf{$env{'request.course.id'}}=
 3440:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 3441:     $coursenumbuf{$env{'request.course.id'}}=
 3442:        $env{'course.'.$env{'request.course.id'}.'.num'};
 3443:     $coursehombuf{$env{'request.course.id'}}=
 3444:        $env{'course.'.$env{'request.course.id'}.'.home'};
 3445:     $coursedescrbuf{$env{'request.course.id'}}=
 3446:        $env{'course.'.$env{'request.course.id'}.'.description'};
 3447:     $courseinstcodebuf{$env{'request.course.id'}}=
 3448:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 3449:     $courseownerbuf{$env{'request.course.id'}}=
 3450:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 3451:     $coursetypebuf{$env{'request.course.id'}}=
 3452:        $env{'course.'.$env{'request.course.id'}.'.type'};
 3453:     if (defined $courselogs{$env{'request.course.id'}}) {
 3454: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 3455:     } else {
 3456: 	$courselogs{$env{'request.course.id'}}.=$what;
 3457:     }
 3458:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 3459: 	&flushcourselogs();
 3460:     }
 3461: }
 3462: 
 3463: sub courseacclog {
 3464:     my $fnsymb=shift;
 3465:     unless ($env{'request.course.id'}) { return ''; }
 3466:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 3467:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 3468:         $what.=':POST';
 3469:         # FIXME: Probably ought to escape things....
 3470: 	foreach my $key (keys(%env)) {
 3471:             if ($key=~/^form\.(.*)/) {
 3472:                 my $formitem = $1;
 3473:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 3474:                     $what.=':'.$formitem.'='.$env{$key};
 3475:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 3476:                     $what.=':'.$formitem.'='.$env{$key};
 3477:                 }
 3478:             }
 3479:         }
 3480:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 3481:         # FIXME: We should not be depending on a form parameter that someone
 3482:         # editing lonsearchcat.pm might change in the future.
 3483:         if ($env{'form.phase'} eq 'course_search') {
 3484:             $what.= ':POST';
 3485:             # FIXME: Probably ought to escape things....
 3486:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 3487:                                  'crsdiscuss') {
 3488:                 $what.=':'.$element.'='.$env{'form.'.$element};
 3489:             }
 3490:         }
 3491:     }
 3492:     &courselog($what);
 3493: }
 3494: 
 3495: sub countacc {
 3496:     my $url=&declutter(shift);
 3497:     return if (! defined($url) || $url eq '');
 3498:     unless ($env{'request.course.id'}) { return ''; }
 3499: #
 3500: # Mark that this url was used in this course
 3501: #
 3502:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 3503: #
 3504: # Increase the access count for this resource in this child process
 3505: #
 3506:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 3507:     $accesshash{$key}++;
 3508: }
 3509: 
 3510: sub linklog {
 3511:     my ($from,$to)=@_;
 3512:     $from=&declutter($from);
 3513:     $to=&declutter($to);
 3514:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 3515:     $accesshash{$to.'___'.$from.'___goto'}=1;
 3516: }
 3517: 
 3518: sub statslog {
 3519:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 3520:     if ($users<2) { return; }
 3521:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 3522:             'course'       => $env{'request.course.id'},
 3523:             'sections'     => '"all"',
 3524:             'num_students' => $users,
 3525:             'part'         => $part,
 3526:             'symb'         => $symb,
 3527:             'mean_tries'   => $av_attempts,
 3528:             'deg_of_diff'  => $degdiff});
 3529:     foreach my $key (keys(%dynstore)) {
 3530:         $accesshash{$key}=$dynstore{$key};
 3531:     }
 3532: }
 3533:   
 3534: sub userrolelog {
 3535:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 3536:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 3537:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3538:        $userrolehash
 3539:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3540:                     =$tend.':'.$tstart;
 3541:     }
 3542:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 3543:        $userrolehash
 3544:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 3545:                     =$tend.':'.$tstart;
 3546:     }
 3547:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
 3548:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3549:        $domainrolehash
 3550:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3551:                     = $tend.':'.$tstart;
 3552:     }
 3553: }
 3554: 
 3555: sub courserolelog {
 3556:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 3557:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 3558:         my $cdom = $1;
 3559:         my $cnum = $2;
 3560:         my $sec = $3;
 3561:         my $namespace = 'rolelog';
 3562:         my %storehash = (
 3563:                            role    => $trole,
 3564:                            start   => $tstart,
 3565:                            end     => $tend,
 3566:                            selfenroll => $selfenroll,
 3567:                            context    => $context,
 3568:                         );
 3569:         if ($trole eq 'gr') {
 3570:             $namespace = 'groupslog';
 3571:             $storehash{'group'} = $sec;
 3572:         } else {
 3573:             $storehash{'section'} = $sec;
 3574:         }
 3575:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 3576:                    $domain,$cnum,$cdom);
 3577:         if (($trole ne 'st') || ($sec ne '')) {
 3578:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 3579:         }
 3580:     }
 3581:     return;
 3582: }
 3583: 
 3584: sub domainrolelog {
 3585:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 3586:     if ($area =~ m{^/($match_domain)/$}) {
 3587:         my $cdom = $1;
 3588:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 3589:         my $namespace = 'rolelog';
 3590:         my %storehash = (
 3591:                            role    => $trole,
 3592:                            start   => $tstart,
 3593:                            end     => $tend,
 3594:                            context => $context,
 3595:                         );
 3596:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 3597:                    $domain,$domconfiguser,$cdom);
 3598:     }
 3599:     return;
 3600: 
 3601: }
 3602: 
 3603: sub coauthorrolelog {
 3604:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 3605:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 3606:         my $audom = $1;
 3607:         my $auname = $2;
 3608:         my $namespace = 'rolelog';
 3609:         my %storehash = (
 3610:                            role    => $trole,
 3611:                            start   => $tstart,
 3612:                            end     => $tend,
 3613:                            context => $context,
 3614:                         );
 3615:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 3616:                    $domain,$auname,$audom);
 3617:     }
 3618:     return;
 3619: }
 3620: 
 3621: sub get_course_adv_roles {
 3622:     my ($cid,$codes) = @_;
 3623:     $cid=$env{'request.course.id'} unless (defined($cid));
 3624:     my %coursehash=&coursedescription($cid);
 3625:     my $crstype = &Apache::loncommon::course_type($cid);
 3626:     my %nothide=();
 3627:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3628:         if ($user !~ /:/) {
 3629: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 3630:         } else {
 3631:             $nothide{$user}=1;
 3632:         }
 3633:     }
 3634:     my %returnhash=();
 3635:     my %dumphash=
 3636:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 3637:     my $now=time;
 3638:     my %privileged;
 3639:     foreach my $entry (keys(%dumphash)) {
 3640: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 3641:         if (($tstart) && ($tstart<0)) { next; }
 3642:         if (($tend) && ($tend<$now)) { next; }
 3643:         if (($tstart) && ($now<$tstart)) { next; }
 3644:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 3645: 	if ($username eq '' || $domain eq '') { next; }
 3646:         unless (ref($privileged{$domain}) eq 'HASH') {
 3647:             my %dompersonnel =
 3648:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 3649:             $privileged{$domain} = {};
 3650:             foreach my $server (keys(%dompersonnel)) {
 3651:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 3652:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
 3653:                         my ($trole,$uname,$udom) = split(/:/,$user);
 3654:                         $privileged{$udom}{$uname} = 1;
 3655:                     }
 3656:                 }
 3657:             }
 3658:         }
 3659:         if ((exists($privileged{$domain}{$username})) && 
 3660:             (!$nothide{$username.':'.$domain})) { next; }
 3661: 	if ($role eq 'cr') { next; }
 3662:         if ($codes) {
 3663:             if ($section) { $role .= ':'.$section; }
 3664:             if ($returnhash{$role}) {
 3665:                 $returnhash{$role}.=','.$username.':'.$domain;
 3666:             } else {
 3667:                 $returnhash{$role}=$username.':'.$domain;
 3668:             }
 3669:         } else {
 3670:             my $key=&plaintext($role,$crstype);
 3671:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 3672:             if ($returnhash{$key}) {
 3673: 	        $returnhash{$key}.=','.$username.':'.$domain;
 3674:             } else {
 3675:                 $returnhash{$key}=$username.':'.$domain;
 3676:             }
 3677:         }
 3678:     }
 3679:     return %returnhash;
 3680: }
 3681: 
 3682: sub get_my_roles {
 3683:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 3684:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 3685:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 3686:     my (%dumphash,%nothide);
 3687:     if ($context eq 'userroles') {
 3688:         %dumphash = &dump('roles',$udom,$uname);
 3689:     } else {
 3690:         %dumphash=
 3691:             &dump('nohist_userroles',$udom,$uname);
 3692:         if ($hidepriv) {
 3693:             my %coursehash=&coursedescription($udom.'_'.$uname);
 3694:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3695:                 if ($user !~ /:/) {
 3696:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 3697:                 } else {
 3698:                     $nothide{$user} = 1;
 3699:                 }
 3700:             }
 3701:         }
 3702:     }
 3703:     my %returnhash=();
 3704:     my $now=time;
 3705:     my %privileged;
 3706:     foreach my $entry (keys(%dumphash)) {
 3707:         my ($role,$tend,$tstart);
 3708:         if ($context eq 'userroles') {
 3709:             next if ($entry =~ /^rolesdef/);
 3710: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 3711:         } else {
 3712:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 3713:         }
 3714:         if (($tstart) && ($tstart<0)) { next; }
 3715:         my $status = 'active';
 3716:         if (($tend) && ($tend<=$now)) {
 3717:             $status = 'previous';
 3718:         } 
 3719:         if (($tstart) && ($now<$tstart)) {
 3720:             $status = 'future';
 3721:         }
 3722:         if (ref($types) eq 'ARRAY') {
 3723:             if (!grep(/^\Q$status\E$/,@{$types})) {
 3724:                 next;
 3725:             } 
 3726:         } else {
 3727:             if ($status ne 'active') {
 3728:                 next;
 3729:             }
 3730:         }
 3731:         my ($rolecode,$username,$domain,$section,$area);
 3732:         if ($context eq 'userroles') {
 3733:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 3734:             (undef,$domain,$username,$section) = split(/\//,$area);
 3735:         } else {
 3736:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 3737:         }
 3738:         if (ref($roledoms) eq 'ARRAY') {
 3739:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 3740:                 next;
 3741:             }
 3742:         }
 3743:         if (ref($roles) eq 'ARRAY') {
 3744:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 3745:                 if ($role =~ /^cr\//) {
 3746:                     if (!grep(/^cr$/,@{$roles})) {
 3747:                         next;
 3748:                     }
 3749:                 } elsif ($role =~ /^gr\//) {
 3750:                     if (!grep(/^gr$/,@{$roles})) {
 3751:                         next;
 3752:                     }
 3753:                 } else {
 3754:                     next;
 3755:                 }
 3756:             }
 3757:         }
 3758:         if ($hidepriv) {
 3759:             if ($context eq 'userroles') {
 3760:                 if ((&privileged($username,$domain)) &&
 3761:                     (!$nothide{$username.':'.$domain})) {
 3762:                     next;
 3763:                 }
 3764:             } else {
 3765:                 unless (ref($privileged{$domain}) eq 'HASH') {
 3766:                     my %dompersonnel =
 3767:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 3768:                     $privileged{$domain} = {};
 3769:                     if (keys(%dompersonnel)) {
 3770:                         foreach my $server (keys(%dompersonnel)) {
 3771:                             if (ref($dompersonnel{$server}) eq 'HASH') {
 3772:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
 3773:                                     my ($trole,$uname,$udom) = split(/:/,$user);
 3774:                                     $privileged{$udom}{$uname} = $trole;
 3775:                                 }
 3776:                             }
 3777:                         }
 3778:                     }
 3779:                 }
 3780:                 if (exists($privileged{$domain}{$username})) {
 3781:                     if (!$nothide{$username.':'.$domain}) {
 3782:                         next;
 3783:                     }
 3784:                 }
 3785:             }
 3786:         }
 3787:         if ($withsec) {
 3788:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 3789:                 $tstart.':'.$tend;
 3790:         } else {
 3791:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 3792:         }
 3793:     }
 3794:     return %returnhash;
 3795: }
 3796: 
 3797: # ----------------------------------------------------- Frontpage Announcements
 3798: #
 3799: #
 3800: 
 3801: sub postannounce {
 3802:     my ($server,$text)=@_;
 3803:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 3804:     unless ($text=~/\w/) { $text=''; }
 3805:     return &reply('setannounce:'.&escape($text),$server);
 3806: }
 3807: 
 3808: sub getannounce {
 3809: 
 3810:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 3811: 	my $announcement='';
 3812: 	while (my $line = <$fh>) { $announcement .= $line; }
 3813: 	close($fh);
 3814: 	if ($announcement=~/\w/) { 
 3815: 	    return 
 3816:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 3817:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 3818: 	} else {
 3819: 	    return '';
 3820: 	}
 3821:     } else {
 3822: 	return '';
 3823:     }
 3824: }
 3825: 
 3826: # ---------------------------------------------------------- Course ID routines
 3827: # Deal with domain's nohist_courseid.db files
 3828: #
 3829: 
 3830: sub courseidput {
 3831:     my ($domain,$storehash,$coursehome,$caller) = @_;
 3832:     return unless (ref($storehash) eq 'HASH');
 3833:     my $outcome;
 3834:     if ($caller eq 'timeonly') {
 3835:         my $cids = '';
 3836:         foreach my $item (keys(%$storehash)) {
 3837:             $cids.=&escape($item).'&';
 3838:         }
 3839:         $cids=~s/\&$//;
 3840:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 3841:                           $coursehome);       
 3842:     } else {
 3843:         my $items = '';
 3844:         foreach my $item (keys(%$storehash)) {
 3845:             $items.= &escape($item).'='.
 3846:                      &freeze_escape($$storehash{$item}).'&';
 3847:         }
 3848:         $items=~s/\&$//;
 3849:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 3850:                           $coursehome);
 3851:     }
 3852:     if ($outcome eq 'unknown_cmd') {
 3853:         my $what;
 3854:         foreach my $cid (keys(%$storehash)) {
 3855:             $what .= &escape($cid).'=';
 3856:             foreach my $item ('description','inst_code','owner','type') {
 3857:                 $what .= &escape($storehash->{$cid}{$item}).':';
 3858:             }
 3859:             $what =~ s/\:$/&/;
 3860:         }
 3861:         $what =~ s/\&$//;  
 3862:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 3863:     } else {
 3864:         return $outcome;
 3865:     }
 3866: }
 3867: 
 3868: sub courseiddump {
 3869:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 3870:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 3871:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 3872:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
 3873:     my $as_hash = 1;
 3874:     my %returnhash;
 3875:     if (!$domfilter) { $domfilter=''; }
 3876:     my %libserv = &all_library();
 3877:     foreach my $tryserver (keys(%libserv)) {
 3878:         if ( (  $hostidflag == 1 
 3879: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 3880: 	     || (!defined($hostidflag)) ) {
 3881: 
 3882: 	    if (($domfilter eq '') ||
 3883: 		(&host_domain($tryserver) eq $domfilter)) {
 3884:                 my $rep;
 3885:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 3886:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 3887:                         join(":", (&host_domain($tryserver), $sincefilter, 
 3888:                                 &escape($descfilter), &escape($instcodefilter), 
 3889:                                 &escape($ownerfilter), &escape($coursefilter),
 3890:                                 &escape($typefilter), &escape($regexp_ok), 
 3891:                                 $as_hash, &escape($selfenrollonly), 
 3892:                                 &escape($catfilter), $showhidden, $caller, 
 3893:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 3894:                                 &escape($createdbefore), &escape($createdafter), 
 3895:                                 &escape($creationcontext), $domcloner)));
 3896:                 } else {
 3897:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 3898:                              $sincefilter.':'.&escape($descfilter).':'.
 3899:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 3900:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 3901:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 3902:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 3903:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 3904:                              &escape($cc_clone).':'.$cloneonly.':'.
 3905:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 3906:                              &escape($creationcontext).':'.$domcloner,
 3907:                              $tryserver);
 3908:                 }
 3909:                      
 3910:                 my @pairs=split(/\&/,$rep);
 3911:                 foreach my $item (@pairs) {
 3912:                     my ($key,$value)=split(/\=/,$item,2);
 3913:                     $key = &unescape($key);
 3914:                     next if ($key =~ /^error: 2 /);
 3915:                     my $result = &thaw_unescape($value);
 3916:                     if (ref($result) eq 'HASH') {
 3917:                         $returnhash{$key}=$result;
 3918:                     } else {
 3919:                         my @responses = split(/:/,$value);
 3920:                         my @items = ('description','inst_code','owner','type');
 3921:                         for (my $i=0; $i<@responses; $i++) {
 3922:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 3923:                         }
 3924:                     }
 3925:                 }
 3926:             }
 3927:         }
 3928:     }
 3929:     return %returnhash;
 3930: }
 3931: 
 3932: sub courselastaccess {
 3933:     my ($cdom,$cnum,$hostidref) = @_;
 3934:     my %returnhash;
 3935:     if ($cdom && $cnum) {
 3936:         my $chome = &homeserver($cnum,$cdom);
 3937:         if ($chome ne 'no_host') {
 3938:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 3939:             &extract_lastaccess(\%returnhash,$rep);
 3940:         }
 3941:     } else {
 3942:         if (!$cdom) { $cdom=''; }
 3943:         my %libserv = &all_library();
 3944:         foreach my $tryserver (keys(%libserv)) {
 3945:             if (ref($hostidref) eq 'ARRAY') {
 3946:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 3947:             } 
 3948:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 3949:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 3950:                 &extract_lastaccess(\%returnhash,$rep);
 3951:             }
 3952:         }
 3953:     }
 3954:     return %returnhash;
 3955: }
 3956: 
 3957: sub extract_lastaccess {
 3958:     my ($returnhash,$rep) = @_;
 3959:     if (ref($returnhash) eq 'HASH') {
 3960:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 3961:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 3962:                  $rep eq '') {
 3963:             my @pairs=split(/\&/,$rep);
 3964:             foreach my $item (@pairs) {
 3965:                 my ($key,$value)=split(/\=/,$item,2);
 3966:                 $key = &unescape($key);
 3967:                 next if ($key =~ /^error: 2 /);
 3968:                 $returnhash->{$key} = &thaw_unescape($value);
 3969:             }
 3970:         }
 3971:     }
 3972:     return;
 3973: }
 3974: 
 3975: # ---------------------------------------------------------- DC e-mail
 3976: 
 3977: sub dcmailput {
 3978:     my ($domain,$msgid,$message,$server)=@_;
 3979:     my $status = &Apache::lonnet::critical(
 3980:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 3981:        &escape($message),$server);
 3982:     return $status;
 3983: }
 3984: 
 3985: sub dcmaildump {
 3986:     my ($dom,$startdate,$enddate,$senders) = @_;
 3987:     my %returnhash=();
 3988: 
 3989:     if (defined(&domain($dom,'primary'))) {
 3990:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 3991:                                                          &escape($enddate).':';
 3992: 	my @esc_senders=map { &escape($_)} @$senders;
 3993: 	$cmd.=&escape(join('&',@esc_senders));
 3994: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 3995:             my ($key,$value) = split(/\=/,$line,2);
 3996:             if (($key) && ($value)) {
 3997:                 $returnhash{&unescape($key)} = &unescape($value);
 3998:             }
 3999:         }
 4000:     }
 4001:     return %returnhash;
 4002: }
 4003: # ---------------------------------------------------------- Domain roles
 4004: 
 4005: sub get_domain_roles {
 4006:     my ($dom,$roles,$startdate,$enddate)=@_;
 4007:     if ((!defined($startdate)) || ($startdate eq '')) {
 4008:         $startdate = '.';
 4009:     }
 4010:     if ((!defined($enddate)) || ($enddate eq '')) {
 4011:         $enddate = '.';
 4012:     }
 4013:     my $rolelist;
 4014:     if (ref($roles) eq 'ARRAY') {
 4015:         $rolelist = join(':',@{$roles});
 4016:     }
 4017:     my %personnel = ();
 4018: 
 4019:     my %servers = &get_servers($dom,'library');
 4020:     foreach my $tryserver (keys(%servers)) {
 4021: 	%{$personnel{$tryserver}}=();
 4022: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 4023: 					    &escape($startdate).':'.
 4024: 					    &escape($enddate).':'.
 4025: 					    &escape($rolelist), $tryserver))) {
 4026: 	    my ($key,$value) = split(/\=/,$line,2);
 4027: 	    if (($key) && ($value)) {
 4028: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 4029: 	    }
 4030: 	}
 4031:     }
 4032:     return %personnel;
 4033: }
 4034: 
 4035: # ----------------------------------------------------------- Interval timing 
 4036: 
 4037: {
 4038: # Caches needed for speedup of navmaps
 4039: # We don't want to cache this for very long at all (5 seconds at most)
 4040: # 
 4041: # The user for whom we cache
 4042: my $cachedkey='';
 4043: # The cached times for this user
 4044: my %cachedtimes=();
 4045: # When this was last done
 4046: my $cachedtime=();
 4047: 
 4048: sub load_all_first_access {
 4049:     my ($uname,$udom)=@_;
 4050:     if (($cachedkey eq $uname.':'.$udom) &&
 4051:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
 4052:         return;
 4053:     }
 4054:     $cachedtime=time;
 4055:     $cachedkey=$uname.':'.$udom;
 4056:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 4057: }
 4058: 
 4059: sub get_first_access {
 4060:     my ($type,$argsymb,$argmap)=@_;
 4061:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4062:     if ($argsymb) { $symb=$argsymb; }
 4063:     my ($map,$id,$res)=&decode_symb($symb);
 4064:     if ($argmap) { $map = $argmap; }
 4065:     if ($type eq 'course') {
 4066: 	$res='course';
 4067:     } elsif ($type eq 'map') {
 4068: 	$res=&symbread($map);
 4069:     } else {
 4070: 	$res=$symb;
 4071:     }
 4072:     &load_all_first_access($uname,$udom);
 4073:     return $cachedtimes{"$courseid\0$res"};
 4074: }
 4075: 
 4076: sub set_first_access {
 4077:     my ($type,$interval)=@_;
 4078:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4079:     my ($map,$id,$res)=&decode_symb($symb);
 4080:     if ($type eq 'course') {
 4081: 	$res='course';
 4082:     } elsif ($type eq 'map') {
 4083: 	$res=&symbread($map);
 4084:     } else {
 4085: 	$res=$symb;
 4086:     }
 4087:     $cachedkey='';
 4088:     my $firstaccess=&get_first_access($type,$symb,$map);
 4089:     if (!$firstaccess) {
 4090:         my $start = time;
 4091: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 4092:                           $udom,$uname);
 4093:         if ($putres eq 'ok') {
 4094:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 4095:                  $udom,$uname); 
 4096:             &appenv(
 4097:                      {
 4098:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 4099:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 4100:                      }
 4101:                   );
 4102:         }
 4103:         return $putres;
 4104:     }
 4105:     return 'already_set';
 4106: }
 4107: }
 4108: # --------------------------------------------- Set Expire Date for Spreadsheet
 4109: 
 4110: sub expirespread {
 4111:     my ($uname,$udom,$stype,$usymb)=@_;
 4112:     my $cid=$env{'request.course.id'}; 
 4113:     if ($cid) {
 4114:        my $now=time;
 4115:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 4116:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 4117:                             $env{'course.'.$cid.'.num'}.
 4118: 	        	    ':nohist_expirationdates:'.
 4119:                             &escape($key).'='.$now,
 4120:                             $env{'course.'.$cid.'.home'})
 4121:     }
 4122:     return 'ok';
 4123: }
 4124: 
 4125: # ----------------------------------------------------- Devalidate Spreadsheets
 4126: 
 4127: sub devalidate {
 4128:     my ($symb,$uname,$udom)=@_;
 4129:     my $cid=$env{'request.course.id'}; 
 4130:     if ($cid) {
 4131:         # delete the stored spreadsheets for
 4132:         # - the student level sheet of this user in course's homespace
 4133:         # - the assessment level sheet for this resource 
 4134:         #   for this user in user's homespace
 4135: 	# - current conditional state info
 4136: 	my $key=$uname.':'.$udom.':';
 4137:         my $status=
 4138: 	    &del('nohist_calculatedsheets',
 4139: 		 [$key.'studentcalc:'],
 4140: 		 $env{'course.'.$cid.'.domain'},
 4141: 		 $env{'course.'.$cid.'.num'})
 4142: 		.' '.
 4143: 	    &del('nohist_calculatedsheets_'.$cid,
 4144: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 4145:         unless ($status eq 'ok ok') {
 4146:            &logthis('Could not devalidate spreadsheet '.
 4147:                     $uname.' at '.$udom.' for '.
 4148: 		    $symb.': '.$status);
 4149:         }
 4150: 	&delenv('user.state.'.$cid);
 4151:     }
 4152: }
 4153: 
 4154: sub get_scalar {
 4155:     my ($string,$end) = @_;
 4156:     my $value;
 4157:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 4158: 	$value = $1;
 4159:     } elsif ($$string =~ s/^([^&]*?)&//) {
 4160: 	$value = $1;
 4161:     }
 4162:     return &unescape($value);
 4163: }
 4164: 
 4165: sub array2str {
 4166:   my (@array) = @_;
 4167:   my $result=&arrayref2str(\@array);
 4168:   $result=~s/^__ARRAY_REF__//;
 4169:   $result=~s/__END_ARRAY_REF__$//;
 4170:   return $result;
 4171: }
 4172: 
 4173: sub arrayref2str {
 4174:   my ($arrayref) = @_;
 4175:   my $result='__ARRAY_REF__';
 4176:   foreach my $elem (@$arrayref) {
 4177:     if(ref($elem) eq 'ARRAY') {
 4178:       $result.=&arrayref2str($elem).'&';
 4179:     } elsif(ref($elem) eq 'HASH') {
 4180:       $result.=&hashref2str($elem).'&';
 4181:     } elsif(ref($elem)) {
 4182:       #print("Got a ref of ".(ref($elem))." skipping.");
 4183:     } else {
 4184:       $result.=&escape($elem).'&';
 4185:     }
 4186:   }
 4187:   $result=~s/\&$//;
 4188:   $result .= '__END_ARRAY_REF__';
 4189:   return $result;
 4190: }
 4191: 
 4192: sub hash2str {
 4193:   my (%hash) = @_;
 4194:   my $result=&hashref2str(\%hash);
 4195:   $result=~s/^__HASH_REF__//;
 4196:   $result=~s/__END_HASH_REF__$//;
 4197:   return $result;
 4198: }
 4199: 
 4200: sub hashref2str {
 4201:   my ($hashref)=@_;
 4202:   my $result='__HASH_REF__';
 4203:   foreach my $key (sort(keys(%$hashref))) {
 4204:     if (ref($key) eq 'ARRAY') {
 4205:       $result.=&arrayref2str($key).'=';
 4206:     } elsif (ref($key) eq 'HASH') {
 4207:       $result.=&hashref2str($key).'=';
 4208:     } elsif (ref($key)) {
 4209:       $result.='=';
 4210:       #print("Got a ref of ".(ref($key))." skipping.");
 4211:     } else {
 4212: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 4213:     }
 4214: 
 4215:     if(ref($hashref->{$key}) eq 'ARRAY') {
 4216:       $result.=&arrayref2str($hashref->{$key}).'&';
 4217:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 4218:       $result.=&hashref2str($hashref->{$key}).'&';
 4219:     } elsif(ref($hashref->{$key})) {
 4220:        $result.='&';
 4221:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 4222:     } else {
 4223:       $result.=&escape($hashref->{$key}).'&';
 4224:     }
 4225:   }
 4226:   $result=~s/\&$//;
 4227:   $result .= '__END_HASH_REF__';
 4228:   return $result;
 4229: }
 4230: 
 4231: sub str2hash {
 4232:     my ($string)=@_;
 4233:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 4234:     return %$hash;
 4235: }
 4236: 
 4237: sub str2hashref {
 4238:   my ($string) = @_;
 4239: 
 4240:   my %hash;
 4241: 
 4242:   if($string !~ /^__HASH_REF__/) {
 4243:       if (! ($string eq '' || !defined($string))) {
 4244: 	  $hash{'error'}='Not hash reference';
 4245:       }
 4246:       return (\%hash, $string);
 4247:   }
 4248: 
 4249:   $string =~ s/^__HASH_REF__//;
 4250: 
 4251:   while($string !~ /^__END_HASH_REF__/) {
 4252:       #key
 4253:       my $key='';
 4254:       if($string =~ /^__HASH_REF__/) {
 4255:           ($key, $string)=&str2hashref($string);
 4256:           if(defined($key->{'error'})) {
 4257:               $hash{'error'}='Bad data';
 4258:               return (\%hash, $string);
 4259:           }
 4260:       } elsif($string =~ /^__ARRAY_REF__/) {
 4261:           ($key, $string)=&str2arrayref($string);
 4262:           if($key->[0] eq 'Array reference error') {
 4263:               $hash{'error'}='Bad data';
 4264:               return (\%hash, $string);
 4265:           }
 4266:       } else {
 4267:           $string =~ s/^(.*?)=//;
 4268: 	  $key=&unescape($1);
 4269:       }
 4270:       $string =~ s/^=//;
 4271: 
 4272:       #value
 4273:       my $value='';
 4274:       if($string =~ /^__HASH_REF__/) {
 4275:           ($value, $string)=&str2hashref($string);
 4276:           if(defined($value->{'error'})) {
 4277:               $hash{'error'}='Bad data';
 4278:               return (\%hash, $string);
 4279:           }
 4280:       } elsif($string =~ /^__ARRAY_REF__/) {
 4281:           ($value, $string)=&str2arrayref($string);
 4282:           if($value->[0] eq 'Array reference error') {
 4283:               $hash{'error'}='Bad data';
 4284:               return (\%hash, $string);
 4285:           }
 4286:       } else {
 4287: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 4288:       }
 4289:       $string =~ s/^&//;
 4290: 
 4291:       $hash{$key}=$value;
 4292:   }
 4293: 
 4294:   $string =~ s/^__END_HASH_REF__//;
 4295: 
 4296:   return (\%hash, $string);
 4297: }
 4298: 
 4299: sub str2array {
 4300:     my ($string)=@_;
 4301:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 4302:     return @$array;
 4303: }
 4304: 
 4305: sub str2arrayref {
 4306:   my ($string) = @_;
 4307:   my @array;
 4308: 
 4309:   if($string !~ /^__ARRAY_REF__/) {
 4310:       if (! ($string eq '' || !defined($string))) {
 4311: 	  $array[0]='Array reference error';
 4312:       }
 4313:       return (\@array, $string);
 4314:   }
 4315: 
 4316:   $string =~ s/^__ARRAY_REF__//;
 4317: 
 4318:   while($string !~ /^__END_ARRAY_REF__/) {
 4319:       my $value='';
 4320:       if($string =~ /^__HASH_REF__/) {
 4321:           ($value, $string)=&str2hashref($string);
 4322:           if(defined($value->{'error'})) {
 4323:               $array[0] ='Array reference error';
 4324:               return (\@array, $string);
 4325:           }
 4326:       } elsif($string =~ /^__ARRAY_REF__/) {
 4327:           ($value, $string)=&str2arrayref($string);
 4328:           if($value->[0] eq 'Array reference error') {
 4329:               $array[0] ='Array reference error';
 4330:               return (\@array, $string);
 4331:           }
 4332:       } else {
 4333: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 4334:       }
 4335:       $string =~ s/^&//;
 4336: 
 4337:       push(@array, $value);
 4338:   }
 4339: 
 4340:   $string =~ s/^__END_ARRAY_REF__//;
 4341: 
 4342:   return (\@array, $string);
 4343: }
 4344: 
 4345: # -------------------------------------------------------------------Temp Store
 4346: 
 4347: sub tmpreset {
 4348:   my ($symb,$namespace,$domain,$stuname) = @_;
 4349:   if (!$symb) {
 4350:     $symb=&symbread();
 4351:     if (!$symb) { $symb= $env{'request.url'}; }
 4352:   }
 4353:   $symb=escape($symb);
 4354: 
 4355:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4356:   $namespace=~s/\//\_/g;
 4357:   $namespace=~s/\W//g;
 4358: 
 4359:   if (!$domain) { $domain=$env{'user.domain'}; }
 4360:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4361:   if ($domain eq 'public' && $stuname eq 'public') {
 4362:       $stuname=$ENV{'REMOTE_ADDR'};
 4363:   }
 4364:   my $path=LONCAPA::tempdir();
 4365:   my %hash;
 4366:   if (tie(%hash,'GDBM_File',
 4367: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4368: 	  &GDBM_WRCREAT(),0640)) {
 4369:     foreach my $key (keys(%hash)) {
 4370:       if ($key=~ /:$symb/) {
 4371: 	delete($hash{$key});
 4372:       }
 4373:     }
 4374:   }
 4375: }
 4376: 
 4377: sub tmpstore {
 4378:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4379: 
 4380:   if (!$symb) {
 4381:     $symb=&symbread();
 4382:     if (!$symb) { $symb= $env{'request.url'}; }
 4383:   }
 4384:   $symb=escape($symb);
 4385: 
 4386:   if (!$namespace) {
 4387:     # I don't think we would ever want to store this for a course.
 4388:     # it seems this will only be used if we don't have a course.
 4389:     #$namespace=$env{'request.course.id'};
 4390:     #if (!$namespace) {
 4391:       $namespace=$env{'request.state'};
 4392:     #}
 4393:   }
 4394:   $namespace=~s/\//\_/g;
 4395:   $namespace=~s/\W//g;
 4396:   if (!$domain) { $domain=$env{'user.domain'}; }
 4397:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4398:   if ($domain eq 'public' && $stuname eq 'public') {
 4399:       $stuname=$ENV{'REMOTE_ADDR'};
 4400:   }
 4401:   my $now=time;
 4402:   my %hash;
 4403:   my $path=LONCAPA::tempdir();
 4404:   if (tie(%hash,'GDBM_File',
 4405: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4406: 	  &GDBM_WRCREAT(),0640)) {
 4407:     $hash{"version:$symb"}++;
 4408:     my $version=$hash{"version:$symb"};
 4409:     my $allkeys=''; 
 4410:     foreach my $key (keys(%$storehash)) {
 4411:       $allkeys.=$key.':';
 4412:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 4413:     }
 4414:     $hash{"$version:$symb:timestamp"}=$now;
 4415:     $allkeys.='timestamp';
 4416:     $hash{"$version:keys:$symb"}=$allkeys;
 4417:     if (untie(%hash)) {
 4418:       return 'ok';
 4419:     } else {
 4420:       return "error:$!";
 4421:     }
 4422:   } else {
 4423:     return "error:$!";
 4424:   }
 4425: }
 4426: 
 4427: # -----------------------------------------------------------------Temp Restore
 4428: 
 4429: sub tmprestore {
 4430:   my ($symb,$namespace,$domain,$stuname) = @_;
 4431: 
 4432:   if (!$symb) {
 4433:     $symb=&symbread();
 4434:     if (!$symb) { $symb= $env{'request.url'}; }
 4435:   }
 4436:   $symb=escape($symb);
 4437: 
 4438:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4439: 
 4440:   if (!$domain) { $domain=$env{'user.domain'}; }
 4441:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4442:   if ($domain eq 'public' && $stuname eq 'public') {
 4443:       $stuname=$ENV{'REMOTE_ADDR'};
 4444:   }
 4445:   my %returnhash;
 4446:   $namespace=~s/\//\_/g;
 4447:   $namespace=~s/\W//g;
 4448:   my %hash;
 4449:   my $path=LONCAPA::tempdir();
 4450:   if (tie(%hash,'GDBM_File',
 4451: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4452: 	  &GDBM_READER(),0640)) {
 4453:     my $version=$hash{"version:$symb"};
 4454:     $returnhash{'version'}=$version;
 4455:     my $scope;
 4456:     for ($scope=1;$scope<=$version;$scope++) {
 4457:       my $vkeys=$hash{"$scope:keys:$symb"};
 4458:       my @keys=split(/:/,$vkeys);
 4459:       my $key;
 4460:       $returnhash{"$scope:keys"}=$vkeys;
 4461:       foreach $key (@keys) {
 4462: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4463: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4464:       }
 4465:     }
 4466:     if (!(untie(%hash))) {
 4467:       return "error:$!";
 4468:     }
 4469:   } else {
 4470:     return "error:$!";
 4471:   }
 4472:   return %returnhash;
 4473: }
 4474: 
 4475: # ----------------------------------------------------------------------- Store
 4476: 
 4477: sub store {
 4478:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4479:     my $home='';
 4480: 
 4481:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4482: 
 4483:     $symb=&symbclean($symb);
 4484:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4485: 
 4486:     if (!$domain) { $domain=$env{'user.domain'}; }
 4487:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4488: 
 4489:     &devalidate($symb,$stuname,$domain);
 4490: 
 4491:     $symb=escape($symb);
 4492:     if (!$namespace) { 
 4493:        unless ($namespace=$env{'request.course.id'}) { 
 4494:           return ''; 
 4495:        } 
 4496:     }
 4497:     if (!$home) { $home=$env{'user.home'}; }
 4498: 
 4499:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4500:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4501: 
 4502:     my $namevalue='';
 4503:     foreach my $key (keys(%$storehash)) {
 4504:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4505:     }
 4506:     $namevalue=~s/\&$//;
 4507:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 4508:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4509: }
 4510: 
 4511: # -------------------------------------------------------------- Critical Store
 4512: 
 4513: sub cstore {
 4514:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4515:     my $home='';
 4516: 
 4517:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4518: 
 4519:     $symb=&symbclean($symb);
 4520:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4521: 
 4522:     if (!$domain) { $domain=$env{'user.domain'}; }
 4523:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4524: 
 4525:     &devalidate($symb,$stuname,$domain);
 4526: 
 4527:     $symb=escape($symb);
 4528:     if (!$namespace) { 
 4529:        unless ($namespace=$env{'request.course.id'}) { 
 4530:           return ''; 
 4531:        } 
 4532:     }
 4533:     if (!$home) { $home=$env{'user.home'}; }
 4534: 
 4535:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4536:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4537: 
 4538:     my $namevalue='';
 4539:     foreach my $key (keys(%$storehash)) {
 4540:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4541:     }
 4542:     $namevalue=~s/\&$//;
 4543:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 4544:     return critical
 4545:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4546: }
 4547: 
 4548: # --------------------------------------------------------------------- Restore
 4549: 
 4550: sub restore {
 4551:     my ($symb,$namespace,$domain,$stuname) = @_;
 4552:     my $home='';
 4553: 
 4554:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4555: 
 4556:     if (!$symb) {
 4557:       unless ($symb=escape(&symbread())) { return ''; }
 4558:     } else {
 4559:       $symb=&escape(&symbclean($symb));
 4560:     }
 4561:     if (!$namespace) { 
 4562:        unless ($namespace=$env{'request.course.id'}) { 
 4563:           return ''; 
 4564:        } 
 4565:     }
 4566:     if (!$domain) { $domain=$env{'user.domain'}; }
 4567:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4568:     if (!$home) { $home=$env{'user.home'}; }
 4569:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 4570: 
 4571:     my %returnhash=();
 4572:     foreach my $line (split(/\&/,$answer)) {
 4573: 	my ($name,$value)=split(/\=/,$line);
 4574:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 4575:     }
 4576:     my $version;
 4577:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 4578:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 4579:           $returnhash{$item}=$returnhash{$version.':'.$item};
 4580:        }
 4581:     }
 4582:     return %returnhash;
 4583: }
 4584: 
 4585: # ---------------------------------------------------------- Course Description
 4586: #
 4587: #  
 4588: 
 4589: sub coursedescription {
 4590:     my ($courseid,$args)=@_;
 4591:     $courseid=~s/^\///;
 4592:     $courseid=~s/\_/\//g;
 4593:     my ($cdomain,$cnum)=split(/\//,$courseid);
 4594:     my $chome=&homeserver($cnum,$cdomain);
 4595:     my $normalid=$cdomain.'_'.$cnum;
 4596:     # need to always cache even if we get errors otherwise we keep 
 4597:     # trying and trying and trying to get the course description.
 4598:     my %envhash=();
 4599:     my %returnhash=();
 4600:     
 4601:     my $expiretime=600;
 4602:     if ($env{'request.course.id'} eq $normalid) {
 4603: 	$expiretime=120;
 4604:     }
 4605: 
 4606:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 4607:     if (!$args->{'freshen_cache'}
 4608: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 4609: 	foreach my $key (keys(%env)) {
 4610: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 4611: 	    my ($setting) = $1;
 4612: 	    $returnhash{$setting} = $env{$key};
 4613: 	}
 4614: 	return %returnhash;
 4615:     }
 4616: 
 4617:     # get the data again
 4618: 
 4619:     if (!$args->{'one_time'}) {
 4620: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 4621:     }
 4622: 
 4623:     if ($chome ne 'no_host') {
 4624:        %returnhash=&dump('environment',$cdomain,$cnum);
 4625:        if (!exists($returnhash{'con_lost'})) {
 4626: 	   my $username = $env{'user.name'}; # Defult username
 4627: 	   if(defined $args->{'user'}) {
 4628: 	       $username = $args->{'user'};
 4629: 	   }
 4630:            $returnhash{'home'}= $chome;
 4631: 	   $returnhash{'domain'} = $cdomain;
 4632: 	   $returnhash{'num'} = $cnum;
 4633:            if (!defined($returnhash{'type'})) {
 4634:                $returnhash{'type'} = 'Course';
 4635:            }
 4636:            while (my ($name,$value) = each %returnhash) {
 4637:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 4638:            }
 4639:            $returnhash{'url'}=&clutter($returnhash{'url'});
 4640:            $returnhash{'fn'}=LONCAPA::tempdir() .
 4641: 	       $username.'_'.$cdomain.'_'.$cnum;
 4642:            $envhash{'course.'.$normalid.'.home'}=$chome;
 4643:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 4644:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 4645:        }
 4646:     }
 4647:     if (!$args->{'one_time'}) {
 4648: 	&appenv(\%envhash);
 4649:     }
 4650:     return %returnhash;
 4651: }
 4652: 
 4653: sub update_released_required {
 4654:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 4655:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 4656:         $cid = $env{'request.course.id'};
 4657:         $cdom = $env{'course.'.$cid.'.domain'};
 4658:         $cnum = $env{'course.'.$cid.'.num'};
 4659:         $chome = $env{'course.'.$cid.'.home'};
 4660:     }
 4661:     if ($needsrelease) {
 4662:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 4663:         my $needsupdate;
 4664:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 4665:             $needsupdate = 1;
 4666:         } else {
 4667:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 4668:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 4669:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 4670:                 $needsupdate = 1;
 4671:             }
 4672:         }
 4673:         if ($needsupdate) {
 4674:             my %needshash = (
 4675:                              'internal.releaserequired' => $needsrelease,
 4676:                             );
 4677:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 4678:             if ($putresult eq 'ok') {
 4679:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 4680:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 4681:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 4682:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 4683:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 4684:                 }
 4685:             }
 4686:         }
 4687:     }
 4688:     return;
 4689: }
 4690: 
 4691: # -------------------------------------------------See if a user is privileged
 4692: 
 4693: sub privileged {
 4694:     my ($username,$domain)=@_;
 4695: 
 4696:     my %rolesdump = &dump("roles", $domain, $username) or return 0;
 4697:     my $now = time;
 4698: 
 4699:     for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
 4700:             my ($trole, $tend, $tstart) = split(/_/, $role);
 4701:             if (($trole eq 'dc') || ($trole eq 'su')) {
 4702:                 return 1 unless ($tend && $tend < $now) 
 4703:                     or ($tstart && $tstart > $now);
 4704:             }
 4705: 	}
 4706: 
 4707:     return 0;
 4708: }
 4709: 
 4710: # -------------------------------------------------------- Get user privileges
 4711: 
 4712: sub rolesinit {
 4713:     my ($domain, $username) = @_;
 4714:     my %userroles = ('user.login.time' => time);
 4715:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 4716: 
 4717:     # firstaccess and timerinterval are related to timed maps/resources. 
 4718:     # also, blocking can be triggered by an activating timer
 4719:     # it's saved in the user's %env.
 4720:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 4721:     my %timerinterval = &dump('timerinterval', $domain, $username);
 4722:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 4723:         %timerintchk, %timerintenv);
 4724: 
 4725:     foreach my $key (keys(%firstaccess)) {
 4726:         my ($cid, $rest) = split(/\0/, $key);
 4727:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 4728:     }
 4729: 
 4730:     foreach my $key (keys(%timerinterval)) {
 4731:         my ($cid,$rest) = split(/\0/,$key);
 4732:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 4733:     }
 4734: 
 4735:     my %allroles=();
 4736:     my %allgroups=();
 4737: 
 4738:     for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
 4739:         my $role = $rolesdump{$area};
 4740:         $area =~ s/\_\w\w$//;
 4741: 
 4742:         my ($trole, $tend, $tstart, $group_privs);
 4743: 
 4744:         if ($role =~ /^cr/) {
 4745:         # Custom role, defined by a user 
 4746:         # e.g., user.role.cr/msu/smith/mynewrole
 4747:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 4748:                 $trole = $1;
 4749:                 ($tend, $tstart) = split('_', $2);
 4750:             } else {
 4751:                 $trole = $role;
 4752:             }
 4753:         } elsif ($role =~ m|^gr/|) {
 4754:         # Role of member in a group, defined within a course/community
 4755:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 4756:             ($trole, $tend, $tstart) = split(/_/, $role);
 4757:             next if $tstart eq '-1';
 4758:             ($trole, $group_privs) = split(/\//, $trole);
 4759:             $group_privs = &unescape($group_privs);
 4760:         } else {
 4761:         # Just a normal role, defined in roles.tab
 4762:             ($trole, $tend, $tstart) = split(/_/,$role);
 4763:         }
 4764: 
 4765:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 4766:                  $username);
 4767:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 4768: 
 4769:         # role expired or not available yet?
 4770:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 4771:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 4772: 
 4773:         next if $area eq '' or $trole eq '';
 4774: 
 4775:         my $spec = "$trole.$area";
 4776:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 4777: 
 4778:         if ($trole =~ /^cr\//) {
 4779:         # Custom role, defined by a user
 4780:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 4781:         } elsif ($trole eq 'gr') {
 4782:         # Role of a member in a group, defined within a course/community
 4783:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 4784:             next;
 4785:         } else {
 4786:         # Normal role, defined in roles.tab
 4787:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 4788:         }
 4789: 
 4790:         my $cid = $tdomain.'_'.$trest;
 4791:         unless ($firstaccchk{$cid}) {
 4792:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 4793:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 4794:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 4795:                         $coursetimerstarts{$cid}{$item}; 
 4796:                 }
 4797:             }
 4798:             $firstaccchk{$cid} = 1;
 4799:         }
 4800:         unless ($timerintchk{$cid}) {
 4801:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 4802:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 4803:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 4804:                        $coursetimerintervals{$cid}{$item};
 4805:                 }
 4806:             }
 4807:             $timerintchk{$cid} = 1;
 4808:         }
 4809:     }
 4810: 
 4811:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
 4812:         \%allroles, \%allgroups);
 4813:     $env{'user.adv'} = $userroles{'user.adv'};
 4814: 
 4815:     return (\%userroles,\%firstaccenv,\%timerintenv);
 4816: }
 4817: 
 4818: sub set_arearole {
 4819:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 4820: # log the associated role with the area
 4821:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 4822:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 4823: }
 4824: 
 4825: sub custom_roleprivs {
 4826:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 4827:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 4828:     my $homsvr=homeserver($rauthor,$rdomain);
 4829:     if (&hostname($homsvr) ne '') {
 4830:         my ($rdummy,$roledef)=
 4831:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 4832:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4833:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 4834:             if (defined($syspriv)) {
 4835:                 if ($trest =~ /^$match_community$/) {
 4836:                     $syspriv =~ s/bre\&S//; 
 4837:                 }
 4838:                 $$allroles{'cm./'}.=':'.$syspriv;
 4839:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 4840:             }
 4841:             if ($tdomain ne '') {
 4842:                 if (defined($dompriv)) {
 4843:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 4844:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 4845:                 }
 4846:                 if (($trest ne '') && (defined($coursepriv))) {
 4847:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 4848:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 4849:                 }
 4850:             }
 4851:         }
 4852:     }
 4853: }
 4854: 
 4855: sub group_roleprivs {
 4856:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 4857:     my $access = 1;
 4858:     my $now = time;
 4859:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 4860:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 4861:     if ($access) {
 4862:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 4863:         $$allgroups{$course}{$group} .=':'.$group_privs;
 4864:     }
 4865: }
 4866: 
 4867: sub standard_roleprivs {
 4868:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 4869:     if (defined($pr{$trole.':s'})) {
 4870:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 4871:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 4872:     }
 4873:     if ($tdomain ne '') {
 4874:         if (defined($pr{$trole.':d'})) {
 4875:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 4876:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 4877:         }
 4878:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 4879:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 4880:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 4881:         }
 4882:     }
 4883: }
 4884: 
 4885: sub set_userprivs {
 4886:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 4887:     my $author=0;
 4888:     my $adv=0;
 4889:     my %grouproles = ();
 4890:     if (keys(%{$allgroups}) > 0) {
 4891:         my @groupkeys; 
 4892:         foreach my $role (keys(%{$allroles})) {
 4893:             push(@groupkeys,$role);
 4894:         }
 4895:         if (ref($groups_roles) eq 'HASH') {
 4896:             foreach my $key (keys(%{$groups_roles})) {
 4897:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 4898:                     push(@groupkeys,$key);
 4899:                 }
 4900:             }
 4901:         }
 4902:         if (@groupkeys > 0) {
 4903:             foreach my $role (@groupkeys) {
 4904:                 my ($trole,$area,$sec,$extendedarea);
 4905:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 4906:                     $trole = $1;
 4907:                     $area = $2;
 4908:                     $sec = $3;
 4909:                     $extendedarea = $area.$sec;
 4910:                     if (exists($$allgroups{$area})) {
 4911:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 4912:                             my $spec = $trole.'.'.$extendedarea;
 4913:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 4914:                                                 $$allgroups{$area}{$group};
 4915:                         }
 4916:                     }
 4917:                 }
 4918:             }
 4919:         }
 4920:     }
 4921:     foreach my $group (keys(%grouproles)) {
 4922:         $$allroles{$group} = $grouproles{$group};
 4923:     }
 4924:     foreach my $role (keys(%{$allroles})) {
 4925:         my %thesepriv;
 4926:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 4927:         foreach my $item (split(/:/,$$allroles{$role})) {
 4928:             if ($item ne '') {
 4929:                 my ($privilege,$restrictions)=split(/&/,$item);
 4930:                 if ($restrictions eq '') {
 4931:                     $thesepriv{$privilege}='F';
 4932:                 } elsif ($thesepriv{$privilege} ne 'F') {
 4933:                     $thesepriv{$privilege}.=$restrictions;
 4934:                 }
 4935:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 4936:             }
 4937:         }
 4938:         my $thesestr='';
 4939:         foreach my $priv (sort(keys(%thesepriv))) {
 4940: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 4941: 	}
 4942:         $userroles->{'user.priv.'.$role} = $thesestr;
 4943:     }
 4944:     return ($author,$adv);
 4945: }
 4946: 
 4947: sub role_status {
 4948:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 4949:     my @pwhere = ();
 4950:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 4951:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
 4952:         unless (!defined($$role) || $$role eq '') {
 4953:             $$where=join('.',@pwhere);
 4954:             $$trolecode=$$role.'.'.$$where;
 4955:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 4956:             $$tstatus='is';
 4957:             if ($$tstart && $$tstart>$update) {
 4958:                 $$tstatus='future';
 4959:                 if ($$tstart<$now) {
 4960:                     if ($$tstart && $$tstart>$refresh) {
 4961:                         if (($$where ne '') && ($$role ne '')) {
 4962:                             my (%allroles,%allgroups,$group_privs,
 4963:                                 %groups_roles,@rolecodes);
 4964:                             my %userroles = (
 4965:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 4966:                             );
 4967:                             @rolecodes = ('cm'); 
 4968:                             my $spec=$$role.'.'.$$where;
 4969:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 4970:                             if ($$role =~ /^cr\//) {
 4971:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 4972:                                 push(@rolecodes,'cr');
 4973:                             } elsif ($$role eq 'gr') {
 4974:                                 push(@rolecodes,$$role);
 4975:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 4976:                                                     $env{'user.name'});
 4977:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 4978:                                 (undef,my $group_privs) = split(/\//,$trole);
 4979:                                 $group_privs = &unescape($group_privs);
 4980:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 4981:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 4982:                                 &get_groups_roles($tdomain,$trest,
 4983:                                                   \%course_roles,\@rolecodes,
 4984:                                                   \%groups_roles);
 4985:                             } else {
 4986:                                 push(@rolecodes,$$role);
 4987:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 4988:                             }
 4989:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
 4990:                             &appenv(\%userroles,\@rolecodes);
 4991:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 4992:                         }
 4993:                     }
 4994:                     $$tstatus = 'is';
 4995:                 }
 4996:             }
 4997:             if ($$tend) {
 4998:                 if ($$tend<$update) {
 4999:                     $$tstatus='expired';
 5000:                 } elsif ($$tend<$now) {
 5001:                     $$tstatus='will_not';
 5002:                 }
 5003:             }
 5004:         }
 5005:     }
 5006: }
 5007: 
 5008: sub get_groups_roles {
 5009:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 5010:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 5011:                   (ref($rolecodes) eq 'ARRAY') && 
 5012:                   (ref($groups_roles) eq 'HASH')); 
 5013:     if (keys(%{$cdom_courseroles}) > 0) {
 5014:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 5015:         if ($cdom ne '' && $cnum ne '') {
 5016:             foreach my $key (keys(%{$cdom_courseroles})) {
 5017:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 5018:                     my $crsrole = $1;
 5019:                     my $crssec = $2;
 5020:                     if ($crsrole =~ /^cr/) {
 5021:                         unless (grep(/^cr$/,@{$rolecodes})) {
 5022:                             push(@{$rolecodes},'cr');
 5023:                         }
 5024:                     } else {
 5025:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 5026:                             push(@{$rolecodes},$crsrole);
 5027:                         }
 5028:                     }
 5029:                     my $rolekey = "$crsrole./$cdom/$cnum";
 5030:                     if ($crssec ne '') {
 5031:                         $rolekey .= "/$crssec";
 5032:                     }
 5033:                     $rolekey .= './';
 5034:                     $groups_roles->{$rolekey} = $rolecodes;
 5035:                 }
 5036:             }
 5037:         }
 5038:     }
 5039:     return;
 5040: }
 5041: 
 5042: sub delete_env_groupprivs {
 5043:     my ($where,$courseroles,$possroles) = @_;
 5044:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 5045:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 5046:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 5047:         %{$courseroles->{$udom}} =
 5048:             &get_my_roles('','','userroles',['active'],
 5049:                           $possroles,[$udom],1);
 5050:     }
 5051:     if (ref($courseroles->{$udom}) eq 'HASH') {
 5052:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 5053:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 5054:             my $area = '/'.$cdom.'/'.$cnum;
 5055:             my $privkey = "user.priv.$crsrole.$area";
 5056:             if ($crssec ne '') {
 5057:                 $privkey .= '/'.$crssec;
 5058:             }
 5059:             $privkey .= ".$area/$group";
 5060:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 5061:         }
 5062:     }
 5063:     return;
 5064: }
 5065: 
 5066: sub check_adhoc_privs {
 5067:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
 5068:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 5069:     my $setprivs;
 5070:     if ($env{$cckey}) {
 5071:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 5072:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 5073:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 5074:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5075:             $setprivs = 1;
 5076:         }
 5077:     } else {
 5078:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5079:         $setprivs = 1;
 5080:     }
 5081:     return $setprivs;
 5082: }
 5083: 
 5084: sub set_adhoc_privileges {
 5085: # role can be cc or ca
 5086:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
 5087:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 5088:     my $spec = $role.'.'.$area;
 5089:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 5090:                                   $env{'user.name'});
 5091:     my %ccrole = ();
 5092:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
 5093:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
 5094:     &appenv(\%userroles,[$role,'cm']);
 5095:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5096:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 5097:         &appenv( {'request.role'        => $spec,
 5098:                   'request.role.domain' => $dcdom,
 5099:                   'request.course.sec'  => ''
 5100:                  }
 5101:                );
 5102:         my $tadv=0;
 5103:         if (&allowed('adv') eq 'F') { $tadv=1; }
 5104:         &appenv({'request.role.adv'    => $tadv});
 5105:     }
 5106: }
 5107: 
 5108: # --------------------------------------------------------------- get interface
 5109: 
 5110: sub get {
 5111:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5112:    my $items='';
 5113:    foreach my $item (@$storearr) {
 5114:        $items.=&escape($item).'&';
 5115:    }
 5116:    $items=~s/\&$//;
 5117:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5118:    if (!$uname) { $uname=$env{'user.name'}; }
 5119:    my $uhome=&homeserver($uname,$udomain);
 5120: 
 5121:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 5122:    my @pairs=split(/\&/,$rep);
 5123:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 5124:      return @pairs;
 5125:    }
 5126:    my %returnhash=();
 5127:    my $i=0;
 5128:    foreach my $item (@$storearr) {
 5129:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5130:       $i++;
 5131:    }
 5132:    return %returnhash;
 5133: }
 5134: 
 5135: # --------------------------------------------------------------- del interface
 5136: 
 5137: sub del {
 5138:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5139:    my $items='';
 5140:    foreach my $item (@$storearr) {
 5141:        $items.=&escape($item).'&';
 5142:    }
 5143: 
 5144:    $items=~s/\&$//;
 5145:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5146:    if (!$uname) { $uname=$env{'user.name'}; }
 5147:    my $uhome=&homeserver($uname,$udomain);
 5148:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 5149: }
 5150: 
 5151: # -------------------------------------------------------------- dump interface
 5152: 
 5153: sub unserialize {
 5154:     my ($rep, $escapedkeys) = @_;
 5155: 
 5156:     return {} if $rep =~ /^error/;
 5157: 
 5158:     my %returnhash=();
 5159: 	foreach my $item (split /\&/, $rep) {
 5160: 	    my ($key, $value) = split(/=/, $item, 2);
 5161: 	    $key = unescape($key) unless $escapedkeys;
 5162: 	    next if $key =~ /^error: 2 /;
 5163: 	    $returnhash{$key} = Apache::lonnet::thaw_unescape($value);
 5164: 	}
 5165:     #return %returnhash;
 5166:     return \%returnhash;
 5167: }        
 5168: 
 5169: # see Lond::dump_with_regexp
 5170: # if $escapedkeys hash keys won't get unescaped.
 5171: sub dump {
 5172:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 5173:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5174:     if (!$uname) { $uname=$env{'user.name'}; }
 5175:     my $uhome=&homeserver($uname,$udomain);
 5176: 
 5177:     my $reply;
 5178:     if (grep { $_ eq $uhome } current_machine_ids()) {
 5179:         # user is hosted on this machine
 5180:         $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 5181:                     $uname, $namespace, $regexp, $range)), $loncaparevs{$uhome});
 5182:         return %{unserialize($reply, $escapedkeys)};
 5183:     }
 5184:     if ($regexp) {
 5185: 	$regexp=&escape($regexp);
 5186:     } else {
 5187: 	$regexp='.';
 5188:     }
 5189:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 5190:     my @pairs=split(/\&/,$rep);
 5191:     my %returnhash=();
 5192:     if (!($rep =~ /^error/ )) {
 5193: 	foreach my $item (@pairs) {
 5194: 	    my ($key,$value)=split(/=/,$item,2);
 5195:         $key = unescape($key) unless $escapedkeys;
 5196:         #$key = &unescape($key);
 5197: 	    next if ($key =~ /^error: 2 /);
 5198: 	    $returnhash{$key}=&thaw_unescape($value);
 5199: 	}
 5200:     }
 5201:     return %returnhash;
 5202: }
 5203: 
 5204: 
 5205: # --------------------------------------------------------- dumpstore interface
 5206: 
 5207: sub dumpstore {
 5208:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 5209:    # same as dump but keys must be escaped. They may contain colon separated
 5210:    # lists of values that may themself contain colons (e.g. symbs).
 5211:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 5212: }
 5213: 
 5214: # -------------------------------------------------------------- keys interface
 5215: 
 5216: sub getkeys {
 5217:    my ($namespace,$udomain,$uname)=@_;
 5218:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5219:    if (!$uname) { $uname=$env{'user.name'}; }
 5220:    my $uhome=&homeserver($uname,$udomain);
 5221:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 5222:    my @keyarray=();
 5223:    foreach my $key (split(/\&/,$rep)) {
 5224:       next if ($key =~ /^error: 2 /);
 5225:       push(@keyarray,&unescape($key));
 5226:    }
 5227:    return @keyarray;
 5228: }
 5229: 
 5230: # --------------------------------------------------------------- currentdump
 5231: sub currentdump {
 5232:    my ($courseid,$sdom,$sname)=@_;
 5233:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 5234:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 5235:    $sname    = $env{'user.name'}         if (! defined($sname));
 5236:    my $uhome = &homeserver($sname,$sdom);
 5237:    my $rep;
 5238: 
 5239:    if (grep { $_ eq $uhome } current_machine_ids()) {
 5240:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 5241:                    $courseid)));
 5242:    } else {
 5243:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 5244:    }
 5245: 
 5246:    return if ($rep =~ /^(error:|no_such_host)/);
 5247:    #
 5248:    my %returnhash=();
 5249:    #
 5250:    if ($rep eq "unknown_cmd") { 
 5251:        # an old lond will not know currentdump
 5252:        # Do a dump and make it look like a currentdump
 5253:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 5254:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 5255:        my %hash = @tmp;
 5256:        @tmp=();
 5257:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 5258:    } else {
 5259:        my @pairs=split(/\&/,$rep);
 5260:        foreach my $pair (@pairs) {
 5261:            my ($key,$value)=split(/=/,$pair,2);
 5262:            my ($symb,$param) = split(/:/,$key);
 5263:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 5264:                                                         &thaw_unescape($value);
 5265:        }
 5266:    }
 5267:    return %returnhash;
 5268: }
 5269: 
 5270: sub convert_dump_to_currentdump{
 5271:     my %hash = %{shift()};
 5272:     my %returnhash;
 5273:     # Code ripped from lond, essentially.  The only difference
 5274:     # here is the unescaping done by lonnet::dump().  Conceivably
 5275:     # we might run in to problems with parameter names =~ /^v\./
 5276:     while (my ($key,$value) = each(%hash)) {
 5277:         my ($v,$symb,$param) = split(/:/,$key);
 5278: 	$symb  = &unescape($symb);
 5279: 	$param = &unescape($param);
 5280:         next if ($v eq 'version' || $symb eq 'keys');
 5281:         next if (exists($returnhash{$symb}) &&
 5282:                  exists($returnhash{$symb}->{$param}) &&
 5283:                  $returnhash{$symb}->{'v.'.$param} > $v);
 5284:         $returnhash{$symb}->{$param}=$value;
 5285:         $returnhash{$symb}->{'v.'.$param}=$v;
 5286:     }
 5287:     #
 5288:     # Remove all of the keys in the hashes which keep track of
 5289:     # the version of the parameter.
 5290:     while (my ($symb,$param_hash) = each(%returnhash)) {
 5291:         # use a foreach because we are going to delete from the hash.
 5292:         foreach my $key (keys(%$param_hash)) {
 5293:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 5294:         }
 5295:     }
 5296:     return \%returnhash;
 5297: }
 5298: 
 5299: # ------------------------------------------------------ critical inc interface
 5300: 
 5301: sub cinc {
 5302:     return &inc(@_,'critical');
 5303: }
 5304: 
 5305: # --------------------------------------------------------------- inc interface
 5306: 
 5307: sub inc {
 5308:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 5309:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5310:     if (!$uname) { $uname=$env{'user.name'}; }
 5311:     my $uhome=&homeserver($uname,$udomain);
 5312:     my $items='';
 5313:     if (! ref($store)) {
 5314:         # got a single value, so use that instead
 5315:         $items = &escape($store).'=&';
 5316:     } elsif (ref($store) eq 'SCALAR') {
 5317:         $items = &escape($$store).'=&';        
 5318:     } elsif (ref($store) eq 'ARRAY') {
 5319:         $items = join('=&',map {&escape($_);} @{$store});
 5320:     } elsif (ref($store) eq 'HASH') {
 5321:         while (my($key,$value) = each(%{$store})) {
 5322:             $items.= &escape($key).'='.&escape($value).'&';
 5323:         }
 5324:     }
 5325:     $items=~s/\&$//;
 5326:     if ($critical) {
 5327: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 5328:     } else {
 5329: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 5330:     }
 5331: }
 5332: 
 5333: # --------------------------------------------------------------- put interface
 5334: 
 5335: sub put {
 5336:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5337:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5338:    if (!$uname) { $uname=$env{'user.name'}; }
 5339:    my $uhome=&homeserver($uname,$udomain);
 5340:    my $items='';
 5341:    foreach my $item (keys(%$storehash)) {
 5342:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5343:    }
 5344:    $items=~s/\&$//;
 5345:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5346: }
 5347: 
 5348: # ------------------------------------------------------------ newput interface
 5349: 
 5350: sub newput {
 5351:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5352:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5353:    if (!$uname) { $uname=$env{'user.name'}; }
 5354:    my $uhome=&homeserver($uname,$udomain);
 5355:    my $items='';
 5356:    foreach my $key (keys(%$storehash)) {
 5357:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5358:    }
 5359:    $items=~s/\&$//;
 5360:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 5361: }
 5362: 
 5363: # ---------------------------------------------------------  putstore interface
 5364: 
 5365: sub putstore {
 5366:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5367:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5368:    if (!$uname) { $uname=$env{'user.name'}; }
 5369:    my $uhome=&homeserver($uname,$udomain);
 5370:    my $items='';
 5371:    foreach my $key (keys(%$storehash)) {
 5372:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 5373:    }
 5374:    $items=~s/\&$//;
 5375:    my $esc_symb=&escape($symb);
 5376:    my $esc_v=&escape($version);
 5377:    my $reply =
 5378:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 5379: 	      $uhome);
 5380:    if ($reply eq 'unknown_cmd') {
 5381:        # gfall back to way things use to be done
 5382:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 5383: 			    $uname);
 5384:    }
 5385:    return $reply;
 5386: }
 5387: 
 5388: sub old_putstore {
 5389:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5390:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5391:     if (!$uname) { $uname=$env{'user.name'}; }
 5392:     my $uhome=&homeserver($uname,$udomain);
 5393:     my %newstorehash;
 5394:     foreach my $item (keys(%$storehash)) {
 5395: 	my $key = $version.':'.&escape($symb).':'.$item;
 5396: 	$newstorehash{$key} = $storehash->{$item};
 5397:     }
 5398:     my $items='';
 5399:     my %allitems = ();
 5400:     foreach my $item (keys(%newstorehash)) {
 5401: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 5402: 	    my $key = $1.':keys:'.$2;
 5403: 	    $allitems{$key} .= $3.':';
 5404: 	}
 5405: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 5406:     }
 5407:     foreach my $item (keys(%allitems)) {
 5408: 	$allitems{$item} =~ s/\:$//;
 5409: 	$items.= $item.'='.$allitems{$item}.'&';
 5410:     }
 5411:     $items=~s/\&$//;
 5412:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5413: }
 5414: 
 5415: # ------------------------------------------------------ critical put interface
 5416: 
 5417: sub cput {
 5418:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5419:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5420:    if (!$uname) { $uname=$env{'user.name'}; }
 5421:    my $uhome=&homeserver($uname,$udomain);
 5422:    my $items='';
 5423:    foreach my $item (keys(%$storehash)) {
 5424:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5425:    }
 5426:    $items=~s/\&$//;
 5427:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 5428: }
 5429: 
 5430: # -------------------------------------------------------------- eget interface
 5431: 
 5432: sub eget {
 5433:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5434:    my $items='';
 5435:    foreach my $item (@$storearr) {
 5436:        $items.=&escape($item).'&';
 5437:    }
 5438:    $items=~s/\&$//;
 5439:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5440:    if (!$uname) { $uname=$env{'user.name'}; }
 5441:    my $uhome=&homeserver($uname,$udomain);
 5442:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 5443:    my @pairs=split(/\&/,$rep);
 5444:    my %returnhash=();
 5445:    my $i=0;
 5446:    foreach my $item (@$storearr) {
 5447:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5448:       $i++;
 5449:    }
 5450:    return %returnhash;
 5451: }
 5452: 
 5453: # ------------------------------------------------------------ tmpput interface
 5454: sub tmpput {
 5455:     my ($storehash,$server,$context)=@_;
 5456:     my $items='';
 5457:     foreach my $item (keys(%$storehash)) {
 5458: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5459:     }
 5460:     $items=~s/\&$//;
 5461:     if (defined($context)) {
 5462:         $items .= ':'.&escape($context);
 5463:     }
 5464:     return &reply("tmpput:$items",$server);
 5465: }
 5466: 
 5467: # ------------------------------------------------------------ tmpget interface
 5468: sub tmpget {
 5469:     my ($token,$server)=@_;
 5470:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5471:     my $rep=&reply("tmpget:$token",$server);
 5472:     my %returnhash;
 5473:     foreach my $item (split(/\&/,$rep)) {
 5474: 	my ($key,$value)=split(/=/,$item);
 5475:         next if ($key =~ /^error: 2 /);
 5476: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 5477:     }
 5478:     return %returnhash;
 5479: }
 5480: 
 5481: # ------------------------------------------------------------ tmpdel interface
 5482: sub tmpdel {
 5483:     my ($token,$server)=@_;
 5484:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5485:     return &reply("tmpdel:$token",$server);
 5486: }
 5487: 
 5488: # -------------------------------------------------- portfolio access checking
 5489: 
 5490: sub portfolio_access {
 5491:     my ($requrl) = @_;
 5492:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 5493:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 5494:     if ($result) {
 5495:         my %setters;
 5496:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 5497:             my ($startblock,$endblock) =
 5498:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 5499:             if ($startblock && $endblock) {
 5500:                 return 'B';
 5501:             }
 5502:         } else {
 5503:             my ($startblock,$endblock) =
 5504:                 &Apache::loncommon::blockcheck(\%setters,'port');
 5505:             if ($startblock && $endblock) {
 5506:                 return 'B';
 5507:             }
 5508:         }
 5509:     }
 5510:     if ($result eq 'ok') {
 5511:        return 'F';
 5512:     } elsif ($result =~ /^[^:]+:guest_/) {
 5513:        return 'A';
 5514:     }
 5515:     return '';
 5516: }
 5517: 
 5518: sub get_portfolio_access {
 5519:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 5520: 
 5521:     if (!ref($access_hash)) {
 5522: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 5523: 	my %access_controls = &get_access_controls($current_perms,$group,
 5524: 						   $file_name);
 5525: 	$access_hash = $access_controls{$file_name};
 5526:     }
 5527: 
 5528:     my ($public,$guest,@domains,@users,@courses,@groups);
 5529:     my $now = time;
 5530:     if (ref($access_hash) eq 'HASH') {
 5531:         foreach my $key (keys(%{$access_hash})) {
 5532:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 5533:             if ($start > $now) {
 5534:                 next;
 5535:             }
 5536:             if ($end && $end<$now) {
 5537:                 next;
 5538:             }
 5539:             if ($scope eq 'public') {
 5540:                 $public = $key;
 5541:                 last;
 5542:             } elsif ($scope eq 'guest') {
 5543:                 $guest = $key;
 5544:             } elsif ($scope eq 'domains') {
 5545:                 push(@domains,$key);
 5546:             } elsif ($scope eq 'users') {
 5547:                 push(@users,$key);
 5548:             } elsif ($scope eq 'course') {
 5549:                 push(@courses,$key);
 5550:             } elsif ($scope eq 'group') {
 5551:                 push(@groups,$key);
 5552:             }
 5553:         }
 5554:         if ($public) {
 5555:             return 'ok';
 5556:         }
 5557:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 5558:             if ($guest) {
 5559:                 return $guest;
 5560:             }
 5561:         } else {
 5562:             if (@domains > 0) {
 5563:                 foreach my $domkey (@domains) {
 5564:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 5565:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 5566:                             return 'ok';
 5567:                         }
 5568:                     }
 5569:                 }
 5570:             }
 5571:             if (@users > 0) {
 5572:                 foreach my $userkey (@users) {
 5573:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 5574:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 5575:                             if (ref($item) eq 'HASH') {
 5576:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 5577:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 5578:                                     return 'ok';
 5579:                                 }
 5580:                             }
 5581:                         }
 5582:                     } 
 5583:                 }
 5584:             }
 5585:             my %roleshash;
 5586:             my @courses_and_groups = @courses;
 5587:             push(@courses_and_groups,@groups); 
 5588:             if (@courses_and_groups > 0) {
 5589:                 my (%allgroups,%allroles); 
 5590:                 my ($start,$end,$role,$sec,$group);
 5591:                 foreach my $envkey (%env) {
 5592:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 5593:                         my $cid = $2.'_'.$3; 
 5594:                         if ($1 eq 'gr') {
 5595:                             $group = $4;
 5596:                             $allgroups{$cid}{$group} = $env{$envkey};
 5597:                         } else {
 5598:                             if ($4 eq '') {
 5599:                                 $sec = 'none';
 5600:                             } else {
 5601:                                 $sec = $4;
 5602:                             }
 5603:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 5604:                         }
 5605:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 5606:                         my $cid = $2.'_'.$3;
 5607:                         if ($4 eq '') {
 5608:                             $sec = 'none';
 5609:                         } else {
 5610:                             $sec = $4;
 5611:                         }
 5612:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 5613:                     }
 5614:                 }
 5615:                 if (keys(%allroles) == 0) {
 5616:                     return;
 5617:                 }
 5618:                 foreach my $key (@courses_and_groups) {
 5619:                     my %content = %{$$access_hash{$key}};
 5620:                     my $cnum = $content{'number'};
 5621:                     my $cdom = $content{'domain'};
 5622:                     my $cid = $cdom.'_'.$cnum;
 5623:                     if (!exists($allroles{$cid})) {
 5624:                         next;
 5625:                     }    
 5626:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 5627:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 5628:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 5629:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 5630:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 5631:                         foreach my $role (keys(%{$allroles{$cid}})) {
 5632:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 5633:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 5634:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 5635:                                         if (grep/^all$/,@sections) {
 5636:                                             return 'ok';
 5637:                                         } else {
 5638:                                             if (grep/^$sec$/,@sections) {
 5639:                                                 return 'ok';
 5640:                                             }
 5641:                                         }
 5642:                                     }
 5643:                                 }
 5644:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 5645:                                     if (grep/^none$/,@groups) {
 5646:                                         return 'ok';
 5647:                                     }
 5648:                                 } else {
 5649:                                     if (grep/^all$/,@groups) {
 5650:                                         return 'ok';
 5651:                                     } 
 5652:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 5653:                                         if (grep/^$group$/,@groups) {
 5654:                                             return 'ok';
 5655:                                         }
 5656:                                     }
 5657:                                 } 
 5658:                             }
 5659:                         }
 5660:                     }
 5661:                 }
 5662:             }
 5663:             if ($guest) {
 5664:                 return $guest;
 5665:             }
 5666:         }
 5667:     }
 5668:     return;
 5669: }
 5670: 
 5671: sub course_group_datechecker {
 5672:     my ($dates,$now,$status) = @_;
 5673:     my ($start,$end) = split(/\./,$dates);
 5674:     if (!$start && !$end) {
 5675:         return 'ok';
 5676:     }
 5677:     if (grep/^active$/,@{$status}) {
 5678:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 5679:             return 'ok';
 5680:         }
 5681:     }
 5682:     if (grep/^previous$/,@{$status}) {
 5683:         if ($end > $now ) {
 5684:             return 'ok';
 5685:         }
 5686:     }
 5687:     if (grep/^future$/,@{$status}) {
 5688:         if ($start > $now) {
 5689:             return 'ok';
 5690:         }
 5691:     }
 5692:     return; 
 5693: }
 5694: 
 5695: sub parse_portfolio_url {
 5696:     my ($url) = @_;
 5697: 
 5698:     my ($type,$udom,$unum,$group,$file_name);
 5699:     
 5700:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 5701: 	$type = 1;
 5702:         $udom = $1;
 5703:         $unum = $2;
 5704:         $file_name = $3;
 5705:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 5706: 	$type = 2;
 5707:         $udom = $1;
 5708:         $unum = $2;
 5709:         $group = $3;
 5710:         $file_name = $3.'/'.$4;
 5711:     }
 5712:     if (wantarray) {
 5713: 	return ($type,$udom,$unum,$file_name,$group);
 5714:     }
 5715:     return $type;
 5716: }
 5717: 
 5718: sub is_portfolio_url {
 5719:     my ($url) = @_;
 5720:     return scalar(&parse_portfolio_url($url));
 5721: }
 5722: 
 5723: sub is_portfolio_file {
 5724:     my ($file) = @_;
 5725:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 5726:         return 1;
 5727:     }
 5728:     return;
 5729: }
 5730: 
 5731: sub usertools_access {
 5732:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 5733:     my ($access,%tools);
 5734:     if ($context eq '') {
 5735:         $context = 'tools';
 5736:     }
 5737:     if ($context eq 'requestcourses') {
 5738:         %tools = (
 5739:                       official   => 1,
 5740:                       unofficial => 1,
 5741:                       community  => 1,
 5742:                  );
 5743:     } elsif ($context eq 'requestauthor') {
 5744:         %tools = (
 5745:                       requestauthor => 1,
 5746:                  );
 5747:     } else {
 5748:         %tools = (
 5749:                       aboutme   => 1,
 5750:                       blog      => 1,
 5751:                       webdav    => 1,
 5752:                       portfolio => 1,
 5753:                  );
 5754:     }
 5755:     return if (!defined($tools{$tool}));
 5756: 
 5757:     if ((!defined($udom)) || (!defined($uname))) {
 5758:         $udom = $env{'user.domain'};
 5759:         $uname = $env{'user.name'};
 5760:     }
 5761: 
 5762:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 5763:         if ($action ne 'reload') {
 5764:             if ($context eq 'requestcourses') {
 5765:                 return $env{'environment.canrequest.'.$tool};
 5766:             } elsif ($context eq 'requestauthor') {
 5767:                 return $env{'environment.canrequest.author'};
 5768:             } else {
 5769:                 return $env{'environment.availabletools.'.$tool};
 5770:             }
 5771:         }
 5772:     }
 5773: 
 5774:     my ($toolstatus,$inststatus,$envkey);
 5775:     if ($context eq 'requestauthor') {
 5776:         $envkey = $context; 
 5777:     } else {
 5778:         $envkey = $context.'.'.$tool;
 5779:     }
 5780: 
 5781:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 5782:          ($action ne 'reload')) {
 5783:         $toolstatus = $env{'environment.'.$envkey};
 5784:         $inststatus = $env{'environment.inststatus'};
 5785:     } else {
 5786:         if (ref($userenvref) eq 'HASH') {
 5787:             $toolstatus = $userenvref->{$envkey};
 5788:             $inststatus = $userenvref->{'inststatus'};
 5789:         } else {
 5790:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 5791:             $toolstatus = $userenv{$envkey};
 5792:             $inststatus = $userenv{'inststatus'};
 5793:         }
 5794:     }
 5795: 
 5796:     if ($toolstatus ne '') {
 5797:         if ($toolstatus) {
 5798:             $access = 1;
 5799:         } else {
 5800:             $access = 0;
 5801:         }
 5802:         return $access;
 5803:     }
 5804: 
 5805:     my ($is_adv,%domdef);
 5806:     if (ref($is_advref) eq 'HASH') {
 5807:         $is_adv = $is_advref->{'is_adv'};
 5808:     } else {
 5809:         $is_adv = &is_advanced_user($udom,$uname);
 5810:     }
 5811:     if (ref($domdefref) eq 'HASH') {
 5812:         %domdef = %{$domdefref};
 5813:     } else {
 5814:         %domdef = &get_domain_defaults($udom);
 5815:     }
 5816:     if (ref($domdef{$tool}) eq 'HASH') {
 5817:         if ($is_adv) {
 5818:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 5819:                 if ($domdef{$tool}{'_LC_adv'}) { 
 5820:                     $access = 1;
 5821:                 } else {
 5822:                     $access = 0;
 5823:                 }
 5824:                 return $access;
 5825:             }
 5826:         }
 5827:         if ($inststatus ne '') {
 5828:             my ($hasaccess,$hasnoaccess);
 5829:             foreach my $affiliation (split(/:/,$inststatus)) {
 5830:                 if ($domdef{$tool}{$affiliation} ne '') { 
 5831:                     if ($domdef{$tool}{$affiliation}) {
 5832:                         $hasaccess = 1;
 5833:                     } else {
 5834:                         $hasnoaccess = 1;
 5835:                     }
 5836:                 }
 5837:             }
 5838:             if ($hasaccess || $hasnoaccess) {
 5839:                 if ($hasaccess) {
 5840:                     $access = 1;
 5841:                 } elsif ($hasnoaccess) {
 5842:                     $access = 0; 
 5843:                 }
 5844:                 return $access;
 5845:             }
 5846:         } else {
 5847:             if ($domdef{$tool}{'default'} ne '') {
 5848:                 if ($domdef{$tool}{'default'}) {
 5849:                     $access = 1;
 5850:                 } elsif ($domdef{$tool}{'default'} == 0) {
 5851:                     $access = 0;
 5852:                 }
 5853:                 return $access;
 5854:             }
 5855:         }
 5856:     } else {
 5857:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 5858:             $access = 1;
 5859:         } else {
 5860:             $access = 0;
 5861:         }
 5862:         return $access;
 5863:     }
 5864: }
 5865: 
 5866: sub is_course_owner {
 5867:     my ($cdom,$cnum,$udom,$uname) = @_;
 5868:     if (($udom eq '') || ($uname eq '')) {
 5869:         $udom = $env{'user.domain'};
 5870:         $uname = $env{'user.name'};
 5871:     }
 5872:     unless (($udom eq '') || ($uname eq '')) {
 5873:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 5874:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 5875:                 return 1;
 5876:             } else {
 5877:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 5878:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 5879:                     return 1;
 5880:                 }
 5881:             }
 5882:         }
 5883:     }
 5884:     return;
 5885: }
 5886: 
 5887: sub is_advanced_user {
 5888:     my ($udom,$uname) = @_;
 5889:     if ($udom ne '' && $uname ne '') {
 5890:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 5891:             if (wantarray) {
 5892:                 return ($env{'user.adv'},$env{'user.author'});
 5893:             } else {
 5894:                 return $env{'user.adv'};
 5895:             }
 5896:         }
 5897:     }
 5898:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 5899:     my %allroles;
 5900:     my ($is_adv,$is_author);
 5901:     foreach my $role (keys(%roleshash)) {
 5902:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 5903:         my $area = '/'.$tdomain.'/'.$trest;
 5904:         if ($sec ne '') {
 5905:             $area .= '/'.$sec;
 5906:         }
 5907:         if (($area ne '') && ($trole ne '')) {
 5908:             my $spec=$trole.'.'.$area;
 5909:             if ($trole =~ /^cr\//) {
 5910:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 5911:             } elsif ($trole ne 'gr') {
 5912:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 5913:             }
 5914:             if ($trole eq 'au') {
 5915:                 $is_author = 1;
 5916:             }
 5917:         }
 5918:     }
 5919:     foreach my $role (keys(%allroles)) {
 5920:         last if ($is_adv);
 5921:         foreach my $item (split(/:/,$allroles{$role})) {
 5922:             if ($item ne '') {
 5923:                 my ($privilege,$restrictions)=split(/&/,$item);
 5924:                 if ($privilege eq 'adv') {
 5925:                     $is_adv = 1;
 5926:                     last;
 5927:                 }
 5928:             }
 5929:         }
 5930:     }
 5931:     if (wantarray) {
 5932:         return ($is_adv,$is_author);
 5933:     }
 5934:     return $is_adv;
 5935: }
 5936: 
 5937: sub check_can_request {
 5938:     my ($dom,$can_request,$request_domains) = @_;
 5939:     my $canreq = 0;
 5940:     my ($types,$typename) = &Apache::loncommon::course_types();
 5941:     my @options = ('approval','validate','autolimit');
 5942:     my $optregex = join('|',@options);
 5943:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 5944:         foreach my $type (@{$types}) {
 5945:             if (&usertools_access($env{'user.name'},
 5946:                                   $env{'user.domain'},
 5947:                                   $type,undef,'requestcourses')) {
 5948:                 $canreq ++;
 5949:                 if (ref($request_domains) eq 'HASH') {
 5950:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 5951:                 }
 5952:                 if ($dom eq $env{'user.domain'}) {
 5953:                     $can_request->{$type} = 1;
 5954:                 }
 5955:             }
 5956:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 5957:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 5958:                 if (@curr > 0) {
 5959:                     foreach my $item (@curr) {
 5960:                         if (ref($request_domains) eq 'HASH') {
 5961:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 5962:                             if ($otherdom ne '') {
 5963:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 5964:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 5965:                                         push(@{$request_domains->{$type}},$otherdom);
 5966:                                     }
 5967:                                 } else {
 5968:                                     push(@{$request_domains->{$type}},$otherdom);
 5969:                                 }
 5970:                             }
 5971:                         }
 5972:                     }
 5973:                     unless($dom eq $env{'user.domain'}) {
 5974:                         $canreq ++;
 5975:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 5976:                             $can_request->{$type} = 1;
 5977:                         }
 5978:                     }
 5979:                 }
 5980:             }
 5981:         }
 5982:     }
 5983:     return $canreq;
 5984: }
 5985: 
 5986: # ---------------------------------------------- Custom access rule evaluation
 5987: 
 5988: sub customaccess {
 5989:     my ($priv,$uri)=@_;
 5990:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 5991:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 5992:     $udom = &LONCAPA::clean_domain($udom);
 5993:     $ucrs = &LONCAPA::clean_username($ucrs);
 5994:     my $access=0;
 5995:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 5996: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 5997: 	if ($type eq 'user') {
 5998: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 5999: 		my ($tdom,$tuname)=split(m{/},$scope);
 6000: 		if ($tdom) {
 6001: 		    if ($tdom ne $env{'user.domain'}) { next; }
 6002: 		}
 6003: 		if ($tuname) {
 6004: 		    if ($tuname ne $env{'user.name'}) { next; }
 6005: 		}
 6006: 		$access=($effect eq 'allow');
 6007: 		last;
 6008: 	    }
 6009: 	} else {
 6010: 	    if ($role) {
 6011: 		if ($role ne $urole) { next; }
 6012: 	    }
 6013: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 6014: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 6015: 		if ($tdom) {
 6016: 		    if ($tdom ne $udom) { next; }
 6017: 		}
 6018: 		if ($tcrs) {
 6019: 		    if ($tcrs ne $ucrs) { next; }
 6020: 		}
 6021: 		if ($tsec) {
 6022: 		    if ($tsec ne $usec) { next; }
 6023: 		}
 6024: 		$access=($effect eq 'allow');
 6025: 		last;
 6026: 	    }
 6027: 	    if ($realm eq '' && $role eq '') {
 6028: 		$access=($effect eq 'allow');
 6029: 	    }
 6030: 	}
 6031:     }
 6032:     return $access;
 6033: }
 6034: 
 6035: # ------------------------------------------------- Check for a user privilege
 6036: 
 6037: sub allowed {
 6038:     my ($priv,$uri,$symb,$role)=@_;
 6039:     my $ver_orguri=$uri;
 6040:     $uri=&deversion($uri);
 6041:     my $orguri=$uri;
 6042:     $uri=&declutter($uri);
 6043: 
 6044:     if ($priv eq 'evb') {
 6045: # Evade communication block restrictions for specified role in a course
 6046:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 6047:             return $1;
 6048:         } else {
 6049:             return;
 6050:         }
 6051:     }
 6052: 
 6053:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 6054: # Free bre access to adm and meta resources
 6055:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 6056: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 6057: 	&& ($priv eq 'bre')) {
 6058: 	return 'F';
 6059:     }
 6060: 
 6061: # Free bre access to user's own portfolio contents
 6062:     my ($space,$domain,$name,@dir)=split('/',$uri);
 6063:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 6064: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 6065:         my %setters;
 6066:         my ($startblock,$endblock) = 
 6067:             &Apache::loncommon::blockcheck(\%setters,'port');
 6068:         if ($startblock && $endblock) {
 6069:             return 'B';
 6070:         } else {
 6071:             return 'F';
 6072:         }
 6073:     }
 6074: 
 6075: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 6076:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 6077:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 6078:         if (exists($env{'request.course.id'})) {
 6079:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6080:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6081:             if (($domain eq $cdom) && ($name eq $cnum)) {
 6082:                 my $courseprivid=$env{'request.course.id'};
 6083:                 $courseprivid=~s/\_/\//;
 6084:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 6085:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 6086:                     return $1; 
 6087:                 } else {
 6088:                     if ($env{'request.course.sec'}) {
 6089:                         $courseprivid.='/'.$env{'request.course.sec'};
 6090:                     }
 6091:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 6092:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 6093:                         return $2;
 6094:                     }
 6095:                 }
 6096:             }
 6097:         }
 6098:     }
 6099: 
 6100: # Free bre to public access
 6101: 
 6102:     if ($priv eq 'bre') {
 6103:         my $copyright=&metadata($uri,'copyright');
 6104: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 6105:            return 'F'; 
 6106:         }
 6107:         if ($copyright eq 'priv') {
 6108:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6109: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 6110: 		return '';
 6111:             }
 6112:         }
 6113:         if ($copyright eq 'domain') {
 6114:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6115: 	    unless (($env{'user.domain'} eq $1) ||
 6116:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 6117: 		return '';
 6118:             }
 6119:         }
 6120:         if ($env{'request.role'}=~ /li\.\//) {
 6121:             # Library role, so allow browsing of resources in this domain.
 6122:             return 'F';
 6123:         }
 6124:         if ($copyright eq 'custom') {
 6125: 	    unless (&customaccess($priv,$uri)) { return ''; }
 6126:         }
 6127:     }
 6128:     # Domain coordinator is trying to create a course
 6129:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 6130:         # uri is the requested domain in this case.
 6131:         # comparison to 'request.role.domain' shows if the user has selected
 6132:         # a role of dc for the domain in question.
 6133:         return 'F' if ($uri eq $env{'request.role.domain'});
 6134:     }
 6135: 
 6136:     my $thisallowed='';
 6137:     my $statecond=0;
 6138:     my $courseprivid='';
 6139: 
 6140:     my $ownaccess;
 6141:     # Community Coordinator or Assistant Co-author browsing resource space.
 6142:     if (($priv eq 'bro') && ($env{'user.author'})) {
 6143:         if ($uri eq '') {
 6144:             $ownaccess = 1;
 6145:         } else {
 6146:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 6147:                 my $udom = $env{'user.domain'};
 6148:                 my $uname = $env{'user.name'};
 6149:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 6150:                     $ownaccess = 1;
 6151:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 6152:                     unless ($uri =~ m{\.\./}) {
 6153:                         $ownaccess = 1;
 6154:                     }
 6155:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 6156:                     my $now = time;
 6157:                     if ($uri =~ m{^([^/]+)/?$}) {
 6158:                         my $adom = $1;
 6159:                         foreach my $key (keys(%env)) {
 6160:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 6161:                                 my ($start,$end) = split('.',$env{$key});
 6162:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6163:                                     $ownaccess = 1;
 6164:                                     last;
 6165:                                 }
 6166:                             }
 6167:                         }
 6168:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 6169:                         my $adom = $1;
 6170:                         my $aname = $2;
 6171:                         foreach my $role ('ca','aa') { 
 6172:                             if ($env{"user.role.$role./$adom/$aname"}) {
 6173:                                 my ($start,$end) =
 6174:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 6175:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6176:                                     $ownaccess = 1;
 6177:                                     last;
 6178:                                 }
 6179:                             }
 6180:                         }
 6181:                     }
 6182:                 }
 6183:             }
 6184:         }
 6185:     }
 6186: 
 6187: # Course
 6188: 
 6189:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 6190:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6191:             $thisallowed.=$1;
 6192:         }
 6193:     }
 6194: 
 6195: # Domain
 6196: 
 6197:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 6198:        =~/\Q$priv\E\&([^\:]*)/) {
 6199:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6200:             $thisallowed.=$1;
 6201:         }
 6202:     }
 6203: 
 6204: # User who is not author or co-author might still be able to edit
 6205: # resource of an author in the domain (e.g., if Domain Coordinator).
 6206:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 6207:         (&allowed('mdc',$env{'request.course.id'}))) {
 6208:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 6209:             $thisallowed.=$1;
 6210:         }
 6211:     }
 6212: 
 6213: # Course: uri itself is a course
 6214:     my $courseuri=$uri;
 6215:     $courseuri=~s/\_(\d)/\/$1/;
 6216:     $courseuri=~s/^([^\/])/\/$1/;
 6217: 
 6218:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 6219:        =~/\Q$priv\E\&([^\:]*)/) {
 6220:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6221:             $thisallowed.=$1;
 6222:         }
 6223:     }
 6224: 
 6225: # URI is an uploaded document for this course, default permissions don't matter
 6226: # not allowing 'edit' access (editupload) to uploaded course docs
 6227:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 6228: 	$thisallowed='';
 6229:         my ($match)=&is_on_map($uri);
 6230:         if ($match) {
 6231:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 6232:                   =~/\Q$priv\E\&([^\:]*)/) {
 6233:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6234:                 if (@blockers > 0) {
 6235:                     $thisallowed = 'B';
 6236:                 } else {
 6237:                     $thisallowed.=$1;
 6238:                 }
 6239:             }
 6240:         } else {
 6241:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 6242:             if ($refuri) {
 6243:                 if ($refuri =~ m|^/adm/|) {
 6244:                     $thisallowed='F';
 6245:                 } else {
 6246:                     $refuri=&declutter($refuri);
 6247:                     my ($match) = &is_on_map($refuri);
 6248:                     if ($match) {
 6249:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6250:                         if (@blockers > 0) {
 6251:                             $thisallowed = 'B';
 6252:                         } else {
 6253:                             $thisallowed='F';
 6254:                         }
 6255:                     }
 6256:                 }
 6257:             }
 6258:         }
 6259:     }
 6260: 
 6261:     if ($priv eq 'bre'
 6262: 	&& $thisallowed ne 'F' 
 6263: 	&& $thisallowed ne '2'
 6264: 	&& &is_portfolio_url($uri)) {
 6265: 	$thisallowed = &portfolio_access($uri);
 6266:     }
 6267:     
 6268: # Full access at system, domain or course-wide level? Exit.
 6269:     if ($thisallowed=~/F/) {
 6270: 	return 'F';
 6271:     }
 6272: 
 6273: # If this is generating or modifying users, exit with special codes
 6274: 
 6275:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 6276: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 6277: 	    my ($audom,$auname)=split('/',$uri);
 6278: # no author name given, so this just checks on the general right to make a co-author in this domain
 6279: 	    unless ($auname) { return $thisallowed; }
 6280: # an author name is given, so we are about to actually make a co-author for a certain account
 6281: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 6282: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 6283: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 6284: 	}
 6285: 	return $thisallowed;
 6286:     }
 6287: #
 6288: # Gathered so far: system, domain and course wide privileges
 6289: #
 6290: # Course: See if uri or referer is an individual resource that is part of 
 6291: # the course
 6292: 
 6293:     if ($env{'request.course.id'}) {
 6294: 
 6295:        $courseprivid=$env{'request.course.id'};
 6296:        if ($env{'request.course.sec'}) {
 6297:           $courseprivid.='/'.$env{'request.course.sec'};
 6298:        }
 6299:        $courseprivid=~s/\_/\//;
 6300:        my $checkreferer=1;
 6301:        my ($match,$cond)=&is_on_map($uri);
 6302:        if ($match) {
 6303:            $statecond=$cond;
 6304:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6305:                =~/\Q$priv\E\&([^\:]*)/) {
 6306:                my $value = $1;
 6307:                if ($priv eq 'bre') {
 6308:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6309:                    if (@blockers > 0) {
 6310:                        $thisallowed = 'B';
 6311:                    } else {
 6312:                        $thisallowed.=$value;
 6313:                    }
 6314:                } else {
 6315:                    $thisallowed.=$value;
 6316:                }
 6317:                $checkreferer=0;
 6318:            }
 6319:        }
 6320:        
 6321:        if ($checkreferer) {
 6322: 	  my $refuri=$env{'httpref.'.$orguri};
 6323:             unless ($refuri) {
 6324:                 foreach my $key (keys(%env)) {
 6325: 		    if ($key=~/^httpref\..*\*/) {
 6326: 			my $pattern=$key;
 6327:                         $pattern=~s/^httpref\.\/res\///;
 6328:                         $pattern=~s/\*/\[\^\/\]\+/g;
 6329:                         $pattern=~s/\//\\\//g;
 6330:                         if ($orguri=~/$pattern/) {
 6331: 			    $refuri=$env{$key};
 6332:                         }
 6333:                     }
 6334:                 }
 6335:             }
 6336: 
 6337:          if ($refuri) { 
 6338: 	  $refuri=&declutter($refuri);
 6339:           my ($match,$cond)=&is_on_map($refuri);
 6340:             if ($match) {
 6341:               my $refstatecond=$cond;
 6342:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6343:                   =~/\Q$priv\E\&([^\:]*)/) {
 6344:                   my $value = $1;
 6345:                   if ($priv eq 'bre') {
 6346:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6347:                       if (@blockers > 0) {
 6348:                           $thisallowed = 'B';
 6349:                       } else {
 6350:                           $thisallowed.=$value;
 6351:                       }
 6352:                   } else {
 6353:                       $thisallowed.=$value;
 6354:                   }
 6355:                   $uri=$refuri;
 6356:                   $statecond=$refstatecond;
 6357:               }
 6358:           }
 6359:         }
 6360:        }
 6361:    }
 6362: 
 6363: #
 6364: # Gathered now: all privileges that could apply, and condition number
 6365: # 
 6366: #
 6367: # Full or no access?
 6368: #
 6369: 
 6370:     if ($thisallowed=~/F/) {
 6371: 	return 'F';
 6372:     }
 6373: 
 6374:     unless ($thisallowed) {
 6375:         return '';
 6376:     }
 6377: 
 6378: # Restrictions exist, deal with them
 6379: #
 6380: #   C:according to course preferences
 6381: #   R:according to resource settings
 6382: #   L:unless locked
 6383: #   X:according to user session state
 6384: #
 6385: 
 6386: # Possibly locked functionality, check all courses
 6387: # Locks might take effect only after 10 minutes cache expiration for other
 6388: # courses, and 2 minutes for current course
 6389: 
 6390:     my $envkey;
 6391:     if ($thisallowed=~/L/) {
 6392:         foreach $envkey (keys(%env)) {
 6393:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 6394:                my $courseid=$2;
 6395:                my $roleid=$1.'.'.$2;
 6396:                $courseid=~s/^\///;
 6397:                my $expiretime=600;
 6398:                if ($env{'request.role'} eq $roleid) {
 6399: 		  $expiretime=120;
 6400:                }
 6401: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 6402:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 6403:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 6404: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 6405:                }
 6406:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6407:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 6408: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 6409:                        &log($env{'user.domain'},$env{'user.name'},
 6410:                             $env{'user.home'},
 6411:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 6412:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6413:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6414: 		       return '';
 6415:                    }
 6416:                }
 6417:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6418:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 6419: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 6420:                        &log($env{'user.domain'},$env{'user.name'},
 6421:                             $env{'user.home'},
 6422:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 6423:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6424:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6425: 		       return '';
 6426:                    }
 6427:                }
 6428: 	   }
 6429:        }
 6430:     }
 6431:    
 6432: #
 6433: # Rest of the restrictions depend on selected course
 6434: #
 6435: 
 6436:     unless ($env{'request.course.id'}) {
 6437: 	if ($thisallowed eq 'A') {
 6438: 	    return 'A';
 6439:         } elsif ($thisallowed eq 'B') {
 6440:             return 'B';
 6441: 	} else {
 6442: 	    return '1';
 6443: 	}
 6444:     }
 6445: 
 6446: #
 6447: # Now user is definitely in a course
 6448: #
 6449: 
 6450: 
 6451: # Course preferences
 6452: 
 6453:    if ($thisallowed=~/C/) {
 6454:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6455:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 6456:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 6457: 	   =~/\Q$rolecode\E/) {
 6458: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6459: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6460: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 6461: 			$env{'request.course.id'});
 6462: 	   }
 6463:            return '';
 6464:        }
 6465: 
 6466:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 6467: 	   =~/\Q$unamedom\E/) {
 6468: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6469: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 6470: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 6471: 			$env{'request.course.id'});
 6472: 	   }
 6473:            return '';
 6474:        }
 6475:    }
 6476: 
 6477: # Resource preferences
 6478: 
 6479:    if ($thisallowed=~/R/) {
 6480:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6481:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 6482: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6483: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6484: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 6485: 	   }
 6486: 	   return '';
 6487:        }
 6488:    }
 6489: 
 6490: # Restricted by state or randomout?
 6491: 
 6492:    if ($thisallowed=~/X/) {
 6493:       if ($env{'acc.randomout'}) {
 6494: 	 if (!$symb) { $symb=&symbread($uri,1); }
 6495:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 6496:             return ''; 
 6497:          }
 6498:       }
 6499:       if (&condval($statecond)) {
 6500: 	 return '2';
 6501:       } else {
 6502:          return '';
 6503:       }
 6504:    }
 6505: 
 6506:     if ($thisallowed eq 'A') {
 6507: 	return 'A';
 6508:     } elsif ($thisallowed eq 'B') {
 6509:         return 'B';
 6510:     }
 6511:    return 'F';
 6512: }
 6513: 
 6514: # ------------------------------------------- Check construction space access
 6515: 
 6516: sub constructaccess {
 6517:     my ($url,$setpriv)=@_;
 6518: 
 6519: # We do not allow editing of previous versions of files
 6520:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 6521: 
 6522: # Get username and domain from URL
 6523:     my ($ownername,$ownerdomain,$ownerhome);
 6524: 
 6525:     ($ownerdomain,$ownername) =
 6526:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
 6527: 
 6528: # The URL does not really point to any authorspace, forget it
 6529:     unless (($ownername) && ($ownerdomain)) { return ''; }
 6530: 
 6531: # Now we need to see if the user has access to the authorspace of
 6532: # $ownername at $ownerdomain
 6533: 
 6534:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 6535: # Real author for this?
 6536:        $ownerhome = $env{'user.home'};
 6537:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 6538:           return ($ownername,$ownerdomain,$ownerhome);
 6539:        }
 6540:     } else {
 6541: # Co-author for this?
 6542:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 6543:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 6544:             $ownerhome = &homeserver($ownername,$ownerdomain);
 6545:             return ($ownername,$ownerdomain,$ownerhome);
 6546:         }
 6547:     }
 6548: 
 6549: # We don't have any access right now. If we are not possibly going to do anything about this,
 6550: # we might as well leave
 6551:    unless ($setpriv) { return ''; }
 6552: 
 6553: # Backdoor access?
 6554:     my $allowed=&allowed('eco',$ownerdomain);
 6555: # Nope
 6556:     unless ($allowed) { return ''; }
 6557: # Looks like we may have access, but could be locked by the owner of the construction space
 6558:     if ($allowed eq 'U') {
 6559:         my %blocked=&get('environment',['domcoord.author'],
 6560:                          $ownerdomain,$ownername);
 6561: # Is blocked by owner
 6562:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 6563:     }
 6564:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 6565: # Grant temporary access
 6566:         my $then=$env{'user.login.time'};
 6567:         my $update==$env{'user.update.time'};
 6568:         if (!$update) { $update = $then; }
 6569:         my $refresh=$env{'user.refresh.time'};
 6570:         if (!$refresh) { $refresh = $update; }
 6571:         my $now = time;
 6572:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 6573:                            $now,'ca','constructaccess');
 6574:         $ownerhome = &homeserver($ownername,$ownerdomain);
 6575:         return($ownername,$ownerdomain,$ownerhome);
 6576:     }
 6577: # No business here
 6578:     return '';
 6579: }
 6580: 
 6581: sub get_comm_blocks {
 6582:     my ($cdom,$cnum) = @_;
 6583:     if ($cdom eq '' || $cnum eq '') {
 6584:         return unless ($env{'request.course.id'});
 6585:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6586:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6587:     }
 6588:     my %commblocks;
 6589:     my $hashid=$cdom.'_'.$cnum;
 6590:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 6591:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 6592:         %commblocks = %{$blocksref};
 6593:     } else {
 6594:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 6595:         my $cachetime = 600;
 6596:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 6597:     }
 6598:     return %commblocks;
 6599: }
 6600: 
 6601: sub has_comm_blocking {
 6602:     my ($priv,$symb,$uri,$blocks) = @_;
 6603:     return unless ($env{'request.course.id'});
 6604:     return unless ($priv eq 'bre');
 6605:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 6606:     my %commblocks;
 6607:     if (ref($blocks) eq 'HASH') {
 6608:         %commblocks = %{$blocks};
 6609:     } else {
 6610:         %commblocks = &get_comm_blocks();
 6611:     }
 6612:     return unless (keys(%commblocks) > 0);
 6613:     if (!$symb) { $symb=&symbread($uri,1); }
 6614:     my ($map,$resid,undef)=&decode_symb($symb);
 6615:     my %tocheck = (
 6616:                     maps      => $map,
 6617:                     resources => $symb,
 6618:                   );
 6619:     my @blockers;
 6620:     my $now = time;
 6621:     my $navmap = Apache::lonnavmaps::navmap->new();
 6622:     foreach my $block (keys(%commblocks)) {
 6623:         if ($block =~ /^(\d+)____(\d+)$/) {
 6624:             my ($start,$end) = ($1,$2);
 6625:             if ($start <= $now && $end >= $now) {
 6626:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 6627:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 6628:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 6629:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
 6630:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 6631:                                     push(@blockers,$block);
 6632:                                 }
 6633:                             }
 6634:                         }
 6635:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 6636:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
 6637:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
 6638:                                     push(@blockers,$block);
 6639:                                 }
 6640:                             }
 6641:                         }
 6642:                     }
 6643:                 }
 6644:             }
 6645:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 6646:             my $item = $1;
 6647:             my @to_test;
 6648:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 6649:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 6650:                     my $check_interval;
 6651:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
 6652:                         my @interval;
 6653:                         my $type = 'map';
 6654:                         if ($item eq 'course') {
 6655:                             $type = 'course';
 6656:                             @interval=&EXT("resource.0.interval");
 6657:                         } else {
 6658:                             if ($item =~ /___\d+___/) {
 6659:                                 $type = 'resource';
 6660:                                 @interval=&EXT("resource.0.interval",$item);
 6661:                                 if (ref($navmap)) {                        
 6662:                                     my $res = $navmap->getBySymb($item); 
 6663:                                     push(@to_test,$res);
 6664:                                 }
 6665:                             } else {
 6666:                                 my $mapsymb = &symbread($item,1);
 6667:                                 if ($mapsymb) {
 6668:                                     if (ref($navmap)) {
 6669:                                         my $mapres = $navmap->getBySymb($mapsymb);
 6670:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
 6671:                                         foreach my $res (@to_test) {
 6672:                                             my $symb = $res->symb();
 6673:                                             next if ($symb eq $mapsymb);
 6674:                                             if ($symb ne '') {
 6675:                                                 @interval=&EXT("resource.0.interval",$symb);
 6676:                                                 last;
 6677:                                             }
 6678:                                         }
 6679:                                     }
 6680:                                 }
 6681:                             }
 6682:                         }
 6683:                         if ($interval[0] =~ /\d+/) {
 6684:                             my $first_access;
 6685:                             if ($type eq 'resource') {
 6686:                                 $first_access=&get_first_access($interval[1],$item);
 6687:                             } elsif ($type eq 'map') {
 6688:                                 $first_access=&get_first_access($interval[1],undef,$item);
 6689:                             } else {
 6690:                                 $first_access=&get_first_access($interval[1]);
 6691:                             }
 6692:                             if ($first_access) {
 6693:                                 my $timesup = $first_access+$interval[0];
 6694:                                 if ($timesup > $now) {
 6695:                                     foreach my $res (@to_test) {
 6696:                                         if ($res->is_problem()) {
 6697:                                             if ($res->completable()) {
 6698:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 6699:                                                     push(@blockers,$block);
 6700:                                                 }
 6701:                                                 last;
 6702:                                             }
 6703:                                         }
 6704:                                     }
 6705:                                 }
 6706:                             }
 6707:                         }
 6708:                     }
 6709:                 }
 6710:             }
 6711:         }
 6712:     }
 6713:     return @blockers;
 6714: }
 6715: 
 6716: sub check_docs_block {
 6717:     my ($docsblock,$tocheck) =@_;
 6718:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
 6719:         return;
 6720:     }
 6721:     if (ref($docsblock->{'maps'}) eq 'HASH') {
 6722:         if ($tocheck->{'maps'}) {
 6723:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
 6724:                 return 1;
 6725:             }
 6726:         }
 6727:     }
 6728:     if (ref($docsblock->{'resources'}) eq 'HASH') {
 6729:         if ($tocheck->{'resources'}) {
 6730:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
 6731:                 return 1;
 6732:             }
 6733:         }
 6734:     }
 6735:     return;
 6736: }
 6737: 
 6738: #
 6739: #   Removes the versino from a URI and
 6740: #   splits it in to its filename and path to the filename.
 6741: #   Seems like File::Basename could have done this more clearly.
 6742: #   Parameters:
 6743: #      $uri   - input URI
 6744: #   Returns:
 6745: #     Two element list consisting of 
 6746: #     $pathname  - the URI up to and excluding the trailing /
 6747: #     $filename  - The part of the URI following the last /
 6748: #  NOTE:
 6749: #    Another realization of this is simply:
 6750: #    use File::Basename;
 6751: #    ...
 6752: #    $uri = shift;
 6753: #    $filename = basename($uri);
 6754: #    $path     = dirname($uri);
 6755: #    return ($filename, $path);
 6756: #
 6757: #     The implementation below is probably faster however.
 6758: #
 6759: sub split_uri_for_cond {
 6760:     my $uri=&deversion(&declutter(shift));
 6761:     my @uriparts=split(/\//,$uri);
 6762:     my $filename=pop(@uriparts);
 6763:     my $pathname=join('/',@uriparts);
 6764:     return ($pathname,$filename);
 6765: }
 6766: # --------------------------------------------------- Is a resource on the map?
 6767: 
 6768: sub is_on_map {
 6769:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 6770:     #Trying to find the conditional for the file
 6771:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 6772: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 6773:     if ($match) {
 6774: 	return (1,$1);
 6775:     } else {
 6776: 	return (0,0);
 6777:     }
 6778: }
 6779: 
 6780: # --------------------------------------------------------- Get symb from alias
 6781: 
 6782: sub get_symb_from_alias {
 6783:     my $symb=shift;
 6784:     my ($map,$resid,$url)=&decode_symb($symb);
 6785: # Already is a symb
 6786:     if ($url) { return $symb; }
 6787: # Must be an alias
 6788:     my $aliassymb='';
 6789:     my %bighash;
 6790:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6791:                             &GDBM_READER(),0640)) {
 6792:         my $rid=$bighash{'mapalias_'.$symb};
 6793: 	if ($rid) {
 6794: 	    my ($mapid,$resid)=split(/\./,$rid);
 6795: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 6796: 				    $resid,$bighash{'src_'.$rid});
 6797: 	}
 6798:         untie %bighash;
 6799:     }
 6800:     return $aliassymb;
 6801: }
 6802: 
 6803: # ----------------------------------------------------------------- Define Role
 6804: 
 6805: sub definerole {
 6806:   if (allowed('mcr','/')) {
 6807:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 6808:     foreach my $role (split(':',$sysrole)) {
 6809: 	my ($crole,$cqual)=split(/\&/,$role);
 6810:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 6811:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 6812: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 6813:                return "refused:s:$crole&$cqual"; 
 6814:             }
 6815:         }
 6816:     }
 6817:     foreach my $role (split(':',$domrole)) {
 6818: 	my ($crole,$cqual)=split(/\&/,$role);
 6819:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 6820:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 6821: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 6822:                return "refused:d:$crole&$cqual"; 
 6823:             }
 6824:         }
 6825:     }
 6826:     foreach my $role (split(':',$courole)) {
 6827: 	my ($crole,$cqual)=split(/\&/,$role);
 6828:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 6829:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 6830: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 6831:                return "refused:c:$crole&$cqual"; 
 6832:             }
 6833:         }
 6834:     }
 6835:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 6836:                 "$env{'user.domain'}:$env{'user.name'}:".
 6837: 	        "rolesdef_$rolename=".
 6838:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 6839:     return reply($command,$env{'user.home'});
 6840:   } else {
 6841:     return 'refused';
 6842:   }
 6843: }
 6844: 
 6845: # ---------------- Make a metadata query against the network of library servers
 6846: 
 6847: sub metadata_query {
 6848:     my ($query,$custom,$customshow,$server_array)=@_;
 6849:     my %rhash;
 6850:     my %libserv = &all_library();
 6851:     my @server_list = (defined($server_array) ? @$server_array
 6852:                                               : keys(%libserv) );
 6853:     for my $server (@server_list) {
 6854: 	unless ($custom or $customshow) {
 6855: 	    my $reply=&reply("querysend:".&escape($query),$server);
 6856: 	    $rhash{$server}=$reply;
 6857: 	}
 6858: 	else {
 6859: 	    my $reply=&reply("querysend:".&escape($query).':'.
 6860: 			     &escape($custom).':'.&escape($customshow),
 6861: 			     $server);
 6862: 	    $rhash{$server}=$reply;
 6863: 	}
 6864:     }
 6865:     return \%rhash;
 6866: }
 6867: 
 6868: # ----------------------------------------- Send log queries and wait for reply
 6869: 
 6870: sub log_query {
 6871:     my ($uname,$udom,$query,%filters)=@_;
 6872:     my $uhome=&homeserver($uname,$udom);
 6873:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 6874:     my $uhost=&hostname($uhome);
 6875:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 6876:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 6877:                        $uhome);
 6878:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 6879:     return get_query_reply($queryid);
 6880: }
 6881: 
 6882: # -------------------------- Update MySQL table for portfolio file
 6883: 
 6884: sub update_portfolio_table {
 6885:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 6886:     if ($group ne '') {
 6887:         $file_name =~s /^\Q$group\E//;
 6888:     }
 6889:     my $homeserver = &homeserver($uname,$udom);
 6890:     my $queryid=
 6891:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 6892:                ':'.&escape($file_name).':'.$action,$homeserver);
 6893:     my $reply = &get_query_reply($queryid);
 6894:     return $reply;
 6895: }
 6896: 
 6897: # -------------------------- Update MySQL allusers table
 6898: 
 6899: sub update_allusers_table {
 6900:     my ($uname,$udom,$names) = @_;
 6901:     my $homeserver = &homeserver($uname,$udom);
 6902:     my $queryid=
 6903:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 6904:                'lastname='.&escape($names->{'lastname'}).'%%'.
 6905:                'firstname='.&escape($names->{'firstname'}).'%%'.
 6906:                'middlename='.&escape($names->{'middlename'}).'%%'.
 6907:                'generation='.&escape($names->{'generation'}).'%%'.
 6908:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 6909:                'id='.&escape($names->{'id'}),$homeserver);
 6910:     return;
 6911: }
 6912: 
 6913: # ------- Request retrieval of institutional classlists for course(s)
 6914: 
 6915: sub fetch_enrollment_query {
 6916:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 6917:     my $homeserver;
 6918:     my $maxtries = 1;
 6919:     if ($context eq 'automated') {
 6920:         $homeserver = $perlvar{'lonHostID'};
 6921:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 6922:     } else {
 6923:         $homeserver = &homeserver($cnum,$dom);
 6924:     }
 6925:     my $host=&hostname($homeserver);
 6926:     my $cmd = '';
 6927:     foreach my $affiliate (keys(%{$affiliatesref})) {
 6928:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 6929:     }
 6930:     $cmd =~ s/%%$//;
 6931:     $cmd = &escape($cmd);
 6932:     my $query = 'fetchenrollment';
 6933:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 6934:     unless ($queryid=~/^\Q$host\E\_/) { 
 6935:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 6936:         return 'error: '.$queryid;
 6937:     }
 6938:     my $reply = &get_query_reply($queryid);
 6939:     my $tries = 1;
 6940:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 6941:         $reply = &get_query_reply($queryid);
 6942:         $tries ++;
 6943:     }
 6944:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 6945:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 6946:     } else {
 6947:         my @responses = split(/:/,$reply);
 6948:         if ($homeserver eq $perlvar{'lonHostID'}) {
 6949:             foreach my $line (@responses) {
 6950:                 my ($key,$value) = split(/=/,$line,2);
 6951:                 $$replyref{$key} = $value;
 6952:             }
 6953:         } else {
 6954:             my $pathname = LONCAPA::tempdir();
 6955:             foreach my $line (@responses) {
 6956:                 my ($key,$value) = split(/=/,$line);
 6957:                 $$replyref{$key} = $value;
 6958:                 if ($value > 0) {
 6959:                     foreach my $item (@{$$affiliatesref{$key}}) {
 6960:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 6961:                         my $destname = $pathname.'/'.$filename;
 6962:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 6963:                         if ($xml_classlist =~ /^error/) {
 6964:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 6965:                         } else {
 6966:                             if ( open(FILE,">$destname") ) {
 6967:                                 print FILE &unescape($xml_classlist);
 6968:                                 close(FILE);
 6969:                             } else {
 6970:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 6971:                             }
 6972:                         }
 6973:                     }
 6974:                 }
 6975:             }
 6976:         }
 6977:         return 'ok';
 6978:     }
 6979:     return 'error';
 6980: }
 6981: 
 6982: sub get_query_reply {
 6983:     my $queryid=shift;
 6984:     my $replyfile=LONCAPA::tempdir().$queryid;
 6985:     my $reply='';
 6986:     for (1..100) {
 6987: 	sleep 2;
 6988:         if (-e $replyfile.'.end') {
 6989: 	    if (open(my $fh,$replyfile)) {
 6990: 		$reply = join('',<$fh>);
 6991: 		close($fh);
 6992: 	   } else { return 'error: reply_file_error'; }
 6993:            return &unescape($reply);
 6994: 	}
 6995:     }
 6996:     return 'timeout:'.$queryid;
 6997: }
 6998: 
 6999: sub courselog_query {
 7000: #
 7001: # possible filters:
 7002: # url: url or symb
 7003: # username
 7004: # domain
 7005: # action: view, submit, grade
 7006: # start: timestamp
 7007: # end: timestamp
 7008: #
 7009:     my (%filters)=@_;
 7010:     unless ($env{'request.course.id'}) { return 'no_course'; }
 7011:     if ($filters{'url'}) {
 7012: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 7013:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 7014:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 7015:     }
 7016:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7017:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7018:     return &log_query($cname,$cdom,'courselog',%filters);
 7019: }
 7020: 
 7021: sub userlog_query {
 7022: #
 7023: # possible filters:
 7024: # action: log check role
 7025: # start: timestamp
 7026: # end: timestamp
 7027: #
 7028:     my ($uname,$udom,%filters)=@_;
 7029:     return &log_query($uname,$udom,'userlog',%filters);
 7030: }
 7031: 
 7032: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 7033: 
 7034: sub auto_run {
 7035:     my ($cnum,$cdom) = @_;
 7036:     my $response = 0;
 7037:     my $settings;
 7038:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 7039:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 7040:         $settings = $domconfig{'autoenroll'};
 7041:         if ($settings->{'run'} eq '1') {
 7042:             $response = 1;
 7043:         }
 7044:     } else {
 7045:         my $homeserver;
 7046:         if (&is_course($cdom,$cnum)) {
 7047:             $homeserver = &homeserver($cnum,$cdom);
 7048:         } else {
 7049:             $homeserver = &domain($cdom,'primary');
 7050:         }
 7051:         if ($homeserver ne 'no_host') {
 7052:             $response = &reply('autorun:'.$cdom,$homeserver);
 7053:         }
 7054:     }
 7055:     return $response;
 7056: }
 7057: 
 7058: sub auto_get_sections {
 7059:     my ($cnum,$cdom,$inst_coursecode) = @_;
 7060:     my $homeserver;
 7061:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 7062:         $homeserver = &homeserver($cnum,$cdom);
 7063:     }
 7064:     if (!defined($homeserver)) { 
 7065:         if ($cdom =~ /^$match_domain$/) {
 7066:             $homeserver = &domain($cdom,'primary');
 7067:         }
 7068:     }
 7069:     my @secs;
 7070:     if (defined($homeserver)) {
 7071:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 7072:         unless ($response eq 'refused') {
 7073:             @secs = split(/:/,$response);
 7074:         }
 7075:     }
 7076:     return @secs;
 7077: }
 7078: 
 7079: sub auto_new_course {
 7080:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 7081:     my $homeserver = &homeserver($cnum,$cdom);
 7082:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 7083:     return $response;
 7084: }
 7085: 
 7086: sub auto_validate_courseID {
 7087:     my ($cnum,$cdom,$inst_course_id) = @_;
 7088:     my $homeserver = &homeserver($cnum,$cdom);
 7089:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 7090:     return $response;
 7091: }
 7092: 
 7093: sub auto_validate_instcode {
 7094:     my ($cnum,$cdom,$instcode,$owner) = @_;
 7095:     my ($homeserver,$response);
 7096:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7097:         $homeserver = &homeserver($cnum,$cdom);
 7098:     }
 7099:     if (!defined($homeserver)) {
 7100:         if ($cdom =~ /^$match_domain$/) {
 7101:             $homeserver = &domain($cdom,'primary');
 7102:         }
 7103:     }
 7104:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 7105:                         &escape($instcode).':'.&escape($owner),$homeserver));
 7106:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
 7107:     return ($outcome,$description);
 7108: }
 7109: 
 7110: sub auto_create_password {
 7111:     my ($cnum,$cdom,$authparam,$udom) = @_;
 7112:     my ($homeserver,$response);
 7113:     my $create_passwd = 0;
 7114:     my $authchk = '';
 7115:     if ($udom =~ /^$match_domain$/) {
 7116:         $homeserver = &domain($udom,'primary');
 7117:     }
 7118:     if ($homeserver eq '') {
 7119:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7120:             $homeserver = &homeserver($cnum,$cdom);
 7121:         }
 7122:     }
 7123:     if ($homeserver eq '') {
 7124:         $authchk = 'nodomain';
 7125:     } else {
 7126:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 7127:         if ($response eq 'refused') {
 7128:             $authchk = 'refused';
 7129:         } else {
 7130:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 7131:         }
 7132:     }
 7133:     return ($authparam,$create_passwd,$authchk);
 7134: }
 7135: 
 7136: sub auto_photo_permission {
 7137:     my ($cnum,$cdom,$students) = @_;
 7138:     my $homeserver = &homeserver($cnum,$cdom);
 7139:     my ($outcome,$perm_reqd,$conditions) = 
 7140: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 7141:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7142: 	return (undef,undef);
 7143:     }
 7144:     return ($outcome,$perm_reqd,$conditions);
 7145: }
 7146: 
 7147: sub auto_checkphotos {
 7148:     my ($uname,$udom,$pid) = @_;
 7149:     my $homeserver = &homeserver($uname,$udom);
 7150:     my ($result,$resulttype);
 7151:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 7152: 				   &escape($uname).':'.&escape($pid),
 7153: 				   $homeserver));
 7154:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7155: 	return (undef,undef);
 7156:     }
 7157:     if ($outcome) {
 7158:         ($result,$resulttype) = split(/:/,$outcome);
 7159:     } 
 7160:     return ($result,$resulttype);
 7161: }
 7162: 
 7163: sub auto_photochoice {
 7164:     my ($cnum,$cdom) = @_;
 7165:     my $homeserver = &homeserver($cnum,$cdom);
 7166:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 7167: 						       &escape($cdom),
 7168: 						       $homeserver)));
 7169:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7170: 	return (undef,undef);
 7171:     }
 7172:     return ($update,$comment);
 7173: }
 7174: 
 7175: sub auto_photoupdate {
 7176:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 7177:     my $homeserver = &homeserver($cnum,$dom);
 7178:     my $host=&hostname($homeserver);
 7179:     my $cmd = '';
 7180:     my $maxtries = 1;
 7181:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7182:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7183:     }
 7184:     $cmd =~ s/%%$//;
 7185:     $cmd = &escape($cmd);
 7186:     my $query = 'institutionalphotos';
 7187:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 7188:     unless ($queryid=~/^\Q$host\E\_/) {
 7189:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 7190:         return 'error: '.$queryid;
 7191:     }
 7192:     my $reply = &get_query_reply($queryid);
 7193:     my $tries = 1;
 7194:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7195:         $reply = &get_query_reply($queryid);
 7196:         $tries ++;
 7197:     }
 7198:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7199:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7200:     } else {
 7201:         my @responses = split(/:/,$reply);
 7202:         my $outcome = shift(@responses); 
 7203:         foreach my $item (@responses) {
 7204:             my ($key,$value) = split(/=/,$item);
 7205:             $$photo{$key} = $value;
 7206:         }
 7207:         return $outcome;
 7208:     }
 7209:     return 'error';
 7210: }
 7211: 
 7212: sub auto_instcode_format {
 7213:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 7214: 	$cat_order) = @_;
 7215:     my $courses = '';
 7216:     my @homeservers;
 7217:     if ($caller eq 'global') {
 7218: 	my %servers = &get_servers($codedom,'library');
 7219: 	foreach my $tryserver (keys(%servers)) {
 7220: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7221: 		push(@homeservers,$tryserver);
 7222: 	    }
 7223:         }
 7224:     } elsif ($caller eq 'requests') {
 7225:         if ($codedom =~ /^$match_domain$/) {
 7226:             my $chome = &domain($codedom,'primary');
 7227:             unless ($chome eq 'no_host') {
 7228:                 push(@homeservers,$chome);
 7229:             }
 7230:         }
 7231:     } else {
 7232:         push(@homeservers,&homeserver($caller,$codedom));
 7233:     }
 7234:     foreach my $code (keys(%{$instcodes})) {
 7235:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 7236:     }
 7237:     chop($courses);
 7238:     my $ok_response = 0;
 7239:     my $response;
 7240:     while (@homeservers > 0 && $ok_response == 0) {
 7241:         my $server = shift(@homeservers); 
 7242:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 7243:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 7244:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 7245: 		split(/:/,$response);
 7246:             %{$codes} = (%{$codes},&str2hash($codes_str));
 7247:             push(@{$codetitles},&str2array($codetitles_str));
 7248:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 7249:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 7250:             $ok_response = 1;
 7251:         }
 7252:     }
 7253:     if ($ok_response) {
 7254:         return 'ok';
 7255:     } else {
 7256:         return $response;
 7257:     }
 7258: }
 7259: 
 7260: sub auto_instcode_defaults {
 7261:     my ($domain,$returnhash,$code_order) = @_;
 7262:     my @homeservers;
 7263: 
 7264:     my %servers = &get_servers($domain,'library');
 7265:     foreach my $tryserver (keys(%servers)) {
 7266: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7267: 	    push(@homeservers,$tryserver);
 7268: 	}
 7269:     }
 7270: 
 7271:     my $response;
 7272:     foreach my $server (@homeservers) {
 7273:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 7274:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7275: 	
 7276: 	foreach my $pair (split(/\&/,$response)) {
 7277: 	    my ($name,$value)=split(/\=/,$pair);
 7278: 	    if ($name eq 'code_order') {
 7279: 		@{$code_order} = split(/\&/,&unescape($value));
 7280: 	    } else {
 7281: 		$returnhash->{&unescape($name)}=&unescape($value);
 7282: 	    }
 7283: 	}
 7284: 	return 'ok';
 7285:     }
 7286: 
 7287:     return $response;
 7288: }
 7289: 
 7290: sub auto_possible_instcodes {
 7291:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 7292:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 7293:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 7294:         return;
 7295:     }
 7296:     my (@homeservers,$uhome);
 7297:     if (defined(&domain($domain,'primary'))) {
 7298:         $uhome=&domain($domain,'primary');
 7299:         push(@homeservers,&domain($domain,'primary'));
 7300:     } else {
 7301:         my %servers = &get_servers($domain,'library');
 7302:         foreach my $tryserver (keys(%servers)) {
 7303:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7304:                 push(@homeservers,$tryserver);
 7305:             }
 7306:         }
 7307:     }
 7308:     my $response;
 7309:     foreach my $server (@homeservers) {
 7310:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 7311:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7312:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 7313:             split(':',$response);
 7314:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 7315:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 7316:         foreach my $item (split('&',$cat_title)) {   
 7317:             my ($name,$value)=split('=',$item);
 7318:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 7319:         }
 7320:         foreach my $item (split('&',$cat_order)) {
 7321:             my ($name,$value)=split('=',$item);
 7322:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 7323:         }
 7324:         return 'ok';
 7325:     }
 7326:     return $response;
 7327: }
 7328: 
 7329: sub auto_courserequest_checks {
 7330:     my ($dom) = @_;
 7331:     my ($homeserver,%validations);
 7332:     if ($dom =~ /^$match_domain$/) {
 7333:         $homeserver = &domain($dom,'primary');
 7334:     }
 7335:     unless ($homeserver eq 'no_host') {
 7336:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 7337:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 7338:             my @items = split(/&/,$response);
 7339:             foreach my $item (@items) {
 7340:                 my ($key,$value) = split('=',$item);
 7341:                 $validations{&unescape($key)} = &thaw_unescape($value);
 7342:             }
 7343:         }
 7344:     }
 7345:     return %validations; 
 7346: }
 7347: 
 7348: sub auto_courserequest_validation {
 7349:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
 7350:     my ($homeserver,$response);
 7351:     if ($dom =~ /^$match_domain$/) {
 7352:         $homeserver = &domain($dom,'primary');
 7353:     }
 7354:     unless ($homeserver eq 'no_host') {  
 7355:           
 7356:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 7357:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 7358:                                     ':'.&escape($instcode).':'.&escape($instseclist),
 7359:                                     $homeserver));
 7360:     }
 7361:     return $response;
 7362: }
 7363: 
 7364: sub auto_validate_class_sec {
 7365:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 7366:     my $homeserver = &homeserver($cnum,$cdom);
 7367:     my $ownerlist;
 7368:     if (ref($owners) eq 'ARRAY') {
 7369:         $ownerlist = join(',',@{$owners});
 7370:     } else {
 7371:         $ownerlist = $owners;
 7372:     }
 7373:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 7374:                         &escape($ownerlist).':'.$cdom,$homeserver);
 7375:     return $response;
 7376: }
 7377: 
 7378: # ------------------------------------------------------- Course Group routines
 7379: 
 7380: sub get_coursegroups {
 7381:     my ($cdom,$cnum,$group,$namespace) = @_;
 7382:     return(&dump($namespace,$cdom,$cnum,$group));
 7383: }
 7384: 
 7385: sub modify_coursegroup {
 7386:     my ($cdom,$cnum,$groupsettings) = @_;
 7387:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 7388: }
 7389: 
 7390: sub toggle_coursegroup_status {
 7391:     my ($cdom,$cnum,$group,$action) = @_;
 7392:     my ($from_namespace,$to_namespace);
 7393:     if ($action eq 'delete') {
 7394:         $from_namespace = 'coursegroups';
 7395:         $to_namespace = 'deleted_groups';
 7396:     } else {
 7397:         $from_namespace = 'deleted_groups';
 7398:         $to_namespace = 'coursegroups';
 7399:     }
 7400:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 7401:     if (my $tmp = &error(%curr_group)) {
 7402:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 7403:         return ('read error',$tmp);
 7404:     } else {
 7405:         my %savedsettings = %curr_group; 
 7406:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 7407:         my $deloutcome;
 7408:         if ($result eq 'ok') {
 7409:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 7410:         } else {
 7411:             return ('write error',$result);
 7412:         }
 7413:         if ($deloutcome eq 'ok') {
 7414:             return 'ok';
 7415:         } else {
 7416:             return ('delete error',$deloutcome);
 7417:         }
 7418:     }
 7419: }
 7420: 
 7421: sub modify_group_roles {
 7422:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 7423:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 7424:     my $role = 'gr/'.&escape($userprivs);
 7425:     my ($uname,$udom) = split(/:/,$user);
 7426:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 7427:     if ($result eq 'ok') {
 7428:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 7429:     }
 7430:     return $result;
 7431: }
 7432: 
 7433: sub modify_coursegroup_membership {
 7434:     my ($cdom,$cnum,$membership) = @_;
 7435:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 7436:     return $result;
 7437: }
 7438: 
 7439: sub get_active_groups {
 7440:     my ($udom,$uname,$cdom,$cnum) = @_;
 7441:     my $now = time;
 7442:     my %groups = ();
 7443:     foreach my $key (keys(%env)) {
 7444:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 7445:             my ($start,$end) = split(/\./,$env{$key});
 7446:             if (($end!=0) && ($end<$now)) { next; }
 7447:             if (($start!=0) && ($start>$now)) { next; }
 7448:             if ($1 eq $cdom && $2 eq $cnum) {
 7449:                 $groups{$3} = $env{$key} ;
 7450:             }
 7451:         }
 7452:     }
 7453:     return %groups;
 7454: }
 7455: 
 7456: sub get_group_membership {
 7457:     my ($cdom,$cnum,$group) = @_;
 7458:     return(&dump('groupmembership',$cdom,$cnum,$group));
 7459: }
 7460: 
 7461: sub get_users_groups {
 7462:     my ($udom,$uname,$courseid) = @_;
 7463:     my @usersgroups;
 7464:     my $cachetime=1800;
 7465: 
 7466:     my $hashid="$udom:$uname:$courseid";
 7467:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 7468:     if (defined($cached)) {
 7469:         @usersgroups = split(/:/,$grouplist);
 7470:     } else {  
 7471:         $grouplist = '';
 7472:         my $courseurl = &courseid_to_courseurl($courseid);
 7473:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 7474:         my $access_end = $env{'course.'.$courseid.
 7475:                               '.default_enrollment_end_date'};
 7476:         my $now = time;
 7477:         foreach my $key (keys(%roleshash)) {
 7478:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 7479:                 my $group = $1;
 7480:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 7481:                     my $start = $2;
 7482:                     my $end = $1;
 7483:                     if ($start == -1) { next; } # deleted from group
 7484:                     if (($start!=0) && ($start>$now)) { next; }
 7485:                     if (($end!=0) && ($end<$now)) {
 7486:                         if ($access_end && $access_end < $now) {
 7487:                             if ($access_end - $end < 86400) {
 7488:                                 push(@usersgroups,$group);
 7489:                             }
 7490:                         }
 7491:                         next;
 7492:                     }
 7493:                     push(@usersgroups,$group);
 7494:                 }
 7495:             }
 7496:         }
 7497:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 7498:         $grouplist = join(':',@usersgroups);
 7499:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 7500:     }
 7501:     return @usersgroups;
 7502: }
 7503: 
 7504: sub devalidate_getgroups_cache {
 7505:     my ($udom,$uname,$cdom,$cnum)=@_;
 7506:     my $courseid = $cdom.'_'.$cnum;
 7507: 
 7508:     my $hashid="$udom:$uname:$courseid";
 7509:     &devalidate_cache_new('getgroups',$hashid);
 7510: }
 7511: 
 7512: # ------------------------------------------------------------------ Plain Text
 7513: 
 7514: sub plaintext {
 7515:     my ($short,$type,$cid,$forcedefault) = @_;
 7516:     if ($short =~ m{^cr/}) {
 7517: 	return (split('/',$short))[-1];
 7518:     }
 7519:     if (!defined($cid)) {
 7520:         $cid = $env{'request.course.id'};
 7521:     }
 7522:     my %rolenames = (
 7523:                       Course    => 'std',
 7524:                       Community => 'alt1',
 7525:                     );
 7526:     if ($cid ne '') {
 7527:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 7528:             unless ($forcedefault) {
 7529:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 7530:                 &Apache::lonlocal::mt_escape(\$roletext);
 7531:                 return &Apache::lonlocal::mt($roletext);
 7532:             }
 7533:         }
 7534:     }
 7535:     if ((defined($type)) && (defined($rolenames{$type})) &&
 7536:         (defined($rolenames{$type})) && 
 7537:         (defined($prp{$short}{$rolenames{$type}}))) {
 7538:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 7539:     } elsif ($cid ne '') {
 7540:         my $crstype = $env{'course.'.$cid.'.type'};
 7541:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 7542:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 7543:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 7544:         }
 7545:     }
 7546:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 7547: }
 7548: 
 7549: # ----------------------------------------------------------------- Assign Role
 7550: 
 7551: sub assignrole {
 7552:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 7553:         $context)=@_;
 7554:     my $mrole;
 7555:     if ($role =~ /^cr\//) {
 7556:         my $cwosec=$url;
 7557:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 7558: 	unless (&allowed('ccr',$cwosec)) {
 7559:            my $refused = 1;
 7560:            if ($context eq 'requestcourses') {
 7561:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 7562:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 7563:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 7564:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 7565:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7566:                            if ($crsenv{'internal.courseowner'} eq
 7567:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 7568:                                $refused = '';
 7569:                            }
 7570:                        }
 7571:                    }
 7572:                }
 7573:            }
 7574:            if ($refused) {
 7575:                &logthis('Refused custom assignrole: '.
 7576:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 7577:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 7578:                return 'refused';
 7579:            }
 7580:         }
 7581:         $mrole='cr';
 7582:     } elsif ($role =~ /^gr\//) {
 7583:         my $cwogrp=$url;
 7584:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 7585:         unless (&allowed('mdg',$cwogrp)) {
 7586:             &logthis('Refused group assignrole: '.
 7587:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 7588:                     $env{'user.name'}.' at '.$env{'user.domain'});
 7589:             return 'refused';
 7590:         }
 7591:         $mrole='gr';
 7592:     } else {
 7593:         my $cwosec=$url;
 7594:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 7595:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 7596:             my $refused;
 7597:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 7598:                 if (!(&allowed('c'.$role,$url))) {
 7599:                     $refused = 1;
 7600:                 }
 7601:             } else {
 7602:                 $refused = 1;
 7603:             }
 7604:             if ($refused) {
 7605:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 7606:                 if (!$selfenroll && $context eq 'course') {
 7607:                     my %crsenv;
 7608:                     if ($role eq 'cc' || $role eq 'co') {
 7609:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7610:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 7611:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 7612:                                 if ($crsenv{'internal.courseowner'} eq 
 7613:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 7614:                                     $refused = '';
 7615:                                 }
 7616:                             }
 7617:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 7618:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 7619:                                 if ($crsenv{'internal.courseowner'} eq 
 7620:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 7621:                                     $refused = '';
 7622:                                 }
 7623:                             }
 7624:                         }
 7625:                     }
 7626:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7627:                     $refused = '';
 7628:                 } elsif ($context eq 'requestcourses') {
 7629:                     my @possroles = ('st','ta','ep','in','cc','co');
 7630:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 7631:                         my $wrongcc;
 7632:                         if ($cnum =~ /^$match_community$/) {
 7633:                             $wrongcc = 1 if ($role eq 'cc');
 7634:                         } else {
 7635:                             $wrongcc = 1 if ($role eq 'co');
 7636:                         }
 7637:                         unless ($wrongcc) {
 7638:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7639:                             if ($crsenv{'internal.courseowner'} eq 
 7640:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 7641:                                 $refused = '';
 7642:                             }
 7643:                         }
 7644:                     }
 7645:                 } elsif ($context eq 'requestauthor') {
 7646:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
 7647:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 7648:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 7649:                             $refused = '';
 7650:                         } else {
 7651:                             my %domdefaults = &get_domain_defaults($udom);
 7652:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 7653:                                 my $checkbystatus;
 7654:                                 if ($env{'user.adv'}) { 
 7655:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 7656:                                     if ($disposition eq 'automatic') {
 7657:                                         $refused = '';
 7658:                                     } elsif ($disposition eq '') {
 7659:                                         $checkbystatus = 1;
 7660:                                     } 
 7661:                                 } else {
 7662:                                     $checkbystatus = 1;
 7663:                                 }
 7664:                                 if ($checkbystatus) {
 7665:                                     if ($env{'environment.inststatus'}) {
 7666:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 7667:                                         foreach my $type (@inststatuses) {
 7668:                                             if (($type ne '') &&
 7669:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 7670:                                                 $refused = '';
 7671:                                             }
 7672:                                         }
 7673:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 7674:                                         $refused = '';
 7675:                                     }
 7676:                                 }
 7677:                             }
 7678:                         }
 7679:                     }
 7680:                 }
 7681:                 if ($refused) {
 7682:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 7683:                              ' '.$role.' '.$end.' '.$start.' by '.
 7684: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 7685:                     return 'refused';
 7686:                 }
 7687:             }
 7688:         } elsif ($role eq 'au') {
 7689:             if ($url ne '/'.$udom.'/') {
 7690:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 7691:                          ' to assign author role for '.$uname.':'.$udom.
 7692:                          ' in domain: '.$url.' refused (wrong domain).');
 7693:                 return 'refused';
 7694:             }
 7695:         }
 7696:         $mrole=$role;
 7697:     }
 7698:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 7699:                 "$udom:$uname:$url".'_'."$mrole=$role";
 7700:     if ($end) { $command.='_'.$end; }
 7701:     if ($start) {
 7702: 	if ($end) { 
 7703:            $command.='_'.$start; 
 7704:         } else {
 7705:            $command.='_0_'.$start;
 7706:         }
 7707:     }
 7708:     my $origstart = $start;
 7709:     my $origend = $end;
 7710:     my $delflag;
 7711: # actually delete
 7712:     if ($deleteflag) {
 7713: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 7714: # modify command to delete the role
 7715:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 7716:                 "$udom:$uname:$url".'_'."$mrole";
 7717: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 7718: # set start and finish to negative values for userrolelog
 7719:            $start=-1;
 7720:            $end=-1;
 7721:            $delflag = 1;
 7722:         }
 7723:     }
 7724: # send command
 7725:     my $answer=&reply($command,&homeserver($uname,$udom));
 7726: # log new user role if status is ok
 7727:     if ($answer eq 'ok') {
 7728: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 7729: # for course roles, perform group memberships changes triggered by role change.
 7730:         unless ($role =~ /^gr/) {
 7731:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 7732:                                              $origstart,$selfenroll,$context);
 7733:         }
 7734:         if (($role eq 'cc') || ($role eq 'in') ||
 7735:             ($role eq 'ep') || ($role eq 'ad') ||
 7736:             ($role eq 'ta') || ($role eq 'st') ||
 7737:             ($role=~/^cr/) || ($role eq 'gr') ||
 7738:             ($role eq 'co')) {
 7739:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 7740:                            $selfenroll,$context);
 7741:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
 7742:                  ($role eq 'au') || ($role eq 'dc')) {
 7743:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 7744:                            $context);
 7745:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
 7746:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 7747:                              $context); 
 7748:         }
 7749:         if ($role eq 'cc') {
 7750:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 7751:         }
 7752:     }
 7753:     return $answer;
 7754: }
 7755: 
 7756: sub autoupdate_coowners {
 7757:     my ($url,$end,$start,$uname,$udom) = @_;
 7758:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 7759:     if (($cdom ne '') && ($cnum ne '')) {
 7760:         my $now = time;
 7761:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 7762:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 7763:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 7764:             my $instcode = $coursehash{'internal.coursecode'};
 7765:             if ($instcode ne '') {
 7766:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 7767:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 7768:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 7769:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 7770:                         if ($result eq 'valid') {
 7771:                             if ($coursehash{'internal.co-owners'}) {
 7772:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 7773:                                     push(@newcoowners,$coowner);
 7774:                                 }
 7775:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 7776:                                     push(@newcoowners,$uname.':'.$udom);
 7777:                                 }
 7778:                                 @newcoowners = sort(@newcoowners);
 7779:                             } else {
 7780:                                 push(@newcoowners,$uname.':'.$udom);
 7781:                             }
 7782:                         } else {
 7783:                             if ($coursehash{'internal.co-owners'}) {
 7784:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 7785:                                     unless ($coowner eq $uname.':'.$udom) {
 7786:                                         push(@newcoowners,$coowner);
 7787:                                     }
 7788:                                 }
 7789:                                 unless (@newcoowners > 0) {
 7790:                                     $delcoowners = 1;
 7791:                                     $coowners = '';
 7792:                                 }
 7793:                             }
 7794:                         }
 7795:                         if (@newcoowners || $delcoowners) {
 7796:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 7797:                                             $delcoowners,@newcoowners);
 7798:                         }
 7799:                     }
 7800:                 }
 7801:             }
 7802:         }
 7803:     }
 7804: }
 7805: 
 7806: sub store_coowners {
 7807:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 7808:     my $cid = $cdom.'_'.$cnum;
 7809:     my ($coowners,$delresult,$putresult);
 7810:     if (@newcoowners) {
 7811:         $coowners = join(',',@newcoowners);
 7812:         my %coownershash = (
 7813:                             'internal.co-owners' => $coowners,
 7814:                            );
 7815:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 7816:         if ($putresult eq 'ok') {
 7817:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 7818:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 7819:             }
 7820:         }
 7821:     }
 7822:     if ($delcoowners) {
 7823:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 7824:         if ($delresult eq 'ok') {
 7825:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 7826:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 7827:             }
 7828:         }
 7829:     }
 7830:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 7831:         my %crsinfo =
 7832:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 7833:         if (ref($crsinfo{$cid}) eq 'HASH') {
 7834:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 7835:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 7836:         }
 7837:     }
 7838: }
 7839: 
 7840: # -------------------------------------------------- Modify user authentication
 7841: # Overrides without validation
 7842: 
 7843: sub modifyuserauth {
 7844:     my ($udom,$uname,$umode,$upass)=@_;
 7845:     my $uhome=&homeserver($uname,$udom);
 7846:     unless (&allowed('mau',$udom)) { return 'refused'; }
 7847:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 7848:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 7849:              ' in domain '.$env{'request.role.domain'});  
 7850:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 7851: 		     &escape($upass),$uhome);
 7852:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 7853:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 7854:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 7855:     &log($udom,,$uname,$uhome,
 7856:         'Authentication changed by '.$env{'user.domain'}.', '.
 7857:                                      $env{'user.name'}.', '.$umode.
 7858:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 7859:     unless ($reply eq 'ok') {
 7860:         &logthis('Authentication mode error: '.$reply);
 7861: 	return 'error: '.$reply;
 7862:     }   
 7863:     return 'ok';
 7864: }
 7865: 
 7866: # --------------------------------------------------------------- Modify a user
 7867: 
 7868: sub modifyuser {
 7869:     my ($udom,    $uname, $uid,
 7870:         $umode,   $upass, $first,
 7871:         $middle,  $last,  $gene,
 7872:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 7873:     $udom= &LONCAPA::clean_domain($udom);
 7874:     $uname=&LONCAPA::clean_username($uname);
 7875:     my $showcandelete = 'none';
 7876:     if (ref($candelete) eq 'ARRAY') {
 7877:         if (@{$candelete} > 0) {
 7878:             $showcandelete = join(', ',@{$candelete});
 7879:         }
 7880:     }
 7881:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 7882:              $umode.', '.$first.', '.$middle.', '.
 7883: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 7884:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 7885:                                      ' desiredhome not specified'). 
 7886:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 7887:              ' in domain '.$env{'request.role.domain'});
 7888:     my $uhome=&homeserver($uname,$udom,'true');
 7889:     my $newuser;
 7890:     if ($uhome eq 'no_host') {
 7891:         $newuser = 1;
 7892:     }
 7893: # ----------------------------------------------------------------- Create User
 7894:     if (($uhome eq 'no_host') && 
 7895: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 7896:         my $unhome='';
 7897:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 7898:             $unhome = $desiredhome;
 7899: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 7900: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 7901:         } else { # load balancing routine for determining $unhome
 7902:             my $loadm=10000000;
 7903: 	    my %servers = &get_servers($udom,'library');
 7904: 	    foreach my $tryserver (keys(%servers)) {
 7905: 		my $answer=reply('load',$tryserver);
 7906: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 7907: 		    $loadm=$answer;
 7908: 		    $unhome=$tryserver;
 7909: 		}
 7910: 	    }
 7911:         }
 7912:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 7913: 	    return 'error: unable to find a home server for '.$uname.
 7914:                    ' in domain '.$udom;
 7915:         }
 7916:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 7917:                          &escape($upass),$unhome);
 7918: 	unless ($reply eq 'ok') {
 7919:             return 'error: '.$reply;
 7920:         }   
 7921:         $uhome=&homeserver($uname,$udom,'true');
 7922:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 7923: 	    return 'error: unable verify users home machine.';
 7924:         }
 7925:     }   # End of creation of new user
 7926: # ---------------------------------------------------------------------- Add ID
 7927:     if ($uid) {
 7928:        $uid=~tr/A-Z/a-z/;
 7929:        my %uidhash=&idrget($udom,$uname);
 7930:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 7931:          && (!$forceid)) {
 7932: 	  unless ($uid eq $uidhash{$uname}) {
 7933: 	      return 'error: user id "'.$uid.'" does not match '.
 7934:                   'current user id "'.$uidhash{$uname}.'".';
 7935:           }
 7936:        } else {
 7937: 	  &idput($udom,($uname => $uid));
 7938:        }
 7939:     }
 7940: # -------------------------------------------------------------- Add names, etc
 7941:     my @tmp=&get('environment',
 7942: 		   ['firstname','middlename','lastname','generation','id',
 7943:                     'permanentemail','inststatus'],
 7944: 		   $udom,$uname);
 7945:     my (%names,%oldnames);
 7946:     if ($tmp[0] =~ m/^error:.*/) { 
 7947:         %names=(); 
 7948:     } else {
 7949:         %names = @tmp;
 7950:         %oldnames = %names;
 7951:     }
 7952: #
 7953: # If name, email and/or uid are blank (e.g., because an uploaded file
 7954: # of users did not contain them), do not overwrite existing values
 7955: # unless field is in $candelete array ref.  
 7956: #
 7957: 
 7958:     my @fields = ('firstname','middlename','lastname','generation',
 7959:                   'permanentemail','id');
 7960:     my %newvalues;
 7961:     if (ref($candelete) eq 'ARRAY') {
 7962:         foreach my $field (@fields) {
 7963:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 7964:                 if ($field eq 'firstname') {
 7965:                     $names{$field} = $first;
 7966:                 } elsif ($field eq 'middlename') {
 7967:                     $names{$field} = $middle;
 7968:                 } elsif ($field eq 'lastname') {
 7969:                     $names{$field} = $last;
 7970:                 } elsif ($field eq 'generation') { 
 7971:                     $names{$field} = $gene;
 7972:                 } elsif ($field eq 'permanentemail') {
 7973:                     $names{$field} = $email;
 7974:                 } elsif ($field eq 'id') {
 7975:                     $names{$field}  = $uid;
 7976:                 }
 7977:             }
 7978:         }
 7979:     }
 7980:     if ($first)  { $names{'firstname'}  = $first; }
 7981:     if (defined($middle)) { $names{'middlename'} = $middle; }
 7982:     if ($last)   { $names{'lastname'}   = $last; }
 7983:     if (defined($gene))   { $names{'generation'} = $gene; }
 7984:     if ($email) {
 7985:        $email=~s/[^\w\@\.\-\,]//gs;
 7986:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 7987:     }
 7988:     if ($uid) { $names{'id'}  = $uid; }
 7989:     if (defined($inststatus)) {
 7990:         $names{'inststatus'} = '';
 7991:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 7992:         if (ref($usertypes) eq 'HASH') {
 7993:             my @okstatuses; 
 7994:             foreach my $item (split(/:/,$inststatus)) {
 7995:                 if (defined($usertypes->{$item})) {
 7996:                     push(@okstatuses,$item);  
 7997:                 }
 7998:             }
 7999:             if (@okstatuses) {
 8000:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 8001:             }
 8002:         }
 8003:     }
 8004:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 8005:                  $umode.', '.$first.', '.$middle.', '.
 8006:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 8007:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 8008:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 8009:     } else {
 8010:         $logmsg .= ' during self creation';
 8011:     }
 8012:     my $changed;
 8013:     if ($newuser) {
 8014:         $changed = 1;
 8015:     } else {
 8016:         foreach my $field (@fields) {
 8017:             if ($names{$field} ne $oldnames{$field}) {
 8018:                 $changed = 1;
 8019:                 last;
 8020:             }
 8021:         }
 8022:     }
 8023:     unless ($changed) {
 8024:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 8025:         &logthis($logmsg);
 8026:         return 'ok';
 8027:     }
 8028:     my $reply = &put('environment', \%names, $udom,$uname);
 8029:     if ($reply ne 'ok') { 
 8030:         return 'error: '.$reply;
 8031:     }
 8032:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
 8033:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
 8034:     }
 8035:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 8036:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 8037:     $logmsg = 'Success modifying user '.$logmsg;
 8038:     &logthis($logmsg);
 8039:     return 'ok';
 8040: }
 8041: 
 8042: # -------------------------------------------------------------- Modify student
 8043: 
 8044: sub modifystudent {
 8045:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 8046:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 8047:         $selfenroll,$context,$inststatus)=@_;
 8048:     if (!$cid) {
 8049: 	unless ($cid=$env{'request.course.id'}) {
 8050: 	    return 'not_in_class';
 8051: 	}
 8052:     }
 8053: # --------------------------------------------------------------- Make the user
 8054:     my $reply=&modifyuser
 8055: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 8056:          $desiredhome,$email,$inststatus);
 8057:     unless ($reply eq 'ok') { return $reply; }
 8058:     # This will cause &modify_student_enrollment to get the uid from the
 8059:     # students environment
 8060:     $uid = undef if (!$forceid);
 8061:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 8062: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
 8063:     return $reply;
 8064: }
 8065: 
 8066: sub modify_student_enrollment {
 8067:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
 8068:     my ($cdom,$cnum,$chome);
 8069:     if (!$cid) {
 8070: 	unless ($cid=$env{'request.course.id'}) {
 8071: 	    return 'not_in_class';
 8072: 	}
 8073: 	$cdom=$env{'course.'.$cid.'.domain'};
 8074: 	$cnum=$env{'course.'.$cid.'.num'};
 8075:     } else {
 8076: 	($cdom,$cnum)=split(/_/,$cid);
 8077:     }
 8078:     $chome=$env{'course.'.$cid.'.home'};
 8079:     if (!$chome) {
 8080: 	$chome=&homeserver($cnum,$cdom);
 8081:     }
 8082:     if (!$chome) { return 'unknown_course'; }
 8083:     # Make sure the user exists
 8084:     my $uhome=&homeserver($uname,$udom);
 8085:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8086: 	return 'error: no such user';
 8087:     }
 8088:     # Get student data if we were not given enough information
 8089:     if (!defined($first)  || $first  eq '' || 
 8090:         !defined($last)   || $last   eq '' || 
 8091:         !defined($uid)    || $uid    eq '' || 
 8092:         !defined($middle) || $middle eq '' || 
 8093:         !defined($gene)   || $gene   eq '') {
 8094:         # They did not supply us with enough data to enroll the student, so
 8095:         # we need to pick up more information.
 8096:         my %tmp = &get('environment',
 8097:                        ['firstname','middlename','lastname', 'generation','id']
 8098:                        ,$udom,$uname);
 8099: 
 8100:         #foreach my $key (keys(%tmp)) {
 8101:         #    &logthis("key $key = ".$tmp{$key});
 8102:         #}
 8103:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 8104:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 8105:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 8106:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 8107:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 8108:     }
 8109:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 8110:     my $user = "$uname:$udom";
 8111:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
 8112:     my $reply=cput('classlist',
 8113: 		   {$user => 
 8114: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 8115: 		   $cdom,$cnum);
 8116:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
 8117:         &devalidate_getsection_cache($udom,$uname,$cid);
 8118:     } else { 
 8119: 	return 'error: '.$reply;
 8120:     }
 8121:     # Add student role to user
 8122:     my $uurl='/'.$cid;
 8123:     $uurl=~s/\_/\//g;
 8124:     if ($usec) {
 8125: 	$uurl.='/'.$usec;
 8126:     }
 8127:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
 8128:                              $selfenroll,$context);
 8129:     if ($result ne 'ok') {
 8130:         if ($old_entry{$user} ne '') {
 8131:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
 8132:         } else {
 8133:             $reply = &del('classlist',[$user],$cdom,$cnum);
 8134:         }
 8135:     }
 8136:     return $result; 
 8137: }
 8138: 
 8139: sub format_name {
 8140:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 8141:     my $name;
 8142:     if ($first ne 'lastname') {
 8143: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 8144:     } else {
 8145: 	if ($lastname=~/\S/) {
 8146: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 8147: 	    $name=~s/\s+,/,/;
 8148: 	} else {
 8149: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 8150: 	}
 8151:     }
 8152:     $name=~s/^\s+//;
 8153:     $name=~s/\s+$//;
 8154:     $name=~s/\s+/ /g;
 8155:     return $name;
 8156: }
 8157: 
 8158: # ------------------------------------------------- Write to course preferences
 8159: 
 8160: sub writecoursepref {
 8161:     my ($courseid,%prefs)=@_;
 8162:     $courseid=~s/^\///;
 8163:     $courseid=~s/\_/\//g;
 8164:     my ($cdomain,$cnum)=split(/\//,$courseid);
 8165:     my $chome=homeserver($cnum,$cdomain);
 8166:     if (($chome eq '') || ($chome eq 'no_host')) { 
 8167: 	return 'error: no such course';
 8168:     }
 8169:     my $cstring='';
 8170:     foreach my $pref (keys(%prefs)) {
 8171: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 8172:     }
 8173:     $cstring=~s/\&$//;
 8174:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 8175: }
 8176: 
 8177: # ---------------------------------------------------------- Make/modify course
 8178: 
 8179: sub createcourse {
 8180:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 8181:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 8182:     $url=&declutter($url);
 8183:     my $cid='';
 8184:     if ($context eq 'requestcourses') {
 8185:         my $can_create = 0;
 8186:         my ($ownername,$ownerdom) = split(':',$course_owner);
 8187:         if ($udom eq $ownerdom) {
 8188:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 8189:                                   $context)) {
 8190:                 $can_create = 1;
 8191:             }
 8192:         } else {
 8193:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 8194:                                            $category);
 8195:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 8196:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 8197:                 if (@curr > 0) {
 8198:                     my @options = qw(approval validate autolimit);
 8199:                     my $optregex = join('|',@options);
 8200:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 8201:                         $can_create = 1;
 8202:                     }
 8203:                 }
 8204:             }
 8205:         }
 8206:         if ($can_create) {
 8207:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 8208:                 unless (&allowed('ccc',$udom)) {
 8209:                     return 'refused'; 
 8210:                 }
 8211:             }
 8212:         } else {
 8213:             return 'refused';
 8214:         }
 8215:     } elsif (!&allowed('ccc',$udom)) {
 8216:         return 'refused';
 8217:     }
 8218: # --------------------------------------------------------------- Get Unique ID
 8219:     my $uname;
 8220:     if ($cnum =~ /^$match_courseid$/) {
 8221:         my $chome=&homeserver($cnum,$udom,'true');
 8222:         if (($chome eq '') || ($chome eq 'no_host')) {
 8223:             $uname = $cnum;
 8224:         } else {
 8225:             $uname = &generate_coursenum($udom,$crstype);
 8226:         }
 8227:     } else {
 8228:         $uname = &generate_coursenum($udom,$crstype);
 8229:     }
 8230:     return $uname if ($uname =~ /^error/);
 8231: # -------------------------------------------------- Check supplied server name
 8232:     if (!defined($course_server)) {
 8233:         if (defined(&domain($udom,'primary'))) {
 8234:             $course_server = &domain($udom,'primary');
 8235:         } else {
 8236:             $course_server = $env{'user.home'}; 
 8237:         }
 8238:     }
 8239:     my %host_servers =
 8240:         &Apache::lonnet::get_servers($udom,'library');
 8241:     unless ($host_servers{$course_server}) {
 8242:         return 'error: invalid home server for course: '.$course_server;
 8243:     }
 8244: # ------------------------------------------------------------- Make the course
 8245:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 8246:                       $course_server);
 8247:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 8248:     my $uhome=&homeserver($uname,$udom,'true');
 8249:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8250: 	return 'error: no such course';
 8251:     }
 8252: # ----------------------------------------------------------------- Course made
 8253: # log existence
 8254:     my $now = time;
 8255:     my $newcourse = {
 8256:                     $udom.'_'.$uname => {
 8257:                                      description => $description,
 8258:                                      inst_code   => $inst_code,
 8259:                                      owner       => $course_owner,
 8260:                                      type        => $crstype,
 8261:                                      creator     => $env{'user.name'}.':'.
 8262:                                                     $env{'user.domain'},
 8263:                                      created     => $now,
 8264:                                      context     => $context,
 8265:                                                 },
 8266:                     };
 8267:     &courseidput($udom,$newcourse,$uhome,'notime');
 8268: # set toplevel url
 8269:     my $topurl=$url;
 8270:     unless ($nonstandard) {
 8271: # ------------------------------------------ For standard courses, make top url
 8272:         my $mapurl=&clutter($url);
 8273:         if ($mapurl eq '/res/') { $mapurl=''; }
 8274:         $env{'form.initmap'}=(<<ENDINITMAP);
 8275: <map>
 8276: <resource id="1" type="start"></resource>
 8277: <resource id="2" src="$mapurl"></resource>
 8278: <resource id="3" type="finish"></resource>
 8279: <link index="1" from="1" to="2"></link>
 8280: <link index="2" from="2" to="3"></link>
 8281: </map>
 8282: ENDINITMAP
 8283:         $topurl=&declutter(
 8284:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 8285:                           );
 8286:     }
 8287: # ----------------------------------------------------------- Write preferences
 8288:     &writecoursepref($udom.'_'.$uname,
 8289:                      ('description'              => $description,
 8290:                       'url'                      => $topurl,
 8291:                       'internal.creator'         => $env{'user.name'}.':'.
 8292:                                                     $env{'user.domain'},
 8293:                       'internal.created'         => $now,
 8294:                       'internal.creationcontext' => $context)
 8295:                     );
 8296:     return '/'.$udom.'/'.$uname;
 8297: }
 8298: 
 8299: # ------------------------------------------------------------------- Create ID
 8300: sub generate_coursenum {
 8301:     my ($udom,$crstype) = @_;
 8302:     my $domdesc = &domain($udom);
 8303:     return 'error: invalid domain' if ($domdesc eq '');
 8304:     my $first;
 8305:     if ($crstype eq 'Community') {
 8306:         $first = '0';
 8307:     } else {
 8308:         $first = int(1+rand(9)); 
 8309:     } 
 8310:     my $uname=$first.
 8311:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8312:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8313:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8314: # ----------------------------------------------- Make sure that does not exist
 8315:     my $uhome=&homeserver($uname,$udom,'true');
 8316:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8317:         if ($crstype eq 'Community') {
 8318:             $first = '0';
 8319:         } else {
 8320:             $first = int(1+rand(9));
 8321:         }
 8322:         $uname=$first.
 8323:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8324:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8325:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8326:         $uhome=&homeserver($uname,$udom,'true');
 8327:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8328:             return 'error: unable to generate unique course-ID';
 8329:         }
 8330:     }
 8331:     return $uname;
 8332: }
 8333: 
 8334: sub is_course {
 8335:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
 8336:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
 8337: 
 8338:     return unless $cdom and $cnum;
 8339: 
 8340:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
 8341:         '.');
 8342: 
 8343:     return unless exists($courses{$cdom.'_'.$cnum});
 8344:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
 8345: }
 8346: 
 8347: sub store_userdata {
 8348:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
 8349:     my $result;
 8350:     if ($datakey ne '') {
 8351:         if (ref($storehash) eq 'HASH') {
 8352:             if ($udom eq '' || $uname eq '') {
 8353:                 $udom = $env{'user.domain'};
 8354:                 $uname = $env{'user.name'};
 8355:             }
 8356:             my $uhome=&homeserver($uname,$udom);
 8357:             if (($uhome eq '') || ($uhome eq 'no_host')) {
 8358:                 $result = 'error: no_host';
 8359:             } else {
 8360:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
 8361:                 $storehash->{'host'} = $perlvar{'lonHostID'};
 8362: 
 8363:                 my $namevalue='';
 8364:                 foreach my $key (keys(%{$storehash})) {
 8365:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 8366:                 }
 8367:                 $namevalue=~s/\&$//;
 8368:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
 8369:                                   $namevalue,$uhome);
 8370:             }
 8371:         } else {
 8372:             $result = 'error: data to store was not a hash reference'; 
 8373:         }
 8374:     } else {
 8375:         $result= 'error: invalid requestkey'; 
 8376:     }
 8377:     return $result;
 8378: }
 8379: 
 8380: # ---------------------------------------------------------- Assign Custom Role
 8381: 
 8382: sub assigncustomrole {
 8383:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 8384:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 8385:                        $end,$start,$deleteflag,$selfenroll,$context);
 8386: }
 8387: 
 8388: # ----------------------------------------------------------------- Revoke Role
 8389: 
 8390: sub revokerole {
 8391:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 8392:     my $now=time;
 8393:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 8394: }
 8395: 
 8396: # ---------------------------------------------------------- Revoke Custom Role
 8397: 
 8398: sub revokecustomrole {
 8399:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 8400:     my $now=time;
 8401:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 8402:            $deleteflag,$selfenroll,$context);
 8403: }
 8404: 
 8405: # ------------------------------------------------------------ Disk usage
 8406: sub diskusage {
 8407:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 8408:     $directorypath =~ s/\/$//;
 8409:     my $listing=&reply('du2:'.&escape($directorypath).':'
 8410:                        .&escape($getpropath).':'.&escape($uname).':'
 8411:                        .&escape($udom),homeserver($uname,$udom));
 8412:     if ($listing eq 'unknown_cmd') {
 8413:         if ($getpropath) {
 8414:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 8415:         }
 8416:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 8417:     }
 8418:     return $listing;
 8419: }
 8420: 
 8421: sub is_locked {
 8422:     my ($file_name, $domain, $user, $which) = @_;
 8423:     my @check;
 8424:     my $is_locked;
 8425:     push (@check,$file_name);
 8426:     my %locked = &get('file_permissions',\@check,
 8427: 		      $env{'user.domain'},$env{'user.name'});
 8428:     my ($tmp)=keys(%locked);
 8429:     if ($tmp=~/^error:/) { undef(%locked); }
 8430:     
 8431:     if (ref($locked{$file_name}) eq 'ARRAY') {
 8432:         $is_locked = 'false';
 8433:         foreach my $entry (@{$locked{$file_name}}) {
 8434:            if (ref($entry) eq 'ARRAY') {
 8435:                $is_locked = 'true';
 8436:                if (ref($which) eq 'ARRAY') {
 8437:                    push(@{$which},$entry);
 8438:                } else {
 8439:                    last;
 8440:                }
 8441:            }
 8442:        }
 8443:     } else {
 8444:         $is_locked = 'false';
 8445:     }
 8446:     return $is_locked;
 8447: }
 8448: 
 8449: sub declutter_portfile {
 8450:     my ($file) = @_;
 8451:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 8452:     return $file;
 8453: }
 8454: 
 8455: # ------------------------------------------------------------- Mark as Read Only
 8456: 
 8457: sub mark_as_readonly {
 8458:     my ($domain,$user,$files,$what) = @_;
 8459:     my %current_permissions = &dump('file_permissions',$domain,$user);
 8460:     my ($tmp)=keys(%current_permissions);
 8461:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8462:     foreach my $file (@{$files}) {
 8463: 	$file = &declutter_portfile($file);
 8464:         push(@{$current_permissions{$file}},$what);
 8465:     }
 8466:     &put('file_permissions',\%current_permissions,$domain,$user);
 8467:     return;
 8468: }
 8469: 
 8470: # ------------------------------------------------------------Save Selected Files
 8471: 
 8472: sub save_selected_files {
 8473:     my ($user, $path, @files) = @_;
 8474:     my $filename = $user."savedfiles";
 8475:     my @other_files = &files_not_in_path($user, $path);
 8476:     open (OUT, '>'.$tmpdir.$filename);
 8477:     foreach my $file (@files) {
 8478:         print (OUT $env{'form.currentpath'}.$file."\n");
 8479:     }
 8480:     foreach my $file (@other_files) {
 8481:         print (OUT $file."\n");
 8482:     }
 8483:     close (OUT);
 8484:     return 'ok';
 8485: }
 8486: 
 8487: sub clear_selected_files {
 8488:     my ($user) = @_;
 8489:     my $filename = $user."savedfiles";
 8490:     open (OUT, '>'.LONCAPA::tempdir().$filename);
 8491:     print (OUT undef);
 8492:     close (OUT);
 8493:     return ("ok");    
 8494: }
 8495: 
 8496: sub files_in_path {
 8497:     my ($user, $path) = @_;
 8498:     my $filename = $user."savedfiles";
 8499:     my %return_files;
 8500:     open (IN, '<'.LONCAPA::tempdir().$filename);
 8501:     while (my $line_in = <IN>) {
 8502:         chomp ($line_in);
 8503:         my @paths_and_file = split (m!/!, $line_in);
 8504:         my $file_part = pop (@paths_and_file);
 8505:         my $path_part = join ('/', @paths_and_file);
 8506:         $path_part.='/';
 8507:         my $path_and_file = $path_part.$file_part;
 8508:         if ($path_part eq $path) {
 8509:             $return_files{$file_part}= 'selected';
 8510:         }
 8511:     }
 8512:     close (IN);
 8513:     return (\%return_files);
 8514: }
 8515: 
 8516: # called in portfolio select mode, to show files selected NOT in current directory
 8517: sub files_not_in_path {
 8518:     my ($user, $path) = @_;
 8519:     my $filename = $user."savedfiles";
 8520:     my @return_files;
 8521:     my $path_part;
 8522:     open(IN, '<'.LONCAPA::.$filename);
 8523:     while (my $line = <IN>) {
 8524:         #ok, I know it's clunky, but I want it to work
 8525:         my @paths_and_file = split(m|/|, $line);
 8526:         my $file_part = pop(@paths_and_file);
 8527:         chomp($file_part);
 8528:         my $path_part = join('/', @paths_and_file);
 8529:         $path_part .= '/';
 8530:         my $path_and_file = $path_part.$file_part;
 8531:         if ($path_part ne $path) {
 8532:             push(@return_files, ($path_and_file));
 8533:         }
 8534:     }
 8535:     close(OUT);
 8536:     return (@return_files);
 8537: }
 8538: 
 8539: #----------------------------------------------Get portfolio file permissions
 8540: 
 8541: sub get_portfile_permissions {
 8542:     my ($domain,$user) = @_;
 8543:     my %current_permissions = &dump('file_permissions',$domain,$user);
 8544:     my ($tmp)=keys(%current_permissions);
 8545:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8546:     return \%current_permissions;
 8547: }
 8548: 
 8549: #---------------------------------------------Get portfolio file access controls
 8550: 
 8551: sub get_access_controls {
 8552:     my ($current_permissions,$group,$file) = @_;
 8553:     my %access;
 8554:     my $real_file = $file;
 8555:     $file =~ s/\.meta$//;
 8556:     if (defined($file)) {
 8557:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 8558:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 8559:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 8560:             }
 8561:         }
 8562:     } else {
 8563:         foreach my $key (keys(%{$current_permissions})) {
 8564:             if ($key =~ /\0accesscontrol$/) {
 8565:                 if (defined($group)) {
 8566:                     if ($key !~ m-^\Q$group\E/-) {
 8567:                         next;
 8568:                     }
 8569:                 }
 8570:                 my ($fullpath) = split(/\0/,$key);
 8571:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 8572:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 8573:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 8574:                     }
 8575:                 }
 8576:             }
 8577:         }
 8578:     }
 8579:     return %access;
 8580: }
 8581: 
 8582: sub modify_access_controls {
 8583:     my ($file_name,$changes,$domain,$user)=@_;
 8584:     my ($outcome,$deloutcome);
 8585:     my %store_permissions;
 8586:     my %new_values;
 8587:     my %new_control;
 8588:     my %translation;
 8589:     my @deletions = ();
 8590:     my $now = time;
 8591:     if (exists($$changes{'activate'})) {
 8592:         if (ref($$changes{'activate'}) eq 'HASH') {
 8593:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 8594:             my $numnew = scalar(@newitems);
 8595:             for (my $i=0; $i<$numnew; $i++) {
 8596:                 my $newkey = $newitems[$i];
 8597:                 my $newid = &Apache::loncommon::get_cgi_id();
 8598:                 if ($newkey =~ /^\d+:/) { 
 8599:                     $newkey =~ s/^(\d+)/$newid/;
 8600:                     $translation{$1} = $newid;
 8601:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 8602:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 8603:                     $translation{$1} = $newid;
 8604:                 }
 8605:                 $new_values{$file_name."\0".$newkey} = 
 8606:                                           $$changes{'activate'}{$newitems[$i]};
 8607:                 $new_control{$newkey} = $now;
 8608:             }
 8609:         }
 8610:     }
 8611:     my %todelete;
 8612:     my %changed_items;
 8613:     foreach my $action ('delete','update') {
 8614:         if (exists($$changes{$action})) {
 8615:             if (ref($$changes{$action}) eq 'HASH') {
 8616:                 foreach my $key (keys(%{$$changes{$action}})) {
 8617:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 8618:                     if ($action eq 'delete') { 
 8619:                         $todelete{$itemnum} = 1;
 8620:                     } else {
 8621:                         $changed_items{$itemnum} = $key;
 8622:                     }
 8623:                 }
 8624:             }
 8625:         }
 8626:     }
 8627:     # get lock on access controls for file.
 8628:     my $lockhash = {
 8629:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 8630:                                                        ':'.$env{'user.domain'},
 8631:                    }; 
 8632:     my $tries = 0;
 8633:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 8634:    
 8635:     while (($gotlock ne 'ok') && $tries <3) {
 8636:         $tries ++;
 8637:         sleep 1;
 8638:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 8639:     }
 8640:     if ($gotlock eq 'ok') {
 8641:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 8642:         my ($tmp)=keys(%curr_permissions);
 8643:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 8644:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 8645:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 8646:             if (ref($curr_controls) eq 'HASH') {
 8647:                 foreach my $control_item (keys(%{$curr_controls})) {
 8648:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 8649:                     if (defined($todelete{$itemnum})) {
 8650:                         push(@deletions,$file_name."\0".$control_item);
 8651:                     } else {
 8652:                         if (defined($changed_items{$itemnum})) {
 8653:                             $new_control{$changed_items{$itemnum}} = $now;
 8654:                             push(@deletions,$file_name."\0".$control_item);
 8655:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 8656:                         } else {
 8657:                             $new_control{$control_item} = $$curr_controls{$control_item};
 8658:                         }
 8659:                     }
 8660:                 }
 8661:             }
 8662:         }
 8663:         my ($group);
 8664:         if (&is_course($domain,$user)) {
 8665:             ($group,my $file) = split(/\//,$file_name,2);
 8666:         }
 8667:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 8668:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 8669:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 8670:         #  remove lock
 8671:         my @del_lock = ($file_name."\0".'locked_access_records');
 8672:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 8673:         my $sqlresult =
 8674:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 8675:                                     $group);
 8676:     } else {
 8677:         $outcome = "error: could not obtain lockfile\n";  
 8678:     }
 8679:     return ($outcome,$deloutcome,\%new_values,\%translation);
 8680: }
 8681: 
 8682: sub make_public_indefinitely {
 8683:     my ($requrl) = @_;
 8684:     my $now = time;
 8685:     my $action = 'activate';
 8686:     my $aclnum = 0;
 8687:     if (&is_portfolio_url($requrl)) {
 8688:         my (undef,$udom,$unum,$file_name,$group) =
 8689:             &parse_portfolio_url($requrl);
 8690:         my $current_perms = &get_portfile_permissions($udom,$unum);
 8691:         my %access_controls = &get_access_controls($current_perms,
 8692:                                                    $group,$file_name);
 8693:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 8694:             my ($num,$scope,$end,$start) = 
 8695:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 8696:             if ($scope eq 'public') {
 8697:                 if ($start <= $now && $end == 0) {
 8698:                     $action = 'none';
 8699:                 } else {
 8700:                     $action = 'update';
 8701:                     $aclnum = $num;
 8702:                 }
 8703:                 last;
 8704:             }
 8705:         }
 8706:         if ($action eq 'none') {
 8707:              return 'ok';
 8708:         } else {
 8709:             my %changes;
 8710:             my $newend = 0;
 8711:             my $newstart = $now;
 8712:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 8713:             $changes{$action}{$newkey} = {
 8714:                 type => 'public',
 8715:                 time => {
 8716:                     start => $newstart,
 8717:                     end   => $newend,
 8718:                 },
 8719:             };
 8720:             my ($outcome,$deloutcome,$new_values,$translation) =
 8721:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 8722:             return $outcome;
 8723:         }
 8724:     } else {
 8725:         return 'invalid';
 8726:     }
 8727: }
 8728: 
 8729: #------------------------------------------------------Get Marked as Read Only
 8730: 
 8731: sub get_marked_as_readonly {
 8732:     my ($domain,$user,$what,$group) = @_;
 8733:     my $current_permissions = &get_portfile_permissions($domain,$user);
 8734:     my @readonly_files;
 8735:     my $cmp1=$what;
 8736:     if (ref($what)) { $cmp1=join('',@{$what}) };
 8737:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 8738:         if (defined($group)) {
 8739:             if ($file_name !~ m-^\Q$group\E/-) {
 8740:                 next;
 8741:             }
 8742:         }
 8743:         if (ref($value) eq "ARRAY"){
 8744:             foreach my $stored_what (@{$value}) {
 8745:                 my $cmp2=$stored_what;
 8746:                 if (ref($stored_what) eq 'ARRAY') {
 8747:                     $cmp2=join('',@{$stored_what});
 8748:                 }
 8749:                 if ($cmp1 eq $cmp2) {
 8750:                     push(@readonly_files, $file_name);
 8751:                     last;
 8752:                 } elsif (!defined($what)) {
 8753:                     push(@readonly_files, $file_name);
 8754:                     last;
 8755:                 }
 8756:             }
 8757:         }
 8758:     }
 8759:     return @readonly_files;
 8760: }
 8761: #-----------------------------------------------------------Get Marked as Read Only Hash
 8762: 
 8763: sub get_marked_as_readonly_hash {
 8764:     my ($current_permissions,$group,$what) = @_;
 8765:     my %readonly_files;
 8766:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 8767:         if (defined($group)) {
 8768:             if ($file_name !~ m-^\Q$group\E/-) {
 8769:                 next;
 8770:             }
 8771:         }
 8772:         if (ref($value) eq "ARRAY"){
 8773:             foreach my $stored_what (@{$value}) {
 8774:                 if (ref($stored_what) eq 'ARRAY') {
 8775:                     foreach my $lock_descriptor(@{$stored_what}) {
 8776:                         if ($lock_descriptor eq 'graded') {
 8777:                             $readonly_files{$file_name} = 'graded';
 8778:                         } elsif ($lock_descriptor eq 'handback') {
 8779:                             $readonly_files{$file_name} = 'handback';
 8780:                         } else {
 8781:                             if (!exists($readonly_files{$file_name})) {
 8782:                                 $readonly_files{$file_name} = 'locked';
 8783:                             }
 8784:                         }
 8785:                     }
 8786:                 } 
 8787:             }
 8788:         } 
 8789:     }
 8790:     return %readonly_files;
 8791: }
 8792: # ------------------------------------------------------------ Unmark as Read Only
 8793: 
 8794: sub unmark_as_readonly {
 8795:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 8796:     # for portfolio submissions, $what contains [$symb,$crsid] 
 8797:     my ($domain,$user,$what,$file_name,$group) = @_;
 8798:     $file_name = &declutter_portfile($file_name);
 8799:     my $symb_crs = $what;
 8800:     if (ref($what)) { $symb_crs=join('',@$what); }
 8801:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 8802:     my ($tmp)=keys(%current_permissions);
 8803:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8804:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 8805:     foreach my $file (@readonly_files) {
 8806: 	my $clean_file = &declutter_portfile($file);
 8807: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 8808: 	my $current_locks = $current_permissions{$file};
 8809:         my @new_locks;
 8810:         my @del_keys;
 8811:         if (ref($current_locks) eq "ARRAY"){
 8812:             foreach my $locker (@{$current_locks}) {
 8813:                 my $compare=$locker;
 8814:                 if (ref($locker) eq 'ARRAY') {
 8815:                     $compare=join('',@{$locker});
 8816:                     if ($compare ne $symb_crs) {
 8817:                         push(@new_locks, $locker);
 8818:                     }
 8819:                 }
 8820:             }
 8821:             if (scalar(@new_locks) > 0) {
 8822:                 $current_permissions{$file} = \@new_locks;
 8823:             } else {
 8824:                 push(@del_keys, $file);
 8825:                 &del('file_permissions',\@del_keys, $domain, $user);
 8826:                 delete($current_permissions{$file});
 8827:             }
 8828:         }
 8829:     }
 8830:     &put('file_permissions',\%current_permissions,$domain,$user);
 8831:     return;
 8832: }
 8833: 
 8834: # ------------------------------------------------------------ Directory lister
 8835: 
 8836: sub dirlist {
 8837:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 8838:     $uri=~s/^\///;
 8839:     $uri=~s/\/$//;
 8840:     my ($udom, $uname);
 8841:     if ($getuserdir) {
 8842:         $udom = $userdomain;
 8843:         $uname = $username;
 8844:     } else {
 8845:         (undef,$udom,$uname)=split(/\//,$uri);
 8846:         if(defined($userdomain)) {
 8847:             $udom = $userdomain;
 8848:         }
 8849:         if(defined($username)) {
 8850:             $uname = $username;
 8851:         }
 8852:     }
 8853:     my ($dirRoot,$listing,@listing_results);
 8854: 
 8855:     $dirRoot = $perlvar{'lonDocRoot'};
 8856:     if (defined($getpropath)) {
 8857:         $dirRoot = &propath($udom,$uname);
 8858:         $dirRoot =~ s/\/$//;
 8859:     } elsif (defined($getuserdir)) {
 8860:         my $subdir=$uname.'__';
 8861:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 8862:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 8863:                    ."/$udom/$subdir/$uname";
 8864:     } elsif (defined($alternateRoot)) {
 8865:         $dirRoot = $alternateRoot;
 8866:     }
 8867: 
 8868:     if($udom) {
 8869:         if($uname) {
 8870:             my $uhome = &homeserver($uname,$udom);
 8871:             if ($uhome eq 'no_host') {
 8872:                 return ([],'no_host');
 8873:             }
 8874:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 8875:                               .$getuserdir.':'.&escape($dirRoot)
 8876:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
 8877:             if ($listing eq 'unknown_cmd') {
 8878:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
 8879:             } else {
 8880:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 8881:             }
 8882:             if ($listing eq 'unknown_cmd') {
 8883:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
 8884:                 @listing_results = split(/:/,$listing);
 8885:             } else {
 8886:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 8887:             }
 8888:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
 8889:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
 8890:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 8891:                 return ([],$listing);
 8892:             } else {
 8893:                 return (\@listing_results);
 8894:             }
 8895:         } elsif(!$alternateRoot) {
 8896:             my (%allusers,%listerror);
 8897: 	    my %servers = &get_servers($udom,'library');
 8898:  	    foreach my $tryserver (keys(%servers)) {
 8899:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 8900:                                   &escape($udom),$tryserver);
 8901:                 if ($listing eq 'unknown_cmd') {
 8902: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 8903: 				      $udom, $tryserver);
 8904:                 } else {
 8905:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 8906:                 }
 8907: 		if ($listing eq 'unknown_cmd') {
 8908: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 8909: 				      $udom, $tryserver);
 8910: 		    @listing_results = split(/:/,$listing);
 8911: 		} else {
 8912: 		    @listing_results =
 8913: 			map { &unescape($_); } split(/:/,$listing);
 8914: 		}
 8915:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
 8916:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
 8917:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 8918:                     $listerror{$tryserver} = $listing;
 8919:                 } else {
 8920: 		    foreach my $line (@listing_results) {
 8921: 			my ($entry) = split(/&/,$line,2);
 8922: 			$allusers{$entry} = 1;
 8923: 		    }
 8924: 		}
 8925:             }
 8926:             my @alluserslist=();
 8927:             foreach my $user (sort(keys(%allusers))) {
 8928:                 push(@alluserslist,$user.'&user');
 8929:             }
 8930:             return (\@alluserslist);
 8931:         } else {
 8932:             return ([],'missing username');
 8933:         }
 8934:     } elsif(!defined($getpropath)) {
 8935:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
 8936:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
 8937:         return (\@all_domains);
 8938:     } else {
 8939:         return ([],'missing domain');
 8940:     }
 8941: }
 8942: 
 8943: # --------------------------------------------- GetFileTimestamp
 8944: # This function utilizes dirlist and returns the date stamp for
 8945: # when it was last modified.  It will also return an error of -1
 8946: # if an error occurs
 8947: 
 8948: sub GetFileTimestamp {
 8949:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 8950:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 8951:     $studentName   = &LONCAPA::clean_username($studentName);
 8952:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
 8953:                                     undef,$getuserdir);
 8954:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 8955:         return -1;
 8956:     }
 8957:     if (ref($fileref) eq 'ARRAY') {
 8958:         my @stats = split('&',$fileref->[0]);
 8959:         # @stats contains first the filename, then the stat output
 8960:         return $stats[10]; # so this is 10 instead of 9.
 8961:     } else {
 8962:         return -1;
 8963:     }
 8964: }
 8965: 
 8966: sub stat_file {
 8967:     my ($uri) = @_;
 8968:     $uri = &clutter_with_no_wrapper($uri);
 8969: 
 8970:     my ($udom,$uname,$file);
 8971:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 8972: 	($udom,$uname,$file) =
 8973: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 8974: 	$file = 'userfiles/'.$file;
 8975:     }
 8976:     if ($uri =~ m-^/res/-) {
 8977: 	($udom,$uname) = 
 8978: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 8979: 	$file = $uri;
 8980:     }
 8981: 
 8982:     if (!$udom || !$uname || !$file) {
 8983: 	# unable to handle the uri
 8984: 	return ();
 8985:     }
 8986:     my $getpropath;
 8987:     if ($file =~ /^userfiles\//) {
 8988:         $getpropath = 1;
 8989:     }
 8990:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
 8991:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 8992:         return ();
 8993:     } else {
 8994:         if (ref($listref) eq 'ARRAY') {
 8995:             my @stats = split('&',$listref->[0]);
 8996: 	    shift(@stats); #filename is first
 8997: 	    return @stats;
 8998:         }
 8999:     }
 9000:     return ();
 9001: }
 9002: 
 9003: # -------------------------------------------------------- Value of a Condition
 9004: 
 9005: # gets the value of a specific preevaluated condition
 9006: #    stored in the string  $env{user.state.<cid>}
 9007: # or looks up a condition reference in the bighash and if if hasn't
 9008: # already been evaluated recurses into docondval to get the value of
 9009: # the condition, then memoizing it to 
 9010: #   $env{user.state.<cid>.<condition>}
 9011: sub directcondval {
 9012:     my $number=shift;
 9013:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 9014: 	&Apache::lonuserstate::evalstate();
 9015:     }
 9016:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 9017: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 9018:     } elsif ($number =~ /^_/) {
 9019: 	my $sub_condition;
 9020: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9021: 		&GDBM_READER(),0640)) {
 9022: 	    $sub_condition=$bighash{'conditions'.$number};
 9023: 	    untie(%bighash);
 9024: 	}
 9025: 	my $value = &docondval($sub_condition);
 9026: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 9027: 	return $value;
 9028:     }
 9029:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 9030:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 9031:     } else {
 9032:        return 2;
 9033:     }
 9034: }
 9035: 
 9036: # get the collection of conditions for this resource
 9037: sub condval {
 9038:     my $condidx=shift;
 9039:     my $allpathcond='';
 9040:     foreach my $cond (split(/\|/,$condidx)) {
 9041: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 9042: 	    $allpathcond.=
 9043: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 9044: 	}
 9045:     }
 9046:     $allpathcond=~s/\|$//;
 9047:     return &docondval($allpathcond);
 9048: }
 9049: 
 9050: #evaluates an expression of conditions
 9051: sub docondval {
 9052:     my ($allpathcond) = @_;
 9053:     my $result=0;
 9054:     if ($env{'request.course.id'}
 9055: 	&& defined($allpathcond)) {
 9056: 	my $operand='|';
 9057: 	my @stack;
 9058: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 9059: 	    if ($chunk eq '(') {
 9060: 		push @stack,($operand,$result);
 9061: 	    } elsif ($chunk eq ')') {
 9062: 		my $before=pop @stack;
 9063: 		if (pop @stack eq '&') {
 9064: 		    $result=$result>$before?$before:$result;
 9065: 		} else {
 9066: 		    $result=$result>$before?$result:$before;
 9067: 		}
 9068: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 9069: 		$operand=$chunk;
 9070: 	    } else {
 9071: 		my $new=directcondval($chunk);
 9072: 		if ($operand eq '&') {
 9073: 		    $result=$result>$new?$new:$result;
 9074: 		} else {
 9075: 		    $result=$result>$new?$result:$new;
 9076: 		}
 9077: 	    }
 9078: 	}
 9079:     }
 9080:     return $result;
 9081: }
 9082: 
 9083: # ---------------------------------------------------- Devalidate courseresdata
 9084: 
 9085: sub devalidatecourseresdata {
 9086:     my ($coursenum,$coursedomain)=@_;
 9087:     my $hashid=$coursenum.':'.$coursedomain;
 9088:     &devalidate_cache_new('courseres',$hashid);
 9089: }
 9090: 
 9091: 
 9092: # --------------------------------------------------- Course Resourcedata Query
 9093: #
 9094: #  Parameters:
 9095: #      $coursenum    - Number of the course.
 9096: #      $coursedomain - Domain at which the course was created.
 9097: #  Returns:
 9098: #     A hash of the course parameters along (I think) with timestamps
 9099: #     and version info.
 9100: 
 9101: sub get_courseresdata {
 9102:     my ($coursenum,$coursedomain)=@_;
 9103:     my $coursehom=&homeserver($coursenum,$coursedomain);
 9104:     my $hashid=$coursenum.':'.$coursedomain;
 9105:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 9106:     my %dumpreply;
 9107:     unless (defined($cached)) {
 9108: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 9109: 	$result=\%dumpreply;
 9110: 	my ($tmp) = keys(%dumpreply);
 9111: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9112: 	    &do_cache_new('courseres',$hashid,$result,600);
 9113: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 9114: 	    return $tmp;
 9115: 	} elsif ($tmp =~ /^(error)/) {
 9116: 	    $result=undef;
 9117: 	    &do_cache_new('courseres',$hashid,$result,600);
 9118: 	}
 9119:     }
 9120:     return $result;
 9121: }
 9122: 
 9123: sub devalidateuserresdata {
 9124:     my ($uname,$udom)=@_;
 9125:     my $hashid="$udom:$uname";
 9126:     &devalidate_cache_new('userres',$hashid);
 9127: }
 9128: 
 9129: sub get_userresdata {
 9130:     my ($uname,$udom)=@_;
 9131:     #most student don\'t have any data set, check if there is some data
 9132:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 9133: 
 9134:     my $hashid="$udom:$uname";
 9135:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 9136:     if (!defined($cached)) {
 9137: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 9138: 	$result=\%resourcedata;
 9139: 	&do_cache_new('userres',$hashid,$result,600);
 9140:     }
 9141:     my ($tmp)=keys(%$result);
 9142:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 9143: 	return $result;
 9144:     }
 9145:     #error 2 occurs when the .db doesn't exist
 9146:     if ($tmp!~/error: 2 /) {
 9147: 	&logthis("<font color=\"blue\">WARNING:".
 9148: 		 " Trying to get resource data for ".
 9149: 		 $uname." at ".$udom.": ".
 9150: 		 $tmp."</font>");
 9151:     } elsif ($tmp=~/error: 2 /) {
 9152: 	#&EXT_cache_set($udom,$uname);
 9153: 	&do_cache_new('userres',$hashid,undef,600);
 9154: 	undef($tmp); # not really an error so don't send it back
 9155:     }
 9156:     return $tmp;
 9157: }
 9158: #----------------------------------------------- resdata - return resource data
 9159: #  Purpose:
 9160: #    Return resource data for either users or for a course.
 9161: #  Parameters:
 9162: #     $name      - Course/user name.
 9163: #     $domain    - Name of the domain the user/course is registered on.
 9164: #     $type      - Type of thing $name is (must be 'course' or 'user'
 9165: #     @which     - Array of names of resources desired.
 9166: #  Returns:
 9167: #     The value of the first reasource in @which that is found in the
 9168: #     resource hash.
 9169: #  Exceptional Conditions:
 9170: #     If the $type passed in is not valid (not the string 'course' or 
 9171: #     'user', an undefined  reference is returned.
 9172: #     If none of the resources are found, an undef is returned
 9173: sub resdata {
 9174:     my ($name,$domain,$type,@which)=@_;
 9175:     my $result;
 9176:     if ($type eq 'course') {
 9177: 	$result=&get_courseresdata($name,$domain);
 9178:     } elsif ($type eq 'user') {
 9179: 	$result=&get_userresdata($name,$domain);
 9180:     }
 9181:     if (!ref($result)) { return $result; }    
 9182:     foreach my $item (@which) {
 9183: 	if (defined($result->{$item->[0]})) {
 9184: 	    return [$result->{$item->[0]},$item->[1]];
 9185: 	}
 9186:     }
 9187:     return undef;
 9188: }
 9189: 
 9190: #
 9191: # EXT resource caching routines
 9192: #
 9193: 
 9194: sub clear_EXT_cache_status {
 9195:     &delenv('cache.EXT.');
 9196: }
 9197: 
 9198: sub EXT_cache_status {
 9199:     my ($target_domain,$target_user) = @_;
 9200:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 9201:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 9202:         # We know already the user has no data
 9203:         return 1;
 9204:     } else {
 9205:         return 0;
 9206:     }
 9207: }
 9208: 
 9209: sub EXT_cache_set {
 9210:     my ($target_domain,$target_user) = @_;
 9211:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 9212:     #&appenv({$cachename => time});
 9213: }
 9214: 
 9215: # --------------------------------------------------------- Value of a Variable
 9216: sub EXT {
 9217: 
 9218:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 9219:     unless ($varname) { return ''; }
 9220:     #get real user name/domain, courseid and symb
 9221:     my $courseid;
 9222:     my $publicuser;
 9223:     if ($symbparm) {
 9224: 	$symbparm=&get_symb_from_alias($symbparm);
 9225:     }
 9226:     if (!($uname && $udom)) {
 9227:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 9228:       if (!$symbparm) {	$symbparm=$cursymb; }
 9229:     } else {
 9230: 	$courseid=$env{'request.course.id'};
 9231:     }
 9232:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 9233:     my $rest;
 9234:     if (defined($therest[0])) {
 9235:        $rest=join('.',@therest);
 9236:     } else {
 9237:        $rest='';
 9238:     }
 9239: 
 9240:     my $qualifierrest=$qualifier;
 9241:     if ($rest) { $qualifierrest.='.'.$rest; }
 9242:     my $spacequalifierrest=$space;
 9243:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 9244:     if ($realm eq 'user') {
 9245: # --------------------------------------------------------------- user.resource
 9246: 	if ($space eq 'resource') {
 9247: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 9248: 		  || defined($Apache::lonhomework::parsing_a_task))
 9249: 		 &&
 9250: 		 ($symbparm eq &symbread()) ) {	
 9251: 		# if we are in the middle of processing the resource the
 9252: 		# get the value we are planning on committing
 9253:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 9254:                     return $Apache::lonhomework::results{$qualifierrest};
 9255:                 } else {
 9256:                     return $Apache::lonhomework::history{$qualifierrest};
 9257:                 }
 9258: 	    } else {
 9259: 		my %restored;
 9260: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 9261: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 9262: 		} else {
 9263: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 9264: 		}
 9265: 		return $restored{$qualifierrest};
 9266: 	    }
 9267: # ----------------------------------------------------------------- user.access
 9268:         } elsif ($space eq 'access') {
 9269: 	    # FIXME - not supporting calls for a specific user
 9270:             return &allowed($qualifier,$rest);
 9271: # ------------------------------------------ user.preferences, user.environment
 9272:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 9273: 	    if (($uname eq $env{'user.name'}) &&
 9274: 		($udom eq $env{'user.domain'})) {
 9275: 		return $env{join('.',('environment',$qualifierrest))};
 9276: 	    } else {
 9277: 		my %returnhash;
 9278: 		if (!$publicuser) {
 9279: 		    %returnhash=&userenvironment($udom,$uname,
 9280: 						 $qualifierrest);
 9281: 		}
 9282: 		return $returnhash{$qualifierrest};
 9283: 	    }
 9284: # ----------------------------------------------------------------- user.course
 9285:         } elsif ($space eq 'course') {
 9286: 	    # FIXME - not supporting calls for a specific user
 9287:             return $env{join('.',('request.course',$qualifier))};
 9288: # ------------------------------------------------------------------- user.role
 9289:         } elsif ($space eq 'role') {
 9290: 	    # FIXME - not supporting calls for a specific user
 9291:             my ($role,$where)=split(/\./,$env{'request.role'});
 9292:             if ($qualifier eq 'value') {
 9293: 		return $role;
 9294:             } elsif ($qualifier eq 'extent') {
 9295:                 return $where;
 9296:             }
 9297: # ----------------------------------------------------------------- user.domain
 9298:         } elsif ($space eq 'domain') {
 9299:             return $udom;
 9300: # ------------------------------------------------------------------- user.name
 9301:         } elsif ($space eq 'name') {
 9302:             return $uname;
 9303: # ---------------------------------------------------- Any other user namespace
 9304:         } else {
 9305: 	    my %reply;
 9306: 	    if (!$publicuser) {
 9307: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 9308: 	    }
 9309: 	    return $reply{$qualifierrest};
 9310:         }
 9311:     } elsif ($realm eq 'query') {
 9312: # ---------------------------------------------- pull stuff out of query string
 9313:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 9314: 						[$spacequalifierrest]);
 9315: 	return $env{'form.'.$spacequalifierrest}; 
 9316:    } elsif ($realm eq 'request') {
 9317: # ------------------------------------------------------------- request.browser
 9318:         if ($space eq 'browser') {
 9319:             return $env{'browser.'.$qualifier};
 9320: # ------------------------------------------------------------ request.filename
 9321:         } else {
 9322:             return $env{'request.'.$spacequalifierrest};
 9323:         }
 9324:     } elsif ($realm eq 'course') {
 9325: # ---------------------------------------------------------- course.description
 9326:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 9327:     } elsif ($realm eq 'resource') {
 9328: 
 9329: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 9330: 	    if (!$symbparm) { $symbparm=&symbread(); }
 9331: 	}
 9332: 
 9333: 	if ($space eq 'title') {
 9334: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 9335: 	    return &gettitle($symbparm);
 9336: 	}
 9337: 	
 9338: 	if ($space eq 'map') {
 9339: 	    my ($map) = &decode_symb($symbparm);
 9340: 	    return &symbread($map);
 9341: 	}
 9342: 	if ($space eq 'filename') {
 9343: 	    if ($symbparm) {
 9344: 		return &clutter((&decode_symb($symbparm))[2]);
 9345: 	    }
 9346: 	    return &hreflocation('',$env{'request.filename'});
 9347: 	}
 9348: 
 9349: 	my ($section, $group, @groups);
 9350: 	my ($courselevelm,$courselevel);
 9351: 	if ($symbparm && defined($courseid) && 
 9352: 	    $courseid eq $env{'request.course.id'}) {
 9353: 
 9354: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 9355: 
 9356: # ----------------------------------------------------- Cascading lookup scheme
 9357: 	    my $symbp=$symbparm;
 9358: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 9359: 
 9360: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 9361: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 9362: 
 9363: 	    if (($env{'user.name'} eq $uname) &&
 9364: 		($env{'user.domain'} eq $udom)) {
 9365: 		$section=$env{'request.course.sec'};
 9366:                 @groups = split(/:/,$env{'request.course.groups'});  
 9367:                 @groups=&sort_course_groups($courseid,@groups); 
 9368: 	    } else {
 9369: 		if (! defined($usection)) {
 9370: 		    $section=&getsection($udom,$uname,$courseid);
 9371: 		} else {
 9372: 		    $section = $usection;
 9373: 		}
 9374:                 @groups = &get_users_groups($udom,$uname,$courseid);
 9375: 	    }
 9376: 
 9377: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 9378: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 9379: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 9380: 
 9381: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 9382: 	    my $courselevelr=$courseid.'.'.$symbparm;
 9383: 	    $courselevelm=$courseid.'.'.$mapparm;
 9384: 
 9385: # ----------------------------------------------------------- first, check user
 9386: 
 9387: 	    my $userreply=&resdata($uname,$udom,'user',
 9388: 				       ([$courselevelr,'resource'],
 9389: 					[$courselevelm,'map'     ],
 9390: 					[$courselevel, 'course'  ]));
 9391: 	    if (defined($userreply)) { return &get_reply($userreply); }
 9392: 
 9393: # ------------------------------------------------ second, check some of course
 9394:             my $coursereply;
 9395:             if (@groups > 0) {
 9396:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 9397:                                        $mapparm,$spacequalifierrest);
 9398:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 9399:             }
 9400: 
 9401: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 9402: 				  $env{'course.'.$courseid.'.domain'},
 9403: 				  'course',
 9404: 				  ([$seclevelr,   'resource'],
 9405: 				   [$seclevelm,   'map'     ],
 9406: 				   [$seclevel,    'course'  ],
 9407: 				   [$courselevelr,'resource']));
 9408: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 9409: 
 9410: # ------------------------------------------------------ third, check map parms
 9411: 	    my %parmhash=();
 9412: 	    my $thisparm='';
 9413: 	    if (tie(%parmhash,'GDBM_File',
 9414: 		    $env{'request.course.fn'}.'_parms.db',
 9415: 		    &GDBM_READER(),0640)) {
 9416: 		$thisparm=$parmhash{$symbparm};
 9417: 		untie(%parmhash);
 9418: 	    }
 9419: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 9420: 	}
 9421: # ------------------------------------------ fourth, look in resource metadata
 9422: 
 9423: 	$spacequalifierrest=~s/\./\_/;
 9424: 	my $filename;
 9425: 	if (!$symbparm) { $symbparm=&symbread(); }
 9426: 	if ($symbparm) {
 9427: 	    $filename=(&decode_symb($symbparm))[2];
 9428: 	} else {
 9429: 	    $filename=$env{'request.filename'};
 9430: 	}
 9431: 	my $metadata=&metadata($filename,$spacequalifierrest);
 9432: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 9433: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 9434: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 9435: 
 9436: # ---------------------------------------------- fourth, look in rest of course
 9437: 	if ($symbparm && defined($courseid) && 
 9438: 	    $courseid eq $env{'request.course.id'}) {
 9439: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 9440: 				     $env{'course.'.$courseid.'.domain'},
 9441: 				     'course',
 9442: 				     ([$courselevelm,'map'   ],
 9443: 				      [$courselevel, 'course']));
 9444: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 9445: 	}
 9446: # ------------------------------------------------------------------ Cascade up
 9447: 	unless ($space eq '0') {
 9448: 	    my @parts=split(/_/,$space);
 9449: 	    my $id=pop(@parts);
 9450: 	    my $part=join('_',@parts);
 9451: 	    if ($part eq '') { $part='0'; }
 9452: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 9453: 				 $symbparm,$udom,$uname,$section,1);
 9454: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 9455: 	}
 9456: 	if ($recurse) { return undef; }
 9457: 	my $pack_def=&packages_tab_default($filename,$varname);
 9458: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 9459: # ---------------------------------------------------- Any other user namespace
 9460:     } elsif ($realm eq 'environment') {
 9461: # ----------------------------------------------------------------- environment
 9462: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 9463: 	    return $env{'environment.'.$spacequalifierrest};
 9464: 	} else {
 9465: 	    if ($uname eq 'anonymous' && $udom eq '') {
 9466: 		return '';
 9467: 	    }
 9468: 	    my %returnhash=&userenvironment($udom,$uname,
 9469: 					    $spacequalifierrest);
 9470: 	    return $returnhash{$spacequalifierrest};
 9471: 	}
 9472:     } elsif ($realm eq 'system') {
 9473: # ----------------------------------------------------------------- system.time
 9474: 	if ($space eq 'time') {
 9475: 	    return time;
 9476:         }
 9477:     } elsif ($realm eq 'server') {
 9478: # ----------------------------------------------------------------- system.time
 9479: 	if ($space eq 'name') {
 9480: 	    return $ENV{'SERVER_NAME'};
 9481:         }
 9482:     }
 9483:     return '';
 9484: }
 9485: 
 9486: sub get_reply {
 9487:     my ($reply_value) = @_;
 9488:     if (ref($reply_value) eq 'ARRAY') {
 9489:         if (wantarray) {
 9490: 	    return @$reply_value;
 9491:         }
 9492:         return $reply_value->[0];
 9493:     } else {
 9494:         return $reply_value;
 9495:     }
 9496: }
 9497: 
 9498: sub check_group_parms {
 9499:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 9500:     my @groupitems = ();
 9501:     my $resultitem;
 9502:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 9503:     foreach my $group (@{$groups}) {
 9504:         foreach my $level (@levels) {
 9505:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 9506:              push(@groupitems,[$item,$level->[1]]);
 9507:         }
 9508:     }
 9509:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 9510:                             $env{'course.'.$courseid.'.domain'},
 9511:                                      'course',@groupitems);
 9512:     return $coursereply;
 9513: }
 9514: 
 9515: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 9516:     my ($courseid,@groups) = @_;
 9517:     @groups = sort(@groups);
 9518:     return @groups;
 9519: }
 9520: 
 9521: sub packages_tab_default {
 9522:     my ($uri,$varname)=@_;
 9523:     my (undef,$part,$name)=split(/\./,$varname);
 9524: 
 9525:     my (@extension,@specifics,$do_default);
 9526:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 9527: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 9528: 	if ($pack_type eq 'default') {
 9529: 	    $do_default=1;
 9530: 	} elsif ($pack_type eq 'extension') {
 9531: 	    push(@extension,[$package,$pack_type,$pack_part]);
 9532: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 9533: 	    # only look at packages defaults for packages that this id is
 9534: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 9535: 	}
 9536:     }
 9537:     # first look for a package that matches the requested part id
 9538:     foreach my $package (@specifics) {
 9539: 	my (undef,$pack_type,$pack_part)=@{$package};
 9540: 	next if ($pack_part ne $part);
 9541: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9542: 	    return $packagetab{"$pack_type&$name&default"};
 9543: 	}
 9544:     }
 9545:     # look for any possible matching non extension_ package
 9546:     foreach my $package (@specifics) {
 9547: 	my (undef,$pack_type,$pack_part)=@{$package};
 9548: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9549: 	    return $packagetab{"$pack_type&$name&default"};
 9550: 	}
 9551: 	if ($pack_type eq 'part') { $pack_part='0'; }
 9552: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 9553: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 9554: 	}
 9555:     }
 9556:     # look for any posible extension_ match
 9557:     foreach my $package (@extension) {
 9558: 	my ($package,$pack_type)=@{$package};
 9559: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9560: 	    return $packagetab{"$pack_type&$name&default"};
 9561: 	}
 9562: 	if (defined($packagetab{$package."&$name&default"})) {
 9563: 	    return $packagetab{$package."&$name&default"};
 9564: 	}
 9565:     }
 9566:     # look for a global default setting
 9567:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 9568: 	return $packagetab{"default&$name&default"};
 9569:     }
 9570:     return undef;
 9571: }
 9572: 
 9573: sub add_prefix_and_part {
 9574:     my ($prefix,$part)=@_;
 9575:     my $keyroot;
 9576:     if (defined($prefix) && $prefix !~ /^__/) {
 9577: 	# prefix that has a part already
 9578: 	$keyroot=$prefix;
 9579:     } elsif (defined($prefix)) {
 9580: 	# prefix that is missing a part
 9581: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 9582:     } else {
 9583: 	# no prefix at all
 9584: 	if (defined($part)) { $keyroot='_'.$part; }
 9585:     }
 9586:     return $keyroot;
 9587: }
 9588: 
 9589: # ---------------------------------------------------------------- Get metadata
 9590: 
 9591: my %metaentry;
 9592: my %importedpartids;
 9593: sub metadata {
 9594:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 9595:     $uri=&declutter($uri);
 9596:     # if it is a non metadata possible uri return quickly
 9597:     if (($uri eq '') || 
 9598: 	(($uri =~ m|^/*adm/|) && 
 9599: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 9600:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
 9601: 	return undef;
 9602:     }
 9603:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
 9604: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
 9605: 	return undef;
 9606:     }
 9607:     my $filename=$uri;
 9608:     $uri=~s/\.meta$//;
 9609: #
 9610: # Is the metadata already cached?
 9611: # Look at timestamp of caching
 9612: # Everything is cached by the main uri, libraries are never directly cached
 9613: #
 9614:     if (!defined($liburi)) {
 9615: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 9616: 	if (defined($cached)) { return $result->{':'.$what}; }
 9617:     }
 9618:     {
 9619: # Imported parts would go here
 9620:         my %importedids=();
 9621:         my @origfileimportpartids=();
 9622:         my $importedparts=0;
 9623: #
 9624: # Is this a recursive call for a library?
 9625: #
 9626: #	if (! exists($metacache{$uri})) {
 9627: #	    $metacache{$uri}={};
 9628: #	}
 9629: 	my $cachetime = 60*60;
 9630:         if ($liburi) {
 9631: 	    $liburi=&declutter($liburi);
 9632:             $filename=$liburi;
 9633:         } else {
 9634: 	    &devalidate_cache_new('meta',$uri);
 9635: 	    undef(%metaentry);
 9636: 	}
 9637:         my %metathesekeys=();
 9638:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 9639: 	my $metastring;
 9640: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
 9641: 	    my $which = &hreflocation('','/'.($liburi || $uri));
 9642: 	    $metastring = 
 9643: 		&Apache::lonnet::ssi_body($which,
 9644: 					  ('grade_target' => 'meta'));
 9645: 	    $cachetime = 1; # only want this cached in the child not long term
 9646: 	} elsif (($uri !~ m -^(editupload)/-) && 
 9647:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
 9648: 	    my $file=&filelocation('',&clutter($filename));
 9649: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 9650: 	    $metastring=&getfile($file);
 9651: 	}
 9652:         my $parser=HTML::LCParser->new(\$metastring);
 9653:         my $token;
 9654:         undef %metathesekeys;
 9655:         while ($token=$parser->get_token) {
 9656: 	    if ($token->[0] eq 'S') {
 9657: 		if (defined($token->[2]->{'package'})) {
 9658: #
 9659: # This is a package - get package info
 9660: #
 9661: 		    my $package=$token->[2]->{'package'};
 9662: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9663: 		    if (defined($token->[2]->{'id'})) { 
 9664: 			$keyroot.='_'.$token->[2]->{'id'}; 
 9665: 		    }
 9666: 		    if ($metaentry{':packages'}) {
 9667: 			$metaentry{':packages'}.=','.$package.$keyroot;
 9668: 		    } else {
 9669: 			$metaentry{':packages'}=$package.$keyroot;
 9670: 		    }
 9671: 		    foreach my $pack_entry (keys(%packagetab)) {
 9672: 			my $part=$keyroot;
 9673: 			$part=~s/^\_//;
 9674: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 9675: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 9676: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 9677: 			    # ignore package.tab specified default values
 9678:                             # here &package_tab_default() will fetch those
 9679: 			    if ($subp eq 'default') { next; }
 9680: 			    my $value=$packagetab{$pack_entry};
 9681: 			    my $unikey;
 9682: 			    if ($pack =~ /_0$/) {
 9683: 				$unikey='parameter_0_'.$name;
 9684: 				$part=0;
 9685: 			    } else {
 9686: 				$unikey='parameter'.$keyroot.'_'.$name;
 9687: 			    }
 9688: 			    if ($subp eq 'display') {
 9689: 				$value.=' [Part: '.$part.']';
 9690: 			    }
 9691: 			    $metaentry{':'.$unikey.'.part'}=$part;
 9692: 			    $metathesekeys{$unikey}=1;
 9693: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 9694: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 9695: 			    }
 9696: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 9697: 				$metaentry{':'.$unikey}=
 9698: 				    $metaentry{':'.$unikey.'.default'};
 9699: 			    }
 9700: 			}
 9701: 		    }
 9702: 		} else {
 9703: #
 9704: # This is not a package - some other kind of start tag
 9705: #
 9706: 		    my $entry=$token->[1];
 9707: 		    my $unikey='';
 9708: 
 9709: 		    if ($entry eq 'import') {
 9710: #
 9711: # Importing a library here
 9712: #
 9713:                         my $location=$parser->get_text('/import');
 9714:                         my $dir=$filename;
 9715:                         $dir=~s|[^/]*$||;
 9716:                         $location=&filelocation($dir,$location);
 9717:                        
 9718:                         my $importmode=$token->[2]->{'importmode'};
 9719:                         if ($importmode eq 'problem') {
 9720: # Import as problem/response
 9721:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9722:                         } elsif ($importmode eq 'part') {
 9723: # Import as part(s)
 9724:                            $importedparts=1;
 9725: # We need to get the original file and the imported file to get the part order correct
 9726: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
 9727: # Load and inspect original file
 9728:                            if ($#origfileimportpartids<0) {
 9729:                               undef(%importedpartids);
 9730:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
 9731:                               my $origfile=&getfile($origfilelocation);
 9732:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
 9733:                            }
 9734: 
 9735: # Load and inspect imported file
 9736:                            my $impfile=&getfile($location);
 9737:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
 9738:                            if ($#impfilepartids>=0) {
 9739: # This problem had parts
 9740:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
 9741:                            } else {
 9742: # Importing by turning a single problem into a problem part
 9743: # It gets the import-tags ID as part-ID
 9744:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
 9745:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
 9746:                            }
 9747:                         } else {
 9748: # Normal import
 9749:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9750:                            if (defined($token->[2]->{'id'})) {
 9751:                               $unikey.='_'.$token->[2]->{'id'};
 9752:                            }
 9753:                         }
 9754: 
 9755: 			if ($depthcount<20) {
 9756: 			    my $metadata = 
 9757: 				&metadata($uri,'keys', $location,$unikey,
 9758: 					  $depthcount+1);
 9759: 			    foreach my $meta (split(',',$metadata)) {
 9760: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 9761: 				$metathesekeys{$meta}=1;
 9762: 			    }
 9763: 			
 9764:                         }
 9765: 		    } else {
 9766: #
 9767: # Not importing, some other kind of non-package, non-library start tag
 9768: # 
 9769:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9770:                         if (defined($token->[2]->{'id'})) {
 9771:                             $unikey.='_'.$token->[2]->{'id'};
 9772:                         }
 9773: 			if (defined($token->[2]->{'name'})) { 
 9774: 			    $unikey.='_'.$token->[2]->{'name'}; 
 9775: 			}
 9776: 			$metathesekeys{$unikey}=1;
 9777: 			foreach my $param (@{$token->[3]}) {
 9778: 			    $metaentry{':'.$unikey.'.'.$param} =
 9779: 				$token->[2]->{$param};
 9780: 			}
 9781: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 9782: 			my $default=$metaentry{':'.$unikey.'.default'};
 9783: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 9784: 		 # only ws inside the tag, and not in default, so use default
 9785: 		 # as value
 9786: 			    $metaentry{':'.$unikey}=$default;
 9787: 			} elsif ( $internaltext =~ /\S/ ) {
 9788: 		  # something interesting inside the tag
 9789: 			    $metaentry{':'.$unikey}=$internaltext;
 9790: 			} else {
 9791: 		  # no interesting values, don't set a default
 9792: 			}
 9793: # end of not-a-package not-a-library import
 9794: 		    }
 9795: # end of not-a-package start tag
 9796: 		}
 9797: # the next is the end of "start tag"
 9798: 	    }
 9799: 	}
 9800: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 9801: 	$extension = lc($extension);
 9802: 	if ($extension eq 'htm') { $extension='html'; }
 9803: 
 9804: 	foreach my $key (keys(%packagetab)) {
 9805: 	    #no specific packages #how's our extension
 9806: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 9807: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 9808: 					 \%metathesekeys);
 9809: 	}
 9810: 
 9811: 	if (!exists($metaentry{':packages'})
 9812: 	    || $packagetab{"import_defaults&extension_$extension"}) {
 9813: 	    foreach my $key (keys(%packagetab)) {
 9814: 		#no specific packages well let's get default then
 9815: 		if ($key!~/^default&/) { next; }
 9816: 		&metadata_create_package_def($uri,$key,'default',
 9817: 					     \%metathesekeys);
 9818: 	    }
 9819: 	}
 9820: # are there custom rights to evaluate
 9821: 	if ($metaentry{':copyright'} eq 'custom') {
 9822: 
 9823:     #
 9824:     # Importing a rights file here
 9825:     #
 9826: 	    unless ($depthcount) {
 9827: 		my $location=$metaentry{':customdistributionfile'};
 9828: 		my $dir=$filename;
 9829: 		$dir=~s|[^/]*$||;
 9830: 		$location=&filelocation($dir,$location);
 9831: 		my $rights_metadata =
 9832: 		    &metadata($uri,'keys',$location,'_rights',
 9833: 			      $depthcount+1);
 9834: 		foreach my $rights (split(',',$rights_metadata)) {
 9835: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 9836: 		    $metathesekeys{$rights}=1;
 9837: 		}
 9838: 	    }
 9839: 	}
 9840: 	# uniqifiy package listing
 9841: 	my %seen;
 9842: 	my @uniq_packages =
 9843: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 9844: 	$metaentry{':packages'} = join(',',@uniq_packages);
 9845: 
 9846:         if ($importedparts) {
 9847: # We had imported parts and need to rebuild partorder
 9848:            $metaentry{':partorder'}='';
 9849:            $metathesekeys{'partorder'}=1;
 9850:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
 9851:                if ($origfileimportpartids[$index] eq 'part') {
 9852: # original part, part of the problem
 9853:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
 9854:                } else {
 9855: # we have imported parts at this position
 9856:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
 9857:                }
 9858:            }
 9859:            $metaentry{':partorder'}=~s/^\,//;
 9860:         }
 9861: 
 9862: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 9863: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 9864: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 9865: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
 9866: # this is the end of "was not already recently cached
 9867:     }
 9868:     return $metaentry{':'.$what};
 9869: }
 9870: 
 9871: sub metadata_create_package_def {
 9872:     my ($uri,$key,$package,$metathesekeys)=@_;
 9873:     my ($pack,$name,$subp)=split(/\&/,$key);
 9874:     if ($subp eq 'default') { next; }
 9875:     
 9876:     if (defined($metaentry{':packages'})) {
 9877: 	$metaentry{':packages'}.=','.$package;
 9878:     } else {
 9879: 	$metaentry{':packages'}=$package;
 9880:     }
 9881:     my $value=$packagetab{$key};
 9882:     my $unikey;
 9883:     $unikey='parameter_0_'.$name;
 9884:     $metaentry{':'.$unikey.'.part'}=0;
 9885:     $$metathesekeys{$unikey}=1;
 9886:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 9887: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 9888:     }
 9889:     if (defined($metaentry{':'.$unikey.'.default'})) {
 9890: 	$metaentry{':'.$unikey}=
 9891: 	    $metaentry{':'.$unikey.'.default'};
 9892:     }
 9893: }
 9894: 
 9895: sub metadata_generate_part0 {
 9896:     my ($metadata,$metacache,$uri) = @_;
 9897:     my %allnames;
 9898:     foreach my $metakey (keys(%$metadata)) {
 9899: 	if ($metakey=~/^parameter\_(.*)/) {
 9900: 	  my $part=$$metacache{':'.$metakey.'.part'};
 9901: 	  my $name=$$metacache{':'.$metakey.'.name'};
 9902: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 9903: 	    $allnames{$name}=$part;
 9904: 	  }
 9905: 	}
 9906:     }
 9907:     foreach my $name (keys(%allnames)) {
 9908:       $$metadata{"parameter_0_$name"}=1;
 9909:       my $key=":parameter_0_$name";
 9910:       $$metacache{"$key.part"}='0';
 9911:       $$metacache{"$key.name"}=$name;
 9912:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 9913: 					   $allnames{$name}.'_'.$name.
 9914: 					   '.type'};
 9915:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 9916: 			     '.display'};
 9917:       my $expr='[Part: '.$allnames{$name}.']';
 9918:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 9919:       $$metacache{"$key.display"}=$olddis;
 9920:     }
 9921: }
 9922: 
 9923: # ------------------------------------------------------ Devalidate title cache
 9924: 
 9925: sub devalidate_title_cache {
 9926:     my ($url)=@_;
 9927:     if (!$env{'request.course.id'}) { return; }
 9928:     my $symb=&symbread($url);
 9929:     if (!$symb) { return; }
 9930:     my $key=$env{'request.course.id'}."\0".$symb;
 9931:     &devalidate_cache_new('title',$key);
 9932: }
 9933: 
 9934: # ------------------------------------------------- Get the title of a course
 9935: 
 9936: sub current_course_title {
 9937:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
 9938: }
 9939: # ------------------------------------------------- Get the title of a resource
 9940: 
 9941: sub gettitle {
 9942:     my $urlsymb=shift;
 9943:     my $symb=&symbread($urlsymb);
 9944:     if ($symb) {
 9945: 	my $key=$env{'request.course.id'}."\0".$symb;
 9946: 	my ($result,$cached)=&is_cached_new('title',$key);
 9947: 	if (defined($cached)) { 
 9948: 	    return $result;
 9949: 	}
 9950: 	my ($map,$resid,$url)=&decode_symb($symb);
 9951: 	my $title='';
 9952: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
 9953: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
 9954: 	} else {
 9955: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9956: 		    &GDBM_READER(),0640)) {
 9957: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
 9958: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
 9959: 		untie(%bighash);
 9960: 	    }
 9961: 	}
 9962: 	$title=~s/\&colon\;/\:/gs;
 9963: 	if ($title) {
 9964: # Remember both $symb and $title for dynamic metadata
 9965:             $accesshash{$symb.'___crstitle'}=$title;
 9966:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
 9967: # Cache this title and then return it
 9968: 	    return &do_cache_new('title',$key,$title,600);
 9969: 	}
 9970: 	$urlsymb=$url;
 9971:     }
 9972:     my $title=&metadata($urlsymb,'title');
 9973:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 9974:     return $title;
 9975: }
 9976: 
 9977: sub get_slot {
 9978:     my ($which,$cnum,$cdom)=@_;
 9979:     if (!$cnum || !$cdom) {
 9980: 	(undef,my $courseid)=&whichuser();
 9981: 	$cdom=$env{'course.'.$courseid.'.domain'};
 9982: 	$cnum=$env{'course.'.$courseid.'.num'};
 9983:     }
 9984:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 9985:     my %slotinfo;
 9986:     if (exists($remembered{$key})) {
 9987: 	$slotinfo{$which} = $remembered{$key};
 9988:     } else {
 9989: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 9990: 	&Apache::lonhomework::showhash(%slotinfo);
 9991: 	my ($tmp)=keys(%slotinfo);
 9992: 	if ($tmp=~/^error:/) { return (); }
 9993: 	$remembered{$key} = $slotinfo{$which};
 9994:     }
 9995:     if (ref($slotinfo{$which}) eq 'HASH') {
 9996: 	return %{$slotinfo{$which}};
 9997:     }
 9998:     return $slotinfo{$which};
 9999: }
10000: 
10001: sub get_reservable_slots {
10002:     my ($cnum,$cdom,$uname,$udom) = @_;
10003:     my $now = time;
10004:     my $reservable_info;
10005:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10006:     if (exists($remembered{$key})) {
10007:         $reservable_info = $remembered{$key};
10008:     } else {
10009:         my %resv;
10010:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10011:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10012:         $reservable_info = \%resv;
10013:         $remembered{$key} = $reservable_info;
10014:     }
10015:     return $reservable_info;
10016: }
10017: 
10018: sub get_course_slots {
10019:     my ($cnum,$cdom) = @_;
10020:     my $hashid=$cnum.':'.$cdom;
10021:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10022:     if (defined($cached)) {
10023:         if (ref($result) eq 'HASH') {
10024:             return %{$result};
10025:         }
10026:     } else {
10027:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10028:         my ($tmp) = keys(%slots);
10029:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10030:             &Apache::lonnet::do_cache_new('allslots',$hashid,\%slots,600);
10031:             return %slots;
10032:         }
10033:     }
10034:     return;
10035: }
10036: 
10037: sub devalidate_slots_cache {
10038:     my ($cnum,$cdom)=@_;
10039:     my $hashid=$cnum.':'.$cdom;
10040:     &devalidate_cache_new('allslots',$hashid);
10041: }
10042: 
10043: sub get_coursechange {
10044:     my ($cdom,$cnum) = @_;
10045:     if ($cdom eq '' || $cnum eq '') {
10046:         return unless ($env{'request.course.id'});
10047:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10048:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10049:     }
10050:     my $hashid=$cdom.'_'.$cnum;
10051:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
10052:     if ((defined($cached)) && ($change ne '')) {
10053:         return $change;
10054:     } else {
10055:         my %crshash;
10056:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10057:         if ($crshash{'internal.contentchange'} eq '') {
10058:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
10059:             if ($change eq '') {
10060:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
10061:                 $change = $crshash{'internal.created'};
10062:             }
10063:         } else {
10064:             $change = $crshash{'internal.contentchange'};
10065:         }
10066:         my $cachetime = 600;
10067:         &do_cache_new('crschange',$hashid,$change,$cachetime);
10068:     }
10069:     return $change;
10070: }
10071: 
10072: sub devalidate_coursechange_cache {
10073:     my ($cnum,$cdom)=@_;
10074:     my $hashid=$cnum.':'.$cdom;
10075:     &devalidate_cache_new('crschange',$hashid);
10076: }
10077: 
10078: # ------------------------------------------------- Update symbolic store links
10079: 
10080: sub symblist {
10081:     my ($mapname,%newhash)=@_;
10082:     $mapname=&deversion(&declutter($mapname));
10083:     my %hash;
10084:     if (($env{'request.course.fn'}) && (%newhash)) {
10085:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10086:                       &GDBM_WRCREAT(),0640)) {
10087: 	    foreach my $url (keys(%newhash)) {
10088: 		next if ($url eq 'last_known'
10089: 			 && $env{'form.no_update_last_known'});
10090: 		$hash{declutter($url)}=&encode_symb($mapname,
10091: 						    $newhash{$url}->[1],
10092: 						    $newhash{$url}->[0]);
10093:             }
10094:             if (untie(%hash)) {
10095: 		return 'ok';
10096:             }
10097:         }
10098:     }
10099:     return 'error';
10100: }
10101: 
10102: # --------------------------------------------------------------- Verify a symb
10103: 
10104: sub symbverify {
10105:     my ($symb,$thisurl,$encstate)=@_;
10106:     my $thisfn=$thisurl;
10107:     $thisfn=&declutter($thisfn);
10108: # direct jump to resource in page or to a sequence - will construct own symbs
10109:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10110: # check URL part
10111:     my ($map,$resid,$url)=&decode_symb($symb);
10112: 
10113:     unless ($url eq $thisfn) { return 0; }
10114: 
10115:     $symb=&symbclean($symb);
10116:     $thisurl=&deversion($thisurl);
10117:     $thisfn=&deversion($thisfn);
10118: 
10119:     my %bighash;
10120:     my $okay=0;
10121: 
10122:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10123:                             &GDBM_READER(),0640)) {
10124:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10125:             $thisurl =~ s/\?.+$//;
10126:         }
10127:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
10128:         unless ($ids) {
10129:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
10130:             $ids=$bighash{$idkey};
10131:         }
10132:         if ($ids) {
10133: # ------------------------------------------------------------------- Has ID(s)
10134: 	    foreach my $id (split(/\,/,$ids)) {
10135: 	       my ($mapid,$resid)=split(/\./,$id);
10136:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
10137:                    $symb =~ s/\?.+$//;
10138:                }
10139:                if (
10140:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
10141:    eq $symb) {
10142:                    if (ref($encstate)) {
10143:                        $$encstate = $bighash{'encrypted_'.$id};
10144:                    }
10145: 		   if (($env{'request.role.adv'}) ||
10146: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
10147:                        ($thisurl eq '/adm/navmaps')) {
10148: 		       $okay=1;
10149: 		   }
10150: 	       }
10151: 	   }
10152:         }
10153: 	untie(%bighash);
10154:     }
10155:     return $okay;
10156: }
10157: 
10158: # --------------------------------------------------------------- Clean-up symb
10159: 
10160: sub symbclean {
10161:     my $symb=shift;
10162:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10163: # remove version from map
10164:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
10165: 
10166: # remove version from URL
10167:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
10168: 
10169: # remove wrapper
10170: 
10171:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
10172:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
10173:     return $symb;
10174: }
10175: 
10176: # ---------------------------------------------- Split symb to find map and url
10177: 
10178: sub encode_symb {
10179:     my ($map,$resid,$url)=@_;
10180:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
10181: }
10182: 
10183: sub decode_symb {
10184:     my $symb=shift;
10185:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10186:     my ($map,$resid,$url)=split(/___/,$symb);
10187:     return (&fixversion($map),$resid,&fixversion($url));
10188: }
10189: 
10190: sub fixversion {
10191:     my $fn=shift;
10192:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
10193:     my %bighash;
10194:     my $uri=&clutter($fn);
10195:     my $key=$env{'request.course.id'}.'_'.$uri;
10196: # is this cached?
10197:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
10198:     if (defined($cached)) { return $result; }
10199: # unfortunately not cached, or expired
10200:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10201: 	    &GDBM_READER(),0640)) {
10202:  	if ($bighash{'version_'.$uri}) {
10203:  	    my $version=$bighash{'version_'.$uri};
10204:  	    unless (($version eq 'mostrecent') || 
10205: 		    ($version==&getversion($uri))) {
10206:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
10207:  	    }
10208:  	}
10209:  	untie %bighash;
10210:     }
10211:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
10212: }
10213: 
10214: sub deversion {
10215:     my $url=shift;
10216:     $url=~s/\.\d+\.(\w+)$/\.$1/;
10217:     return $url;
10218: }
10219: 
10220: # ------------------------------------------------------ Return symb list entry
10221: 
10222: sub symbread {
10223:     my ($thisfn,$donotrecurse)=@_;
10224:     my $cache_str='request.symbread.cached.'.$thisfn;
10225:     if (defined($env{$cache_str})) {
10226:         if (($thisfn) || ($env{$cache_str} ne '')) {
10227:             return $env{$cache_str};
10228:         }
10229:     }
10230: # no filename provided? try from environment
10231:     unless ($thisfn) {
10232:         if ($env{'request.symb'}) {
10233: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
10234: 	}
10235: 	$thisfn=$env{'request.filename'};
10236:     }
10237:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
10238: # is that filename actually a symb? Verify, clean, and return
10239:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
10240: 	if (&symbverify($thisfn,$1)) {
10241: 	    return $env{$cache_str}=&symbclean($thisfn);
10242: 	}
10243:     }
10244:     $thisfn=declutter($thisfn);
10245:     my %hash;
10246:     my %bighash;
10247:     my $syval='';
10248:     if (($env{'request.course.fn'}) && ($thisfn)) {
10249:         my $targetfn = $thisfn;
10250:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
10251:             $targetfn = 'adm/wrapper/'.$thisfn;
10252:         }
10253: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
10254: 	    $targetfn=$1;
10255: 	}
10256:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10257:                       &GDBM_READER(),0640)) {
10258: 	    $syval=$hash{$targetfn};
10259:             untie(%hash);
10260:         }
10261: # ---------------------------------------------------------- There was an entry
10262:         if ($syval) {
10263: 	    #unless ($syval=~/\_\d+$/) {
10264: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
10265: 		    #&appenv({'request.ambiguous' => $thisfn});
10266: 		    #return $env{$cache_str}='';
10267: 		#}    
10268: 		#$syval.=$1;
10269: 	    #}
10270:         } else {
10271: # ------------------------------------------------------- Was not in symb table
10272:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10273:                             &GDBM_READER(),0640)) {
10274: # ---------------------------------------------- Get ID(s) for current resource
10275:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
10276:               unless ($ids) { 
10277:                  $ids=$bighash{'ids_/'.$thisfn};
10278:               }
10279:               unless ($ids) {
10280: # alias?
10281: 		  $ids=$bighash{'mapalias_'.$thisfn};
10282:               }
10283:               if ($ids) {
10284: # ------------------------------------------------------------------- Has ID(s)
10285:                  my @possibilities=split(/\,/,$ids);
10286:                  if ($#possibilities==0) {
10287: # ----------------------------------------------- There is only one possibility
10288: 		     my ($mapid,$resid)=split(/\./,$ids);
10289: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
10290: 						    $resid,$thisfn);
10291:                  } elsif (!$donotrecurse) {
10292: # ------------------------------------------ There is more than one possibility
10293:                      my $realpossible=0;
10294:                      foreach my $id (@possibilities) {
10295: 			 my $file=$bighash{'src_'.$id};
10296:                          if (&allowed('bre',$file)) {
10297:          		    my ($mapid,$resid)=split(/\./,$id);
10298:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
10299: 				$realpossible++;
10300:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
10301: 						    $resid,$thisfn);
10302:                             }
10303: 			 }
10304:                      }
10305: 		     if ($realpossible!=1) { $syval=''; }
10306:                  } else {
10307:                      $syval='';
10308:                  }
10309: 	      }
10310:               untie(%bighash)
10311:            }
10312:         }
10313:         if ($syval) {
10314: 	    return $env{$cache_str}=$syval;
10315:         }
10316:     }
10317:     &appenv({'request.ambiguous' => $thisfn});
10318:     return $env{$cache_str}='';
10319: }
10320: 
10321: # ---------------------------------------------------------- Return random seed
10322: 
10323: sub numval {
10324:     my $txt=shift;
10325:     $txt=~tr/A-J/0-9/;
10326:     $txt=~tr/a-j/0-9/;
10327:     $txt=~tr/K-T/0-9/;
10328:     $txt=~tr/k-t/0-9/;
10329:     $txt=~tr/U-Z/0-5/;
10330:     $txt=~tr/u-z/0-5/;
10331:     $txt=~s/\D//g;
10332:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
10333:     return int($txt);
10334: }
10335: 
10336: sub numval2 {
10337:     my $txt=shift;
10338:     $txt=~tr/A-J/0-9/;
10339:     $txt=~tr/a-j/0-9/;
10340:     $txt=~tr/K-T/0-9/;
10341:     $txt=~tr/k-t/0-9/;
10342:     $txt=~tr/U-Z/0-5/;
10343:     $txt=~tr/u-z/0-5/;
10344:     $txt=~s/\D//g;
10345:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10346:     my $total;
10347:     foreach my $val (@txts) { $total+=$val; }
10348:     if ($_64bit) { if ($total > 2**32) { return -1; } }
10349:     return int($total);
10350: }
10351: 
10352: sub numval3 {
10353:     use integer;
10354:     my $txt=shift;
10355:     $txt=~tr/A-J/0-9/;
10356:     $txt=~tr/a-j/0-9/;
10357:     $txt=~tr/K-T/0-9/;
10358:     $txt=~tr/k-t/0-9/;
10359:     $txt=~tr/U-Z/0-5/;
10360:     $txt=~tr/u-z/0-5/;
10361:     $txt=~s/\D//g;
10362:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10363:     my $total;
10364:     foreach my $val (@txts) { $total+=$val; }
10365:     if ($_64bit) { $total=(($total<<32)>>32); }
10366:     return $total;
10367: }
10368: 
10369: sub digest {
10370:     my ($data)=@_;
10371:     my $digest=&Digest::MD5::md5($data);
10372:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
10373:     my ($e,$f);
10374:     {
10375:         use integer;
10376:         $e=($a+$b);
10377:         $f=($c+$d);
10378:         if ($_64bit) {
10379:             $e=(($e<<32)>>32);
10380:             $f=(($f<<32)>>32);
10381:         }
10382:     }
10383:     if (wantarray) {
10384: 	return ($e,$f);
10385:     } else {
10386: 	my $g;
10387: 	{
10388: 	    use integer;
10389: 	    $g=($e+$f);
10390: 	    if ($_64bit) {
10391: 		$g=(($g<<32)>>32);
10392: 	    }
10393: 	}
10394: 	return $g;
10395:     }
10396: }
10397: 
10398: sub latest_rnd_algorithm_id {
10399:     return '64bit5';
10400: }
10401: 
10402: sub get_rand_alg {
10403:     my ($courseid)=@_;
10404:     if (!$courseid) { $courseid=(&whichuser())[1]; }
10405:     if ($courseid) {
10406: 	return $env{"course.$courseid.rndseed"};
10407:     }
10408:     return &latest_rnd_algorithm_id();
10409: }
10410: 
10411: sub validCODE {
10412:     my ($CODE)=@_;
10413:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
10414:     return 0;
10415: }
10416: 
10417: sub getCODE {
10418:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
10419:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
10420: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
10421: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
10422: 	return $Apache::lonhomework::history{'resource.CODE'};
10423:     }
10424:     return undef;
10425: }
10426: #
10427: #  Determines the random seed for a specific context:
10428: #
10429: # parameters:
10430: #   symb      - in course context the symb for the seed.
10431: #   course_id - The course id of the form domain_coursenum.
10432: #   domain    - Domain for the user.
10433: #   course    - Course for the user.
10434: #   cenv      - environment of the course.
10435: #
10436: # NOTE:
10437: #   All parameters are picked out of the environment if missing
10438: #   or not defined.
10439: #   If a symb cannot be determined the current time is used instead.
10440: #
10441: #  For a given well defined symb, courside, domain, username,
10442: #  and course environment, the seed is reproducible.
10443: #
10444: sub rndseed {
10445:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
10446:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
10447:     if (!defined($symb)) {
10448: 	unless ($symb=$wsymb) { return time; }
10449:     }
10450:     if (!defined $courseid) { 
10451: 	$courseid=$wcourseid; 
10452:     }
10453:     if (!defined $domain) { $domain=$wdomain; }
10454:     if (!defined $username) { $username=$wusername }
10455: 
10456:     my $which;
10457:     if (defined($cenv->{'rndseed'})) {
10458: 	$which = $cenv->{'rndseed'};
10459:     } else {
10460: 	$which =&get_rand_alg($courseid);
10461:     }
10462:     if (defined(&getCODE())) {
10463: 
10464: 	if ($which eq '64bit5') {
10465: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
10466: 	} elsif ($which eq '64bit4') {
10467: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
10468: 	} else {
10469: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
10470: 	}
10471:     } elsif ($which eq '64bit5') {
10472: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
10473:     } elsif ($which eq '64bit4') {
10474: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
10475:     } elsif ($which eq '64bit3') {
10476: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
10477:     } elsif ($which eq '64bit2') {
10478: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
10479:     } elsif ($which eq '64bit') {
10480: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
10481:     }
10482:     return &rndseed_32bit($symb,$courseid,$domain,$username);
10483: }
10484: 
10485: sub rndseed_32bit {
10486:     my ($symb,$courseid,$domain,$username)=@_;
10487:     {
10488: 	use integer;
10489: 	my $symbchck=unpack("%32C*",$symb) << 27;
10490: 	my $symbseed=numval($symb) << 22;
10491: 	my $namechck=unpack("%32C*",$username) << 17;
10492: 	my $nameseed=numval($username) << 12;
10493: 	my $domainseed=unpack("%32C*",$domain) << 7;
10494: 	my $courseseed=unpack("%32C*",$courseid);
10495: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
10496: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10497: 	#&logthis("rndseed :$num:$symb");
10498: 	if ($_64bit) { $num=(($num<<32)>>32); }
10499: 	return $num;
10500:     }
10501: }
10502: 
10503: sub rndseed_64bit {
10504:     my ($symb,$courseid,$domain,$username)=@_;
10505:     {
10506: 	use integer;
10507: 	my $symbchck=unpack("%32S*",$symb) << 21;
10508: 	my $symbseed=numval($symb) << 10;
10509: 	my $namechck=unpack("%32S*",$username);
10510: 	
10511: 	my $nameseed=numval($username) << 21;
10512: 	my $domainseed=unpack("%32S*",$domain) << 10;
10513: 	my $courseseed=unpack("%32S*",$courseid);
10514: 	
10515: 	my $num1=$symbchck+$symbseed+$namechck;
10516: 	my $num2=$nameseed+$domainseed+$courseseed;
10517: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10518: 	#&logthis("rndseed :$num:$symb");
10519: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10520: 	return "$num1,$num2";
10521:     }
10522: }
10523: 
10524: sub rndseed_64bit2 {
10525:     my ($symb,$courseid,$domain,$username)=@_;
10526:     {
10527: 	use integer;
10528: 	# strings need to be an even # of cahracters long, it it is odd the
10529:         # last characters gets thrown away
10530: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
10531: 	my $symbseed=numval($symb) << 10;
10532: 	my $namechck=unpack("%32S*",$username.' ');
10533: 	
10534: 	my $nameseed=numval($username) << 21;
10535: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
10536: 	my $courseseed=unpack("%32S*",$courseid.' ');
10537: 	
10538: 	my $num1=$symbchck+$symbseed+$namechck;
10539: 	my $num2=$nameseed+$domainseed+$courseseed;
10540: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10541: 	#&logthis("rndseed :$num:$symb");
10542: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10543: 	return "$num1,$num2";
10544:     }
10545: }
10546: 
10547: sub rndseed_64bit3 {
10548:     my ($symb,$courseid,$domain,$username)=@_;
10549:     {
10550: 	use integer;
10551: 	# strings need to be an even # of cahracters long, it it is odd the
10552:         # last characters gets thrown away
10553: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
10554: 	my $symbseed=numval2($symb) << 10;
10555: 	my $namechck=unpack("%32S*",$username.' ');
10556: 	
10557: 	my $nameseed=numval2($username) << 21;
10558: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
10559: 	my $courseseed=unpack("%32S*",$courseid.' ');
10560: 	
10561: 	my $num1=$symbchck+$symbseed+$namechck;
10562: 	my $num2=$nameseed+$domainseed+$courseseed;
10563: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10564: 	#&logthis("rndseed :$num1:$num2:$_64bit");
10565: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10566: 	
10567: 	return "$num1:$num2";
10568:     }
10569: }
10570: 
10571: sub rndseed_64bit4 {
10572:     my ($symb,$courseid,$domain,$username)=@_;
10573:     {
10574: 	use integer;
10575: 	# strings need to be an even # of cahracters long, it it is odd the
10576:         # last characters gets thrown away
10577: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
10578: 	my $symbseed=numval3($symb) << 10;
10579: 	my $namechck=unpack("%32S*",$username.' ');
10580: 	
10581: 	my $nameseed=numval3($username) << 21;
10582: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
10583: 	my $courseseed=unpack("%32S*",$courseid.' ');
10584: 	
10585: 	my $num1=$symbchck+$symbseed+$namechck;
10586: 	my $num2=$nameseed+$domainseed+$courseseed;
10587: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10588: 	#&logthis("rndseed :$num1:$num2:$_64bit");
10589: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10590: 	
10591: 	return "$num1:$num2";
10592:     }
10593: }
10594: 
10595: sub rndseed_64bit5 {
10596:     my ($symb,$courseid,$domain,$username)=@_;
10597:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
10598:     return "$num1:$num2";
10599: }
10600: 
10601: sub rndseed_CODE_64bit {
10602:     my ($symb,$courseid,$domain,$username)=@_;
10603:     {
10604: 	use integer;
10605: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
10606: 	my $symbseed=numval2($symb);
10607: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
10608: 	my $CODEseed=numval(&getCODE());
10609: 	my $courseseed=unpack("%32S*",$courseid.' ');
10610: 	my $num1=$symbseed+$CODEchck;
10611: 	my $num2=$CODEseed+$courseseed+$symbchck;
10612: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
10613: 	#&logthis("rndseed :$num1:$num2:$symb");
10614: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
10615: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
10616: 	return "$num1:$num2";
10617:     }
10618: }
10619: 
10620: sub rndseed_CODE_64bit4 {
10621:     my ($symb,$courseid,$domain,$username)=@_;
10622:     {
10623: 	use integer;
10624: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
10625: 	my $symbseed=numval3($symb);
10626: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
10627: 	my $CODEseed=numval3(&getCODE());
10628: 	my $courseseed=unpack("%32S*",$courseid.' ');
10629: 	my $num1=$symbseed+$CODEchck;
10630: 	my $num2=$CODEseed+$courseseed+$symbchck;
10631: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
10632: 	#&logthis("rndseed :$num1:$num2:$symb");
10633: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
10634: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
10635: 	return "$num1:$num2";
10636:     }
10637: }
10638: 
10639: sub rndseed_CODE_64bit5 {
10640:     my ($symb,$courseid,$domain,$username)=@_;
10641:     my $code = &getCODE();
10642:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
10643:     return "$num1:$num2";
10644: }
10645: 
10646: sub setup_random_from_rndseed {
10647:     my ($rndseed)=@_;
10648:     if ($rndseed =~/([,:])/) {
10649: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
10650: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
10651:     } else {
10652: 	&Math::Random::random_set_seed_from_phrase($rndseed);
10653:     }
10654: }
10655: 
10656: sub latest_receipt_algorithm_id {
10657:     return 'receipt3';
10658: }
10659: 
10660: sub recunique {
10661:     my $fucourseid=shift;
10662:     my $unique;
10663:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
10664: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
10665: 	$unique=$env{"course.$fucourseid.internal.encseed"};
10666:     } else {
10667: 	$unique=$perlvar{'lonReceipt'};
10668:     }
10669:     return unpack("%32C*",$unique);
10670: }
10671: 
10672: sub recprefix {
10673:     my $fucourseid=shift;
10674:     my $prefix;
10675:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
10676: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
10677: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
10678:     } else {
10679: 	$prefix=$perlvar{'lonHostID'};
10680:     }
10681:     return unpack("%32C*",$prefix);
10682: }
10683: 
10684: sub ireceipt {
10685:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
10686: 
10687:     my $return =&recprefix($fucourseid).'-';
10688: 
10689:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
10690: 	$env{'request.state'} eq 'construct') {
10691: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
10692: 	return $return;
10693:     }
10694: 
10695:     my $cuname=unpack("%32C*",$funame);
10696:     my $cudom=unpack("%32C*",$fudom);
10697:     my $cucourseid=unpack("%32C*",$fucourseid);
10698:     my $cusymb=unpack("%32C*",$fusymb);
10699:     my $cunique=&recunique($fucourseid);
10700:     my $cpart=unpack("%32S*",$part);
10701:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
10702: 
10703: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
10704: 			       
10705: 	$return.= ($cunique%$cuname+
10706: 		   $cunique%$cudom+
10707: 		   $cusymb%$cuname+
10708: 		   $cusymb%$cudom+
10709: 		   $cucourseid%$cuname+
10710: 		   $cucourseid%$cudom+
10711: 		   $cpart%$cuname+
10712: 		   $cpart%$cudom);
10713:     } else {
10714: 	$return.= ($cunique%$cuname+
10715: 		   $cunique%$cudom+
10716: 		   $cusymb%$cuname+
10717: 		   $cusymb%$cudom+
10718: 		   $cucourseid%$cuname+
10719: 		   $cucourseid%$cudom);
10720:     }
10721:     return $return;
10722: }
10723: 
10724: sub receipt {
10725:     my ($part)=@_;
10726:     my ($symb,$courseid,$domain,$name) = &whichuser();
10727:     return &ireceipt($name,$domain,$courseid,$symb,$part);
10728: }
10729: 
10730: sub whichuser {
10731:     my ($passedsymb)=@_;
10732:     my ($symb,$courseid,$domain,$name,$publicuser);
10733:     if (defined($env{'form.grade_symb'})) {
10734: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
10735: 	my $allowed=&allowed('vgr',$tmp_courseid);
10736: 	if (!$allowed &&
10737: 	    exists($env{'request.course.sec'}) &&
10738: 	    $env{'request.course.sec'} !~ /^\s*$/) {
10739: 	    $allowed=&allowed('vgr',$tmp_courseid.
10740: 			      '/'.$env{'request.course.sec'});
10741: 	}
10742: 	if ($allowed) {
10743: 	    ($symb)=&get_env_multiple('form.grade_symb');
10744: 	    $courseid=$tmp_courseid;
10745: 	    ($domain)=&get_env_multiple('form.grade_domain');
10746: 	    ($name)=&get_env_multiple('form.grade_username');
10747: 	    return ($symb,$courseid,$domain,$name,$publicuser);
10748: 	}
10749:     }
10750:     if (!$passedsymb) {
10751: 	$symb=&symbread();
10752:     } else {
10753: 	$symb=$passedsymb;
10754:     }
10755:     $courseid=$env{'request.course.id'};
10756:     $domain=$env{'user.domain'};
10757:     $name=$env{'user.name'};
10758:     if ($name eq 'public' && $domain eq 'public') {
10759: 	if (!defined($env{'form.username'})) {
10760: 	    $env{'form.username'}.=time.rand(10000000);
10761: 	}
10762: 	$name.=$env{'form.username'};
10763:     }
10764:     return ($symb,$courseid,$domain,$name,$publicuser);
10765: 
10766: }
10767: 
10768: # ------------------------------------------------------------ Serves up a file
10769: # returns either the contents of the file or 
10770: # -1 if the file doesn't exist
10771: #
10772: # if the target is a file that was uploaded via DOCS, 
10773: # a check will be made to see if a current copy exists on the local server,
10774: # if it does this will be served, otherwise a copy will be retrieved from
10775: # the home server for the course and stored in /home/httpd/html/userfiles on
10776: # the local server.   
10777: 
10778: sub getfile {
10779:     my ($file) = @_;
10780:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
10781:     &repcopy($file);
10782:     return &readfile($file);
10783: }
10784: 
10785: sub repcopy_userfile {
10786:     my ($file)=@_;
10787:     my $londocroot = $perlvar{'lonDocRoot'};
10788:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
10789:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
10790:     my ($cdom,$cnum,$filename) = 
10791: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
10792:     my $uri="/uploaded/$cdom/$cnum/$filename";
10793:     if (-e "$file") {
10794: # we already have a local copy, check it out
10795: 	my @fileinfo = stat($file);
10796: 	my $rtncode;
10797: 	my $info;
10798: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
10799: 	if ($lwpresp ne 'ok') {
10800: # there is no such file anymore, even though we had a local copy
10801: 	    if ($rtncode eq '404') {
10802: 		unlink($file);
10803: 	    }
10804: 	    return -1;
10805: 	}
10806: 	if ($info < $fileinfo[9]) {
10807: # nice, the file we have is up-to-date, just say okay
10808: 	    return 'ok';
10809: 	} else {
10810: # the file is outdated, get rid of it
10811: 	    unlink($file);
10812: 	}
10813:     }
10814: # one way or the other, at this point, we don't have the file
10815: # construct the correct path for the file
10816:     my @parts = ($cdom,$cnum); 
10817:     if ($filename =~ m|^(.+)/[^/]+$|) {
10818: 	push @parts, split(/\//,$1);
10819:     }
10820:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
10821:     foreach my $part (@parts) {
10822: 	$path .= '/'.$part;
10823: 	if (!-e $path) {
10824: 	    mkdir($path,0770);
10825: 	}
10826:     }
10827: # now the path exists for sure
10828: # get a user agent
10829:     my $ua=new LWP::UserAgent;
10830:     my $transferfile=$file.'.in.transfer';
10831: # FIXME: this should flock
10832:     if (-e $transferfile) { return 'ok'; }
10833:     my $request;
10834:     $uri=~s/^\///;
10835:     my $homeserver = &homeserver($cnum,$cdom);
10836:     my $protocol = $protocol{$homeserver};
10837:     $protocol = 'http' if ($protocol ne 'https');
10838:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
10839:     my $response=$ua->request($request,$transferfile);
10840: # did it work?
10841:     if ($response->is_error()) {
10842: 	unlink($transferfile);
10843: 	&logthis("Userfile repcopy failed for $uri");
10844: 	return -1;
10845:     }
10846: # worked, rename the transfer file
10847:     rename($transferfile,$file);
10848:     return 'ok';
10849: }
10850: 
10851: sub tokenwrapper {
10852:     my $uri=shift;
10853:     $uri=~s|^https?\://([^/]+)||;
10854:     $uri=~s|^/||;
10855:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
10856:     my $token=$1;
10857:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
10858:     if ($udom && $uname && $file) {
10859: 	$file=~s|(\?\.*)*$||;
10860:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
10861:         my $homeserver = &homeserver($uname,$udom);
10862:         my $protocol = $protocol{$homeserver};
10863:         $protocol = 'http' if ($protocol ne 'https');
10864:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
10865:                (($uri=~/\?/)?'&':'?').'token='.$token.
10866:                                '&tokenissued='.$perlvar{'lonHostID'};
10867:     } else {
10868:         return '/adm/notfound.html';
10869:     }
10870: }
10871: 
10872: # call with reqtype HEAD: get last modification time
10873: # call with reqtype GET: get the file contents
10874: # Do not call this with reqtype GET for large files! It loads everything into memory
10875: #
10876: sub getuploaded {
10877:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
10878:     $uri=~s/^\///;
10879:     my $homeserver = &homeserver($cnum,$cdom);
10880:     my $protocol = $protocol{$homeserver};
10881:     $protocol = 'http' if ($protocol ne 'https');
10882:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
10883:     my $ua=new LWP::UserAgent;
10884:     my $request=new HTTP::Request($reqtype,$uri);
10885:     my $response=$ua->request($request);
10886:     $$rtncode = $response->code;
10887:     if (! $response->is_success()) {
10888: 	return 'failed';
10889:     }      
10890:     if ($reqtype eq 'HEAD') {
10891: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
10892:     } elsif ($reqtype eq 'GET') {
10893: 	$$info = $response->content;
10894:     }
10895:     return 'ok';
10896: }
10897: 
10898: sub readfile {
10899:     my $file = shift;
10900:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
10901:     my $fh;
10902:     open($fh,"<$file");
10903:     my $a='';
10904:     while (my $line = <$fh>) { $a .= $line; }
10905:     return $a;
10906: }
10907: 
10908: sub filelocation {
10909:     my ($dir,$file) = @_;
10910:     my $location;
10911:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
10912: 
10913:     if ($file =~ m-^/adm/-) {
10914: 	$file=~s-^/adm/wrapper/-/-;
10915: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
10916:     }
10917: 
10918:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
10919:         $location = $file;
10920:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
10921:         my ($udom,$uname,$filename)=
10922:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
10923:         my $home=&homeserver($uname,$udom);
10924:         my $is_me=0;
10925:         my @ids=&current_machine_ids();
10926:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
10927:         if ($is_me) {
10928:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
10929:         } else {
10930:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
10931:   	      $udom.'/'.$uname.'/'.$filename;
10932:         }
10933:     } elsif ($file =~ m-^/adm/-) {
10934: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
10935:     } else {
10936:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
10937:         $file=~s:^/(res|priv)/:/:;
10938:         my $space=$1;
10939:         if ( !( $file =~ m:^/:) ) {
10940:             $location = $dir. '/'.$file;
10941:         } else {
10942:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
10943:         }
10944:     }
10945:     $location=~s://+:/:g; # remove duplicate /
10946:     while ($location=~m{/\.\./}) {
10947: 	if ($location =~ m{/[^/]+/\.\./}) {
10948: 	    $location=~ s{/[^/]+/\.\./}{/}g;
10949: 	} else {
10950: 	    $location=~ s{/\.\./}{/}g;
10951: 	}
10952:     } #remove dir/..
10953:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
10954:     return $location;
10955: }
10956: 
10957: sub hreflocation {
10958:     my ($dir,$file)=@_;
10959:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
10960: 	$file=filelocation($dir,$file);
10961:     } elsif ($file=~m-^/adm/-) {
10962: 	$file=~s-^/adm/wrapper/-/-;
10963: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
10964:     }
10965:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
10966: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
10967:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
10968: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
10969: 	        {/uploaded/$1/$2/}x;
10970:     }
10971:     if ($file=~ m{^/userfiles/}) {
10972: 	$file =~ s{^/userfiles/}{/uploaded/};
10973:     }
10974:     return $file;
10975: }
10976: 
10977: 
10978: 
10979: 
10980: 
10981: sub current_machine_domains {
10982:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
10983: }
10984: 
10985: sub machine_domains {
10986:     my ($hostname) = @_;
10987:     my @domains;
10988:     my %hostname = &all_hostnames();
10989:     while( my($id, $name) = each(%hostname)) {
10990: #	&logthis("-$id-$name-$hostname-");
10991: 	if ($hostname eq $name) {
10992: 	    push(@domains,&host_domain($id));
10993: 	}
10994:     }
10995:     return @domains;
10996: }
10997: 
10998: sub current_machine_ids {
10999:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
11000: }
11001: 
11002: sub machine_ids {
11003:     my ($hostname) = @_;
11004:     $hostname ||= &hostname($perlvar{'lonHostID'});
11005:     my @ids;
11006:     my %name_to_host = &all_names();
11007:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11008: 	return @{ $name_to_host{$hostname} };
11009:     }
11010:     return;
11011: }
11012: 
11013: sub additional_machine_domains {
11014:     my @domains;
11015:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
11016:     while( my $line = <$fh>) {
11017:         $line =~ s/\s//g;
11018:         push(@domains,$line);
11019:     }
11020:     return @domains;
11021: }
11022: 
11023: sub default_login_domain {
11024:     my $domain = $perlvar{'lonDefDomain'};
11025:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
11026:     foreach my $posdom (&current_machine_domains(),
11027:                         &additional_machine_domains()) {
11028:         if (lc($posdom) eq lc($testdomain)) {
11029:             $domain=$posdom;
11030:             last;
11031:         }
11032:     }
11033:     return $domain;
11034: }
11035: 
11036: # ------------------------------------------------------------- Declutters URLs
11037: 
11038: sub declutter {
11039:     my $thisfn=shift;
11040:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
11041:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
11042:     $thisfn=~s/^\///;
11043:     $thisfn=~s|^adm/wrapper/||;
11044:     $thisfn=~s|^adm/coursedocs/showdoc/||;
11045:     $thisfn=~s/^res\///;
11046:     $thisfn=~s/^priv\///;
11047:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
11048:         $thisfn=~s/\?.+$//;
11049:     }
11050:     return $thisfn;
11051: }
11052: 
11053: # ------------------------------------------------------------- Clutter up URLs
11054: 
11055: sub clutter {
11056:     my $thisfn='/'.&declutter(shift);
11057:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
11058: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
11059:        $thisfn='/res'.$thisfn; 
11060:     }
11061:     if ($thisfn !~m|^/adm|) {
11062: 	if ($thisfn =~ m|^/ext/|) {
11063: 	    $thisfn='/adm/wrapper'.$thisfn;
11064: 	} else {
11065: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
11066: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
11067: 	    if ($embstyle eq 'ssi'
11068: 		|| ($embstyle eq 'hdn')
11069: 		|| ($embstyle eq 'rat')
11070: 		|| ($embstyle eq 'prv')
11071: 		|| ($embstyle eq 'ign')) {
11072: 		#do nothing with these
11073: 	    } elsif (($embstyle eq 'img') 
11074: 		|| ($embstyle eq 'emb')
11075: 		|| ($embstyle eq 'wrp')) {
11076: 		$thisfn='/adm/wrapper'.$thisfn;
11077: 	    } elsif ($embstyle eq 'unk'
11078: 		     && $thisfn!~/\.(sequence|page)$/) {
11079: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
11080: 	    } else {
11081: #		&logthis("Got a blank emb style");
11082: 	    }
11083: 	}
11084:     }
11085:     return $thisfn;
11086: }
11087: 
11088: sub clutter_with_no_wrapper {
11089:     my $uri = &clutter(shift);
11090:     if ($uri =~ m-^/adm/-) {
11091: 	$uri =~ s-^/adm/wrapper/-/-;
11092: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
11093:     }
11094:     return $uri;
11095: }
11096: 
11097: sub freeze_escape {
11098:     my ($value)=@_;
11099:     if (ref($value)) {
11100: 	$value=&nfreeze($value);
11101: 	return '__FROZEN__'.&escape($value);
11102:     }
11103:     return &escape($value);
11104: }
11105: 
11106: 
11107: sub thaw_unescape {
11108:     my ($value)=@_;
11109:     if ($value =~ /^__FROZEN__/) {
11110: 	substr($value,0,10,undef);
11111: 	$value=&unescape($value);
11112: 	return &thaw($value);
11113:     }
11114:     return &unescape($value);
11115: }
11116: 
11117: sub correct_line_ends {
11118:     my ($result)=@_;
11119:     $$result =~s/\r\n/\n/mg;
11120:     $$result =~s/\r/\n/mg;
11121: }
11122: # ================================================================ Main Program
11123: 
11124: sub goodbye {
11125:    &logthis("Starting Shut down");
11126: #not converted to using infrastruture and probably shouldn't be
11127:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
11128: #converted
11129: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
11130:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
11131: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
11132: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
11133: #1.1 only
11134: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
11135: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
11136: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
11137: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
11138:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
11139:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
11140:    &logthis(sprintf("%-20s is %s",'hits',$hits));
11141:    &flushcourselogs();
11142:    &logthis("Shutting down");
11143: }
11144: 
11145: sub get_dns {
11146:     my ($url,$func,$ignore_cache) = @_;
11147:     if (!$ignore_cache) {
11148: 	my ($content,$cached)=
11149: 	    &Apache::lonnet::is_cached_new('dns',$url);
11150: 	if ($cached) {
11151: 	    &$func($content);
11152: 	    return;
11153: 	}
11154:     }
11155: 
11156:     my %alldns;
11157:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11158:     foreach my $dns (<$config>) {
11159: 	next if ($dns !~ /^\^(\S*)/x);
11160:         my $line = $1;
11161:         my ($host,$protocol) = split(/:/,$line);
11162:         if ($protocol ne 'https') {
11163:             $protocol = 'http';
11164:         }
11165: 	$alldns{$host} = $protocol;
11166:     }
11167:     while (%alldns) {
11168: 	my ($dns) = keys(%alldns);
11169: 	my $ua=new LWP::UserAgent;
11170:         $ua->timeout(30);
11171: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
11172: 	my $response=$ua->request($request);
11173:         delete($alldns{$dns});
11174: 	next if ($response->is_error());
11175: 	my @content = split("\n",$response->content);
11176: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
11177: 	&$func(\@content);
11178: 	return;
11179:     }
11180:     close($config);
11181:     my $which = (split('/',$url))[3];
11182:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
11183:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
11184:     my @content = <$config>;
11185:     &$func(\@content);
11186:     return;
11187: }
11188: # ------------------------------------------------------------ Read domain file
11189: {
11190:     my $loaded;
11191:     my %domain;
11192: 
11193:     sub parse_domain_tab {
11194: 	my ($lines) = @_;
11195: 	foreach my $line (@$lines) {
11196: 	    next if ($line =~ /^(\#|\s*$ )/x);
11197: 
11198: 	    chomp($line);
11199: 	    my ($name,@elements) = split(/:/,$line,9);
11200: 	    my %this_domain;
11201: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
11202: 			       'lang_def', 'city', 'longi', 'lati',
11203: 			       'primary') {
11204: 		$this_domain{$field} = shift(@elements);
11205: 	    }
11206: 	    $domain{$name} = \%this_domain;
11207: 	}
11208:     }
11209: 
11210:     sub reset_domain_info {
11211: 	undef($loaded);
11212: 	undef(%domain);
11213:     }
11214: 
11215:     sub load_domain_tab {
11216: 	my ($ignore_cache) = @_;
11217: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
11218: 	my $fh;
11219: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
11220: 	    my @lines = <$fh>;
11221: 	    &parse_domain_tab(\@lines);
11222: 	}
11223: 	close($fh);
11224: 	$loaded = 1;
11225:     }
11226: 
11227:     sub domain {
11228: 	&load_domain_tab() if (!$loaded);
11229: 
11230: 	my ($name,$what) = @_;
11231: 	return if ( !exists($domain{$name}) );
11232: 
11233: 	if (!$what) {
11234: 	    return $domain{$name}{'description'};
11235: 	}
11236: 	return $domain{$name}{$what};
11237:     }
11238: 
11239:     sub domain_info {
11240:         &load_domain_tab() if (!$loaded);
11241:         return %domain;
11242:     }
11243: 
11244: }
11245: 
11246: 
11247: # ------------------------------------------------------------- Read hosts file
11248: {
11249:     my %hostname;
11250:     my %hostdom;
11251:     my %libserv;
11252:     my $loaded;
11253:     my %name_to_host;
11254:     my %internetdom;
11255:     my %LC_dns_serv;
11256: 
11257:     sub parse_hosts_tab {
11258: 	my ($file) = @_;
11259: 	foreach my $configline (@$file) {
11260: 	    next if ($configline =~ /^(\#|\s*$ )/x);
11261:             chomp($configline);
11262: 	    if ($configline =~ /^\^/) {
11263:                 if ($configline =~ /^\^([\w.\-]+)/) {
11264:                     $LC_dns_serv{$1} = 1;
11265:                 }
11266:                 next;
11267:             }
11268: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
11269: 	    $name=~s/\s//g;
11270: 	    if ($id && $domain && $role && $name) {
11271: 		$hostname{$id}=$name;
11272: 		push(@{$name_to_host{$name}}, $id);
11273: 		$hostdom{$id}=$domain;
11274: 		if ($role eq 'library') { $libserv{$id}=$name; }
11275:                 if (defined($protocol)) {
11276:                     if ($protocol eq 'https') {
11277:                         $protocol{$id} = $protocol;
11278:                     } else {
11279:                         $protocol{$id} = 'http'; 
11280:                     }
11281:                 } else {
11282:                     $protocol{$id} = 'http';
11283:                 }
11284:                 if (defined($intdom)) {
11285:                     $internetdom{$id} = $intdom;
11286:                 }
11287: 	    }
11288: 	}
11289:     }
11290:     
11291:     sub reset_hosts_info {
11292: 	&purge_remembered();
11293: 	&reset_domain_info();
11294: 	&reset_hosts_ip_info();
11295: 	undef(%name_to_host);
11296: 	undef(%hostname);
11297: 	undef(%hostdom);
11298: 	undef(%libserv);
11299: 	undef($loaded);
11300:     }
11301: 
11302:     sub load_hosts_tab {
11303: 	my ($ignore_cache) = @_;
11304: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
11305: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11306: 	my @config = <$config>;
11307: 	&parse_hosts_tab(\@config);
11308: 	close($config);
11309: 	$loaded=1;
11310:     }
11311: 
11312:     sub hostname {
11313: 	&load_hosts_tab() if (!$loaded);
11314: 
11315: 	my ($lonid) = @_;
11316: 	return $hostname{$lonid};
11317:     }
11318: 
11319:     sub all_hostnames {
11320: 	&load_hosts_tab() if (!$loaded);
11321: 
11322: 	return %hostname;
11323:     }
11324: 
11325:     sub all_names {
11326: 	&load_hosts_tab() if (!$loaded);
11327: 
11328: 	return %name_to_host;
11329:     }
11330: 
11331:     sub all_host_domain {
11332:         &load_hosts_tab() if (!$loaded);
11333:         return %hostdom;
11334:     }
11335: 
11336:     sub is_library {
11337: 	&load_hosts_tab() if (!$loaded);
11338: 
11339: 	return exists($libserv{$_[0]});
11340:     }
11341: 
11342:     sub all_library {
11343: 	&load_hosts_tab() if (!$loaded);
11344: 
11345: 	return %libserv;
11346:     }
11347: 
11348:     sub unique_library {
11349: 	#2x reverse removes all hostnames that appear more than once
11350:         my %unique = reverse &all_library();
11351:         return reverse %unique;
11352:     }
11353: 
11354:     sub get_servers {
11355: 	&load_hosts_tab() if (!$loaded);
11356: 
11357: 	my ($domain,$type) = @_;
11358: 	my %possible_hosts = ($type eq 'library') ? %libserv
11359: 	                                          : %hostname;
11360: 	my %result;
11361: 	if (ref($domain) eq 'ARRAY') {
11362: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
11363: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
11364: 		    $result{$host} = $hostname;
11365: 		}
11366: 	    }
11367: 	} else {
11368: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
11369: 		if ($hostdom{$host} eq $domain) {
11370: 		    $result{$host} = $hostname;
11371: 		}
11372: 	    }
11373: 	}
11374: 	return %result;
11375:     }
11376: 
11377:     sub get_unique_servers {
11378:         my %unique = reverse &get_servers(@_);
11379: 	return reverse %unique;
11380:     }
11381: 
11382:     sub host_domain {
11383: 	&load_hosts_tab() if (!$loaded);
11384: 
11385: 	my ($lonid) = @_;
11386: 	return $hostdom{$lonid};
11387:     }
11388: 
11389:     sub all_domains {
11390: 	&load_hosts_tab() if (!$loaded);
11391: 
11392: 	my %seen;
11393: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
11394: 	return @uniq;
11395:     }
11396: 
11397:     sub internet_dom {
11398:         &load_hosts_tab() if (!$loaded);
11399: 
11400:         my ($lonid) = @_;
11401:         return $internetdom{$lonid};
11402:     }
11403: 
11404:     sub is_LC_dns {
11405:         &load_hosts_tab() if (!$loaded);
11406: 
11407:         my ($hostname) = @_;
11408:         return exists($LC_dns_serv{$hostname});
11409:     }
11410: 
11411: }
11412: 
11413: { 
11414:     my %iphost;
11415:     my %name_to_ip;
11416:     my %lonid_to_ip;
11417: 
11418:     sub get_hosts_from_ip {
11419: 	my ($ip) = @_;
11420: 	my %iphosts = &get_iphost();
11421: 	if (ref($iphosts{$ip})) {
11422: 	    return @{$iphosts{$ip}};
11423: 	}
11424: 	return;
11425:     }
11426:     
11427:     sub reset_hosts_ip_info {
11428: 	undef(%iphost);
11429: 	undef(%name_to_ip);
11430: 	undef(%lonid_to_ip);
11431:     }
11432: 
11433:     sub get_host_ip {
11434: 	my ($lonid) = @_;
11435: 	if (exists($lonid_to_ip{$lonid})) {
11436: 	    return $lonid_to_ip{$lonid};
11437: 	}
11438: 	my $name=&hostname($lonid);
11439:    	my $ip = gethostbyname($name);
11440: 	return if (!$ip || length($ip) ne 4);
11441: 	$ip=inet_ntoa($ip);
11442: 	$name_to_ip{$name}   = $ip;
11443: 	$lonid_to_ip{$lonid} = $ip;
11444: 	return $ip;
11445:     }
11446:     
11447:     sub get_iphost {
11448: 	my ($ignore_cache) = @_;
11449: 
11450: 	if (!$ignore_cache) {
11451: 	    if (%iphost) {
11452: 		return %iphost;
11453: 	    }
11454: 	    my ($ip_info,$cached)=
11455: 		&Apache::lonnet::is_cached_new('iphost','iphost');
11456: 	    if ($cached) {
11457: 		%iphost      = %{$ip_info->[0]};
11458: 		%name_to_ip  = %{$ip_info->[1]};
11459: 		%lonid_to_ip = %{$ip_info->[2]};
11460: 		return %iphost;
11461: 	    }
11462: 	}
11463: 
11464: 	# get yesterday's info for fallback
11465: 	my %old_name_to_ip;
11466: 	my ($ip_info,$cached)=
11467: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
11468: 	if ($cached) {
11469: 	    %old_name_to_ip = %{$ip_info->[1]};
11470: 	}
11471: 
11472: 	my %name_to_host = &all_names();
11473: 	foreach my $name (keys(%name_to_host)) {
11474: 	    my $ip;
11475: 	    if (!exists($name_to_ip{$name})) {
11476: 		$ip = gethostbyname($name);
11477: 		if (!$ip || length($ip) ne 4) {
11478: 		    if (defined($old_name_to_ip{$name})) {
11479: 			$ip = $old_name_to_ip{$name};
11480: 			&logthis("Can't find $name defaulting to old $ip");
11481: 		    } else {
11482: 			&logthis("Name $name no IP found");
11483: 			next;
11484: 		    }
11485: 		} else {
11486: 		    $ip=inet_ntoa($ip);
11487: 		}
11488: 		$name_to_ip{$name} = $ip;
11489: 	    } else {
11490: 		$ip = $name_to_ip{$name};
11491: 	    }
11492: 	    foreach my $id (@{ $name_to_host{$name} }) {
11493: 		$lonid_to_ip{$id} = $ip;
11494: 	    }
11495: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
11496: 	}
11497: 	&Apache::lonnet::do_cache_new('iphost','iphost',
11498: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
11499: 				      48*60*60);
11500: 
11501: 	return %iphost;
11502:     }
11503: 
11504:     #
11505:     #  Given a DNS returns the loncapa host name for that DNS 
11506:     # 
11507:     sub host_from_dns {
11508:         my ($dns) = @_;
11509:         my @hosts;
11510:         my $ip;
11511: 
11512:         if (exists($name_to_ip{$dns})) {
11513:             $ip = $name_to_ip{$dns};
11514:         }
11515:         if (!$ip) {
11516:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
11517:             if (length($ip) == 4) { 
11518: 	        $ip   = &IO::Socket::inet_ntoa($ip);
11519:             }
11520:         }
11521:         if ($ip) {
11522: 	    @hosts = get_hosts_from_ip($ip);
11523: 	    return $hosts[0];
11524:         }
11525:         return undef;
11526:     }
11527: 
11528:     sub get_internet_names {
11529:         my ($lonid) = @_;
11530:         return if ($lonid eq '');
11531:         my ($idnref,$cached)=
11532:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
11533:         if ($cached) {
11534:             return $idnref;
11535:         }
11536:         my $ip = &get_host_ip($lonid);
11537:         my @hosts = &get_hosts_from_ip($ip);
11538:         my %iphost = &get_iphost();
11539:         my (@idns,%seen);
11540:         foreach my $id (@hosts) {
11541:             my $dom = &host_domain($id);
11542:             my $prim_id = &domain($dom,'primary');
11543:             my $prim_ip = &get_host_ip($prim_id);
11544:             next if ($seen{$prim_ip});
11545:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
11546:                 foreach my $id (@{$iphost{$prim_ip}}) {
11547:                     my $intdom = &internet_dom($id);
11548:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
11549:                         push(@idns,$intdom);
11550:                     }
11551:                 }
11552:             }
11553:             $seen{$prim_ip} = 1;
11554:         }
11555:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
11556:     }
11557: 
11558: }
11559: 
11560: sub all_loncaparevs {
11561:     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);
11562: }
11563: 
11564: BEGIN {
11565: 
11566: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
11567:     unless ($readit) {
11568: {
11569:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
11570:     %perlvar = (%perlvar,%{$configvars});
11571: }
11572: 
11573: 
11574: # ------------------------------------------------------ Read spare server file
11575: {
11576:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
11577: 
11578:     while (my $configline=<$config>) {
11579:        chomp($configline);
11580:        if ($configline) {
11581: 	   my ($host,$type) = split(':',$configline,2);
11582: 	   if (!defined($type) || $type eq '') { $type = 'default' };
11583: 	   push(@{ $spareid{$type} }, $host);
11584:        }
11585:     }
11586:     close($config);
11587: }
11588: # ------------------------------------------------------------ Read permissions
11589: {
11590:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
11591: 
11592:     while (my $configline=<$config>) {
11593: 	chomp($configline);
11594: 	if ($configline) {
11595: 	    my ($role,$perm)=split(/ /,$configline);
11596: 	    if ($perm ne '') { $pr{$role}=$perm; }
11597: 	}
11598:     }
11599:     close($config);
11600: }
11601: 
11602: # -------------------------------------------- Read plain texts for permissions
11603: {
11604:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
11605: 
11606:     while (my $configline=<$config>) {
11607: 	chomp($configline);
11608: 	if ($configline) {
11609: 	    my ($short,@plain)=split(/:/,$configline);
11610:             %{$prp{$short}} = ();
11611: 	    if (@plain > 0) {
11612:                 $prp{$short}{'std'} = $plain[0];
11613:                 for (my $i=1; $i<@plain; $i++) {
11614:                     $prp{$short}{'alt'.$i} = $plain[$i];  
11615:                 }
11616:             }
11617: 	}
11618:     }
11619:     close($config);
11620: }
11621: 
11622: # ---------------------------------------------------------- Read package table
11623: {
11624:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
11625: 
11626:     while (my $configline=<$config>) {
11627: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
11628: 	chomp($configline);
11629: 	my ($short,$plain)=split(/:/,$configline);
11630: 	my ($pack,$name)=split(/\&/,$short);
11631: 	if ($plain ne '') {
11632: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
11633: 	    $packagetab{$short}=$plain; 
11634: 	}
11635:     }
11636:     close($config);
11637: }
11638: 
11639: # ---------------------------------------------------------- Read loncaparev table
11640: {
11641:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
11642:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
11643:             while (my $configline=<$config>) {
11644:                 chomp($configline);
11645:                 my ($hostid,$loncaparev)=split(/:/,$configline);
11646:                 $loncaparevs{$hostid}=$loncaparev;
11647:             }
11648:             close($config);
11649:         }
11650:     }
11651: }
11652: 
11653: # ---------------------------------------------------------- Read serverhostID table
11654: {
11655:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
11656:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
11657:             while (my $configline=<$config>) {
11658:                 chomp($configline);
11659:                 my ($name,$id)=split(/:/,$configline);
11660:                 $serverhomeIDs{$name}=$id;
11661:             }
11662:             close($config);
11663:         }
11664:     }
11665: }
11666: 
11667: {
11668:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
11669:     if (-e $file) {
11670:         my $parser = HTML::LCParser->new($file);
11671:         while (my $token = $parser->get_token()) {
11672:             if ($token->[0] eq 'S') {
11673:                 my $item = $token->[1];
11674:                 my $name = $token->[2]{'name'};
11675:                 my $value = $token->[2]{'value'};
11676:                 if ($item ne '' && $name ne '' && $value ne '') {
11677:                     my $release = $parser->get_text();
11678:                     $release =~ s/(^\s*|\s*$ )//gx;
11679:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
11680:                 }
11681:             }
11682:         }
11683:     }
11684: }
11685: 
11686: # ---------------------------------------------------------- Read managers table
11687: {
11688:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
11689:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
11690:             while (my $configline=<$config>) {
11691:                 chomp($configline);
11692:                 next if ($configline =~ /^\#/);
11693:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
11694:                     $managerstab{$configline} = 1;
11695:                 }
11696:             }
11697:             close($config);
11698:         }
11699:     }
11700: }
11701: 
11702: # ------------- set up temporary directory
11703: {
11704:     $tmpdir = LONCAPA::tempdir();
11705: 
11706: }
11707: 
11708: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
11709: 				'compress_threshold'=> 20_000,
11710:  			        });
11711: 
11712: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
11713: $dumpcount=0;
11714: $locknum=0;
11715: 
11716: &logtouch();
11717: &logthis('<font color="yellow">INFO: Read configuration</font>');
11718: $readit=1;
11719:     {
11720: 	use integer;
11721: 	my $test=(2**32)+1;
11722: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
11723: 	&logthis(" Detected 64bit platform ($_64bit)");
11724:     }
11725: }
11726: }
11727: 
11728: 1;
11729: __END__
11730: 
11731: =pod
11732: 
11733: =head1 NAME
11734: 
11735: Apache::lonnet - Subroutines to ask questions about things in the network.
11736: 
11737: =head1 SYNOPSIS
11738: 
11739: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
11740: 
11741:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
11742: 
11743: Common parameters:
11744: 
11745: =over 4
11746: 
11747: =item *
11748: 
11749: $uname : an internal username (if $cname expecting a course Id specifically)
11750: 
11751: =item *
11752: 
11753: $udom : a domain (if $cdom expecting a course's domain specifically)
11754: 
11755: =item *
11756: 
11757: $symb : a resource instance identifier
11758: 
11759: =item *
11760: 
11761: $namespace : the name of a .db file that contains the data needed or
11762: being set.
11763: 
11764: =back
11765: 
11766: =head1 OVERVIEW
11767: 
11768: lonnet provides subroutines which interact with the
11769: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
11770: about classes, users, and resources.
11771: 
11772: For many of these objects you can also use this to store data about
11773: them or modify them in various ways.
11774: 
11775: =head2 Symbs
11776: 
11777: To identify a specific instance of a resource, LON-CAPA uses symbols
11778: or "symbs"X<symb>. These identifiers are built from the URL of the
11779: map, the resource number of the resource in the map, and the URL of
11780: the resource itself. The latter is somewhat redundant, but might help
11781: if maps change.
11782: 
11783: An example is
11784: 
11785:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
11786: 
11787: The respective map entry is
11788: 
11789:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
11790:   title="Problem 2">
11791:  </resource>
11792: 
11793: Symbs are used by the random number generator, as well as to store and
11794: restore data specific to a certain instance of for example a problem.
11795: 
11796: =head2 Storing And Retrieving Data
11797: 
11798: X<store()>X<cstore()>X<restore()>Three of the most important functions
11799: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
11800: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
11801: is is the non-critical message twin of cstore. These functions are for
11802: handlers to store a perl hash to a user's permanent data space in an
11803: easy manner, and to retrieve it again on another call. It is expected
11804: that a handler would use this once at the beginning to retrieve data,
11805: and then again once at the end to send only the new data back.
11806: 
11807: The data is stored in the user's data directory on the user's
11808: homeserver under the ID of the course.
11809: 
11810: The hash that is returned by restore will have all of the previous
11811: value for all of the elements of the hash.
11812: 
11813: Example:
11814: 
11815:  #creating a hash
11816:  my %hash;
11817:  $hash{'foo'}='bar';
11818: 
11819:  #storing it
11820:  &Apache::lonnet::cstore(\%hash);
11821: 
11822:  #changing a value
11823:  $hash{'foo'}='notbar';
11824: 
11825:  #adding a new value
11826:  $hash{'bar'}='foo';
11827:  &Apache::lonnet::cstore(\%hash);
11828: 
11829:  #retrieving the hash
11830:  my %history=&Apache::lonnet::restore();
11831: 
11832:  #print the hash
11833:  foreach my $key (sort(keys(%history))) {
11834:    print("\%history{$key} = $history{$key}");
11835:  }
11836: 
11837: Will print out:
11838: 
11839:  %history{1:foo} = bar
11840:  %history{1:keys} = foo:timestamp
11841:  %history{1:timestamp} = 990455579
11842:  %history{2:bar} = foo
11843:  %history{2:foo} = notbar
11844:  %history{2:keys} = foo:bar:timestamp
11845:  %history{2:timestamp} = 990455580
11846:  %history{bar} = foo
11847:  %history{foo} = notbar
11848:  %history{timestamp} = 990455580
11849:  %history{version} = 2
11850: 
11851: Note that the special hash entries C<keys>, C<version> and
11852: C<timestamp> were added to the hash. C<version> will be equal to the
11853: total number of versions of the data that have been stored. The
11854: C<timestamp> attribute will be the UNIX time the hash was
11855: stored. C<keys> is available in every historical section to list which
11856: keys were added or changed at a specific historical revision of a
11857: hash.
11858: 
11859: B<Warning>: do not store the hash that restore returns directly. This
11860: will cause a mess since it will restore the historical keys as if the
11861: were new keys. I.E. 1:foo will become 1:1:foo etc.
11862: 
11863: Calling convention:
11864: 
11865:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
11866:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
11867: 
11868: For more detailed information, see lonnet specific documentation.
11869: 
11870: =head1 RETURN MESSAGES
11871: 
11872: =over 4
11873: 
11874: =item * B<con_lost>: unable to contact remote host
11875: 
11876: =item * B<con_delayed>: unable to contact remote host, message will be delivered
11877: when the connection is brought back up
11878: 
11879: =item * B<con_failed>: unable to contact remote host and unable to save message
11880: for later delivery
11881: 
11882: =item * B<error:>: an error a occurred, a description of the error follows the :
11883: 
11884: =item * B<no_such_host>: unable to fund a host associated with the user/domain
11885: that was requested
11886: 
11887: =back
11888: 
11889: =head1 PUBLIC SUBROUTINES
11890: 
11891: =head2 Session Environment Functions
11892: 
11893: =over 4
11894: 
11895: =item * 
11896: X<appenv()>
11897: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
11898: the user envirnoment file, and will be restored for each access this
11899: user makes during this session, also modifies the %env for the current
11900: process. Optional rolesarrayref - if defined contains a reference to an array
11901: of roles which are exempt from the restriction on modifying user.role entries 
11902: in the user's environment.db and in %env.    
11903: 
11904: =item *
11905: X<delenv()>
11906: B<delenv($delthis,$regexp)>: removes all items from the session
11907: environment file that begin with $delthis. If the 
11908: optional second arg - $regexp - is true, $delthis is treated as a 
11909: regular expression, otherwise \Q$delthis\E is used. 
11910: The values are also deleted from the current processes %env.
11911: 
11912: =item * get_env_multiple($name) 
11913: 
11914: gets $name from the %env hash, it seemlessly handles the cases where multiple
11915: values may be defined and end up as an array ref.
11916: 
11917: returns an array of values
11918: 
11919: =back
11920: 
11921: =head2 User Information
11922: 
11923: =over 4
11924: 
11925: =item *
11926: X<queryauthenticate()>
11927: B<queryauthenticate($uname,$udom)>: try to determine user's current 
11928: authentication scheme
11929: 
11930: =item *
11931: X<authenticate()>
11932: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
11933: authenticate user from domain's lib servers (first use the current
11934: one). C<$upass> should be the users password.
11935: $checkdefauth is optional (value is 1 if a check should be made to
11936:    authenticate user using default authentication method, and allow
11937:    account creation if username does not have account in the domain).
11938: $clientcancheckhost is optional (value is 1 if checking whether the
11939:    server can host will occur on the client side in lonauth.pm).   
11940: 
11941: =item *
11942: X<homeserver()>
11943: B<homeserver($uname,$udom)>: find the server which has
11944: the user's directory and files (there must be only one), this caches
11945: the answer, and also caches if there is a borken connection.
11946: 
11947: =item *
11948: X<idget()>
11949: B<idget($udom,@ids)>: find the usernames behind a list of IDs
11950: (IDs are a unique resource in a domain, there must be only 1 ID per
11951: username, and only 1 username per ID in a specific domain) (returns
11952: hash: id=>name,id=>name)
11953: 
11954: =item *
11955: X<idrget()>
11956: B<idrget($udom,@unames)>: find the IDs behind a list of
11957: usernames (returns hash: name=>id,name=>id)
11958: 
11959: =item *
11960: X<idput()>
11961: B<idput($udom,%ids)>: store away a list of names and associated IDs
11962: 
11963: =item *
11964: X<rolesinit()>
11965: B<rolesinit($udom,$username)>: get user privileges.
11966: returns user role, first access and timer interval hashes
11967: 
11968: =item *
11969: X<privileged()>
11970: B<privileged($username,$domain)>: returns a true if user has a
11971: privileged and active role (i.e. su or dc), false otherwise.
11972: 
11973: =item *
11974: X<getsection()>
11975: B<getsection($udom,$uname,$cname)>: finds the section of student in the
11976: course $cname, return section name/number or '' for "not in course"
11977: and '-1' for "no section"
11978: 
11979: =item *
11980: X<userenvironment()>
11981: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
11982: passed in @what from the requested user's environment, returns a hash
11983: 
11984: =item * 
11985: X<userlog_query()>
11986: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
11987: activity.log file. %filters defines filters applied when parsing the
11988: log file. These can be start or end timestamps, or the type of action
11989: - log to look for Login or Logout events, check for Checkin or
11990: Checkout, role for role selection. The response is in the form
11991: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
11992: escaped strings of the action recorded in the activity.log file.
11993: 
11994: =back
11995: 
11996: =head2 User Roles
11997: 
11998: =over 4
11999: 
12000: =item *
12001: 
12002: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
12003:  F: full access
12004:  U,I,K: authentication modes (cxx only)
12005:  '': forbidden
12006:  1: user needs to choose course
12007:  2: browse allowed
12008:  A: passphrase authentication needed
12009: 
12010: =item *
12011: 
12012: constructaccess($url,$setpriv) : check for access to construction space URL
12013: 
12014: See if the owner domain and name in the URL match those in the
12015: expected environment.  If so, return three element list
12016: ($ownername,$ownerdomain,$ownerhome).
12017: 
12018: Otherwise return the null string.
12019: 
12020: If second argument 'setpriv' is true, it assigns the privileges,
12021: and returns the same three element list, unless the owner has
12022: blocked "ad hoc" Domain Coordinator access to the Author Space,
12023: in which case the null string is returned.
12024: 
12025: =item *
12026: 
12027: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
12028: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
12029: and course level
12030: 
12031: =item *
12032: 
12033: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
12034: (rolesplain.tab); plain text explanation of a user role term.
12035: $type is Course (default) or Community.
12036: If $forcedefault evaluates to true, text returned will be default 
12037: text for $type. Otherwise, if this is a course, the text returned 
12038: will be a custom name for the role (if defined in the course's 
12039: environment).  If no custom name is defined the default is returned.
12040:    
12041: =item *
12042: 
12043: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
12044: All arguments are optional. Returns a hash of a roles, either for
12045: co-author/assistant author roles for a user's Construction Space
12046: (default), or if $context is 'userroles', roles for the user himself,
12047: In the hash, keys are set to colon-separated $uname,$udom,$role, and
12048: (optionally) if $withsec is true, a fourth colon-separated item - $section.
12049: For each key, value is set to colon-separated start and end times for
12050: the role.  If no username and domain are specified, will default to
12051: current user/domain. Types, roles, and roledoms are references to arrays
12052: of role statuses (active, future or previous), roles 
12053: (e.g., cc,in, st etc.) and domains of the roles which can be used
12054: to restrict the list of roles reported. If no array ref is 
12055: provided for types, will default to return only active roles.
12056: 
12057: =back
12058: 
12059: =head2 User Modification
12060: 
12061: =over 4
12062: 
12063: =item *
12064: 
12065: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
12066: user for the level given by URL.  Optional start and end dates (leave empty
12067: string or zero for "no date")
12068: 
12069: =item *
12070: 
12071: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
12072: change a users, password, possible return values are: ok,
12073: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
12074: refused
12075: 
12076: =item *
12077: 
12078: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
12079: 
12080: =item *
12081: 
12082: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
12083:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
12084: 
12085: will update user information (firstname,middlename,lastname,generation,
12086: permanentemail), and if forceid is true, student/employee ID also.
12087: A user's institutional affiliation(s) can also be updated.
12088: User information fields will not be overwritten with empty entries 
12089: unless the field is included in the $candelete array reference.
12090: This array is included when a single user is modified via "Manage Users",
12091: or when Autoupdate.pl is run by cron in a domain.
12092: 
12093: =item *
12094: 
12095: modifystudent
12096: 
12097: modify a student's enrollment and identification information.
12098: The course id is resolved based on the current users environment.  
12099: This means the envoking user must be a course coordinator or otherwise
12100: associated with a course.
12101: 
12102: This call is essentially a wrapper for lonnet::modifyuser and
12103: lonnet::modify_student_enrollment
12104: 
12105: Inputs: 
12106: 
12107: =over 4
12108: 
12109: =item B<$udom> Student's loncapa domain
12110: 
12111: =item B<$uname> Student's loncapa login name
12112: 
12113: =item B<$uid> Student/Employee ID
12114: 
12115: =item B<$umode> Student's authentication mode
12116: 
12117: =item B<$upass> Student's password
12118: 
12119: =item B<$first> Student's first name
12120: 
12121: =item B<$middle> Student's middle name
12122: 
12123: =item B<$last> Student's last name
12124: 
12125: =item B<$gene> Student's generation
12126: 
12127: =item B<$usec> Student's section in course
12128: 
12129: =item B<$end> Unix time of the roles expiration
12130: 
12131: =item B<$start> Unix time of the roles start date
12132: 
12133: =item B<$forceid> If defined, allow $uid to be changed
12134: 
12135: =item B<$desiredhome> server to use as home server for student
12136: 
12137: =item B<$email> Student's permanent e-mail address
12138: 
12139: =item B<$type> Type of enrollment (auto or manual)
12140: 
12141: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
12142: 
12143: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
12144: 
12145: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
12146: 
12147: =item B<$context> role change context (shown in User Management Logs display in a course)
12148: 
12149: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
12150: 
12151: =back
12152: 
12153: =item *
12154: 
12155: modify_student_enrollment
12156: 
12157: Change a students enrollment status in a class.  The environment variable
12158: 'role.request.course' must be defined for this function to proceed.
12159: 
12160: Inputs:
12161: 
12162: =over 4
12163: 
12164: =item $udom, students domain
12165: 
12166: =item $uname, students name
12167: 
12168: =item $uid, students user id
12169: 
12170: =item $first, students first name
12171: 
12172: =item $middle
12173: 
12174: =item $last
12175: 
12176: =item $gene
12177: 
12178: =item $usec
12179: 
12180: =item $end
12181: 
12182: =item $start
12183: 
12184: =item $type
12185: 
12186: =item $locktype
12187: 
12188: =item $cid
12189: 
12190: =item $selfenroll
12191: 
12192: =item $context
12193: 
12194: =back
12195: 
12196: 
12197: =item *
12198: 
12199: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
12200: custom role; give a custom role to a user for the level given by URL.  Specify
12201: name and domain of role author, and role name
12202: 
12203: =item *
12204: 
12205: revokerole($udom,$uname,$url,$role) : revoke a role for url
12206: 
12207: =item *
12208: 
12209: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
12210: 
12211: =back
12212: 
12213: =head2 Course Infomation
12214: 
12215: =over 4
12216: 
12217: =item *
12218: 
12219: coursedescription($courseid,$options) : returns a hash of information about the
12220: specified course id, including all environment settings for the
12221: course, the description of the course will be in the hash under the
12222: key 'description'
12223: 
12224: $options is an optional parameter that if supplied is a hash reference that controls
12225: what how this function works.  It has the following key/values:
12226: 
12227: =over 4
12228: 
12229: =item freshen_cache
12230: 
12231: If defined, and the environment cache for the course is valid, it is 
12232: returned in the returned hash.
12233: 
12234: =item one_time
12235: 
12236: If defined, the last cache time is set to _now_
12237: 
12238: =item user
12239: 
12240: If defined, the supplied username is used instead of the current user.
12241: 
12242: 
12243: =back
12244: 
12245: =item *
12246: 
12247: resdata($name,$domain,$type,@which) : request for current parameter
12248: setting for a specific $type, where $type is either 'course' or 'user',
12249: @what should be a list of parameters to ask about. This routine caches
12250: answers for 5 minutes.
12251: 
12252: =item *
12253: 
12254: get_courseresdata($courseid, $domain) : dump the entire course resource
12255: data base, returning a hash that is keyed by the resource name and has
12256: values that are the resource value.  I believe that the timestamps and
12257: versions are also returned.
12258: 
12259: 
12260: =back
12261: 
12262: =head2 Course Modification
12263: 
12264: =over 4
12265: 
12266: =item *
12267: 
12268: writecoursepref($courseid,%prefs) : write preferences (environment
12269: database) for a course
12270: 
12271: =item *
12272: 
12273: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
12274: 
12275: =item *
12276: 
12277: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
12278: 
12279: =item *
12280: 
12281: is_course($courseid), is_course($cdom, $cnum)
12282: 
12283: Accepts either a combined $courseid (in the form of domain_courseid) or the
12284: two component version $cdom, $cnum. It checks if the specified course exists.
12285: 
12286: Returns:
12287:     undef if the course doesn't exist, otherwise
12288:     in scalar context the combined courseid.
12289:     in list context the two components of the course identifier, domain and 
12290:     courseid.    
12291: 
12292: =back
12293: 
12294: =head2 Resource Subroutines
12295: 
12296: =over 4
12297: 
12298: =item *
12299: 
12300: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
12301: 
12302: =item *
12303: 
12304: repcopy($filename) : subscribes to the requested file, and attempts to
12305: replicate from the owning library server, Might return
12306: 'unavailable', 'not_found', 'forbidden', 'ok', or
12307: 'bad_request', also attempts to grab the metadata for the
12308: resource. Expects the local filesystem pathname
12309: (/home/httpd/html/res/....)
12310: 
12311: =back
12312: 
12313: =head2 Resource Information
12314: 
12315: =over 4
12316: 
12317: =item *
12318: 
12319: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
12320: a vairety of different possible values, $varname should be a request
12321: string, and the other parameters can be used to specify who and what
12322: one is asking about.
12323: 
12324: Possible values for $varname are environment.lastname (or other item
12325: from the envirnment hash), user.name (or someother aspect about the
12326: user), resource.0.maxtries (or some other part and parameter of a
12327: resource)
12328: 
12329: =item *
12330: 
12331: directcondval($number) : get current value of a condition; reads from a state
12332: string
12333: 
12334: =item *
12335: 
12336: condval($condidx) : value of condition index based on state
12337: 
12338: =item *
12339: 
12340: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
12341: resource's metadata, $what should be either a specific key, or either
12342: 'keys' (to get a list of possible keys) or 'packages' to get a list of
12343: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
12344: 
12345: this function automatically caches all requests
12346: 
12347: =item *
12348: 
12349: metadata_query($query,$custom,$customshow) : make a metadata query against the
12350: network of library servers; returns file handle of where SQL and regex results
12351: will be stored for query
12352: 
12353: =item *
12354: 
12355: symbread($filename) : return symbolic list entry (filename argument optional);
12356: returns the data handle
12357: 
12358: =item *
12359: 
12360: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
12361: and is a possible symb for the URL in $thisfn, and if is an encrypted
12362: resource that the user accessed using /enc/ returns a 1 on success, 0
12363: on failure, user must be in a course, as it assumes the existence of
12364: the course initial hash, and uses $env('request.course.id'}.  The third
12365: arg is an optional reference to a scalar.  If this arg is passed in the 
12366: call to symbverify, it will be set to 1 if the symb has been set to be 
12367: encrypted; otherwise it will be null.  
12368: 
12369: =item *
12370: 
12371: symbclean($symb) : removes versions numbers from a symb, returns the
12372: cleaned symb
12373: 
12374: =item *
12375: 
12376: is_on_map($uri) : checks if the $uri is somewhere on the current
12377: course map, user must be in a course for it to work.
12378: 
12379: =item *
12380: 
12381: numval($salt) : return random seed value (addend for rndseed)
12382: 
12383: =item *
12384: 
12385: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
12386: a random seed, all arguments are optional, if they aren't sent it uses the
12387: environment to derive them. Note: if symb isn't sent and it can't get one
12388: from &symbread it will use the current time as its return value
12389: 
12390: =item *
12391: 
12392: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
12393: unfakeable, receipt
12394: 
12395: =item *
12396: 
12397: receipt() : API to ireceipt working off of env values; given out to users
12398: 
12399: =item *
12400: 
12401: countacc($url) : count the number of accesses to a given URL
12402: 
12403: =item *
12404: 
12405: 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
12406: 
12407: =item *
12408: 
12409: 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)
12410: 
12411: =item *
12412: 
12413: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
12414: 
12415: =item *
12416: 
12417: devalidate($symb) : devalidate temporary spreadsheet calculations,
12418: forcing spreadsheet to reevaluate the resource scores next time.
12419: 
12420: =back
12421: 
12422: =head2 Storing/Retreiving Data
12423: 
12424: =over 4
12425: 
12426: =item *
12427: 
12428: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
12429: for this url; hashref needs to be given and should be a \%hashname; the
12430: remaining args aren't required and if they aren't passed or are '' they will
12431: be derived from the env
12432: 
12433: =item *
12434: 
12435: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
12436: uses critical subroutine
12437: 
12438: =item *
12439: 
12440: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
12441: all args are optional
12442: 
12443: =item *
12444: 
12445: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
12446: dumps the complete (or key matching regexp) namespace into a hash
12447: ($udom, $uname, $regexp, $range are optional) for a namespace that is
12448: normally &store()ed into
12449: 
12450: $range should be either an integer '100' (give me the first 100
12451:                                            matching records)
12452:               or be  two integers sperated by a - with no spaces
12453:                  '30-50' (give me the 30th through the 50th matching
12454:                           records)
12455: 
12456: 
12457: =item *
12458: 
12459: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
12460: replaces a &store() version of data with a replacement set of data
12461: for a particular resource in a namespace passed in the $storehash hash 
12462: reference
12463: 
12464: =item *
12465: 
12466: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
12467: works very similar to store/cstore, but all data is stored in a
12468: temporary location and can be reset using tmpreset, $storehash should
12469: be a hash reference, returns nothing on success
12470: 
12471: =item *
12472: 
12473: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
12474: similar to restore, but all data is stored in a temporary location and
12475: can be reset using tmpreset. Returns a hash of values on success,
12476: error string otherwise.
12477: 
12478: =item *
12479: 
12480: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
12481: deltes all keys for $symb form the temporary storage hash.
12482: 
12483: =item *
12484: 
12485: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
12486: reference filled in from namesp ($udom and $uname are optional)
12487: 
12488: =item *
12489: 
12490: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
12491: namesp ($udom and $uname are optional)
12492: 
12493: =item *
12494: 
12495: dump($namespace,$udom,$uname,$regexp,$range) : 
12496: dumps the complete (or key matching regexp) namespace into a hash
12497: ($udom, $uname, $regexp, $range are optional)
12498: 
12499: $range should be either an integer '100' (give me the first 100
12500:                                            matching records)
12501:               or be  two integers sperated by a - with no spaces
12502:                  '30-50' (give me the 30th through the 50th matching
12503:                           records)
12504: =item *
12505: 
12506: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
12507: $store can be a scalar, an array reference, or if the amount to be 
12508: incremented is > 1, a hash reference.
12509: 
12510: ($udom and $uname are optional)
12511: 
12512: =item *
12513: 
12514: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
12515: ($udom and $uname are optional)
12516: 
12517: =item *
12518: 
12519: cput($namespace,$storehash,$udom,$uname) : critical put
12520: ($udom and $uname are optional)
12521: 
12522: =item *
12523: 
12524: newput($namespace,$storehash,$udom,$uname) :
12525: 
12526: Attempts to store the items in the $storehash, but only if they don't
12527: currently exist, if this succeeds you can be certain that you have 
12528: successfully created a new key value pair in the $namespace db.
12529: 
12530: 
12531: Args:
12532:  $namespace: name of database to store values to
12533:  $storehash: hashref to store to the db
12534:  $udom: (optional) domain of user containing the db
12535:  $uname: (optional) name of user caontaining the db
12536: 
12537: Returns:
12538:  'ok' -> succeeded in storing all keys of $storehash
12539:  'key_exists: <key>' -> failed to anything out of $storehash, as at
12540:                         least <key> already existed in the db (other
12541:                         requested keys may also already exist)
12542:  'error: <msg>' -> unable to tie the DB or other error occurred
12543:  'con_lost' -> unable to contact request server
12544:  'refused' -> action was not allowed by remote machine
12545: 
12546: 
12547: =item *
12548: 
12549: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
12550: reference filled in from namesp (encrypts the return communication)
12551: ($udom and $uname are optional)
12552: 
12553: =item *
12554: 
12555: log($udom,$name,$home,$message) : write to permanent log for user; use
12556: critical subroutine
12557: 
12558: =item *
12559: 
12560: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
12561: array reference filled in from namespace found in domain level on either
12562: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
12563: 
12564: =item *
12565: 
12566: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
12567: domain level either on specified domain server ($uhome) or primary domain 
12568: server ($udom and $uhome are optional)
12569: 
12570: =item * 
12571: 
12572: get_domain_defaults($target_domain) : returns hash with defaults for
12573: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
12574: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
12575: or localauth), initial password or a kerberos realm, language (e.g., en-us).
12576: Values are retrieved from cache (if current), or from domain's configuration.db
12577: (if available), or lastly from values in lonTabs/dns_domain,tab, 
12578: or lonTabs/domain.tab. 
12579: 
12580: %domdefaults = &get_auth_defaults($target_domain);
12581: 
12582: =back
12583: 
12584: =head2 Network Status Functions
12585: 
12586: =over 4
12587: 
12588: =item *
12589: 
12590: dirlist() : return directory list based on URI (first arg).
12591: 
12592: Inputs: 1 required, 5 optional.
12593: 
12594: =over
12595: 
12596: =item 
12597: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
12598: 
12599: =item
12600: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
12601: 
12602: =item
12603: $username -  username of user/course to be listed. Extracted from $uri if absent. 
12604: 
12605: =item
12606: $getpropath - boolean: 1 if prepend path using &propath(). 
12607: 
12608: =item
12609: $getuserdir - boolean: 1 if prepend path for "userfiles".
12610: 
12611: =item 
12612: $alternateRoot - path to prepend in place of path from $uri.
12613: 
12614: =back
12615: 
12616: Returns: Array of up to two items.
12617: 
12618: =over
12619: 
12620: a reference to an array of files/subdirectories
12621: 
12622: =over
12623: 
12624: Each element in the array of files/subdirectories is a & separated list of
12625: item name and the result of running stat on the item.  If dirlist was requested
12626: for a file instead of a directory, the item name will be ''. For a directory 
12627: listing, if the item is a metadata file, the element will end &N&M 
12628: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
12629: default copyright set (1).  
12630: 
12631: =back
12632: 
12633: a scalar containing error condition (if encountered).
12634: 
12635: =over
12636: 
12637: =item 
12638: no_host (no homeserver identified for $username:$domain).
12639: 
12640: =item 
12641: no_such_host (server contacted for listing not identified as valid host).
12642: 
12643: =item 
12644: con_lost (connection to remote server failed).
12645: 
12646: =item 
12647: refused (invalid $username:$domain received on lond side).
12648: 
12649: =item 
12650: no_such_dir (directory at specified path on lond side does not exist). 
12651: 
12652: =item 
12653: empty (directory at specified path on lond side is empty).
12654: 
12655: =over
12656: 
12657: This is currently not encountered because the &ls3, &ls2, 
12658: &ls (_handler) routines on the lond side do not filter out
12659: . and .. from a directory listing. 
12660: 
12661: =back
12662: 
12663: =back
12664: 
12665: =back
12666: 
12667: =item *
12668: 
12669: spareserver() : find server with least workload from spare.tab
12670: 
12671: 
12672: =item *
12673: 
12674: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
12675: if there is no corresponding loncapa host.
12676: 
12677: =back
12678: 
12679: 
12680: =head2 Apache Request
12681: 
12682: =over 4
12683: 
12684: =item *
12685: 
12686: ssi($url,%hash) : server side include, does a complete request cycle on url to
12687: localhost, posts hash
12688: 
12689: =back
12690: 
12691: =head2 Data to String to Data
12692: 
12693: =over 4
12694: 
12695: =item *
12696: 
12697: hash2str(%hash) : convert a hash into a string complete with escaping and '='
12698: and '&' separators, supports elements that are arrayrefs and hashrefs
12699: 
12700: =item *
12701: 
12702: hashref2str($hashref) : convert a hashref into a string complete with
12703: escaping and '=' and '&' separators, supports elements that are
12704: arrayrefs and hashrefs
12705: 
12706: =item *
12707: 
12708: arrayref2str($arrayref) : convert an arrayref into a string complete
12709: with escaping and '&' separators, supports elements that are arrayrefs
12710: and hashrefs
12711: 
12712: =item *
12713: 
12714: str2hash($string) : convert string to hash using unescaping and
12715: splitting on '=' and '&', supports elements that are arrayrefs and
12716: hashrefs
12717: 
12718: =item *
12719: 
12720: str2array($string) : convert string to hash using unescaping and
12721: splitting on '&', supports elements that are arrayrefs and hashrefs
12722: 
12723: =back
12724: 
12725: =head2 Logging Routines
12726: 
12727: 
12728: These routines allow one to make log messages in the lonnet.log and
12729: lonnet.perm logfiles.
12730: 
12731: =over 4
12732: 
12733: =item *
12734: 
12735: logtouch() : make sure the logfile, lonnet.log, exists
12736: 
12737: =item *
12738: 
12739: logthis() : append message to the normal lonnet.log file, it gets
12740: preiodically rolled over and deleted.
12741: 
12742: =item *
12743: 
12744: logperm() : append a permanent message to lonnet.perm.log, this log
12745: file never gets deleted by any automated portion of the system, only
12746: messages of critical importance should go in here.
12747: 
12748: 
12749: =back
12750: 
12751: =head2 General File Helper Routines
12752: 
12753: =over 4
12754: 
12755: =item *
12756: 
12757: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
12758: (a) files in /uploaded
12759:   (i) If a local copy of the file exists - 
12760:       compares modification date of local copy with last-modified date for 
12761:       definitive version stored on home server for course. If local copy is 
12762:       stale, requests a new version from the home server and stores it. 
12763:       If the original has been removed from the home server, then local copy 
12764:       is unlinked.
12765:   (ii) If local copy does not exist -
12766:       requests the file from the home server and stores it. 
12767:   
12768:   If $caller is 'uploadrep':  
12769:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
12770:     for request for files originally uploaded via DOCS. 
12771:      - returns 'ok' if fresh local copy now available, -1 otherwise.
12772:   
12773:   Otherwise:
12774:      This indicates a call from the content generation phase of the request.
12775:      -  returns the entire contents of the file or -1.
12776:      
12777: (b) files in /res
12778:    - returns the entire contents of a file or -1; 
12779:    it properly subscribes to and replicates the file if neccessary.
12780: 
12781: 
12782: =item *
12783: 
12784: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
12785:                   reference
12786: 
12787: returns either a stat() list of data about the file or an empty list
12788: if the file doesn't exist or couldn't find out about it (connection
12789: problems or user unknown)
12790: 
12791: =item *
12792: 
12793: filelocation($dir,$file) : returns file system location of a file
12794: based on URI; meant to be "fairly clean" absolute reference, $dir is a
12795: directory that relative $file lookups are to looked in ($dir of /a/dir
12796: and a file of ../bob will become /a/bob)
12797: 
12798: =item *
12799: 
12800: hreflocation($dir,$file) : returns file system location or a URL; same as
12801: filelocation except for hrefs
12802: 
12803: =item *
12804: 
12805: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
12806: 
12807: =back
12808: 
12809: =head2 Usererfile file routines (/uploaded*)
12810: 
12811: =over 4
12812: 
12813: =item *
12814: 
12815: userfileupload(): main rotine for putting a file in a user or course's
12816:                   filespace, arguments are,
12817: 
12818:  formname - required - this is the name of the element in $env where the
12819:            filename, and the contents of the file to create/modifed exist
12820:            the filename is in $env{'form.'.$formname.'.filename'} and the
12821:            contents of the file is located in $env{'form.'.$formname}
12822:  context - if coursedoc, store the file in the course of the active role
12823:              of the current user; 
12824:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
12825:            if 'canceloverwrite': delete file in tmp/overwrites directory
12826:  subdir - required - subdirectory to put the file in under ../userfiles/
12827:          if undefined, it will be placed in "unknown"
12828: 
12829:  (This routine calls clean_filename() to remove any dangerous
12830:  characters from the filename, and then calls finuserfileupload() to
12831:  complete the transaction)
12832: 
12833:  returns either the url of the uploaded file (/uploaded/....) if successful
12834:  and /adm/notfound.html if unsuccessful
12835: 
12836: =item *
12837: 
12838: clean_filename(): routine for cleaing a filename up for storage in
12839:                  userfile space, argument is:
12840: 
12841:  filename - proposed filename
12842: 
12843: returns: the new clean filename
12844: 
12845: =item *
12846: 
12847: finishuserfileupload(): routine that creates and sends the file to
12848: userspace, probably shouldn't be called directly
12849: 
12850:   docuname: username or courseid of destination for the file
12851:   docudom: domain of user/course of destination for the file
12852:   formname: same as for userfileupload()
12853:   fname: filename (including subdirectories) for the file
12854:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
12855:   allfiles: reference to hash used to store objects found by parser
12856:   codebase: reference to hash used for codebases of java objects found by parser
12857:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
12858:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
12859:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
12860:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
12861:   context: if 'overwrite', will move the uploaded file from its temporary location to
12862:             userfiles to facilitate overwriting a previously uploaded file with same name.
12863:   mimetype: reference to scalar to accommodate mime type determined
12864:             from File::MMagic if $parser = parse.
12865: 
12866:  returns either the url of the uploaded file (/uploaded/....) if successful
12867:  and /adm/notfound.html if unsuccessful (or an error message if context 
12868:  was 'overwrite').
12869:  
12870: 
12871: =item *
12872: 
12873: renameuserfile(): renames an existing userfile to a new name
12874: 
12875:   Args:
12876:    docuname: username or courseid of destination for the file
12877:    docudom: domain of user/course of destination for the file
12878:    old: current file name (including any subdirs under userfiles)
12879:    new: desired file name (including any subdirs under userfiles)
12880: 
12881: =item *
12882: 
12883: mkdiruserfile(): creates a directory is a userfiles dir
12884: 
12885:   Args:
12886:    docuname: username or courseid of destination for the file
12887:    docudom: domain of user/course of destination for the file
12888:    dir: dir to create (including any subdirs under userfiles)
12889: 
12890: =item *
12891: 
12892: removeuserfile(): removes a file that exists in userfiles
12893: 
12894:   Args:
12895:    docuname: username or courseid of destination for the file
12896:    docudom: domain of user/course of destination for the file
12897:    fname: filname to delete (including any subdirs under userfiles)
12898: 
12899: =item *
12900: 
12901: removeuploadedurl(): convience function for removeuserfile()
12902: 
12903:   Args:
12904:    url:  a full /uploaded/... url to delete
12905: 
12906: =item * 
12907: 
12908: get_portfile_permissions():
12909:   Args:
12910:     domain: domain of user or course contain the portfolio files
12911:     user: name of user or num of course contain the portfolio files
12912:   Returns:
12913:     hashref of a dump of the proper file_permissions.db
12914:    
12915: 
12916: =item * 
12917: 
12918: get_access_controls():
12919: 
12920: Args:
12921:   current_permissions: the hash ref returned from get_portfile_permissions()
12922:   group: (optional) the group you want the files associated with
12923:   file: (optional) the file you want access info on
12924: 
12925: Returns:
12926:     a hash (keys are file names) of hashes containing
12927:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
12928:         values are XML containing access control settings (see below) 
12929: 
12930: Internal notes:
12931: 
12932:  access controls are stored in file_permissions.db as key=value pairs.
12933:     key -> path to file/file_name\0uniqueID:scope_end_start
12934:         where scope -> public,guest,course,group,domains or users.
12935:               end -> UNIX time for end of access (0 -> no end date)
12936:               start -> UNIX time for start of access
12937: 
12938:     value -> XML description of access control
12939:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
12940:             <start></start>
12941:             <end></end>
12942: 
12943:             <password></password>  for scope type = guest
12944: 
12945:             <domain></domain>     for scope type = course or group
12946:             <number></number>
12947:             <roles id="">
12948:              <role></role>
12949:              <access></access>
12950:              <section></section>
12951:              <group></group>
12952:             </roles>
12953: 
12954:             <dom></dom>         for scope type = domains
12955: 
12956:             <users>             for scope type = users
12957:              <user>
12958:               <uname></uname>
12959:               <udom></udom>
12960:              </user>
12961:             </users>
12962:            </scope> 
12963:               
12964:  Access data is also aggregated for each file in an additional key=value pair:
12965:  key -> path to file/file_name\0accesscontrol 
12966:  value -> reference to hash
12967:           hash contains key = value pairs
12968:           where key = uniqueID:scope_end_start
12969:                 value = UNIX time record was last updated
12970: 
12971:           Used to improve speed of look-ups of access controls for each file.  
12972:  
12973:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
12974: 
12975: modify_access_controls():
12976: 
12977: Modifies access controls for a portfolio file
12978: Args
12979: 1. file name
12980: 2. reference to hash of required changes,
12981: 3. domain
12982: 4. username
12983:   where domain,username are the domain of the portfolio owner 
12984:   (either a user or a course) 
12985: 
12986: Returns:
12987: 1. result of additions or updates ('ok' or 'error', with error message). 
12988: 2. result of deletions ('ok' or 'error', with error message).
12989: 3. reference to hash of any new or updated access controls.
12990: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
12991:    key = integer (inbound ID)
12992:    value = uniqueID  
12993: 
12994: =back
12995: 
12996: =head2 HTTP Helper Routines
12997: 
12998: =over 4
12999: 
13000: =item *
13001: 
13002: escape() : unpack non-word characters into CGI-compatible hex codes
13003: 
13004: =item *
13005: 
13006: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
13007: 
13008: =back
13009: 
13010: =head1 PRIVATE SUBROUTINES
13011: 
13012: =head2 Underlying communication routines (Shouldn't call)
13013: 
13014: =over 4
13015: 
13016: =item *
13017: 
13018: subreply() : tries to pass a message to lonc, returns con_lost if incapable
13019: 
13020: =item *
13021: 
13022: reply() : uses subreply to send a message to remote machine, logs all failures
13023: 
13024: =item *
13025: 
13026: critical() : passes a critical message to another server; if cannot
13027: get through then place message in connection buffer directory and
13028: returns con_delayed, if incapable of saving message, returns
13029: con_failed
13030: 
13031: =item *
13032: 
13033: reconlonc() : tries to reconnect lonc client processes.
13034: 
13035: =back
13036: 
13037: =head2 Resource Access Logging
13038: 
13039: =over 4
13040: 
13041: =item *
13042: 
13043: flushcourselogs() : flush (save) buffer logs and access logs
13044: 
13045: =item *
13046: 
13047: courselog($what) : save message for course in hash
13048: 
13049: =item *
13050: 
13051: courseacclog($what) : save message for course using &courselog().  Perform
13052: special processing for specific resource types (problems, exams, quizzes, etc).
13053: 
13054: =item *
13055: 
13056: goodbye() : flush course logs and log shutting down; it is called in srm.conf
13057: as a PerlChildExitHandler
13058: 
13059: =back
13060: 
13061: =head2 Other
13062: 
13063: =over 4
13064: 
13065: =item *
13066: 
13067: symblist($mapname,%newhash) : update symbolic storage links
13068: 
13069: =back
13070: 
13071: =cut
13072: 

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