File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1199: download - view: text, annotated - select for diffs
Tue Nov 27 23:45:22 2012 UTC (11 years, 7 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Breadcrumbs trail for uploaded content in nested folders in
  Supplemental Content.
- Breadcrumbs trail for external resource in Supplemental Content.
- lonwrapper.pm
  - more sanity checking in lonwrapper.pm.
  - increase offset for iframe when functions box is populated.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1199 2012/11/27 23:45:22 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: #
 2649: # Determine if the current user should be able to edit a particular resource,
 2650: # when viewing in course context.
 2651: # (a) When viewing resource used to determine if "Edit" item is included in 
 2652: #     Functions.
 2653: # (b) When displaying folder contents in course editor, used to determine if
 2654: #     "Edit" link will be displayed alongside resource.
 2655: #
 2656: #  input: six args -- filename (decluttered), course number, course domain,
 2657: #                   url, symb (if registered) and group (if this is a group
 2658: #                   item -- e.g., bulletin board, group page etc.).
 2659: #  output: array of five scalars -- 
 2660: #          $cfile -- url for file editing if editable on current server
 2661: #          $home -- homeserver of resource (i.e., for author if published,
 2662: #                                           or course if uploaded.).
 2663: #          $switchserver --  1 if server switch will be needed.
 2664: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 2665: #          $forceview -- 1 if icon/link should be to go to view mode
 2666: #
 2667: 
 2668: sub can_edit_resource {
 2669:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 2670:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 2671: #
 2672: # For aboutme pages user can only edit his/her own.
 2673: #
 2674:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 2675:         my ($sdom,$sname) = ($1,$2);
 2676:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 2677:             $home = $env{'user.home'};
 2678:             $cfile = $resurl;
 2679:             if ($env{'form.forceedit'}) {
 2680:                 $forceview = 1;
 2681:             } else {
 2682:                 $forceedit = 1;
 2683:             }
 2684:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 2685:         } else {
 2686:             return;
 2687:         }
 2688:     }
 2689: 
 2690:     if ($env{'request.course.id'}) {
 2691:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 2692:         if ($group ne '') {
 2693: # if this is a group homepage or group bulletin board, check group privs
 2694:             my $allowed = 0;
 2695:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 2696:                 if ((&allowed('mdg',$env{'request.course.id'}.
 2697:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 2698:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 2699:                     $allowed = 1;
 2700:                 }
 2701:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 2702:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 2703:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 2704:                     $allowed = 1;
 2705:                 }
 2706:             }
 2707:             if ($allowed) {
 2708:                 $home=&homeserver($cnum,$cdom);
 2709:                 if ($env{'form.forceedit'}) {
 2710:                     $forceview = 1;
 2711:                 } else {
 2712:                     $forceedit = 1;
 2713:                 }
 2714:                 $cfile = $resurl;
 2715:             } else {
 2716:                 return;
 2717:             }
 2718:         } else {
 2719: #
 2720: # No edit allowed where CC has switched to student role.
 2721: #
 2722:             unless ($crsedit) {
 2723:                 return;
 2724:             }
 2725:         }
 2726:     }
 2727: 
 2728:     if ($file ne '') {
 2729:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 2730:             if (&is_course_upload($file,$cnum,$cdom)) {
 2731:                 $uploaded = 1;
 2732:                 $incourse = 1;
 2733:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 2734:                     $cfile = &hreflocation('',$file);
 2735:                     $forceedit = 1;
 2736:                 }
 2737:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 2738:                 $incourse = 1;
 2739:                 if ($env{'form.forceedit'}) {
 2740:                     $forceview = 1;
 2741:                 } else {
 2742:                     $forceedit = 1;
 2743:                 }
 2744:                 $cfile = $resurl;
 2745:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 2746:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 2747:                     $incourse = 1;
 2748:                     if ($env{'form.forceedit'}) {
 2749:                         $forceview = 1;
 2750:                     } else {
 2751:                         $forceedit = 1;
 2752:                     }
 2753:                     $cfile = $resurl;
 2754:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 2755:                     $incourse = 1;
 2756:                     $cfile = $resurl.'/smpedit';
 2757:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 2758:                     $incourse = 1;
 2759:                     if ($env{'form.forceedit'}) {
 2760:                         $forceview = 1;
 2761:                     } else {
 2762:                         $forceedit = 1;
 2763:                     }
 2764:                     $cfile = $resurl;
 2765:                 }
 2766:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 2767:                 my $template = '/res/lib/templates/simpleproblem.problem';
 2768:                 if (&is_on_map($template)) { 
 2769:                     $incourse = 1;
 2770:                     $forceview = 1;
 2771:                     $cfile = $template;
 2772:                 }
 2773:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 2774:                     $incourse = 1;
 2775:                     if ($env{'form.forceedit'}) {
 2776:                         $forceview = 1;
 2777:                     } else {
 2778:                         $forceedit = 1;
 2779:                     }
 2780:                     $cfile = $resurl;
 2781:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 2782:                 $incourse = 1;
 2783:                 $forceview = 1;
 2784:                 if ($symb) {
 2785:                     my ($map,$id,$res)=&decode_symb($symb);
 2786:                     $env{'request.symb'} = $symb;
 2787:                     $cfile = &clutter($res);
 2788:                 } else {
 2789:                     $cfile = $env{'form.suppurl'};
 2790:                     $cfile =~ s{^http://}{};
 2791:                     $cfile = '/adm/wrapper/ext/'.$cfile;
 2792:                 }
 2793:             }
 2794:         }
 2795:         if ($uploaded || $incourse) {
 2796:             $home=&homeserver($cnum,$cdom);
 2797:         } else {
 2798:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 2799:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 2800:             # Check that the user has permission to edit this resource
 2801:             my $setpriv = 1;
 2802:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 2803:             if (defined($cfudom)) {
 2804:                 $home=&homeserver($cfuname,$cfudom);
 2805:                 $cfile=$file;
 2806:             }
 2807:         }
 2808:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 2809:             (($home ne '') && ($home ne 'no_host'))) {
 2810:             my @ids=&current_machine_ids();
 2811:             unless (grep(/^\Q$home\E$/,@ids)) {
 2812:                 $switchserver=1;
 2813:             }
 2814:         }
 2815:     }
 2816:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 2817: }
 2818: 
 2819: sub is_course_upload {
 2820:     my ($file,$cnum,$cdom) = @_;
 2821:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 2822:     $uploadpath =~ s{^\/}{};
 2823:     if (($file =~ m{^\Q$uploadpath\E/userfiles/docs/}) ||
 2824:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/docs/})) {
 2825:         return 1;
 2826:     }
 2827:     return;
 2828: }
 2829: 
 2830: sub in_course {
 2831:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 2832:     if ($hideprivileged) {
 2833:         my $skipuser;
 2834:         if (&privileged($uname,$udom)) {
 2835:             $skipuser = 1;
 2836:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 2837:             if ($coursehash{'nothideprivileged'}) {
 2838:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2839:                     my $user;
 2840:                     if ($item =~ /:/) {
 2841:                         $user = $item;
 2842:                     } else {
 2843:                         $user = join(':',split(/[\@]/,$item));
 2844:                     }
 2845:                     if ($user eq $uname.':'.$udom) {
 2846:                         undef($skipuser);
 2847:                         last;
 2848:                     }
 2849:                 }
 2850:             }
 2851:             if ($skipuser) {
 2852:                 return 0;
 2853:             }
 2854:         }
 2855:     }
 2856:     $type ||= 'any';
 2857:     if (!defined($cdom) || !defined($cnum)) {
 2858:         my $cid  = $env{'request.course.id'};
 2859:         $cdom = $env{'course.'.$cid.'.domain'};
 2860:         $cnum = $env{'course.'.$cid.'.num'};
 2861:     }
 2862:     my $typesref;
 2863:     if (($type eq 'any') || ($type eq 'all')) {
 2864:         $typesref = ['active','previous','future'];
 2865:     } elsif ($type eq 'previous' || $type eq 'future') {
 2866:         $typesref = [$type];
 2867:     }
 2868:     my %roles = &get_my_roles($uname,$udom,'userroles',
 2869:                               $typesref,undef,[$cdom]);
 2870:     my ($tmp) = keys(%roles);
 2871:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 2872:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 2873:     if (@course_roles > 0) {
 2874:         return 1;
 2875:     }
 2876:     return 0;
 2877: }
 2878: 
 2879: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 2880: # input: action, courseID, current domain, intended
 2881: #        path to file, source of file, instruction to parse file for objects,
 2882: #        ref to hash for embedded objects,
 2883: #        ref to hash for codebase of java objects.
 2884: #        reference to scalar to accommodate mime type determined
 2885: #          from File::MMagic if $parser = parse.
 2886: #
 2887: # output: url to file (if action was uploaddoc), 
 2888: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 2889: #
 2890: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 2891: # course.
 2892: #
 2893: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2894: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 2895: #          course's home server.
 2896: #
 2897: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 2898: #          be copied from $source (current location) to 
 2899: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2900: #         and will then be copied to
 2901: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 2902: #         course's home server.
 2903: #
 2904: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2905: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 2906: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2907: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 2908: #         in course's home server.
 2909: #
 2910: 
 2911: sub process_coursefile {
 2912:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 2913:         $mimetype)=@_;
 2914:     my $fetchresult;
 2915:     my $home=&homeserver($docuname,$docudom);
 2916:     if ($action eq 'propagate') {
 2917:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2918: 			     $home);
 2919:     } else {
 2920:         my $fpath = '';
 2921:         my $fname = $file;
 2922:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2923:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2924:         my $filepath = &build_filepath($fpath);
 2925:         if ($action eq 'copy') {
 2926:             if ($source eq '') {
 2927:                 $fetchresult = 'no source file';
 2928:                 return $fetchresult;
 2929:             } else {
 2930:                 my $destination = $filepath.'/'.$fname;
 2931:                 rename($source,$destination);
 2932:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2933:                                  $home);
 2934:             }
 2935:         } elsif ($action eq 'uploaddoc') {
 2936:             open(my $fh,'>'.$filepath.'/'.$fname);
 2937:             print $fh $env{'form.'.$source};
 2938:             close($fh);
 2939:             if ($parser eq 'parse') {
 2940:                 my $mm = new File::MMagic;
 2941:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 2942:                 if ($type eq 'text/html') {
 2943:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 2944:                     unless ($parse_result eq 'ok') {
 2945:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 2946:                     }
 2947:                 }
 2948:                 if (ref($mimetype)) {
 2949:                     $$mimetype = $type;
 2950:                 } 
 2951:             }
 2952:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2953:                                  $home);
 2954:             if ($fetchresult eq 'ok') {
 2955:                 return '/uploaded/'.$fpath.'/'.$fname;
 2956:             } else {
 2957:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2958:                         ' to host '.$home.': '.$fetchresult);
 2959:                 return '/adm/notfound.html';
 2960:             }
 2961:         }
 2962:     }
 2963:     unless ( $fetchresult eq 'ok') {
 2964:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2965:              ' to host '.$home.': '.$fetchresult);
 2966:     }
 2967:     return $fetchresult;
 2968: }
 2969: 
 2970: sub build_filepath {
 2971:     my ($fpath) = @_;
 2972:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 2973:     unless ($fpath eq '') {
 2974:         my @parts=split('/',$fpath);
 2975:         foreach my $part (@parts) {
 2976:             $filepath.= '/'.$part;
 2977:             if ((-e $filepath)!=1) {
 2978:                 mkdir($filepath,0777);
 2979:             }
 2980:         }
 2981:     }
 2982:     return $filepath;
 2983: }
 2984: 
 2985: sub store_edited_file {
 2986:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 2987:     my $file = $primary_url;
 2988:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 2989:     my $fpath = '';
 2990:     my $fname = $file;
 2991:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2992:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2993:     my $filepath = &build_filepath($fpath);
 2994:     open(my $fh,'>'.$filepath.'/'.$fname);
 2995:     print $fh $content;
 2996:     close($fh);
 2997:     my $home=&homeserver($docuname,$docudom);
 2998:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2999: 			  $home);
 3000:     if ($$fetchresult eq 'ok') {
 3001:         return '/uploaded/'.$fpath.'/'.$fname;
 3002:     } else {
 3003:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3004: 		 ' to host '.$home.': '.$$fetchresult);
 3005:         return '/adm/notfound.html';
 3006:     }
 3007: }
 3008: 
 3009: sub clean_filename {
 3010:     my ($fname,$args)=@_;
 3011: # Replace Windows backslashes by forward slashes
 3012:     $fname=~s/\\/\//g;
 3013:     if (!$args->{'keep_path'}) {
 3014:         # Get rid of everything but the actual filename
 3015: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 3016:     }
 3017: # Replace spaces by underscores
 3018:     $fname=~s/\s+/\_/g;
 3019: # Replace all other weird characters by nothing
 3020:     $fname=~s{[^/\w\.\-]}{}g;
 3021: # Replace all .\d. sequences with _\d. so they no longer look like version
 3022: # numbers
 3023:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 3024:     return $fname;
 3025: }
 3026: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 3027: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 3028: # image with the same aspect ratio as the original, but with dimensions which do 
 3029: # not exceed $resizewidth and $resizeheight.
 3030:  
 3031: sub resizeImage {
 3032:     my ($img_path,$resizewidth,$resizeheight) = @_;
 3033:     my $ima = Image::Magick->new;
 3034:     my $resized;
 3035:     if (-e $img_path) {
 3036:         $ima->Read($img_path);
 3037:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 3038:             my $width = $ima->Get('width');
 3039:             my $height = $ima->Get('height');
 3040:             if ($width > $resizewidth) {
 3041: 	        my $factor = $width/$resizewidth;
 3042:                 my $newheight = $height/$factor;
 3043:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 3044:                 $resized = 1;
 3045:             }
 3046:         }
 3047:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 3048:             my $width = $ima->Get('width');
 3049:             my $height = $ima->Get('height');
 3050:             if ($height > $resizeheight) {
 3051:                 my $factor = $height/$resizeheight;
 3052:                 my $newwidth = $width/$factor;
 3053:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 3054:                 $resized = 1;
 3055:             }
 3056:         }
 3057:         if ($resized) {
 3058:             $ima->Write($img_path);
 3059:         }
 3060:     }
 3061:     return;
 3062: }
 3063: 
 3064: # --------------- Take an uploaded file and put it into the userfiles directory
 3065: # input: $formname - the contents of the file are in $env{"form.$formname"}
 3066: #                    the desired filename is in $env{"form.$formname.filename"}
 3067: #        $context - possible values: coursedoc, existingfile, overwrite, 
 3068: #                                    canceloverwrite, or ''. 
 3069: #                   if 'coursedoc': upload to the current course
 3070: #                   if 'existingfile': write file to tmp/overwrites directory 
 3071: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 3072: #                   $context is passed as argument to &finishuserfileupload
 3073: #        $subdir - directory in userfile to store the file into
 3074: #        $parser - instruction to parse file for objects ($parser = parse)    
 3075: #        $allfiles - reference to hash for embedded objects
 3076: #        $codebase - reference to hash for codebase of java objects
 3077: #        $desuname - username for permanent storage of uploaded file
 3078: #        $dsetudom - domain for permanaent storage of uploaded file
 3079: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 3080: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 3081: #        $resizewidth - width (pixels) to which to resize uploaded image
 3082: #        $resizeheight - height (pixels) to which to resize uploaded image
 3083: #        $mimetype - reference to scalar to accommodate mime type determined
 3084: #                    from File::MMagic.
 3085: # 
 3086: # output: url of file in userspace, or error: <message> 
 3087: #             or /adm/notfound.html if failure to upload occurse
 3088: 
 3089: sub userfileupload {
 3090:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 3091:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 3092:     if (!defined($subdir)) { $subdir='unknown'; }
 3093:     my $fname=$env{'form.'.$formname.'.filename'};
 3094:     $fname=&clean_filename($fname);
 3095:     # See if there is anything left
 3096:     unless ($fname) { return 'error: no uploaded file'; }
 3097:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 3098:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 3099:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 3100:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3101:         my $now = time;
 3102:         my $filepath;
 3103:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 3104:              $filepath = 'tmp/helprequests/'.$now;
 3105:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 3106:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 3107:                          '_'.$env{'user.domain'}.'/pending';
 3108:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3109:             my ($docuname,$docudom);
 3110:             if ($destudom) {
 3111:                 $docudom = $destudom;
 3112:             } else {
 3113:                 $docudom = $env{'user.domain'};
 3114:             }
 3115:             if ($destuname) {
 3116:                 $docuname = $destuname;
 3117:             } else {
 3118:                 $docuname = $env{'user.name'};
 3119:             }
 3120:             if (exists($env{'form.group'})) {
 3121:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3122:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3123:             }
 3124:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 3125:             if ($context eq 'canceloverwrite') {
 3126:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 3127:                 if (-e  $tempfile) {
 3128:                     my @info = stat($tempfile);
 3129:                     if ($info[9] eq $env{'form.timestamp'}) {
 3130:                         unlink($tempfile);
 3131:                     }
 3132:                 }
 3133:                 return;
 3134:             }
 3135:         }
 3136:         # Create the directory if not present
 3137:         my @parts=split(/\//,$filepath);
 3138:         my $fullpath = $perlvar{'lonDaemons'};
 3139:         for (my $i=0;$i<@parts;$i++) {
 3140:             $fullpath .= '/'.$parts[$i];
 3141:             if ((-e $fullpath)!=1) {
 3142:                 mkdir($fullpath,0777);
 3143:             }
 3144:         }
 3145:         open(my $fh,'>'.$fullpath.'/'.$fname);
 3146:         print $fh $env{'form.'.$formname};
 3147:         close($fh);
 3148:         if ($context eq 'existingfile') {
 3149:             my @info = stat($fullpath.'/'.$fname);
 3150:             return ($fullpath.'/'.$fname,$info[9]);
 3151:         } else {
 3152:             return $fullpath.'/'.$fname;
 3153:         }
 3154:     }
 3155:     if ($subdir eq 'scantron') {
 3156:         $fname = 'scantron_orig_'.$fname;
 3157:     } else {
 3158:         $fname="$subdir/$fname";
 3159:     }
 3160:     if ($context eq 'coursedoc') {
 3161: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3162: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3163:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 3164:             return &finishuserfileupload($docuname,$docudom,
 3165: 					 $formname,$fname,$parser,$allfiles,
 3166: 					 $codebase,$thumbwidth,$thumbheight,
 3167:                                          $resizewidth,$resizeheight,$context,$mimetype);
 3168:         } else {
 3169:             $fname=$env{'form.folder'}.'/'.$fname;
 3170:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 3171: 				       $fname,$formname,$parser,
 3172: 				       $allfiles,$codebase,$mimetype);
 3173:         }
 3174:     } elsif (defined($destuname)) {
 3175:         my $docuname=$destuname;
 3176:         my $docudom=$destudom;
 3177: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3178: 				     $parser,$allfiles,$codebase,
 3179:                                      $thumbwidth,$thumbheight,
 3180:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3181:     } else {
 3182:         my $docuname=$env{'user.name'};
 3183:         my $docudom=$env{'user.domain'};
 3184:         if (exists($env{'form.group'})) {
 3185:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3186:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3187:         }
 3188: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3189: 				     $parser,$allfiles,$codebase,
 3190:                                      $thumbwidth,$thumbheight,
 3191:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3192:     }
 3193: }
 3194: 
 3195: sub finishuserfileupload {
 3196:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 3197:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 3198:     my $path=$docudom.'/'.$docuname.'/';
 3199:     my $filepath=$perlvar{'lonDocRoot'};
 3200:   
 3201:     my ($fnamepath,$file,$fetchthumb);
 3202:     $file=$fname;
 3203:     if ($fname=~m|/|) {
 3204:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 3205: 	$path.=$fnamepath.'/';
 3206:     }
 3207:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 3208:     my $count;
 3209:     for ($count=4;$count<=$#parts;$count++) {
 3210:         $filepath.="/$parts[$count]";
 3211:         if ((-e $filepath)!=1) {
 3212: 	    mkdir($filepath,0777);
 3213:         }
 3214:     }
 3215: 
 3216: # Save the file
 3217:     {
 3218: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 3219: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 3220: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 3221: 	    return '/adm/notfound.html';
 3222: 	}
 3223:         if ($context eq 'overwrite') {
 3224:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 3225:             my $target = $filepath.'/'.$file;
 3226:             if (-e $source) {
 3227:                 my @info = stat($source);
 3228:                 if ($info[9] eq $env{'form.timestamp'}) {   
 3229:                     unless (&File::Copy::move($source,$target)) {
 3230:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 3231:                         return "Moving from $source failed";
 3232:                     }
 3233:                 } else {
 3234:                     return "Temporary file: $source had unexpected date/time for last modification";
 3235:                 }
 3236:             } else {
 3237:                 return "Temporary file: $source missing";
 3238:             }
 3239:         } elsif (!print FH ($env{'form.'.$formname})) {
 3240: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 3241: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 3242: 	    return '/adm/notfound.html';
 3243: 	}
 3244: 	close(FH);
 3245:         if ($resizewidth && $resizeheight) {
 3246:             my $mm = new File::MMagic;
 3247:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 3248:             if ($mime_type =~ m{^image/}) {
 3249: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 3250:             }  
 3251: 	}
 3252:     }
 3253:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 3254:         if (ref($mimetype)) {
 3255:             if ($$mimetype eq '') {
 3256:                 my $mm = new File::MMagic;
 3257:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 3258:                 $$mimetype = $type;
 3259:             }
 3260:         }
 3261:     }
 3262:     if ($parser eq 'parse') {
 3263:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 3264:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 3265:                                                        $allfiles,$codebase);
 3266:             unless ($parse_result eq 'ok') {
 3267:                 &logthis('Failed to parse '.$filepath.$file.
 3268: 	   	         ' for embedded media: '.$parse_result); 
 3269:             }
 3270:         }
 3271:     }
 3272:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 3273:         my $input = $filepath.'/'.$file;
 3274:         my $output = $filepath.'/'.'tn-'.$file;
 3275:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 3276:         system("convert -sample $thumbsize $input $output");
 3277:         if (-e $filepath.'/'.'tn-'.$file) {
 3278:             $fetchthumb  = 1; 
 3279:         }
 3280:     }
 3281:  
 3282: # Notify homeserver to grep it
 3283: #
 3284:     my $docuhome=&homeserver($docuname,$docudom);	
 3285:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 3286:     if ($fetchresult eq 'ok') {
 3287:         if ($fetchthumb) {
 3288:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 3289:             if ($thumbresult ne 'ok') {
 3290:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 3291:                          $docuhome.': '.$thumbresult);
 3292:             }
 3293:         }
 3294: #
 3295: # Return the URL to it
 3296:         return '/uploaded/'.$path.$file;
 3297:     } else {
 3298:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 3299: 		 ': '.$fetchresult);
 3300:         return '/adm/notfound.html';
 3301:     }
 3302: }
 3303: 
 3304: sub extract_embedded_items {
 3305:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 3306:     my @state = ();
 3307:     my (%lastids,%related,%shockwave,%flashvars);
 3308:     my %javafiles = (
 3309:                       codebase => '',
 3310:                       code => '',
 3311:                       archive => ''
 3312:                     );
 3313:     my %mediafiles = (
 3314:                       src => '',
 3315:                       movie => '',
 3316:                      );
 3317:     my $p;
 3318:     if ($content) {
 3319:         $p = HTML::LCParser->new($content);
 3320:     } else {
 3321:         $p = HTML::LCParser->new($fullpath);
 3322:     }
 3323:     while (my $t=$p->get_token()) {
 3324: 	if ($t->[0] eq 'S') {
 3325: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 3326: 	    push(@state, $tagname);
 3327:             if (lc($tagname) eq 'allow') {
 3328:                 &add_filetype($allfiles,$attr->{'src'},'src');
 3329:             }
 3330: 	    if (lc($tagname) eq 'img') {
 3331: 		&add_filetype($allfiles,$attr->{'src'},'src');
 3332: 	    }
 3333: 	    if (lc($tagname) eq 'a') {
 3334: 		&add_filetype($allfiles,$attr->{'href'},'href');
 3335: 	    }
 3336:             if (lc($tagname) eq 'script') {
 3337:                 my $src;
 3338:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 3339:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 3340:                 } else {
 3341:                     if ($attr->{'src'} ne '') {
 3342:                         $src = $attr->{'src'};
 3343:                         &add_filetype($allfiles,$src,'src');
 3344:                     }
 3345:                 }
 3346:                 my $text = $p->get_trimmed_text();
 3347:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 3348:                     my @swfargs = split(/,/,$1);
 3349:                     foreach my $item (@swfargs) {
 3350:                         $item =~ s/["']//g;
 3351:                         $item =~ s/^\s+//;
 3352:                         $item =~ s/\s+$//;
 3353:                     }
 3354:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 3355:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 3356:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 3357:                         } else {
 3358:                             $related{$swfargs[0]} = [$swfargs[2]];
 3359:                         }
 3360:                     }
 3361:                 }
 3362:             }
 3363:             if (lc($tagname) eq 'link') {
 3364:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 3365:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3366:                 }
 3367:             }
 3368: 	    if (lc($tagname) eq 'object' ||
 3369: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 3370: 		foreach my $item (keys(%javafiles)) {
 3371: 		    $javafiles{$item} = '';
 3372: 		}
 3373:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 3374:                     $lastids{lc($tagname)} = $attr->{'id'};
 3375:                 }
 3376: 	    }
 3377: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 3378: 		my $name = lc($attr->{'name'});
 3379: 		foreach my $item (keys(%javafiles)) {
 3380: 		    if ($name eq $item) {
 3381: 			$javafiles{$item} = $attr->{'value'};
 3382: 			last;
 3383: 		    }
 3384: 		}
 3385:                 my $pathfrom;
 3386: 		foreach my $item (keys(%mediafiles)) {
 3387: 		    if ($name eq $item) {
 3388:                         $pathfrom = $attr->{'value'};
 3389:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 3390: 			&add_filetype($allfiles,$pathfrom,$name);
 3391: 			last;
 3392: 		    }
 3393: 		}
 3394:                 if ($name eq 'flashvars') {
 3395:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 3396:                 }
 3397:                 if ($pathfrom ne '') {
 3398:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 3399:                                          $pathfrom);
 3400:                 }
 3401: 	    }
 3402: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 3403: 		foreach my $item (keys(%javafiles)) {
 3404: 		    if ($attr->{$item}) {
 3405: 			$javafiles{$item} = $attr->{$item};
 3406: 			last;
 3407: 		    }
 3408: 		}
 3409: 		foreach my $item (keys(%mediafiles)) {
 3410: 		    if ($attr->{$item}) {
 3411: 			&add_filetype($allfiles,$attr->{$item},$item);
 3412: 			last;
 3413: 		    }
 3414: 		}
 3415:                 if (lc($tagname) eq 'embed') {
 3416:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 3417:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 3418:                                              $attr->{'src'});
 3419:                     }
 3420:                 }
 3421: 	    }
 3422:             if ($t->[4] =~ m{/>$}) {
 3423:                 pop(@state);  
 3424:             }
 3425: 	} elsif ($t->[0] eq 'E') {
 3426: 	    my ($tagname) = ($t->[1]);
 3427: 	    if ($javafiles{'codebase'} ne '') {
 3428: 		$javafiles{'codebase'} .= '/';
 3429: 	    }  
 3430: 	    if (lc($tagname) eq 'applet' ||
 3431: 		lc($tagname) eq 'object' ||
 3432: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 3433: 		) {
 3434: 		foreach my $item (keys(%javafiles)) {
 3435: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 3436: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 3437: 			&add_filetype($allfiles,$file,$item);
 3438: 		    }
 3439: 		}
 3440: 	    } 
 3441: 	    pop @state;
 3442: 	}
 3443:     }
 3444:     foreach my $id (sort(keys(%flashvars))) {
 3445:         if ($shockwave{$id} ne '') {
 3446:             my @pairs = split(/\&/,$flashvars{$id});
 3447:             foreach my $pair (@pairs) {
 3448:                 my ($key,$value) = split(/\=/,$pair);
 3449:                 if ($key eq 'thumb') {
 3450:                     &add_filetype($allfiles,$value,$key);
 3451:                 } elsif ($key eq 'content') {
 3452:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 3453:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 3454:                     if ($ext ne '') {
 3455:                         &add_filetype($allfiles,$path.$value,$ext);
 3456:                     }
 3457:                 }
 3458:             }
 3459:         }
 3460:     }
 3461:     return 'ok';
 3462: }
 3463: 
 3464: sub add_filetype {
 3465:     my ($allfiles,$file,$type)=@_;
 3466:     if (exists($allfiles->{$file})) {
 3467: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 3468: 	    push(@{$allfiles->{$file}}, &escape($type));
 3469: 	}
 3470:     } else {
 3471: 	@{$allfiles->{$file}} = (&escape($type));
 3472:     }
 3473: }
 3474: 
 3475: sub embedded_dependency {
 3476:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 3477:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 3478:         if (($identifier ne '') &&
 3479:             (ref($related->{$identifier}) eq 'ARRAY') &&
 3480:             ($pathfrom ne '')) {
 3481:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 3482:             foreach my $dep (@{$related->{$identifier}}) {
 3483:                 &add_filetype($allfiles,$path.$dep,'object');
 3484:             }
 3485:         }
 3486:     }
 3487:     return;
 3488: }
 3489: 
 3490: sub removeuploadedurl {
 3491:     my ($url)=@_;	
 3492:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 3493:     return &removeuserfile($uname,$udom,$fname);
 3494: }
 3495: 
 3496: sub removeuserfile {
 3497:     my ($docuname,$docudom,$fname)=@_;
 3498:     my $home=&homeserver($docuname,$docudom);    
 3499:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 3500:     if ($result eq 'ok') {	
 3501:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 3502:             my $metafile = $fname.'.meta';
 3503:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 3504: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 3505:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 3506:             my $sqlresult = 
 3507:                 &update_portfolio_table($docuname,$docudom,$file,
 3508:                                         'portfolio_metadata',$group,
 3509:                                         'delete');
 3510:         }
 3511:     }
 3512:     return $result;
 3513: }
 3514: 
 3515: sub mkdiruserfile {
 3516:     my ($docuname,$docudom,$dir)=@_;
 3517:     my $home=&homeserver($docuname,$docudom);
 3518:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 3519: }
 3520: 
 3521: sub renameuserfile {
 3522:     my ($docuname,$docudom,$old,$new)=@_;
 3523:     my $home=&homeserver($docuname,$docudom);
 3524:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 3525:                         &escape("$old").':'.&escape("$new"),$home);
 3526:     if ($result eq 'ok') {
 3527:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 3528:             my $oldmeta = $old.'.meta';
 3529:             my $newmeta = $new.'.meta';
 3530:             my $metaresult = 
 3531:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 3532: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 3533:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 3534:             my $sqlresult = 
 3535:                 &update_portfolio_table($docuname,$docudom,$file,
 3536:                                         'portfolio_metadata',$group,
 3537:                                         'delete');
 3538:         }
 3539:     }
 3540:     return $result;
 3541: }
 3542: 
 3543: # ------------------------------------------------------------------------- Log
 3544: 
 3545: sub log {
 3546:     my ($dom,$nam,$hom,$what)=@_;
 3547:     return critical("log:$dom:$nam:$what",$hom);
 3548: }
 3549: 
 3550: # ------------------------------------------------------------------ Course Log
 3551: #
 3552: # This routine flushes several buffers of non-mission-critical nature
 3553: #
 3554: 
 3555: sub flushcourselogs {
 3556:     &logthis('Flushing log buffers');
 3557: #
 3558: # course logs
 3559: # This is a log of all transactions in a course, which can be used
 3560: # for data mining purposes
 3561: #
 3562: # It also collects the courseid database, which lists last transaction
 3563: # times and course titles for all courseids
 3564: #
 3565:     my %courseidbuffer=();
 3566:     foreach my $crsid (keys(%courselogs)) {
 3567:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 3568: 		          &escape($courselogs{$crsid}),
 3569: 		          $coursehombuf{$crsid}) eq 'ok') {
 3570: 	    delete $courselogs{$crsid};
 3571:         } else {
 3572:             &logthis('Failed to flush log buffer for '.$crsid);
 3573:             if (length($courselogs{$crsid})>40000) {
 3574:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 3575:                         " exceeded maximum size, deleting.</font>");
 3576:                delete $courselogs{$crsid};
 3577:             }
 3578:         }
 3579:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 3580:             'description' => $coursedescrbuf{$crsid},
 3581:             'inst_code'    => $courseinstcodebuf{$crsid},
 3582:             'type'        => $coursetypebuf{$crsid},
 3583:             'owner'       => $courseownerbuf{$crsid},
 3584:         };
 3585:     }
 3586: #
 3587: # Write course id database (reverse lookup) to homeserver of courses 
 3588: # Is used in pickcourse
 3589: #
 3590:     foreach my $crs_home (keys(%courseidbuffer)) {
 3591:         my $response = &courseidput(&host_domain($crs_home),
 3592:                                     $courseidbuffer{$crs_home},
 3593:                                     $crs_home,'timeonly');
 3594:     }
 3595: #
 3596: # File accesses
 3597: # Writes to the dynamic metadata of resources to get hit counts, etc.
 3598: #
 3599:     foreach my $entry (keys(%accesshash)) {
 3600:         if ($entry =~ /___count$/) {
 3601:             my ($dom,$name);
 3602:             ($dom,$name,undef)=
 3603: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 3604:             if (! defined($dom) || $dom eq '' || 
 3605:                 ! defined($name) || $name eq '') {
 3606:                 my $cid = $env{'request.course.id'};
 3607:                 $dom  = $env{'request.'.$cid.'.domain'};
 3608:                 $name = $env{'request.'.$cid.'.num'};
 3609:             }
 3610:             my $value = $accesshash{$entry};
 3611:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 3612:             my %temphash=($url => $value);
 3613:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 3614:             if ($result eq 'ok') {
 3615:                 delete $accesshash{$entry};
 3616:             }
 3617:         } else {
 3618:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 3619:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 3620:             my %temphash=($entry => $accesshash{$entry});
 3621:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 3622:                 delete $accesshash{$entry};
 3623:             }
 3624:         }
 3625:     }
 3626: #
 3627: # Roles
 3628: # Reverse lookup of user roles for course faculty/staff and co-authorship
 3629: #
 3630:     foreach my $entry (keys(%userrolehash)) {
 3631:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 3632: 	    split(/\:/,$entry);
 3633:         if (&Apache::lonnet::put('nohist_userroles',
 3634:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 3635:                 $rudom,$runame) eq 'ok') {
 3636: 	    delete $userrolehash{$entry};
 3637:         }
 3638:     }
 3639: #
 3640: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 3641: #
 3642:     my %domrolebuffer = ();
 3643:     foreach my $entry (keys(%domainrolehash)) {
 3644:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 3645:         if ($domrolebuffer{$rudom}) {
 3646:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 3647:                       '='.&escape($domainrolehash{$entry});
 3648:         } else {
 3649:             $domrolebuffer{$rudom}.=&escape($entry).
 3650:                       '='.&escape($domainrolehash{$entry});
 3651:         }
 3652:         delete $domainrolehash{$entry};
 3653:     }
 3654:     foreach my $dom (keys(%domrolebuffer)) {
 3655: 	my %servers = &get_servers($dom,'library');
 3656: 	foreach my $tryserver (keys(%servers)) {
 3657: 	    unless (&reply('domroleput:'.$dom.':'.
 3658: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 3659: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 3660: 	    }
 3661:         }
 3662:     }
 3663:     $dumpcount++;
 3664: }
 3665: 
 3666: sub courselog {
 3667:     my $what=shift;
 3668:     $what=time.':'.$what;
 3669:     unless ($env{'request.course.id'}) { return ''; }
 3670:     $coursedombuf{$env{'request.course.id'}}=
 3671:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 3672:     $coursenumbuf{$env{'request.course.id'}}=
 3673:        $env{'course.'.$env{'request.course.id'}.'.num'};
 3674:     $coursehombuf{$env{'request.course.id'}}=
 3675:        $env{'course.'.$env{'request.course.id'}.'.home'};
 3676:     $coursedescrbuf{$env{'request.course.id'}}=
 3677:        $env{'course.'.$env{'request.course.id'}.'.description'};
 3678:     $courseinstcodebuf{$env{'request.course.id'}}=
 3679:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 3680:     $courseownerbuf{$env{'request.course.id'}}=
 3681:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 3682:     $coursetypebuf{$env{'request.course.id'}}=
 3683:        $env{'course.'.$env{'request.course.id'}.'.type'};
 3684:     if (defined $courselogs{$env{'request.course.id'}}) {
 3685: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 3686:     } else {
 3687: 	$courselogs{$env{'request.course.id'}}.=$what;
 3688:     }
 3689:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 3690: 	&flushcourselogs();
 3691:     }
 3692: }
 3693: 
 3694: sub courseacclog {
 3695:     my $fnsymb=shift;
 3696:     unless ($env{'request.course.id'}) { return ''; }
 3697:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 3698:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 3699:         $what.=':POST';
 3700:         # FIXME: Probably ought to escape things....
 3701: 	foreach my $key (keys(%env)) {
 3702:             if ($key=~/^form\.(.*)/) {
 3703:                 my $formitem = $1;
 3704:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 3705:                     $what.=':'.$formitem.'='.$env{$key};
 3706:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 3707:                     $what.=':'.$formitem.'='.$env{$key};
 3708:                 }
 3709:             }
 3710:         }
 3711:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 3712:         # FIXME: We should not be depending on a form parameter that someone
 3713:         # editing lonsearchcat.pm might change in the future.
 3714:         if ($env{'form.phase'} eq 'course_search') {
 3715:             $what.= ':POST';
 3716:             # FIXME: Probably ought to escape things....
 3717:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 3718:                                  'crsdiscuss') {
 3719:                 $what.=':'.$element.'='.$env{'form.'.$element};
 3720:             }
 3721:         }
 3722:     }
 3723:     &courselog($what);
 3724: }
 3725: 
 3726: sub countacc {
 3727:     my $url=&declutter(shift);
 3728:     return if (! defined($url) || $url eq '');
 3729:     unless ($env{'request.course.id'}) { return ''; }
 3730: #
 3731: # Mark that this url was used in this course
 3732: #
 3733:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 3734: #
 3735: # Increase the access count for this resource in this child process
 3736: #
 3737:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 3738:     $accesshash{$key}++;
 3739: }
 3740: 
 3741: sub linklog {
 3742:     my ($from,$to)=@_;
 3743:     $from=&declutter($from);
 3744:     $to=&declutter($to);
 3745:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 3746:     $accesshash{$to.'___'.$from.'___goto'}=1;
 3747: }
 3748: 
 3749: sub statslog {
 3750:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 3751:     if ($users<2) { return; }
 3752:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 3753:             'course'       => $env{'request.course.id'},
 3754:             'sections'     => '"all"',
 3755:             'num_students' => $users,
 3756:             'part'         => $part,
 3757:             'symb'         => $symb,
 3758:             'mean_tries'   => $av_attempts,
 3759:             'deg_of_diff'  => $degdiff});
 3760:     foreach my $key (keys(%dynstore)) {
 3761:         $accesshash{$key}=$dynstore{$key};
 3762:     }
 3763: }
 3764:   
 3765: sub userrolelog {
 3766:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 3767:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 3768:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3769:        $userrolehash
 3770:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3771:                     =$tend.':'.$tstart;
 3772:     }
 3773:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 3774:        $userrolehash
 3775:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 3776:                     =$tend.':'.$tstart;
 3777:     }
 3778:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
 3779:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3780:        $domainrolehash
 3781:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3782:                     = $tend.':'.$tstart;
 3783:     }
 3784: }
 3785: 
 3786: sub courserolelog {
 3787:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 3788:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 3789:         my $cdom = $1;
 3790:         my $cnum = $2;
 3791:         my $sec = $3;
 3792:         my $namespace = 'rolelog';
 3793:         my %storehash = (
 3794:                            role    => $trole,
 3795:                            start   => $tstart,
 3796:                            end     => $tend,
 3797:                            selfenroll => $selfenroll,
 3798:                            context    => $context,
 3799:                         );
 3800:         if ($trole eq 'gr') {
 3801:             $namespace = 'groupslog';
 3802:             $storehash{'group'} = $sec;
 3803:         } else {
 3804:             $storehash{'section'} = $sec;
 3805:         }
 3806:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 3807:                    $domain,$cnum,$cdom);
 3808:         if (($trole ne 'st') || ($sec ne '')) {
 3809:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 3810:         }
 3811:     }
 3812:     return;
 3813: }
 3814: 
 3815: sub domainrolelog {
 3816:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 3817:     if ($area =~ m{^/($match_domain)/$}) {
 3818:         my $cdom = $1;
 3819:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 3820:         my $namespace = 'rolelog';
 3821:         my %storehash = (
 3822:                            role    => $trole,
 3823:                            start   => $tstart,
 3824:                            end     => $tend,
 3825:                            context => $context,
 3826:                         );
 3827:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 3828:                    $domain,$domconfiguser,$cdom);
 3829:     }
 3830:     return;
 3831: 
 3832: }
 3833: 
 3834: sub coauthorrolelog {
 3835:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 3836:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 3837:         my $audom = $1;
 3838:         my $auname = $2;
 3839:         my $namespace = 'rolelog';
 3840:         my %storehash = (
 3841:                            role    => $trole,
 3842:                            start   => $tstart,
 3843:                            end     => $tend,
 3844:                            context => $context,
 3845:                         );
 3846:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 3847:                    $domain,$auname,$audom);
 3848:     }
 3849:     return;
 3850: }
 3851: 
 3852: sub get_course_adv_roles {
 3853:     my ($cid,$codes) = @_;
 3854:     $cid=$env{'request.course.id'} unless (defined($cid));
 3855:     my %coursehash=&coursedescription($cid);
 3856:     my $crstype = &Apache::loncommon::course_type($cid);
 3857:     my %nothide=();
 3858:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3859:         if ($user !~ /:/) {
 3860: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 3861:         } else {
 3862:             $nothide{$user}=1;
 3863:         }
 3864:     }
 3865:     my %returnhash=();
 3866:     my %dumphash=
 3867:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 3868:     my $now=time;
 3869:     my %privileged;
 3870:     foreach my $entry (keys(%dumphash)) {
 3871: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 3872:         if (($tstart) && ($tstart<0)) { next; }
 3873:         if (($tend) && ($tend<$now)) { next; }
 3874:         if (($tstart) && ($now<$tstart)) { next; }
 3875:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 3876: 	if ($username eq '' || $domain eq '') { next; }
 3877:         unless (ref($privileged{$domain}) eq 'HASH') {
 3878:             my %dompersonnel =
 3879:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 3880:             $privileged{$domain} = {};
 3881:             foreach my $server (keys(%dompersonnel)) {
 3882:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 3883:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
 3884:                         my ($trole,$uname,$udom) = split(/:/,$user);
 3885:                         $privileged{$udom}{$uname} = 1;
 3886:                     }
 3887:                 }
 3888:             }
 3889:         }
 3890:         if ((exists($privileged{$domain}{$username})) && 
 3891:             (!$nothide{$username.':'.$domain})) { next; }
 3892: 	if ($role eq 'cr') { next; }
 3893:         if ($codes) {
 3894:             if ($section) { $role .= ':'.$section; }
 3895:             if ($returnhash{$role}) {
 3896:                 $returnhash{$role}.=','.$username.':'.$domain;
 3897:             } else {
 3898:                 $returnhash{$role}=$username.':'.$domain;
 3899:             }
 3900:         } else {
 3901:             my $key=&plaintext($role,$crstype);
 3902:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 3903:             if ($returnhash{$key}) {
 3904: 	        $returnhash{$key}.=','.$username.':'.$domain;
 3905:             } else {
 3906:                 $returnhash{$key}=$username.':'.$domain;
 3907:             }
 3908:         }
 3909:     }
 3910:     return %returnhash;
 3911: }
 3912: 
 3913: sub get_my_roles {
 3914:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 3915:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 3916:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 3917:     my (%dumphash,%nothide);
 3918:     if ($context eq 'userroles') {
 3919:         %dumphash = &dump('roles',$udom,$uname);
 3920:     } else {
 3921:         %dumphash=
 3922:             &dump('nohist_userroles',$udom,$uname);
 3923:         if ($hidepriv) {
 3924:             my %coursehash=&coursedescription($udom.'_'.$uname);
 3925:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3926:                 if ($user !~ /:/) {
 3927:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 3928:                 } else {
 3929:                     $nothide{$user} = 1;
 3930:                 }
 3931:             }
 3932:         }
 3933:     }
 3934:     my %returnhash=();
 3935:     my $now=time;
 3936:     my %privileged;
 3937:     foreach my $entry (keys(%dumphash)) {
 3938:         my ($role,$tend,$tstart);
 3939:         if ($context eq 'userroles') {
 3940:             next if ($entry =~ /^rolesdef/);
 3941: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 3942:         } else {
 3943:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 3944:         }
 3945:         if (($tstart) && ($tstart<0)) { next; }
 3946:         my $status = 'active';
 3947:         if (($tend) && ($tend<=$now)) {
 3948:             $status = 'previous';
 3949:         } 
 3950:         if (($tstart) && ($now<$tstart)) {
 3951:             $status = 'future';
 3952:         }
 3953:         if (ref($types) eq 'ARRAY') {
 3954:             if (!grep(/^\Q$status\E$/,@{$types})) {
 3955:                 next;
 3956:             } 
 3957:         } else {
 3958:             if ($status ne 'active') {
 3959:                 next;
 3960:             }
 3961:         }
 3962:         my ($rolecode,$username,$domain,$section,$area);
 3963:         if ($context eq 'userroles') {
 3964:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 3965:             (undef,$domain,$username,$section) = split(/\//,$area);
 3966:         } else {
 3967:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 3968:         }
 3969:         if (ref($roledoms) eq 'ARRAY') {
 3970:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 3971:                 next;
 3972:             }
 3973:         }
 3974:         if (ref($roles) eq 'ARRAY') {
 3975:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 3976:                 if ($role =~ /^cr\//) {
 3977:                     if (!grep(/^cr$/,@{$roles})) {
 3978:                         next;
 3979:                     }
 3980:                 } elsif ($role =~ /^gr\//) {
 3981:                     if (!grep(/^gr$/,@{$roles})) {
 3982:                         next;
 3983:                     }
 3984:                 } else {
 3985:                     next;
 3986:                 }
 3987:             }
 3988:         }
 3989:         if ($hidepriv) {
 3990:             if ($context eq 'userroles') {
 3991:                 if ((&privileged($username,$domain)) &&
 3992:                     (!$nothide{$username.':'.$domain})) {
 3993:                     next;
 3994:                 }
 3995:             } else {
 3996:                 unless (ref($privileged{$domain}) eq 'HASH') {
 3997:                     my %dompersonnel =
 3998:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 3999:                     $privileged{$domain} = {};
 4000:                     if (keys(%dompersonnel)) {
 4001:                         foreach my $server (keys(%dompersonnel)) {
 4002:                             if (ref($dompersonnel{$server}) eq 'HASH') {
 4003:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
 4004:                                     my ($trole,$uname,$udom) = split(/:/,$user);
 4005:                                     $privileged{$udom}{$uname} = $trole;
 4006:                                 }
 4007:                             }
 4008:                         }
 4009:                     }
 4010:                 }
 4011:                 if (exists($privileged{$domain}{$username})) {
 4012:                     if (!$nothide{$username.':'.$domain}) {
 4013:                         next;
 4014:                     }
 4015:                 }
 4016:             }
 4017:         }
 4018:         if ($withsec) {
 4019:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 4020:                 $tstart.':'.$tend;
 4021:         } else {
 4022:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 4023:         }
 4024:     }
 4025:     return %returnhash;
 4026: }
 4027: 
 4028: # ----------------------------------------------------- Frontpage Announcements
 4029: #
 4030: #
 4031: 
 4032: sub postannounce {
 4033:     my ($server,$text)=@_;
 4034:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 4035:     unless ($text=~/\w/) { $text=''; }
 4036:     return &reply('setannounce:'.&escape($text),$server);
 4037: }
 4038: 
 4039: sub getannounce {
 4040: 
 4041:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 4042: 	my $announcement='';
 4043: 	while (my $line = <$fh>) { $announcement .= $line; }
 4044: 	close($fh);
 4045: 	if ($announcement=~/\w/) { 
 4046: 	    return 
 4047:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 4048:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 4049: 	} else {
 4050: 	    return '';
 4051: 	}
 4052:     } else {
 4053: 	return '';
 4054:     }
 4055: }
 4056: 
 4057: # ---------------------------------------------------------- Course ID routines
 4058: # Deal with domain's nohist_courseid.db files
 4059: #
 4060: 
 4061: sub courseidput {
 4062:     my ($domain,$storehash,$coursehome,$caller) = @_;
 4063:     return unless (ref($storehash) eq 'HASH');
 4064:     my $outcome;
 4065:     if ($caller eq 'timeonly') {
 4066:         my $cids = '';
 4067:         foreach my $item (keys(%$storehash)) {
 4068:             $cids.=&escape($item).'&';
 4069:         }
 4070:         $cids=~s/\&$//;
 4071:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 4072:                           $coursehome);       
 4073:     } else {
 4074:         my $items = '';
 4075:         foreach my $item (keys(%$storehash)) {
 4076:             $items.= &escape($item).'='.
 4077:                      &freeze_escape($$storehash{$item}).'&';
 4078:         }
 4079:         $items=~s/\&$//;
 4080:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 4081:                           $coursehome);
 4082:     }
 4083:     if ($outcome eq 'unknown_cmd') {
 4084:         my $what;
 4085:         foreach my $cid (keys(%$storehash)) {
 4086:             $what .= &escape($cid).'=';
 4087:             foreach my $item ('description','inst_code','owner','type') {
 4088:                 $what .= &escape($storehash->{$cid}{$item}).':';
 4089:             }
 4090:             $what =~ s/\:$/&/;
 4091:         }
 4092:         $what =~ s/\&$//;  
 4093:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 4094:     } else {
 4095:         return $outcome;
 4096:     }
 4097: }
 4098: 
 4099: sub courseiddump {
 4100:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 4101:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 4102:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 4103:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
 4104:     my $as_hash = 1;
 4105:     my %returnhash;
 4106:     if (!$domfilter) { $domfilter=''; }
 4107:     my %libserv = &all_library();
 4108:     foreach my $tryserver (keys(%libserv)) {
 4109:         if ( (  $hostidflag == 1 
 4110: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 4111: 	     || (!defined($hostidflag)) ) {
 4112: 
 4113: 	    if (($domfilter eq '') ||
 4114: 		(&host_domain($tryserver) eq $domfilter)) {
 4115:                 my $rep;
 4116:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 4117:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 4118:                         join(":", (&host_domain($tryserver), $sincefilter, 
 4119:                                 &escape($descfilter), &escape($instcodefilter), 
 4120:                                 &escape($ownerfilter), &escape($coursefilter),
 4121:                                 &escape($typefilter), &escape($regexp_ok), 
 4122:                                 $as_hash, &escape($selfenrollonly), 
 4123:                                 &escape($catfilter), $showhidden, $caller, 
 4124:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 4125:                                 &escape($createdbefore), &escape($createdafter), 
 4126:                                 &escape($creationcontext), $domcloner)));
 4127:                 } else {
 4128:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 4129:                              $sincefilter.':'.&escape($descfilter).':'.
 4130:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 4131:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 4132:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 4133:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 4134:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 4135:                              &escape($cc_clone).':'.$cloneonly.':'.
 4136:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 4137:                              &escape($creationcontext).':'.$domcloner,
 4138:                              $tryserver);
 4139:                 }
 4140:                      
 4141:                 my @pairs=split(/\&/,$rep);
 4142:                 foreach my $item (@pairs) {
 4143:                     my ($key,$value)=split(/\=/,$item,2);
 4144:                     $key = &unescape($key);
 4145:                     next if ($key =~ /^error: 2 /);
 4146:                     my $result = &thaw_unescape($value);
 4147:                     if (ref($result) eq 'HASH') {
 4148:                         $returnhash{$key}=$result;
 4149:                     } else {
 4150:                         my @responses = split(/:/,$value);
 4151:                         my @items = ('description','inst_code','owner','type');
 4152:                         for (my $i=0; $i<@responses; $i++) {
 4153:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 4154:                         }
 4155:                     }
 4156:                 }
 4157:             }
 4158:         }
 4159:     }
 4160:     return %returnhash;
 4161: }
 4162: 
 4163: sub courselastaccess {
 4164:     my ($cdom,$cnum,$hostidref) = @_;
 4165:     my %returnhash;
 4166:     if ($cdom && $cnum) {
 4167:         my $chome = &homeserver($cnum,$cdom);
 4168:         if ($chome ne 'no_host') {
 4169:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 4170:             &extract_lastaccess(\%returnhash,$rep);
 4171:         }
 4172:     } else {
 4173:         if (!$cdom) { $cdom=''; }
 4174:         my %libserv = &all_library();
 4175:         foreach my $tryserver (keys(%libserv)) {
 4176:             if (ref($hostidref) eq 'ARRAY') {
 4177:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 4178:             } 
 4179:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 4180:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 4181:                 &extract_lastaccess(\%returnhash,$rep);
 4182:             }
 4183:         }
 4184:     }
 4185:     return %returnhash;
 4186: }
 4187: 
 4188: sub extract_lastaccess {
 4189:     my ($returnhash,$rep) = @_;
 4190:     if (ref($returnhash) eq 'HASH') {
 4191:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 4192:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 4193:                  $rep eq '') {
 4194:             my @pairs=split(/\&/,$rep);
 4195:             foreach my $item (@pairs) {
 4196:                 my ($key,$value)=split(/\=/,$item,2);
 4197:                 $key = &unescape($key);
 4198:                 next if ($key =~ /^error: 2 /);
 4199:                 $returnhash->{$key} = &thaw_unescape($value);
 4200:             }
 4201:         }
 4202:     }
 4203:     return;
 4204: }
 4205: 
 4206: # ---------------------------------------------------------- DC e-mail
 4207: 
 4208: sub dcmailput {
 4209:     my ($domain,$msgid,$message,$server)=@_;
 4210:     my $status = &Apache::lonnet::critical(
 4211:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 4212:        &escape($message),$server);
 4213:     return $status;
 4214: }
 4215: 
 4216: sub dcmaildump {
 4217:     my ($dom,$startdate,$enddate,$senders) = @_;
 4218:     my %returnhash=();
 4219: 
 4220:     if (defined(&domain($dom,'primary'))) {
 4221:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 4222:                                                          &escape($enddate).':';
 4223: 	my @esc_senders=map { &escape($_)} @$senders;
 4224: 	$cmd.=&escape(join('&',@esc_senders));
 4225: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 4226:             my ($key,$value) = split(/\=/,$line,2);
 4227:             if (($key) && ($value)) {
 4228:                 $returnhash{&unescape($key)} = &unescape($value);
 4229:             }
 4230:         }
 4231:     }
 4232:     return %returnhash;
 4233: }
 4234: # ---------------------------------------------------------- Domain roles
 4235: 
 4236: sub get_domain_roles {
 4237:     my ($dom,$roles,$startdate,$enddate)=@_;
 4238:     if ((!defined($startdate)) || ($startdate eq '')) {
 4239:         $startdate = '.';
 4240:     }
 4241:     if ((!defined($enddate)) || ($enddate eq '')) {
 4242:         $enddate = '.';
 4243:     }
 4244:     my $rolelist;
 4245:     if (ref($roles) eq 'ARRAY') {
 4246:         $rolelist = join(':',@{$roles});
 4247:     }
 4248:     my %personnel = ();
 4249: 
 4250:     my %servers = &get_servers($dom,'library');
 4251:     foreach my $tryserver (keys(%servers)) {
 4252: 	%{$personnel{$tryserver}}=();
 4253: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 4254: 					    &escape($startdate).':'.
 4255: 					    &escape($enddate).':'.
 4256: 					    &escape($rolelist), $tryserver))) {
 4257: 	    my ($key,$value) = split(/\=/,$line,2);
 4258: 	    if (($key) && ($value)) {
 4259: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 4260: 	    }
 4261: 	}
 4262:     }
 4263:     return %personnel;
 4264: }
 4265: 
 4266: # ----------------------------------------------------------- Interval timing 
 4267: 
 4268: {
 4269: # Caches needed for speedup of navmaps
 4270: # We don't want to cache this for very long at all (5 seconds at most)
 4271: # 
 4272: # The user for whom we cache
 4273: my $cachedkey='';
 4274: # The cached times for this user
 4275: my %cachedtimes=();
 4276: # When this was last done
 4277: my $cachedtime=();
 4278: 
 4279: sub load_all_first_access {
 4280:     my ($uname,$udom)=@_;
 4281:     if (($cachedkey eq $uname.':'.$udom) &&
 4282:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
 4283:         return;
 4284:     }
 4285:     $cachedtime=time;
 4286:     $cachedkey=$uname.':'.$udom;
 4287:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 4288: }
 4289: 
 4290: sub get_first_access {
 4291:     my ($type,$argsymb,$argmap)=@_;
 4292:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4293:     if ($argsymb) { $symb=$argsymb; }
 4294:     my ($map,$id,$res)=&decode_symb($symb);
 4295:     if ($argmap) { $map = $argmap; }
 4296:     if ($type eq 'course') {
 4297: 	$res='course';
 4298:     } elsif ($type eq 'map') {
 4299: 	$res=&symbread($map);
 4300:     } else {
 4301: 	$res=$symb;
 4302:     }
 4303:     &load_all_first_access($uname,$udom);
 4304:     return $cachedtimes{"$courseid\0$res"};
 4305: }
 4306: 
 4307: sub set_first_access {
 4308:     my ($type,$interval)=@_;
 4309:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4310:     my ($map,$id,$res)=&decode_symb($symb);
 4311:     if ($type eq 'course') {
 4312: 	$res='course';
 4313:     } elsif ($type eq 'map') {
 4314: 	$res=&symbread($map);
 4315:     } else {
 4316: 	$res=$symb;
 4317:     }
 4318:     $cachedkey='';
 4319:     my $firstaccess=&get_first_access($type,$symb,$map);
 4320:     if (!$firstaccess) {
 4321:         my $start = time;
 4322: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 4323:                           $udom,$uname);
 4324:         if ($putres eq 'ok') {
 4325:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 4326:                  $udom,$uname); 
 4327:             &appenv(
 4328:                      {
 4329:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 4330:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 4331:                      }
 4332:                   );
 4333:         }
 4334:         return $putres;
 4335:     }
 4336:     return 'already_set';
 4337: }
 4338: }
 4339: # --------------------------------------------- Set Expire Date for Spreadsheet
 4340: 
 4341: sub expirespread {
 4342:     my ($uname,$udom,$stype,$usymb)=@_;
 4343:     my $cid=$env{'request.course.id'}; 
 4344:     if ($cid) {
 4345:        my $now=time;
 4346:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 4347:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 4348:                             $env{'course.'.$cid.'.num'}.
 4349: 	        	    ':nohist_expirationdates:'.
 4350:                             &escape($key).'='.$now,
 4351:                             $env{'course.'.$cid.'.home'})
 4352:     }
 4353:     return 'ok';
 4354: }
 4355: 
 4356: # ----------------------------------------------------- Devalidate Spreadsheets
 4357: 
 4358: sub devalidate {
 4359:     my ($symb,$uname,$udom)=@_;
 4360:     my $cid=$env{'request.course.id'}; 
 4361:     if ($cid) {
 4362:         # delete the stored spreadsheets for
 4363:         # - the student level sheet of this user in course's homespace
 4364:         # - the assessment level sheet for this resource 
 4365:         #   for this user in user's homespace
 4366: 	# - current conditional state info
 4367: 	my $key=$uname.':'.$udom.':';
 4368:         my $status=
 4369: 	    &del('nohist_calculatedsheets',
 4370: 		 [$key.'studentcalc:'],
 4371: 		 $env{'course.'.$cid.'.domain'},
 4372: 		 $env{'course.'.$cid.'.num'})
 4373: 		.' '.
 4374: 	    &del('nohist_calculatedsheets_'.$cid,
 4375: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 4376:         unless ($status eq 'ok ok') {
 4377:            &logthis('Could not devalidate spreadsheet '.
 4378:                     $uname.' at '.$udom.' for '.
 4379: 		    $symb.': '.$status);
 4380:         }
 4381: 	&delenv('user.state.'.$cid);
 4382:     }
 4383: }
 4384: 
 4385: sub get_scalar {
 4386:     my ($string,$end) = @_;
 4387:     my $value;
 4388:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 4389: 	$value = $1;
 4390:     } elsif ($$string =~ s/^([^&]*?)&//) {
 4391: 	$value = $1;
 4392:     }
 4393:     return &unescape($value);
 4394: }
 4395: 
 4396: sub array2str {
 4397:   my (@array) = @_;
 4398:   my $result=&arrayref2str(\@array);
 4399:   $result=~s/^__ARRAY_REF__//;
 4400:   $result=~s/__END_ARRAY_REF__$//;
 4401:   return $result;
 4402: }
 4403: 
 4404: sub arrayref2str {
 4405:   my ($arrayref) = @_;
 4406:   my $result='__ARRAY_REF__';
 4407:   foreach my $elem (@$arrayref) {
 4408:     if(ref($elem) eq 'ARRAY') {
 4409:       $result.=&arrayref2str($elem).'&';
 4410:     } elsif(ref($elem) eq 'HASH') {
 4411:       $result.=&hashref2str($elem).'&';
 4412:     } elsif(ref($elem)) {
 4413:       #print("Got a ref of ".(ref($elem))." skipping.");
 4414:     } else {
 4415:       $result.=&escape($elem).'&';
 4416:     }
 4417:   }
 4418:   $result=~s/\&$//;
 4419:   $result .= '__END_ARRAY_REF__';
 4420:   return $result;
 4421: }
 4422: 
 4423: sub hash2str {
 4424:   my (%hash) = @_;
 4425:   my $result=&hashref2str(\%hash);
 4426:   $result=~s/^__HASH_REF__//;
 4427:   $result=~s/__END_HASH_REF__$//;
 4428:   return $result;
 4429: }
 4430: 
 4431: sub hashref2str {
 4432:   my ($hashref)=@_;
 4433:   my $result='__HASH_REF__';
 4434:   foreach my $key (sort(keys(%$hashref))) {
 4435:     if (ref($key) eq 'ARRAY') {
 4436:       $result.=&arrayref2str($key).'=';
 4437:     } elsif (ref($key) eq 'HASH') {
 4438:       $result.=&hashref2str($key).'=';
 4439:     } elsif (ref($key)) {
 4440:       $result.='=';
 4441:       #print("Got a ref of ".(ref($key))." skipping.");
 4442:     } else {
 4443: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 4444:     }
 4445: 
 4446:     if(ref($hashref->{$key}) eq 'ARRAY') {
 4447:       $result.=&arrayref2str($hashref->{$key}).'&';
 4448:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 4449:       $result.=&hashref2str($hashref->{$key}).'&';
 4450:     } elsif(ref($hashref->{$key})) {
 4451:        $result.='&';
 4452:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 4453:     } else {
 4454:       $result.=&escape($hashref->{$key}).'&';
 4455:     }
 4456:   }
 4457:   $result=~s/\&$//;
 4458:   $result .= '__END_HASH_REF__';
 4459:   return $result;
 4460: }
 4461: 
 4462: sub str2hash {
 4463:     my ($string)=@_;
 4464:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 4465:     return %$hash;
 4466: }
 4467: 
 4468: sub str2hashref {
 4469:   my ($string) = @_;
 4470: 
 4471:   my %hash;
 4472: 
 4473:   if($string !~ /^__HASH_REF__/) {
 4474:       if (! ($string eq '' || !defined($string))) {
 4475: 	  $hash{'error'}='Not hash reference';
 4476:       }
 4477:       return (\%hash, $string);
 4478:   }
 4479: 
 4480:   $string =~ s/^__HASH_REF__//;
 4481: 
 4482:   while($string !~ /^__END_HASH_REF__/) {
 4483:       #key
 4484:       my $key='';
 4485:       if($string =~ /^__HASH_REF__/) {
 4486:           ($key, $string)=&str2hashref($string);
 4487:           if(defined($key->{'error'})) {
 4488:               $hash{'error'}='Bad data';
 4489:               return (\%hash, $string);
 4490:           }
 4491:       } elsif($string =~ /^__ARRAY_REF__/) {
 4492:           ($key, $string)=&str2arrayref($string);
 4493:           if($key->[0] eq 'Array reference error') {
 4494:               $hash{'error'}='Bad data';
 4495:               return (\%hash, $string);
 4496:           }
 4497:       } else {
 4498:           $string =~ s/^(.*?)=//;
 4499: 	  $key=&unescape($1);
 4500:       }
 4501:       $string =~ s/^=//;
 4502: 
 4503:       #value
 4504:       my $value='';
 4505:       if($string =~ /^__HASH_REF__/) {
 4506:           ($value, $string)=&str2hashref($string);
 4507:           if(defined($value->{'error'})) {
 4508:               $hash{'error'}='Bad data';
 4509:               return (\%hash, $string);
 4510:           }
 4511:       } elsif($string =~ /^__ARRAY_REF__/) {
 4512:           ($value, $string)=&str2arrayref($string);
 4513:           if($value->[0] eq 'Array reference error') {
 4514:               $hash{'error'}='Bad data';
 4515:               return (\%hash, $string);
 4516:           }
 4517:       } else {
 4518: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 4519:       }
 4520:       $string =~ s/^&//;
 4521: 
 4522:       $hash{$key}=$value;
 4523:   }
 4524: 
 4525:   $string =~ s/^__END_HASH_REF__//;
 4526: 
 4527:   return (\%hash, $string);
 4528: }
 4529: 
 4530: sub str2array {
 4531:     my ($string)=@_;
 4532:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 4533:     return @$array;
 4534: }
 4535: 
 4536: sub str2arrayref {
 4537:   my ($string) = @_;
 4538:   my @array;
 4539: 
 4540:   if($string !~ /^__ARRAY_REF__/) {
 4541:       if (! ($string eq '' || !defined($string))) {
 4542: 	  $array[0]='Array reference error';
 4543:       }
 4544:       return (\@array, $string);
 4545:   }
 4546: 
 4547:   $string =~ s/^__ARRAY_REF__//;
 4548: 
 4549:   while($string !~ /^__END_ARRAY_REF__/) {
 4550:       my $value='';
 4551:       if($string =~ /^__HASH_REF__/) {
 4552:           ($value, $string)=&str2hashref($string);
 4553:           if(defined($value->{'error'})) {
 4554:               $array[0] ='Array reference error';
 4555:               return (\@array, $string);
 4556:           }
 4557:       } elsif($string =~ /^__ARRAY_REF__/) {
 4558:           ($value, $string)=&str2arrayref($string);
 4559:           if($value->[0] eq 'Array reference error') {
 4560:               $array[0] ='Array reference error';
 4561:               return (\@array, $string);
 4562:           }
 4563:       } else {
 4564: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 4565:       }
 4566:       $string =~ s/^&//;
 4567: 
 4568:       push(@array, $value);
 4569:   }
 4570: 
 4571:   $string =~ s/^__END_ARRAY_REF__//;
 4572: 
 4573:   return (\@array, $string);
 4574: }
 4575: 
 4576: # -------------------------------------------------------------------Temp Store
 4577: 
 4578: sub tmpreset {
 4579:   my ($symb,$namespace,$domain,$stuname) = @_;
 4580:   if (!$symb) {
 4581:     $symb=&symbread();
 4582:     if (!$symb) { $symb= $env{'request.url'}; }
 4583:   }
 4584:   $symb=escape($symb);
 4585: 
 4586:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4587:   $namespace=~s/\//\_/g;
 4588:   $namespace=~s/\W//g;
 4589: 
 4590:   if (!$domain) { $domain=$env{'user.domain'}; }
 4591:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4592:   if ($domain eq 'public' && $stuname eq 'public') {
 4593:       $stuname=$ENV{'REMOTE_ADDR'};
 4594:   }
 4595:   my $path=LONCAPA::tempdir();
 4596:   my %hash;
 4597:   if (tie(%hash,'GDBM_File',
 4598: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4599: 	  &GDBM_WRCREAT(),0640)) {
 4600:     foreach my $key (keys(%hash)) {
 4601:       if ($key=~ /:$symb/) {
 4602: 	delete($hash{$key});
 4603:       }
 4604:     }
 4605:   }
 4606: }
 4607: 
 4608: sub tmpstore {
 4609:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4610: 
 4611:   if (!$symb) {
 4612:     $symb=&symbread();
 4613:     if (!$symb) { $symb= $env{'request.url'}; }
 4614:   }
 4615:   $symb=escape($symb);
 4616: 
 4617:   if (!$namespace) {
 4618:     # I don't think we would ever want to store this for a course.
 4619:     # it seems this will only be used if we don't have a course.
 4620:     #$namespace=$env{'request.course.id'};
 4621:     #if (!$namespace) {
 4622:       $namespace=$env{'request.state'};
 4623:     #}
 4624:   }
 4625:   $namespace=~s/\//\_/g;
 4626:   $namespace=~s/\W//g;
 4627:   if (!$domain) { $domain=$env{'user.domain'}; }
 4628:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4629:   if ($domain eq 'public' && $stuname eq 'public') {
 4630:       $stuname=$ENV{'REMOTE_ADDR'};
 4631:   }
 4632:   my $now=time;
 4633:   my %hash;
 4634:   my $path=LONCAPA::tempdir();
 4635:   if (tie(%hash,'GDBM_File',
 4636: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4637: 	  &GDBM_WRCREAT(),0640)) {
 4638:     $hash{"version:$symb"}++;
 4639:     my $version=$hash{"version:$symb"};
 4640:     my $allkeys=''; 
 4641:     foreach my $key (keys(%$storehash)) {
 4642:       $allkeys.=$key.':';
 4643:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 4644:     }
 4645:     $hash{"$version:$symb:timestamp"}=$now;
 4646:     $allkeys.='timestamp';
 4647:     $hash{"$version:keys:$symb"}=$allkeys;
 4648:     if (untie(%hash)) {
 4649:       return 'ok';
 4650:     } else {
 4651:       return "error:$!";
 4652:     }
 4653:   } else {
 4654:     return "error:$!";
 4655:   }
 4656: }
 4657: 
 4658: # -----------------------------------------------------------------Temp Restore
 4659: 
 4660: sub tmprestore {
 4661:   my ($symb,$namespace,$domain,$stuname) = @_;
 4662: 
 4663:   if (!$symb) {
 4664:     $symb=&symbread();
 4665:     if (!$symb) { $symb= $env{'request.url'}; }
 4666:   }
 4667:   $symb=escape($symb);
 4668: 
 4669:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4670: 
 4671:   if (!$domain) { $domain=$env{'user.domain'}; }
 4672:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4673:   if ($domain eq 'public' && $stuname eq 'public') {
 4674:       $stuname=$ENV{'REMOTE_ADDR'};
 4675:   }
 4676:   my %returnhash;
 4677:   $namespace=~s/\//\_/g;
 4678:   $namespace=~s/\W//g;
 4679:   my %hash;
 4680:   my $path=LONCAPA::tempdir();
 4681:   if (tie(%hash,'GDBM_File',
 4682: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4683: 	  &GDBM_READER(),0640)) {
 4684:     my $version=$hash{"version:$symb"};
 4685:     $returnhash{'version'}=$version;
 4686:     my $scope;
 4687:     for ($scope=1;$scope<=$version;$scope++) {
 4688:       my $vkeys=$hash{"$scope:keys:$symb"};
 4689:       my @keys=split(/:/,$vkeys);
 4690:       my $key;
 4691:       $returnhash{"$scope:keys"}=$vkeys;
 4692:       foreach $key (@keys) {
 4693: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4694: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4695:       }
 4696:     }
 4697:     if (!(untie(%hash))) {
 4698:       return "error:$!";
 4699:     }
 4700:   } else {
 4701:     return "error:$!";
 4702:   }
 4703:   return %returnhash;
 4704: }
 4705: 
 4706: # ----------------------------------------------------------------------- Store
 4707: 
 4708: sub store {
 4709:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4710:     my $home='';
 4711: 
 4712:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4713: 
 4714:     $symb=&symbclean($symb);
 4715:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4716: 
 4717:     if (!$domain) { $domain=$env{'user.domain'}; }
 4718:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4719: 
 4720:     &devalidate($symb,$stuname,$domain);
 4721: 
 4722:     $symb=escape($symb);
 4723:     if (!$namespace) { 
 4724:        unless ($namespace=$env{'request.course.id'}) { 
 4725:           return ''; 
 4726:        } 
 4727:     }
 4728:     if (!$home) { $home=$env{'user.home'}; }
 4729: 
 4730:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4731:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4732: 
 4733:     my $namevalue='';
 4734:     foreach my $key (keys(%$storehash)) {
 4735:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4736:     }
 4737:     $namevalue=~s/\&$//;
 4738:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 4739:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4740: }
 4741: 
 4742: # -------------------------------------------------------------- Critical Store
 4743: 
 4744: sub cstore {
 4745:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4746:     my $home='';
 4747: 
 4748:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4749: 
 4750:     $symb=&symbclean($symb);
 4751:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4752: 
 4753:     if (!$domain) { $domain=$env{'user.domain'}; }
 4754:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4755: 
 4756:     &devalidate($symb,$stuname,$domain);
 4757: 
 4758:     $symb=escape($symb);
 4759:     if (!$namespace) { 
 4760:        unless ($namespace=$env{'request.course.id'}) { 
 4761:           return ''; 
 4762:        } 
 4763:     }
 4764:     if (!$home) { $home=$env{'user.home'}; }
 4765: 
 4766:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4767:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4768: 
 4769:     my $namevalue='';
 4770:     foreach my $key (keys(%$storehash)) {
 4771:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4772:     }
 4773:     $namevalue=~s/\&$//;
 4774:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 4775:     return critical
 4776:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4777: }
 4778: 
 4779: # --------------------------------------------------------------------- Restore
 4780: 
 4781: sub restore {
 4782:     my ($symb,$namespace,$domain,$stuname) = @_;
 4783:     my $home='';
 4784: 
 4785:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4786: 
 4787:     if (!$symb) {
 4788:       unless ($symb=escape(&symbread())) { return ''; }
 4789:     } else {
 4790:       $symb=&escape(&symbclean($symb));
 4791:     }
 4792:     if (!$namespace) { 
 4793:        unless ($namespace=$env{'request.course.id'}) { 
 4794:           return ''; 
 4795:        } 
 4796:     }
 4797:     if (!$domain) { $domain=$env{'user.domain'}; }
 4798:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4799:     if (!$home) { $home=$env{'user.home'}; }
 4800:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 4801: 
 4802:     my %returnhash=();
 4803:     foreach my $line (split(/\&/,$answer)) {
 4804: 	my ($name,$value)=split(/\=/,$line);
 4805:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 4806:     }
 4807:     my $version;
 4808:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 4809:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 4810:           $returnhash{$item}=$returnhash{$version.':'.$item};
 4811:        }
 4812:     }
 4813:     return %returnhash;
 4814: }
 4815: 
 4816: # ---------------------------------------------------------- Course Description
 4817: #
 4818: #  
 4819: 
 4820: sub coursedescription {
 4821:     my ($courseid,$args)=@_;
 4822:     $courseid=~s/^\///;
 4823:     $courseid=~s/\_/\//g;
 4824:     my ($cdomain,$cnum)=split(/\//,$courseid);
 4825:     my $chome=&homeserver($cnum,$cdomain);
 4826:     my $normalid=$cdomain.'_'.$cnum;
 4827:     # need to always cache even if we get errors otherwise we keep 
 4828:     # trying and trying and trying to get the course description.
 4829:     my %envhash=();
 4830:     my %returnhash=();
 4831:     
 4832:     my $expiretime=600;
 4833:     if ($env{'request.course.id'} eq $normalid) {
 4834: 	$expiretime=120;
 4835:     }
 4836: 
 4837:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 4838:     if (!$args->{'freshen_cache'}
 4839: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 4840: 	foreach my $key (keys(%env)) {
 4841: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 4842: 	    my ($setting) = $1;
 4843: 	    $returnhash{$setting} = $env{$key};
 4844: 	}
 4845: 	return %returnhash;
 4846:     }
 4847: 
 4848:     # get the data again
 4849: 
 4850:     if (!$args->{'one_time'}) {
 4851: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 4852:     }
 4853: 
 4854:     if ($chome ne 'no_host') {
 4855:        %returnhash=&dump('environment',$cdomain,$cnum);
 4856:        if (!exists($returnhash{'con_lost'})) {
 4857: 	   my $username = $env{'user.name'}; # Defult username
 4858: 	   if(defined $args->{'user'}) {
 4859: 	       $username = $args->{'user'};
 4860: 	   }
 4861:            $returnhash{'home'}= $chome;
 4862: 	   $returnhash{'domain'} = $cdomain;
 4863: 	   $returnhash{'num'} = $cnum;
 4864:            if (!defined($returnhash{'type'})) {
 4865:                $returnhash{'type'} = 'Course';
 4866:            }
 4867:            while (my ($name,$value) = each %returnhash) {
 4868:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 4869:            }
 4870:            $returnhash{'url'}=&clutter($returnhash{'url'});
 4871:            $returnhash{'fn'}=LONCAPA::tempdir() .
 4872: 	       $username.'_'.$cdomain.'_'.$cnum;
 4873:            $envhash{'course.'.$normalid.'.home'}=$chome;
 4874:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 4875:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 4876:        }
 4877:     }
 4878:     if (!$args->{'one_time'}) {
 4879: 	&appenv(\%envhash);
 4880:     }
 4881:     return %returnhash;
 4882: }
 4883: 
 4884: sub update_released_required {
 4885:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 4886:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 4887:         $cid = $env{'request.course.id'};
 4888:         $cdom = $env{'course.'.$cid.'.domain'};
 4889:         $cnum = $env{'course.'.$cid.'.num'};
 4890:         $chome = $env{'course.'.$cid.'.home'};
 4891:     }
 4892:     if ($needsrelease) {
 4893:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 4894:         my $needsupdate;
 4895:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 4896:             $needsupdate = 1;
 4897:         } else {
 4898:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 4899:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 4900:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 4901:                 $needsupdate = 1;
 4902:             }
 4903:         }
 4904:         if ($needsupdate) {
 4905:             my %needshash = (
 4906:                              'internal.releaserequired' => $needsrelease,
 4907:                             );
 4908:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 4909:             if ($putresult eq 'ok') {
 4910:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 4911:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 4912:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 4913:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 4914:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 4915:                 }
 4916:             }
 4917:         }
 4918:     }
 4919:     return;
 4920: }
 4921: 
 4922: # -------------------------------------------------See if a user is privileged
 4923: 
 4924: sub privileged {
 4925:     my ($username,$domain)=@_;
 4926: 
 4927:     my %rolesdump = &dump("roles", $domain, $username) or return 0;
 4928:     my $now = time;
 4929: 
 4930:     for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
 4931:             my ($trole, $tend, $tstart) = split(/_/, $role);
 4932:             if (($trole eq 'dc') || ($trole eq 'su')) {
 4933:                 return 1 unless ($tend && $tend < $now) 
 4934:                     or ($tstart && $tstart > $now);
 4935:             }
 4936: 	}
 4937: 
 4938:     return 0;
 4939: }
 4940: 
 4941: # -------------------------------------------------------- Get user privileges
 4942: 
 4943: sub rolesinit {
 4944:     my ($domain, $username) = @_;
 4945:     my %userroles = ('user.login.time' => time);
 4946:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 4947: 
 4948:     # firstaccess and timerinterval are related to timed maps/resources. 
 4949:     # also, blocking can be triggered by an activating timer
 4950:     # it's saved in the user's %env.
 4951:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 4952:     my %timerinterval = &dump('timerinterval', $domain, $username);
 4953:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 4954:         %timerintchk, %timerintenv);
 4955: 
 4956:     foreach my $key (keys(%firstaccess)) {
 4957:         my ($cid, $rest) = split(/\0/, $key);
 4958:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 4959:     }
 4960: 
 4961:     foreach my $key (keys(%timerinterval)) {
 4962:         my ($cid,$rest) = split(/\0/,$key);
 4963:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 4964:     }
 4965: 
 4966:     my %allroles=();
 4967:     my %allgroups=();
 4968: 
 4969:     for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
 4970:         my $role = $rolesdump{$area};
 4971:         $area =~ s/\_\w\w$//;
 4972: 
 4973:         my ($trole, $tend, $tstart, $group_privs);
 4974: 
 4975:         if ($role =~ /^cr/) {
 4976:         # Custom role, defined by a user 
 4977:         # e.g., user.role.cr/msu/smith/mynewrole
 4978:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 4979:                 $trole = $1;
 4980:                 ($tend, $tstart) = split('_', $2);
 4981:             } else {
 4982:                 $trole = $role;
 4983:             }
 4984:         } elsif ($role =~ m|^gr/|) {
 4985:         # Role of member in a group, defined within a course/community
 4986:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 4987:             ($trole, $tend, $tstart) = split(/_/, $role);
 4988:             next if $tstart eq '-1';
 4989:             ($trole, $group_privs) = split(/\//, $trole);
 4990:             $group_privs = &unescape($group_privs);
 4991:         } else {
 4992:         # Just a normal role, defined in roles.tab
 4993:             ($trole, $tend, $tstart) = split(/_/,$role);
 4994:         }
 4995: 
 4996:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 4997:                  $username);
 4998:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 4999: 
 5000:         # role expired or not available yet?
 5001:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 5002:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 5003: 
 5004:         next if $area eq '' or $trole eq '';
 5005: 
 5006:         my $spec = "$trole.$area";
 5007:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 5008: 
 5009:         if ($trole =~ /^cr\//) {
 5010:         # Custom role, defined by a user
 5011:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 5012:         } elsif ($trole eq 'gr') {
 5013:         # Role of a member in a group, defined within a course/community
 5014:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 5015:             next;
 5016:         } else {
 5017:         # Normal role, defined in roles.tab
 5018:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 5019:         }
 5020: 
 5021:         my $cid = $tdomain.'_'.$trest;
 5022:         unless ($firstaccchk{$cid}) {
 5023:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 5024:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 5025:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 5026:                         $coursetimerstarts{$cid}{$item}; 
 5027:                 }
 5028:             }
 5029:             $firstaccchk{$cid} = 1;
 5030:         }
 5031:         unless ($timerintchk{$cid}) {
 5032:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 5033:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 5034:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 5035:                        $coursetimerintervals{$cid}{$item};
 5036:                 }
 5037:             }
 5038:             $timerintchk{$cid} = 1;
 5039:         }
 5040:     }
 5041: 
 5042:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
 5043:         \%allroles, \%allgroups);
 5044:     $env{'user.adv'} = $userroles{'user.adv'};
 5045: 
 5046:     return (\%userroles,\%firstaccenv,\%timerintenv);
 5047: }
 5048: 
 5049: sub set_arearole {
 5050:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 5051: # log the associated role with the area
 5052:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 5053:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 5054: }
 5055: 
 5056: sub custom_roleprivs {
 5057:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 5058:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 5059:     my $homsvr=homeserver($rauthor,$rdomain);
 5060:     if (&hostname($homsvr) ne '') {
 5061:         my ($rdummy,$roledef)=
 5062:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 5063:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 5064:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 5065:             if (defined($syspriv)) {
 5066:                 if ($trest =~ /^$match_community$/) {
 5067:                     $syspriv =~ s/bre\&S//; 
 5068:                 }
 5069:                 $$allroles{'cm./'}.=':'.$syspriv;
 5070:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 5071:             }
 5072:             if ($tdomain ne '') {
 5073:                 if (defined($dompriv)) {
 5074:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 5075:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 5076:                 }
 5077:                 if (($trest ne '') && (defined($coursepriv))) {
 5078:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 5079:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 5080:                 }
 5081:             }
 5082:         }
 5083:     }
 5084: }
 5085: 
 5086: sub group_roleprivs {
 5087:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 5088:     my $access = 1;
 5089:     my $now = time;
 5090:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 5091:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 5092:     if ($access) {
 5093:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 5094:         $$allgroups{$course}{$group} .=':'.$group_privs;
 5095:     }
 5096: }
 5097: 
 5098: sub standard_roleprivs {
 5099:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 5100:     if (defined($pr{$trole.':s'})) {
 5101:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 5102:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 5103:     }
 5104:     if ($tdomain ne '') {
 5105:         if (defined($pr{$trole.':d'})) {
 5106:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 5107:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 5108:         }
 5109:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 5110:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 5111:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 5112:         }
 5113:     }
 5114: }
 5115: 
 5116: sub set_userprivs {
 5117:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 5118:     my $author=0;
 5119:     my $adv=0;
 5120:     my %grouproles = ();
 5121:     if (keys(%{$allgroups}) > 0) {
 5122:         my @groupkeys; 
 5123:         foreach my $role (keys(%{$allroles})) {
 5124:             push(@groupkeys,$role);
 5125:         }
 5126:         if (ref($groups_roles) eq 'HASH') {
 5127:             foreach my $key (keys(%{$groups_roles})) {
 5128:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 5129:                     push(@groupkeys,$key);
 5130:                 }
 5131:             }
 5132:         }
 5133:         if (@groupkeys > 0) {
 5134:             foreach my $role (@groupkeys) {
 5135:                 my ($trole,$area,$sec,$extendedarea);
 5136:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 5137:                     $trole = $1;
 5138:                     $area = $2;
 5139:                     $sec = $3;
 5140:                     $extendedarea = $area.$sec;
 5141:                     if (exists($$allgroups{$area})) {
 5142:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 5143:                             my $spec = $trole.'.'.$extendedarea;
 5144:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 5145:                                                 $$allgroups{$area}{$group};
 5146:                         }
 5147:                     }
 5148:                 }
 5149:             }
 5150:         }
 5151:     }
 5152:     foreach my $group (keys(%grouproles)) {
 5153:         $$allroles{$group} = $grouproles{$group};
 5154:     }
 5155:     foreach my $role (keys(%{$allroles})) {
 5156:         my %thesepriv;
 5157:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 5158:         foreach my $item (split(/:/,$$allroles{$role})) {
 5159:             if ($item ne '') {
 5160:                 my ($privilege,$restrictions)=split(/&/,$item);
 5161:                 if ($restrictions eq '') {
 5162:                     $thesepriv{$privilege}='F';
 5163:                 } elsif ($thesepriv{$privilege} ne 'F') {
 5164:                     $thesepriv{$privilege}.=$restrictions;
 5165:                 }
 5166:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 5167:             }
 5168:         }
 5169:         my $thesestr='';
 5170:         foreach my $priv (sort(keys(%thesepriv))) {
 5171: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 5172: 	}
 5173:         $userroles->{'user.priv.'.$role} = $thesestr;
 5174:     }
 5175:     return ($author,$adv);
 5176: }
 5177: 
 5178: sub role_status {
 5179:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 5180:     my @pwhere = ();
 5181:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 5182:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
 5183:         unless (!defined($$role) || $$role eq '') {
 5184:             $$where=join('.',@pwhere);
 5185:             $$trolecode=$$role.'.'.$$where;
 5186:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 5187:             $$tstatus='is';
 5188:             if ($$tstart && $$tstart>$update) {
 5189:                 $$tstatus='future';
 5190:                 if ($$tstart<$now) {
 5191:                     if ($$tstart && $$tstart>$refresh) {
 5192:                         if (($$where ne '') && ($$role ne '')) {
 5193:                             my (%allroles,%allgroups,$group_privs,
 5194:                                 %groups_roles,@rolecodes);
 5195:                             my %userroles = (
 5196:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 5197:                             );
 5198:                             @rolecodes = ('cm'); 
 5199:                             my $spec=$$role.'.'.$$where;
 5200:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 5201:                             if ($$role =~ /^cr\//) {
 5202:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 5203:                                 push(@rolecodes,'cr');
 5204:                             } elsif ($$role eq 'gr') {
 5205:                                 push(@rolecodes,$$role);
 5206:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 5207:                                                     $env{'user.name'});
 5208:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 5209:                                 (undef,my $group_privs) = split(/\//,$trole);
 5210:                                 $group_privs = &unescape($group_privs);
 5211:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 5212:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 5213:                                 &get_groups_roles($tdomain,$trest,
 5214:                                                   \%course_roles,\@rolecodes,
 5215:                                                   \%groups_roles);
 5216:                             } else {
 5217:                                 push(@rolecodes,$$role);
 5218:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 5219:                             }
 5220:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
 5221:                             &appenv(\%userroles,\@rolecodes);
 5222:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5223:                         }
 5224:                     }
 5225:                     $$tstatus = 'is';
 5226:                 }
 5227:             }
 5228:             if ($$tend) {
 5229:                 if ($$tend<$update) {
 5230:                     $$tstatus='expired';
 5231:                 } elsif ($$tend<$now) {
 5232:                     $$tstatus='will_not';
 5233:                 }
 5234:             }
 5235:         }
 5236:     }
 5237: }
 5238: 
 5239: sub get_groups_roles {
 5240:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 5241:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 5242:                   (ref($rolecodes) eq 'ARRAY') && 
 5243:                   (ref($groups_roles) eq 'HASH')); 
 5244:     if (keys(%{$cdom_courseroles}) > 0) {
 5245:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 5246:         if ($cdom ne '' && $cnum ne '') {
 5247:             foreach my $key (keys(%{$cdom_courseroles})) {
 5248:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 5249:                     my $crsrole = $1;
 5250:                     my $crssec = $2;
 5251:                     if ($crsrole =~ /^cr/) {
 5252:                         unless (grep(/^cr$/,@{$rolecodes})) {
 5253:                             push(@{$rolecodes},'cr');
 5254:                         }
 5255:                     } else {
 5256:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 5257:                             push(@{$rolecodes},$crsrole);
 5258:                         }
 5259:                     }
 5260:                     my $rolekey = "$crsrole./$cdom/$cnum";
 5261:                     if ($crssec ne '') {
 5262:                         $rolekey .= "/$crssec";
 5263:                     }
 5264:                     $rolekey .= './';
 5265:                     $groups_roles->{$rolekey} = $rolecodes;
 5266:                 }
 5267:             }
 5268:         }
 5269:     }
 5270:     return;
 5271: }
 5272: 
 5273: sub delete_env_groupprivs {
 5274:     my ($where,$courseroles,$possroles) = @_;
 5275:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 5276:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 5277:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 5278:         %{$courseroles->{$udom}} =
 5279:             &get_my_roles('','','userroles',['active'],
 5280:                           $possroles,[$udom],1);
 5281:     }
 5282:     if (ref($courseroles->{$udom}) eq 'HASH') {
 5283:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 5284:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 5285:             my $area = '/'.$cdom.'/'.$cnum;
 5286:             my $privkey = "user.priv.$crsrole.$area";
 5287:             if ($crssec ne '') {
 5288:                 $privkey .= '/'.$crssec;
 5289:             }
 5290:             $privkey .= ".$area/$group";
 5291:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 5292:         }
 5293:     }
 5294:     return;
 5295: }
 5296: 
 5297: sub check_adhoc_privs {
 5298:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
 5299:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 5300:     my $setprivs;
 5301:     if ($env{$cckey}) {
 5302:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 5303:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 5304:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 5305:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5306:             $setprivs = 1;
 5307:         }
 5308:     } else {
 5309:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5310:         $setprivs = 1;
 5311:     }
 5312:     return $setprivs;
 5313: }
 5314: 
 5315: sub set_adhoc_privileges {
 5316: # role can be cc or ca
 5317:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
 5318:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 5319:     my $spec = $role.'.'.$area;
 5320:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 5321:                                   $env{'user.name'});
 5322:     my %ccrole = ();
 5323:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
 5324:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
 5325:     &appenv(\%userroles,[$role,'cm']);
 5326:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5327:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 5328:         &appenv( {'request.role'        => $spec,
 5329:                   'request.role.domain' => $dcdom,
 5330:                   'request.course.sec'  => ''
 5331:                  }
 5332:                );
 5333:         my $tadv=0;
 5334:         if (&allowed('adv') eq 'F') { $tadv=1; }
 5335:         &appenv({'request.role.adv'    => $tadv});
 5336:     }
 5337: }
 5338: 
 5339: # --------------------------------------------------------------- get interface
 5340: 
 5341: sub get {
 5342:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5343:    my $items='';
 5344:    foreach my $item (@$storearr) {
 5345:        $items.=&escape($item).'&';
 5346:    }
 5347:    $items=~s/\&$//;
 5348:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5349:    if (!$uname) { $uname=$env{'user.name'}; }
 5350:    my $uhome=&homeserver($uname,$udomain);
 5351: 
 5352:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 5353:    my @pairs=split(/\&/,$rep);
 5354:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 5355:      return @pairs;
 5356:    }
 5357:    my %returnhash=();
 5358:    my $i=0;
 5359:    foreach my $item (@$storearr) {
 5360:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5361:       $i++;
 5362:    }
 5363:    return %returnhash;
 5364: }
 5365: 
 5366: # --------------------------------------------------------------- del interface
 5367: 
 5368: sub del {
 5369:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5370:    my $items='';
 5371:    foreach my $item (@$storearr) {
 5372:        $items.=&escape($item).'&';
 5373:    }
 5374: 
 5375:    $items=~s/\&$//;
 5376:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5377:    if (!$uname) { $uname=$env{'user.name'}; }
 5378:    my $uhome=&homeserver($uname,$udomain);
 5379:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 5380: }
 5381: 
 5382: # -------------------------------------------------------------- dump interface
 5383: 
 5384: sub unserialize {
 5385:     my ($rep, $escapedkeys) = @_;
 5386: 
 5387:     return {} if $rep =~ /^error/;
 5388: 
 5389:     my %returnhash=();
 5390: 	foreach my $item (split /\&/, $rep) {
 5391: 	    my ($key, $value) = split(/=/, $item, 2);
 5392: 	    $key = unescape($key) unless $escapedkeys;
 5393: 	    next if $key =~ /^error: 2 /;
 5394: 	    $returnhash{$key} = Apache::lonnet::thaw_unescape($value);
 5395: 	}
 5396:     #return %returnhash;
 5397:     return \%returnhash;
 5398: }        
 5399: 
 5400: # see Lond::dump_with_regexp
 5401: # if $escapedkeys hash keys won't get unescaped.
 5402: sub dump {
 5403:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 5404:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5405:     if (!$uname) { $uname=$env{'user.name'}; }
 5406:     my $uhome=&homeserver($uname,$udomain);
 5407: 
 5408:     my $reply;
 5409:     if (grep { $_ eq $uhome } current_machine_ids()) {
 5410:         # user is hosted on this machine
 5411:         $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 5412:                     $uname, $namespace, $regexp, $range)), $loncaparevs{$uhome});
 5413:         return %{unserialize($reply, $escapedkeys)};
 5414:     }
 5415:     if ($regexp) {
 5416: 	$regexp=&escape($regexp);
 5417:     } else {
 5418: 	$regexp='.';
 5419:     }
 5420:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 5421:     my @pairs=split(/\&/,$rep);
 5422:     my %returnhash=();
 5423:     if (!($rep =~ /^error/ )) {
 5424: 	foreach my $item (@pairs) {
 5425: 	    my ($key,$value)=split(/=/,$item,2);
 5426:         $key = unescape($key) unless $escapedkeys;
 5427:         #$key = &unescape($key);
 5428: 	    next if ($key =~ /^error: 2 /);
 5429: 	    $returnhash{$key}=&thaw_unescape($value);
 5430: 	}
 5431:     }
 5432:     return %returnhash;
 5433: }
 5434: 
 5435: 
 5436: # --------------------------------------------------------- dumpstore interface
 5437: 
 5438: sub dumpstore {
 5439:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 5440:    # same as dump but keys must be escaped. They may contain colon separated
 5441:    # lists of values that may themself contain colons (e.g. symbs).
 5442:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 5443: }
 5444: 
 5445: # -------------------------------------------------------------- keys interface
 5446: 
 5447: sub getkeys {
 5448:    my ($namespace,$udomain,$uname)=@_;
 5449:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5450:    if (!$uname) { $uname=$env{'user.name'}; }
 5451:    my $uhome=&homeserver($uname,$udomain);
 5452:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 5453:    my @keyarray=();
 5454:    foreach my $key (split(/\&/,$rep)) {
 5455:       next if ($key =~ /^error: 2 /);
 5456:       push(@keyarray,&unescape($key));
 5457:    }
 5458:    return @keyarray;
 5459: }
 5460: 
 5461: # --------------------------------------------------------------- currentdump
 5462: sub currentdump {
 5463:    my ($courseid,$sdom,$sname)=@_;
 5464:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 5465:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 5466:    $sname    = $env{'user.name'}         if (! defined($sname));
 5467:    my $uhome = &homeserver($sname,$sdom);
 5468:    my $rep;
 5469: 
 5470:    if (grep { $_ eq $uhome } current_machine_ids()) {
 5471:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 5472:                    $courseid)));
 5473:    } else {
 5474:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 5475:    }
 5476: 
 5477:    return if ($rep =~ /^(error:|no_such_host)/);
 5478:    #
 5479:    my %returnhash=();
 5480:    #
 5481:    if ($rep eq "unknown_cmd") { 
 5482:        # an old lond will not know currentdump
 5483:        # Do a dump and make it look like a currentdump
 5484:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 5485:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 5486:        my %hash = @tmp;
 5487:        @tmp=();
 5488:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 5489:    } else {
 5490:        my @pairs=split(/\&/,$rep);
 5491:        foreach my $pair (@pairs) {
 5492:            my ($key,$value)=split(/=/,$pair,2);
 5493:            my ($symb,$param) = split(/:/,$key);
 5494:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 5495:                                                         &thaw_unescape($value);
 5496:        }
 5497:    }
 5498:    return %returnhash;
 5499: }
 5500: 
 5501: sub convert_dump_to_currentdump{
 5502:     my %hash = %{shift()};
 5503:     my %returnhash;
 5504:     # Code ripped from lond, essentially.  The only difference
 5505:     # here is the unescaping done by lonnet::dump().  Conceivably
 5506:     # we might run in to problems with parameter names =~ /^v\./
 5507:     while (my ($key,$value) = each(%hash)) {
 5508:         my ($v,$symb,$param) = split(/:/,$key);
 5509: 	$symb  = &unescape($symb);
 5510: 	$param = &unescape($param);
 5511:         next if ($v eq 'version' || $symb eq 'keys');
 5512:         next if (exists($returnhash{$symb}) &&
 5513:                  exists($returnhash{$symb}->{$param}) &&
 5514:                  $returnhash{$symb}->{'v.'.$param} > $v);
 5515:         $returnhash{$symb}->{$param}=$value;
 5516:         $returnhash{$symb}->{'v.'.$param}=$v;
 5517:     }
 5518:     #
 5519:     # Remove all of the keys in the hashes which keep track of
 5520:     # the version of the parameter.
 5521:     while (my ($symb,$param_hash) = each(%returnhash)) {
 5522:         # use a foreach because we are going to delete from the hash.
 5523:         foreach my $key (keys(%$param_hash)) {
 5524:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 5525:         }
 5526:     }
 5527:     return \%returnhash;
 5528: }
 5529: 
 5530: # ------------------------------------------------------ critical inc interface
 5531: 
 5532: sub cinc {
 5533:     return &inc(@_,'critical');
 5534: }
 5535: 
 5536: # --------------------------------------------------------------- inc interface
 5537: 
 5538: sub inc {
 5539:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 5540:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5541:     if (!$uname) { $uname=$env{'user.name'}; }
 5542:     my $uhome=&homeserver($uname,$udomain);
 5543:     my $items='';
 5544:     if (! ref($store)) {
 5545:         # got a single value, so use that instead
 5546:         $items = &escape($store).'=&';
 5547:     } elsif (ref($store) eq 'SCALAR') {
 5548:         $items = &escape($$store).'=&';        
 5549:     } elsif (ref($store) eq 'ARRAY') {
 5550:         $items = join('=&',map {&escape($_);} @{$store});
 5551:     } elsif (ref($store) eq 'HASH') {
 5552:         while (my($key,$value) = each(%{$store})) {
 5553:             $items.= &escape($key).'='.&escape($value).'&';
 5554:         }
 5555:     }
 5556:     $items=~s/\&$//;
 5557:     if ($critical) {
 5558: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 5559:     } else {
 5560: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 5561:     }
 5562: }
 5563: 
 5564: # --------------------------------------------------------------- put interface
 5565: 
 5566: sub put {
 5567:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5568:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5569:    if (!$uname) { $uname=$env{'user.name'}; }
 5570:    my $uhome=&homeserver($uname,$udomain);
 5571:    my $items='';
 5572:    foreach my $item (keys(%$storehash)) {
 5573:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5574:    }
 5575:    $items=~s/\&$//;
 5576:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5577: }
 5578: 
 5579: # ------------------------------------------------------------ newput interface
 5580: 
 5581: sub newput {
 5582:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5583:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5584:    if (!$uname) { $uname=$env{'user.name'}; }
 5585:    my $uhome=&homeserver($uname,$udomain);
 5586:    my $items='';
 5587:    foreach my $key (keys(%$storehash)) {
 5588:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5589:    }
 5590:    $items=~s/\&$//;
 5591:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 5592: }
 5593: 
 5594: # ---------------------------------------------------------  putstore interface
 5595: 
 5596: sub putstore {
 5597:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5598:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5599:    if (!$uname) { $uname=$env{'user.name'}; }
 5600:    my $uhome=&homeserver($uname,$udomain);
 5601:    my $items='';
 5602:    foreach my $key (keys(%$storehash)) {
 5603:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 5604:    }
 5605:    $items=~s/\&$//;
 5606:    my $esc_symb=&escape($symb);
 5607:    my $esc_v=&escape($version);
 5608:    my $reply =
 5609:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 5610: 	      $uhome);
 5611:    if ($reply eq 'unknown_cmd') {
 5612:        # gfall back to way things use to be done
 5613:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 5614: 			    $uname);
 5615:    }
 5616:    return $reply;
 5617: }
 5618: 
 5619: sub old_putstore {
 5620:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5621:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5622:     if (!$uname) { $uname=$env{'user.name'}; }
 5623:     my $uhome=&homeserver($uname,$udomain);
 5624:     my %newstorehash;
 5625:     foreach my $item (keys(%$storehash)) {
 5626: 	my $key = $version.':'.&escape($symb).':'.$item;
 5627: 	$newstorehash{$key} = $storehash->{$item};
 5628:     }
 5629:     my $items='';
 5630:     my %allitems = ();
 5631:     foreach my $item (keys(%newstorehash)) {
 5632: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 5633: 	    my $key = $1.':keys:'.$2;
 5634: 	    $allitems{$key} .= $3.':';
 5635: 	}
 5636: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 5637:     }
 5638:     foreach my $item (keys(%allitems)) {
 5639: 	$allitems{$item} =~ s/\:$//;
 5640: 	$items.= $item.'='.$allitems{$item}.'&';
 5641:     }
 5642:     $items=~s/\&$//;
 5643:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5644: }
 5645: 
 5646: # ------------------------------------------------------ critical put interface
 5647: 
 5648: sub cput {
 5649:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5650:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5651:    if (!$uname) { $uname=$env{'user.name'}; }
 5652:    my $uhome=&homeserver($uname,$udomain);
 5653:    my $items='';
 5654:    foreach my $item (keys(%$storehash)) {
 5655:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5656:    }
 5657:    $items=~s/\&$//;
 5658:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 5659: }
 5660: 
 5661: # -------------------------------------------------------------- eget interface
 5662: 
 5663: sub eget {
 5664:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5665:    my $items='';
 5666:    foreach my $item (@$storearr) {
 5667:        $items.=&escape($item).'&';
 5668:    }
 5669:    $items=~s/\&$//;
 5670:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5671:    if (!$uname) { $uname=$env{'user.name'}; }
 5672:    my $uhome=&homeserver($uname,$udomain);
 5673:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 5674:    my @pairs=split(/\&/,$rep);
 5675:    my %returnhash=();
 5676:    my $i=0;
 5677:    foreach my $item (@$storearr) {
 5678:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5679:       $i++;
 5680:    }
 5681:    return %returnhash;
 5682: }
 5683: 
 5684: # ------------------------------------------------------------ tmpput interface
 5685: sub tmpput {
 5686:     my ($storehash,$server,$context)=@_;
 5687:     my $items='';
 5688:     foreach my $item (keys(%$storehash)) {
 5689: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5690:     }
 5691:     $items=~s/\&$//;
 5692:     if (defined($context)) {
 5693:         $items .= ':'.&escape($context);
 5694:     }
 5695:     return &reply("tmpput:$items",$server);
 5696: }
 5697: 
 5698: # ------------------------------------------------------------ tmpget interface
 5699: sub tmpget {
 5700:     my ($token,$server)=@_;
 5701:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5702:     my $rep=&reply("tmpget:$token",$server);
 5703:     my %returnhash;
 5704:     foreach my $item (split(/\&/,$rep)) {
 5705: 	my ($key,$value)=split(/=/,$item);
 5706:         next if ($key =~ /^error: 2 /);
 5707: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 5708:     }
 5709:     return %returnhash;
 5710: }
 5711: 
 5712: # ------------------------------------------------------------ tmpdel interface
 5713: sub tmpdel {
 5714:     my ($token,$server)=@_;
 5715:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5716:     return &reply("tmpdel:$token",$server);
 5717: }
 5718: 
 5719: # ------------------------------------------------------------ get_timebased_id 
 5720: 
 5721: sub get_timebased_id {
 5722:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 5723:         $maxtries) = @_;
 5724:     my ($newid,$error,$dellock);
 5725:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 5726:         return ('','ok','invalid call to get suffix');
 5727:     }
 5728: 
 5729: # set defaults for any optional args for which values were not supplied
 5730:     if ($who eq '') {
 5731:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 5732:     }
 5733:     if (!$locktries) {
 5734:         $locktries = 3;
 5735:     }
 5736:     if (!$maxtries) {
 5737:         $maxtries = 10;
 5738:     }
 5739:     
 5740:     if (($cdom eq '') || ($cnum eq '')) {
 5741:         if ($env{'request.course.id'}) {
 5742:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5743:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5744:         }
 5745:         if (($cdom eq '') || ($cnum eq '')) {
 5746:             return ('','ok','call to get suffix not in course context');
 5747:         }
 5748:     }
 5749: 
 5750: # construct locking item
 5751:     my $lockhash = {
 5752:                       $prefix."\0".'locked_'.$keyid => $who,
 5753:                    };
 5754:     my $tries = 0;
 5755: 
 5756: # attempt to get lock on nohist_$namespace file
 5757:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 5758:     while (($gotlock ne 'ok') && $tries <$locktries) {
 5759:         $tries ++;
 5760:         sleep 1;
 5761:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 5762:     }
 5763: 
 5764: # attempt to get unique identifier, based on current timestamp
 5765:     if ($gotlock eq 'ok') {
 5766:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 5767:         my $id = time;
 5768:         $newid = $id;
 5769:         my $idtries = 0;
 5770:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 5771:             if ($idtype eq 'concat') {
 5772:                 $newid = $id.$idtries;
 5773:             } else {
 5774:                 $newid ++;
 5775:             }
 5776:             $idtries ++;
 5777:         }
 5778:         if (!exists($inuse{$prefix."\0".$newid})) {
 5779:             my %new_item =  (
 5780:                               $prefix."\0".$newid => $who,
 5781:                             );
 5782:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 5783:                                                  $cdom,$cnum);
 5784:             if ($putresult ne 'ok') {
 5785:                 undef($newid);
 5786:                 $error = 'error saving new item: '.$putresult;
 5787:             }
 5788:         } else {
 5789:              $error = ('error: no unique suffix available for the new item ');
 5790:         }
 5791: #  remove lock
 5792:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 5793:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 5794:     } else {
 5795:         $error = "error: could not obtain lockfile\n";
 5796:         $dellock = 'ok';
 5797:     }
 5798:     return ($newid,$dellock,$error);
 5799: }
 5800: 
 5801: # -------------------------------------------------- portfolio access checking
 5802: 
 5803: sub portfolio_access {
 5804:     my ($requrl) = @_;
 5805:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 5806:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 5807:     if ($result) {
 5808:         my %setters;
 5809:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 5810:             my ($startblock,$endblock) =
 5811:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 5812:             if ($startblock && $endblock) {
 5813:                 return 'B';
 5814:             }
 5815:         } else {
 5816:             my ($startblock,$endblock) =
 5817:                 &Apache::loncommon::blockcheck(\%setters,'port');
 5818:             if ($startblock && $endblock) {
 5819:                 return 'B';
 5820:             }
 5821:         }
 5822:     }
 5823:     if ($result eq 'ok') {
 5824:        return 'F';
 5825:     } elsif ($result =~ /^[^:]+:guest_/) {
 5826:        return 'A';
 5827:     }
 5828:     return '';
 5829: }
 5830: 
 5831: sub get_portfolio_access {
 5832:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 5833: 
 5834:     if (!ref($access_hash)) {
 5835: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 5836: 	my %access_controls = &get_access_controls($current_perms,$group,
 5837: 						   $file_name);
 5838: 	$access_hash = $access_controls{$file_name};
 5839:     }
 5840: 
 5841:     my ($public,$guest,@domains,@users,@courses,@groups);
 5842:     my $now = time;
 5843:     if (ref($access_hash) eq 'HASH') {
 5844:         foreach my $key (keys(%{$access_hash})) {
 5845:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 5846:             if ($start > $now) {
 5847:                 next;
 5848:             }
 5849:             if ($end && $end<$now) {
 5850:                 next;
 5851:             }
 5852:             if ($scope eq 'public') {
 5853:                 $public = $key;
 5854:                 last;
 5855:             } elsif ($scope eq 'guest') {
 5856:                 $guest = $key;
 5857:             } elsif ($scope eq 'domains') {
 5858:                 push(@domains,$key);
 5859:             } elsif ($scope eq 'users') {
 5860:                 push(@users,$key);
 5861:             } elsif ($scope eq 'course') {
 5862:                 push(@courses,$key);
 5863:             } elsif ($scope eq 'group') {
 5864:                 push(@groups,$key);
 5865:             }
 5866:         }
 5867:         if ($public) {
 5868:             return 'ok';
 5869:         }
 5870:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 5871:             if ($guest) {
 5872:                 return $guest;
 5873:             }
 5874:         } else {
 5875:             if (@domains > 0) {
 5876:                 foreach my $domkey (@domains) {
 5877:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 5878:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 5879:                             return 'ok';
 5880:                         }
 5881:                     }
 5882:                 }
 5883:             }
 5884:             if (@users > 0) {
 5885:                 foreach my $userkey (@users) {
 5886:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 5887:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 5888:                             if (ref($item) eq 'HASH') {
 5889:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 5890:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 5891:                                     return 'ok';
 5892:                                 }
 5893:                             }
 5894:                         }
 5895:                     } 
 5896:                 }
 5897:             }
 5898:             my %roleshash;
 5899:             my @courses_and_groups = @courses;
 5900:             push(@courses_and_groups,@groups); 
 5901:             if (@courses_and_groups > 0) {
 5902:                 my (%allgroups,%allroles); 
 5903:                 my ($start,$end,$role,$sec,$group);
 5904:                 foreach my $envkey (%env) {
 5905:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 5906:                         my $cid = $2.'_'.$3; 
 5907:                         if ($1 eq 'gr') {
 5908:                             $group = $4;
 5909:                             $allgroups{$cid}{$group} = $env{$envkey};
 5910:                         } else {
 5911:                             if ($4 eq '') {
 5912:                                 $sec = 'none';
 5913:                             } else {
 5914:                                 $sec = $4;
 5915:                             }
 5916:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 5917:                         }
 5918:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 5919:                         my $cid = $2.'_'.$3;
 5920:                         if ($4 eq '') {
 5921:                             $sec = 'none';
 5922:                         } else {
 5923:                             $sec = $4;
 5924:                         }
 5925:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 5926:                     }
 5927:                 }
 5928:                 if (keys(%allroles) == 0) {
 5929:                     return;
 5930:                 }
 5931:                 foreach my $key (@courses_and_groups) {
 5932:                     my %content = %{$$access_hash{$key}};
 5933:                     my $cnum = $content{'number'};
 5934:                     my $cdom = $content{'domain'};
 5935:                     my $cid = $cdom.'_'.$cnum;
 5936:                     if (!exists($allroles{$cid})) {
 5937:                         next;
 5938:                     }    
 5939:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 5940:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 5941:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 5942:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 5943:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 5944:                         foreach my $role (keys(%{$allroles{$cid}})) {
 5945:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 5946:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 5947:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 5948:                                         if (grep/^all$/,@sections) {
 5949:                                             return 'ok';
 5950:                                         } else {
 5951:                                             if (grep/^$sec$/,@sections) {
 5952:                                                 return 'ok';
 5953:                                             }
 5954:                                         }
 5955:                                     }
 5956:                                 }
 5957:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 5958:                                     if (grep/^none$/,@groups) {
 5959:                                         return 'ok';
 5960:                                     }
 5961:                                 } else {
 5962:                                     if (grep/^all$/,@groups) {
 5963:                                         return 'ok';
 5964:                                     } 
 5965:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 5966:                                         if (grep/^$group$/,@groups) {
 5967:                                             return 'ok';
 5968:                                         }
 5969:                                     }
 5970:                                 } 
 5971:                             }
 5972:                         }
 5973:                     }
 5974:                 }
 5975:             }
 5976:             if ($guest) {
 5977:                 return $guest;
 5978:             }
 5979:         }
 5980:     }
 5981:     return;
 5982: }
 5983: 
 5984: sub course_group_datechecker {
 5985:     my ($dates,$now,$status) = @_;
 5986:     my ($start,$end) = split(/\./,$dates);
 5987:     if (!$start && !$end) {
 5988:         return 'ok';
 5989:     }
 5990:     if (grep/^active$/,@{$status}) {
 5991:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 5992:             return 'ok';
 5993:         }
 5994:     }
 5995:     if (grep/^previous$/,@{$status}) {
 5996:         if ($end > $now ) {
 5997:             return 'ok';
 5998:         }
 5999:     }
 6000:     if (grep/^future$/,@{$status}) {
 6001:         if ($start > $now) {
 6002:             return 'ok';
 6003:         }
 6004:     }
 6005:     return; 
 6006: }
 6007: 
 6008: sub parse_portfolio_url {
 6009:     my ($url) = @_;
 6010: 
 6011:     my ($type,$udom,$unum,$group,$file_name);
 6012:     
 6013:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 6014: 	$type = 1;
 6015:         $udom = $1;
 6016:         $unum = $2;
 6017:         $file_name = $3;
 6018:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 6019: 	$type = 2;
 6020:         $udom = $1;
 6021:         $unum = $2;
 6022:         $group = $3;
 6023:         $file_name = $3.'/'.$4;
 6024:     }
 6025:     if (wantarray) {
 6026: 	return ($type,$udom,$unum,$file_name,$group);
 6027:     }
 6028:     return $type;
 6029: }
 6030: 
 6031: sub is_portfolio_url {
 6032:     my ($url) = @_;
 6033:     return scalar(&parse_portfolio_url($url));
 6034: }
 6035: 
 6036: sub is_portfolio_file {
 6037:     my ($file) = @_;
 6038:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 6039:         return 1;
 6040:     }
 6041:     return;
 6042: }
 6043: 
 6044: sub usertools_access {
 6045:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 6046:     my ($access,%tools);
 6047:     if ($context eq '') {
 6048:         $context = 'tools';
 6049:     }
 6050:     if ($context eq 'requestcourses') {
 6051:         %tools = (
 6052:                       official   => 1,
 6053:                       unofficial => 1,
 6054:                       community  => 1,
 6055:                  );
 6056:     } elsif ($context eq 'requestauthor') {
 6057:         %tools = (
 6058:                       requestauthor => 1,
 6059:                  );
 6060:     } else {
 6061:         %tools = (
 6062:                       aboutme   => 1,
 6063:                       blog      => 1,
 6064:                       webdav    => 1,
 6065:                       portfolio => 1,
 6066:                  );
 6067:     }
 6068:     return if (!defined($tools{$tool}));
 6069: 
 6070:     if ((!defined($udom)) || (!defined($uname))) {
 6071:         $udom = $env{'user.domain'};
 6072:         $uname = $env{'user.name'};
 6073:     }
 6074: 
 6075:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6076:         if ($action ne 'reload') {
 6077:             if ($context eq 'requestcourses') {
 6078:                 return $env{'environment.canrequest.'.$tool};
 6079:             } elsif ($context eq 'requestauthor') {
 6080:                 return $env{'environment.canrequest.author'};
 6081:             } else {
 6082:                 return $env{'environment.availabletools.'.$tool};
 6083:             }
 6084:         }
 6085:     }
 6086: 
 6087:     my ($toolstatus,$inststatus,$envkey);
 6088:     if ($context eq 'requestauthor') {
 6089:         $envkey = $context; 
 6090:     } else {
 6091:         $envkey = $context.'.'.$tool;
 6092:     }
 6093: 
 6094:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 6095:          ($action ne 'reload')) {
 6096:         $toolstatus = $env{'environment.'.$envkey};
 6097:         $inststatus = $env{'environment.inststatus'};
 6098:     } else {
 6099:         if (ref($userenvref) eq 'HASH') {
 6100:             $toolstatus = $userenvref->{$envkey};
 6101:             $inststatus = $userenvref->{'inststatus'};
 6102:         } else {
 6103:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 6104:             $toolstatus = $userenv{$envkey};
 6105:             $inststatus = $userenv{'inststatus'};
 6106:         }
 6107:     }
 6108: 
 6109:     if ($toolstatus ne '') {
 6110:         if ($toolstatus) {
 6111:             $access = 1;
 6112:         } else {
 6113:             $access = 0;
 6114:         }
 6115:         return $access;
 6116:     }
 6117: 
 6118:     my ($is_adv,%domdef);
 6119:     if (ref($is_advref) eq 'HASH') {
 6120:         $is_adv = $is_advref->{'is_adv'};
 6121:     } else {
 6122:         $is_adv = &is_advanced_user($udom,$uname);
 6123:     }
 6124:     if (ref($domdefref) eq 'HASH') {
 6125:         %domdef = %{$domdefref};
 6126:     } else {
 6127:         %domdef = &get_domain_defaults($udom);
 6128:     }
 6129:     if (ref($domdef{$tool}) eq 'HASH') {
 6130:         if ($is_adv) {
 6131:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 6132:                 if ($domdef{$tool}{'_LC_adv'}) { 
 6133:                     $access = 1;
 6134:                 } else {
 6135:                     $access = 0;
 6136:                 }
 6137:                 return $access;
 6138:             }
 6139:         }
 6140:         if ($inststatus ne '') {
 6141:             my ($hasaccess,$hasnoaccess);
 6142:             foreach my $affiliation (split(/:/,$inststatus)) {
 6143:                 if ($domdef{$tool}{$affiliation} ne '') { 
 6144:                     if ($domdef{$tool}{$affiliation}) {
 6145:                         $hasaccess = 1;
 6146:                     } else {
 6147:                         $hasnoaccess = 1;
 6148:                     }
 6149:                 }
 6150:             }
 6151:             if ($hasaccess || $hasnoaccess) {
 6152:                 if ($hasaccess) {
 6153:                     $access = 1;
 6154:                 } elsif ($hasnoaccess) {
 6155:                     $access = 0; 
 6156:                 }
 6157:                 return $access;
 6158:             }
 6159:         } else {
 6160:             if ($domdef{$tool}{'default'} ne '') {
 6161:                 if ($domdef{$tool}{'default'}) {
 6162:                     $access = 1;
 6163:                 } elsif ($domdef{$tool}{'default'} == 0) {
 6164:                     $access = 0;
 6165:                 }
 6166:                 return $access;
 6167:             }
 6168:         }
 6169:     } else {
 6170:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 6171:             $access = 1;
 6172:         } else {
 6173:             $access = 0;
 6174:         }
 6175:         return $access;
 6176:     }
 6177: }
 6178: 
 6179: sub is_course_owner {
 6180:     my ($cdom,$cnum,$udom,$uname) = @_;
 6181:     if (($udom eq '') || ($uname eq '')) {
 6182:         $udom = $env{'user.domain'};
 6183:         $uname = $env{'user.name'};
 6184:     }
 6185:     unless (($udom eq '') || ($uname eq '')) {
 6186:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 6187:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 6188:                 return 1;
 6189:             } else {
 6190:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 6191:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 6192:                     return 1;
 6193:                 }
 6194:             }
 6195:         }
 6196:     }
 6197:     return;
 6198: }
 6199: 
 6200: sub is_advanced_user {
 6201:     my ($udom,$uname) = @_;
 6202:     if ($udom ne '' && $uname ne '') {
 6203:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6204:             if (wantarray) {
 6205:                 return ($env{'user.adv'},$env{'user.author'});
 6206:             } else {
 6207:                 return $env{'user.adv'};
 6208:             }
 6209:         }
 6210:     }
 6211:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 6212:     my %allroles;
 6213:     my ($is_adv,$is_author);
 6214:     foreach my $role (keys(%roleshash)) {
 6215:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 6216:         my $area = '/'.$tdomain.'/'.$trest;
 6217:         if ($sec ne '') {
 6218:             $area .= '/'.$sec;
 6219:         }
 6220:         if (($area ne '') && ($trole ne '')) {
 6221:             my $spec=$trole.'.'.$area;
 6222:             if ($trole =~ /^cr\//) {
 6223:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6224:             } elsif ($trole ne 'gr') {
 6225:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6226:             }
 6227:             if ($trole eq 'au') {
 6228:                 $is_author = 1;
 6229:             }
 6230:         }
 6231:     }
 6232:     foreach my $role (keys(%allroles)) {
 6233:         last if ($is_adv);
 6234:         foreach my $item (split(/:/,$allroles{$role})) {
 6235:             if ($item ne '') {
 6236:                 my ($privilege,$restrictions)=split(/&/,$item);
 6237:                 if ($privilege eq 'adv') {
 6238:                     $is_adv = 1;
 6239:                     last;
 6240:                 }
 6241:             }
 6242:         }
 6243:     }
 6244:     if (wantarray) {
 6245:         return ($is_adv,$is_author);
 6246:     }
 6247:     return $is_adv;
 6248: }
 6249: 
 6250: sub check_can_request {
 6251:     my ($dom,$can_request,$request_domains) = @_;
 6252:     my $canreq = 0;
 6253:     my ($types,$typename) = &Apache::loncommon::course_types();
 6254:     my @options = ('approval','validate','autolimit');
 6255:     my $optregex = join('|',@options);
 6256:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 6257:         foreach my $type (@{$types}) {
 6258:             if (&usertools_access($env{'user.name'},
 6259:                                   $env{'user.domain'},
 6260:                                   $type,undef,'requestcourses')) {
 6261:                 $canreq ++;
 6262:                 if (ref($request_domains) eq 'HASH') {
 6263:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 6264:                 }
 6265:                 if ($dom eq $env{'user.domain'}) {
 6266:                     $can_request->{$type} = 1;
 6267:                 }
 6268:             }
 6269:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 6270:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 6271:                 if (@curr > 0) {
 6272:                     foreach my $item (@curr) {
 6273:                         if (ref($request_domains) eq 'HASH') {
 6274:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 6275:                             if ($otherdom ne '') {
 6276:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 6277:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 6278:                                         push(@{$request_domains->{$type}},$otherdom);
 6279:                                     }
 6280:                                 } else {
 6281:                                     push(@{$request_domains->{$type}},$otherdom);
 6282:                                 }
 6283:                             }
 6284:                         }
 6285:                     }
 6286:                     unless($dom eq $env{'user.domain'}) {
 6287:                         $canreq ++;
 6288:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 6289:                             $can_request->{$type} = 1;
 6290:                         }
 6291:                     }
 6292:                 }
 6293:             }
 6294:         }
 6295:     }
 6296:     return $canreq;
 6297: }
 6298: 
 6299: # ---------------------------------------------- Custom access rule evaluation
 6300: 
 6301: sub customaccess {
 6302:     my ($priv,$uri)=@_;
 6303:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 6304:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 6305:     $udom = &LONCAPA::clean_domain($udom);
 6306:     $ucrs = &LONCAPA::clean_username($ucrs);
 6307:     my $access=0;
 6308:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 6309: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 6310: 	if ($type eq 'user') {
 6311: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 6312: 		my ($tdom,$tuname)=split(m{/},$scope);
 6313: 		if ($tdom) {
 6314: 		    if ($tdom ne $env{'user.domain'}) { next; }
 6315: 		}
 6316: 		if ($tuname) {
 6317: 		    if ($tuname ne $env{'user.name'}) { next; }
 6318: 		}
 6319: 		$access=($effect eq 'allow');
 6320: 		last;
 6321: 	    }
 6322: 	} else {
 6323: 	    if ($role) {
 6324: 		if ($role ne $urole) { next; }
 6325: 	    }
 6326: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 6327: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 6328: 		if ($tdom) {
 6329: 		    if ($tdom ne $udom) { next; }
 6330: 		}
 6331: 		if ($tcrs) {
 6332: 		    if ($tcrs ne $ucrs) { next; }
 6333: 		}
 6334: 		if ($tsec) {
 6335: 		    if ($tsec ne $usec) { next; }
 6336: 		}
 6337: 		$access=($effect eq 'allow');
 6338: 		last;
 6339: 	    }
 6340: 	    if ($realm eq '' && $role eq '') {
 6341: 		$access=($effect eq 'allow');
 6342: 	    }
 6343: 	}
 6344:     }
 6345:     return $access;
 6346: }
 6347: 
 6348: # ------------------------------------------------- Check for a user privilege
 6349: 
 6350: sub allowed {
 6351:     my ($priv,$uri,$symb,$role)=@_;
 6352:     my $ver_orguri=$uri;
 6353:     $uri=&deversion($uri);
 6354:     my $orguri=$uri;
 6355:     $uri=&declutter($uri);
 6356: 
 6357:     if ($priv eq 'evb') {
 6358: # Evade communication block restrictions for specified role in a course
 6359:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 6360:             return $1;
 6361:         } else {
 6362:             return;
 6363:         }
 6364:     }
 6365: 
 6366:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 6367: # Free bre access to adm and meta resources
 6368:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 6369: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 6370: 	&& ($priv eq 'bre')) {
 6371: 	return 'F';
 6372:     }
 6373: 
 6374: # Free bre access to user's own portfolio contents
 6375:     my ($space,$domain,$name,@dir)=split('/',$uri);
 6376:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 6377: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 6378:         my %setters;
 6379:         my ($startblock,$endblock) = 
 6380:             &Apache::loncommon::blockcheck(\%setters,'port');
 6381:         if ($startblock && $endblock) {
 6382:             return 'B';
 6383:         } else {
 6384:             return 'F';
 6385:         }
 6386:     }
 6387: 
 6388: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 6389:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 6390:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 6391:         if (exists($env{'request.course.id'})) {
 6392:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6393:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6394:             if (($domain eq $cdom) && ($name eq $cnum)) {
 6395:                 my $courseprivid=$env{'request.course.id'};
 6396:                 $courseprivid=~s/\_/\//;
 6397:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 6398:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 6399:                     return $1; 
 6400:                 } else {
 6401:                     if ($env{'request.course.sec'}) {
 6402:                         $courseprivid.='/'.$env{'request.course.sec'};
 6403:                     }
 6404:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 6405:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 6406:                         return $2;
 6407:                     }
 6408:                 }
 6409:             }
 6410:         }
 6411:     }
 6412: 
 6413: # Free bre to public access
 6414: 
 6415:     if ($priv eq 'bre') {
 6416:         my $copyright=&metadata($uri,'copyright');
 6417: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 6418:            return 'F'; 
 6419:         }
 6420:         if ($copyright eq 'priv') {
 6421:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6422: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 6423: 		return '';
 6424:             }
 6425:         }
 6426:         if ($copyright eq 'domain') {
 6427:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6428: 	    unless (($env{'user.domain'} eq $1) ||
 6429:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 6430: 		return '';
 6431:             }
 6432:         }
 6433:         if ($env{'request.role'}=~ /li\.\//) {
 6434:             # Library role, so allow browsing of resources in this domain.
 6435:             return 'F';
 6436:         }
 6437:         if ($copyright eq 'custom') {
 6438: 	    unless (&customaccess($priv,$uri)) { return ''; }
 6439:         }
 6440:     }
 6441:     # Domain coordinator is trying to create a course
 6442:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 6443:         # uri is the requested domain in this case.
 6444:         # comparison to 'request.role.domain' shows if the user has selected
 6445:         # a role of dc for the domain in question.
 6446:         return 'F' if ($uri eq $env{'request.role.domain'});
 6447:     }
 6448: 
 6449:     my $thisallowed='';
 6450:     my $statecond=0;
 6451:     my $courseprivid='';
 6452: 
 6453:     my $ownaccess;
 6454:     # Community Coordinator or Assistant Co-author browsing resource space.
 6455:     if (($priv eq 'bro') && ($env{'user.author'})) {
 6456:         if ($uri eq '') {
 6457:             $ownaccess = 1;
 6458:         } else {
 6459:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 6460:                 my $udom = $env{'user.domain'};
 6461:                 my $uname = $env{'user.name'};
 6462:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 6463:                     $ownaccess = 1;
 6464:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 6465:                     unless ($uri =~ m{\.\./}) {
 6466:                         $ownaccess = 1;
 6467:                     }
 6468:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 6469:                     my $now = time;
 6470:                     if ($uri =~ m{^([^/]+)/?$}) {
 6471:                         my $adom = $1;
 6472:                         foreach my $key (keys(%env)) {
 6473:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 6474:                                 my ($start,$end) = split('.',$env{$key});
 6475:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6476:                                     $ownaccess = 1;
 6477:                                     last;
 6478:                                 }
 6479:                             }
 6480:                         }
 6481:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 6482:                         my $adom = $1;
 6483:                         my $aname = $2;
 6484:                         foreach my $role ('ca','aa') { 
 6485:                             if ($env{"user.role.$role./$adom/$aname"}) {
 6486:                                 my ($start,$end) =
 6487:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 6488:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6489:                                     $ownaccess = 1;
 6490:                                     last;
 6491:                                 }
 6492:                             }
 6493:                         }
 6494:                     }
 6495:                 }
 6496:             }
 6497:         }
 6498:     }
 6499: 
 6500: # Course
 6501: 
 6502:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 6503:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6504:             $thisallowed.=$1;
 6505:         }
 6506:     }
 6507: 
 6508: # Domain
 6509: 
 6510:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 6511:        =~/\Q$priv\E\&([^\:]*)/) {
 6512:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6513:             $thisallowed.=$1;
 6514:         }
 6515:     }
 6516: 
 6517: # User who is not author or co-author might still be able to edit
 6518: # resource of an author in the domain (e.g., if Domain Coordinator).
 6519:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 6520:         (&allowed('mdc',$env{'request.course.id'}))) {
 6521:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 6522:             $thisallowed.=$1;
 6523:         }
 6524:     }
 6525: 
 6526: # Course: uri itself is a course
 6527:     my $courseuri=$uri;
 6528:     $courseuri=~s/\_(\d)/\/$1/;
 6529:     $courseuri=~s/^([^\/])/\/$1/;
 6530: 
 6531:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 6532:        =~/\Q$priv\E\&([^\:]*)/) {
 6533:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6534:             $thisallowed.=$1;
 6535:         }
 6536:     }
 6537: 
 6538: # URI is an uploaded document for this course, default permissions don't matter
 6539: # not allowing 'edit' access (editupload) to uploaded course docs
 6540:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 6541: 	$thisallowed='';
 6542:         my ($match)=&is_on_map($uri);
 6543:         if ($match) {
 6544:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 6545:                   =~/\Q$priv\E\&([^\:]*)/) {
 6546:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6547:                 if (@blockers > 0) {
 6548:                     $thisallowed = 'B';
 6549:                 } else {
 6550:                     $thisallowed.=$1;
 6551:                 }
 6552:             }
 6553:         } else {
 6554:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 6555:             if ($refuri) {
 6556:                 if ($refuri =~ m|^/adm/|) {
 6557:                     $thisallowed='F';
 6558:                 } else {
 6559:                     $refuri=&declutter($refuri);
 6560:                     my ($match) = &is_on_map($refuri);
 6561:                     if ($match) {
 6562:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6563:                         if (@blockers > 0) {
 6564:                             $thisallowed = 'B';
 6565:                         } else {
 6566:                             $thisallowed='F';
 6567:                         }
 6568:                     }
 6569:                 }
 6570:             }
 6571:         }
 6572:     }
 6573: 
 6574:     if ($priv eq 'bre'
 6575: 	&& $thisallowed ne 'F' 
 6576: 	&& $thisallowed ne '2'
 6577: 	&& &is_portfolio_url($uri)) {
 6578: 	$thisallowed = &portfolio_access($uri);
 6579:     }
 6580:     
 6581: # Full access at system, domain or course-wide level? Exit.
 6582:     if ($thisallowed=~/F/) {
 6583: 	return 'F';
 6584:     }
 6585: 
 6586: # If this is generating or modifying users, exit with special codes
 6587: 
 6588:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 6589: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 6590: 	    my ($audom,$auname)=split('/',$uri);
 6591: # no author name given, so this just checks on the general right to make a co-author in this domain
 6592: 	    unless ($auname) { return $thisallowed; }
 6593: # an author name is given, so we are about to actually make a co-author for a certain account
 6594: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 6595: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 6596: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 6597: 	}
 6598: 	return $thisallowed;
 6599:     }
 6600: #
 6601: # Gathered so far: system, domain and course wide privileges
 6602: #
 6603: # Course: See if uri or referer is an individual resource that is part of 
 6604: # the course
 6605: 
 6606:     if ($env{'request.course.id'}) {
 6607: 
 6608:        $courseprivid=$env{'request.course.id'};
 6609:        if ($env{'request.course.sec'}) {
 6610:           $courseprivid.='/'.$env{'request.course.sec'};
 6611:        }
 6612:        $courseprivid=~s/\_/\//;
 6613:        my $checkreferer=1;
 6614:        my ($match,$cond)=&is_on_map($uri);
 6615:        if ($match) {
 6616:            $statecond=$cond;
 6617:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6618:                =~/\Q$priv\E\&([^\:]*)/) {
 6619:                my $value = $1;
 6620:                if ($priv eq 'bre') {
 6621:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6622:                    if (@blockers > 0) {
 6623:                        $thisallowed = 'B';
 6624:                    } else {
 6625:                        $thisallowed.=$value;
 6626:                    }
 6627:                } else {
 6628:                    $thisallowed.=$value;
 6629:                }
 6630:                $checkreferer=0;
 6631:            }
 6632:        }
 6633:        
 6634:        if ($checkreferer) {
 6635: 	  my $refuri=$env{'httpref.'.$orguri};
 6636:             unless ($refuri) {
 6637:                 foreach my $key (keys(%env)) {
 6638: 		    if ($key=~/^httpref\..*\*/) {
 6639: 			my $pattern=$key;
 6640:                         $pattern=~s/^httpref\.\/res\///;
 6641:                         $pattern=~s/\*/\[\^\/\]\+/g;
 6642:                         $pattern=~s/\//\\\//g;
 6643:                         if ($orguri=~/$pattern/) {
 6644: 			    $refuri=$env{$key};
 6645:                         }
 6646:                     }
 6647:                 }
 6648:             }
 6649: 
 6650:          if ($refuri) { 
 6651: 	  $refuri=&declutter($refuri);
 6652:           my ($match,$cond)=&is_on_map($refuri);
 6653:             if ($match) {
 6654:               my $refstatecond=$cond;
 6655:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6656:                   =~/\Q$priv\E\&([^\:]*)/) {
 6657:                   my $value = $1;
 6658:                   if ($priv eq 'bre') {
 6659:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6660:                       if (@blockers > 0) {
 6661:                           $thisallowed = 'B';
 6662:                       } else {
 6663:                           $thisallowed.=$value;
 6664:                       }
 6665:                   } else {
 6666:                       $thisallowed.=$value;
 6667:                   }
 6668:                   $uri=$refuri;
 6669:                   $statecond=$refstatecond;
 6670:               }
 6671:           }
 6672:         }
 6673:        }
 6674:    }
 6675: 
 6676: #
 6677: # Gathered now: all privileges that could apply, and condition number
 6678: # 
 6679: #
 6680: # Full or no access?
 6681: #
 6682: 
 6683:     if ($thisallowed=~/F/) {
 6684: 	return 'F';
 6685:     }
 6686: 
 6687:     unless ($thisallowed) {
 6688:         return '';
 6689:     }
 6690: 
 6691: # Restrictions exist, deal with them
 6692: #
 6693: #   C:according to course preferences
 6694: #   R:according to resource settings
 6695: #   L:unless locked
 6696: #   X:according to user session state
 6697: #
 6698: 
 6699: # Possibly locked functionality, check all courses
 6700: # Locks might take effect only after 10 minutes cache expiration for other
 6701: # courses, and 2 minutes for current course
 6702: 
 6703:     my $envkey;
 6704:     if ($thisallowed=~/L/) {
 6705:         foreach $envkey (keys(%env)) {
 6706:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 6707:                my $courseid=$2;
 6708:                my $roleid=$1.'.'.$2;
 6709:                $courseid=~s/^\///;
 6710:                my $expiretime=600;
 6711:                if ($env{'request.role'} eq $roleid) {
 6712: 		  $expiretime=120;
 6713:                }
 6714: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 6715:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 6716:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 6717: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 6718:                }
 6719:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6720:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 6721: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 6722:                        &log($env{'user.domain'},$env{'user.name'},
 6723:                             $env{'user.home'},
 6724:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 6725:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6726:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6727: 		       return '';
 6728:                    }
 6729:                }
 6730:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6731:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 6732: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 6733:                        &log($env{'user.domain'},$env{'user.name'},
 6734:                             $env{'user.home'},
 6735:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 6736:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6737:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6738: 		       return '';
 6739:                    }
 6740:                }
 6741: 	   }
 6742:        }
 6743:     }
 6744:    
 6745: #
 6746: # Rest of the restrictions depend on selected course
 6747: #
 6748: 
 6749:     unless ($env{'request.course.id'}) {
 6750: 	if ($thisallowed eq 'A') {
 6751: 	    return 'A';
 6752:         } elsif ($thisallowed eq 'B') {
 6753:             return 'B';
 6754: 	} else {
 6755: 	    return '1';
 6756: 	}
 6757:     }
 6758: 
 6759: #
 6760: # Now user is definitely in a course
 6761: #
 6762: 
 6763: 
 6764: # Course preferences
 6765: 
 6766:    if ($thisallowed=~/C/) {
 6767:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6768:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 6769:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 6770: 	   =~/\Q$rolecode\E/) {
 6771: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6772: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6773: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 6774: 			$env{'request.course.id'});
 6775: 	   }
 6776:            return '';
 6777:        }
 6778: 
 6779:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 6780: 	   =~/\Q$unamedom\E/) {
 6781: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6782: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 6783: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 6784: 			$env{'request.course.id'});
 6785: 	   }
 6786:            return '';
 6787:        }
 6788:    }
 6789: 
 6790: # Resource preferences
 6791: 
 6792:    if ($thisallowed=~/R/) {
 6793:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6794:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 6795: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6796: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6797: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 6798: 	   }
 6799: 	   return '';
 6800:        }
 6801:    }
 6802: 
 6803: # Restricted by state or randomout?
 6804: 
 6805:    if ($thisallowed=~/X/) {
 6806:       if ($env{'acc.randomout'}) {
 6807: 	 if (!$symb) { $symb=&symbread($uri,1); }
 6808:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 6809:             return ''; 
 6810:          }
 6811:       }
 6812:       if (&condval($statecond)) {
 6813: 	 return '2';
 6814:       } else {
 6815:          return '';
 6816:       }
 6817:    }
 6818: 
 6819:     if ($thisallowed eq 'A') {
 6820: 	return 'A';
 6821:     } elsif ($thisallowed eq 'B') {
 6822:         return 'B';
 6823:     }
 6824:    return 'F';
 6825: }
 6826: 
 6827: # ------------------------------------------- Check construction space access
 6828: 
 6829: sub constructaccess {
 6830:     my ($url,$setpriv)=@_;
 6831: 
 6832: # We do not allow editing of previous versions of files
 6833:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 6834: 
 6835: # Get username and domain from URL
 6836:     my ($ownername,$ownerdomain,$ownerhome);
 6837: 
 6838:     ($ownerdomain,$ownername) =
 6839:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
 6840: 
 6841: # The URL does not really point to any authorspace, forget it
 6842:     unless (($ownername) && ($ownerdomain)) { return ''; }
 6843: 
 6844: # Now we need to see if the user has access to the authorspace of
 6845: # $ownername at $ownerdomain
 6846: 
 6847:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 6848: # Real author for this?
 6849:        $ownerhome = $env{'user.home'};
 6850:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 6851:           return ($ownername,$ownerdomain,$ownerhome);
 6852:        }
 6853:     } else {
 6854: # Co-author for this?
 6855:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 6856:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 6857:             $ownerhome = &homeserver($ownername,$ownerdomain);
 6858:             return ($ownername,$ownerdomain,$ownerhome);
 6859:         }
 6860:     }
 6861: 
 6862: # We don't have any access right now. If we are not possibly going to do anything about this,
 6863: # we might as well leave
 6864:    unless ($setpriv) { return ''; }
 6865: 
 6866: # Backdoor access?
 6867:     my $allowed=&allowed('eco',$ownerdomain);
 6868: # Nope
 6869:     unless ($allowed) { return ''; }
 6870: # Looks like we may have access, but could be locked by the owner of the construction space
 6871:     if ($allowed eq 'U') {
 6872:         my %blocked=&get('environment',['domcoord.author'],
 6873:                          $ownerdomain,$ownername);
 6874: # Is blocked by owner
 6875:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 6876:     }
 6877:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 6878: # Grant temporary access
 6879:         my $then=$env{'user.login.time'};
 6880:         my $update==$env{'user.update.time'};
 6881:         if (!$update) { $update = $then; }
 6882:         my $refresh=$env{'user.refresh.time'};
 6883:         if (!$refresh) { $refresh = $update; }
 6884:         my $now = time;
 6885:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 6886:                            $now,'ca','constructaccess');
 6887:         $ownerhome = &homeserver($ownername,$ownerdomain);
 6888:         return($ownername,$ownerdomain,$ownerhome);
 6889:     }
 6890: # No business here
 6891:     return '';
 6892: }
 6893: 
 6894: sub get_comm_blocks {
 6895:     my ($cdom,$cnum) = @_;
 6896:     if ($cdom eq '' || $cnum eq '') {
 6897:         return unless ($env{'request.course.id'});
 6898:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6899:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6900:     }
 6901:     my %commblocks;
 6902:     my $hashid=$cdom.'_'.$cnum;
 6903:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 6904:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 6905:         %commblocks = %{$blocksref};
 6906:     } else {
 6907:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 6908:         my $cachetime = 600;
 6909:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 6910:     }
 6911:     return %commblocks;
 6912: }
 6913: 
 6914: sub has_comm_blocking {
 6915:     my ($priv,$symb,$uri,$blocks) = @_;
 6916:     return unless ($env{'request.course.id'});
 6917:     return unless ($priv eq 'bre');
 6918:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 6919:     my %commblocks;
 6920:     if (ref($blocks) eq 'HASH') {
 6921:         %commblocks = %{$blocks};
 6922:     } else {
 6923:         %commblocks = &get_comm_blocks();
 6924:     }
 6925:     return unless (keys(%commblocks) > 0);
 6926:     if (!$symb) { $symb=&symbread($uri,1); }
 6927:     my ($map,$resid,undef)=&decode_symb($symb);
 6928:     my %tocheck = (
 6929:                     maps      => $map,
 6930:                     resources => $symb,
 6931:                   );
 6932:     my @blockers;
 6933:     my $now = time;
 6934:     my $navmap = Apache::lonnavmaps::navmap->new();
 6935:     foreach my $block (keys(%commblocks)) {
 6936:         if ($block =~ /^(\d+)____(\d+)$/) {
 6937:             my ($start,$end) = ($1,$2);
 6938:             if ($start <= $now && $end >= $now) {
 6939:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 6940:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 6941:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 6942:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
 6943:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 6944:                                     push(@blockers,$block);
 6945:                                 }
 6946:                             }
 6947:                         }
 6948:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 6949:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
 6950:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
 6951:                                     push(@blockers,$block);
 6952:                                 }
 6953:                             }
 6954:                         }
 6955:                     }
 6956:                 }
 6957:             }
 6958:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 6959:             my $item = $1;
 6960:             my @to_test;
 6961:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 6962:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 6963:                     my $check_interval;
 6964:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
 6965:                         my @interval;
 6966:                         my $type = 'map';
 6967:                         if ($item eq 'course') {
 6968:                             $type = 'course';
 6969:                             @interval=&EXT("resource.0.interval");
 6970:                         } else {
 6971:                             if ($item =~ /___\d+___/) {
 6972:                                 $type = 'resource';
 6973:                                 @interval=&EXT("resource.0.interval",$item);
 6974:                                 if (ref($navmap)) {                        
 6975:                                     my $res = $navmap->getBySymb($item); 
 6976:                                     push(@to_test,$res);
 6977:                                 }
 6978:                             } else {
 6979:                                 my $mapsymb = &symbread($item,1);
 6980:                                 if ($mapsymb) {
 6981:                                     if (ref($navmap)) {
 6982:                                         my $mapres = $navmap->getBySymb($mapsymb);
 6983:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
 6984:                                         foreach my $res (@to_test) {
 6985:                                             my $symb = $res->symb();
 6986:                                             next if ($symb eq $mapsymb);
 6987:                                             if ($symb ne '') {
 6988:                                                 @interval=&EXT("resource.0.interval",$symb);
 6989:                                                 last;
 6990:                                             }
 6991:                                         }
 6992:                                     }
 6993:                                 }
 6994:                             }
 6995:                         }
 6996:                         if ($interval[0] =~ /\d+/) {
 6997:                             my $first_access;
 6998:                             if ($type eq 'resource') {
 6999:                                 $first_access=&get_first_access($interval[1],$item);
 7000:                             } elsif ($type eq 'map') {
 7001:                                 $first_access=&get_first_access($interval[1],undef,$item);
 7002:                             } else {
 7003:                                 $first_access=&get_first_access($interval[1]);
 7004:                             }
 7005:                             if ($first_access) {
 7006:                                 my $timesup = $first_access+$interval[0];
 7007:                                 if ($timesup > $now) {
 7008:                                     foreach my $res (@to_test) {
 7009:                                         if ($res->is_problem()) {
 7010:                                             if ($res->completable()) {
 7011:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 7012:                                                     push(@blockers,$block);
 7013:                                                 }
 7014:                                                 last;
 7015:                                             }
 7016:                                         }
 7017:                                     }
 7018:                                 }
 7019:                             }
 7020:                         }
 7021:                     }
 7022:                 }
 7023:             }
 7024:         }
 7025:     }
 7026:     return @blockers;
 7027: }
 7028: 
 7029: sub check_docs_block {
 7030:     my ($docsblock,$tocheck) =@_;
 7031:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
 7032:         return;
 7033:     }
 7034:     if (ref($docsblock->{'maps'}) eq 'HASH') {
 7035:         if ($tocheck->{'maps'}) {
 7036:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
 7037:                 return 1;
 7038:             }
 7039:         }
 7040:     }
 7041:     if (ref($docsblock->{'resources'}) eq 'HASH') {
 7042:         if ($tocheck->{'resources'}) {
 7043:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
 7044:                 return 1;
 7045:             }
 7046:         }
 7047:     }
 7048:     return;
 7049: }
 7050: 
 7051: #
 7052: #   Removes the versino from a URI and
 7053: #   splits it in to its filename and path to the filename.
 7054: #   Seems like File::Basename could have done this more clearly.
 7055: #   Parameters:
 7056: #      $uri   - input URI
 7057: #   Returns:
 7058: #     Two element list consisting of 
 7059: #     $pathname  - the URI up to and excluding the trailing /
 7060: #     $filename  - The part of the URI following the last /
 7061: #  NOTE:
 7062: #    Another realization of this is simply:
 7063: #    use File::Basename;
 7064: #    ...
 7065: #    $uri = shift;
 7066: #    $filename = basename($uri);
 7067: #    $path     = dirname($uri);
 7068: #    return ($filename, $path);
 7069: #
 7070: #     The implementation below is probably faster however.
 7071: #
 7072: sub split_uri_for_cond {
 7073:     my $uri=&deversion(&declutter(shift));
 7074:     my @uriparts=split(/\//,$uri);
 7075:     my $filename=pop(@uriparts);
 7076:     my $pathname=join('/',@uriparts);
 7077:     return ($pathname,$filename);
 7078: }
 7079: # --------------------------------------------------- Is a resource on the map?
 7080: 
 7081: sub is_on_map {
 7082:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 7083:     #Trying to find the conditional for the file
 7084:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 7085: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 7086:     if ($match) {
 7087: 	return (1,$1);
 7088:     } else {
 7089: 	return (0,0);
 7090:     }
 7091: }
 7092: 
 7093: # --------------------------------------------------------- Get symb from alias
 7094: 
 7095: sub get_symb_from_alias {
 7096:     my $symb=shift;
 7097:     my ($map,$resid,$url)=&decode_symb($symb);
 7098: # Already is a symb
 7099:     if ($url) { return $symb; }
 7100: # Must be an alias
 7101:     my $aliassymb='';
 7102:     my %bighash;
 7103:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7104:                             &GDBM_READER(),0640)) {
 7105:         my $rid=$bighash{'mapalias_'.$symb};
 7106: 	if ($rid) {
 7107: 	    my ($mapid,$resid)=split(/\./,$rid);
 7108: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 7109: 				    $resid,$bighash{'src_'.$rid});
 7110: 	}
 7111:         untie %bighash;
 7112:     }
 7113:     return $aliassymb;
 7114: }
 7115: 
 7116: # ----------------------------------------------------------------- Define Role
 7117: 
 7118: sub definerole {
 7119:   if (allowed('mcr','/')) {
 7120:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 7121:     foreach my $role (split(':',$sysrole)) {
 7122: 	my ($crole,$cqual)=split(/\&/,$role);
 7123:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 7124:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 7125: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 7126:                return "refused:s:$crole&$cqual"; 
 7127:             }
 7128:         }
 7129:     }
 7130:     foreach my $role (split(':',$domrole)) {
 7131: 	my ($crole,$cqual)=split(/\&/,$role);
 7132:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 7133:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 7134: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 7135:                return "refused:d:$crole&$cqual"; 
 7136:             }
 7137:         }
 7138:     }
 7139:     foreach my $role (split(':',$courole)) {
 7140: 	my ($crole,$cqual)=split(/\&/,$role);
 7141:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 7142:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 7143: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 7144:                return "refused:c:$crole&$cqual"; 
 7145:             }
 7146:         }
 7147:     }
 7148:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 7149:                 "$env{'user.domain'}:$env{'user.name'}:".
 7150: 	        "rolesdef_$rolename=".
 7151:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 7152:     return reply($command,$env{'user.home'});
 7153:   } else {
 7154:     return 'refused';
 7155:   }
 7156: }
 7157: 
 7158: # ---------------- Make a metadata query against the network of library servers
 7159: 
 7160: sub metadata_query {
 7161:     my ($query,$custom,$customshow,$server_array)=@_;
 7162:     my %rhash;
 7163:     my %libserv = &all_library();
 7164:     my @server_list = (defined($server_array) ? @$server_array
 7165:                                               : keys(%libserv) );
 7166:     for my $server (@server_list) {
 7167: 	unless ($custom or $customshow) {
 7168: 	    my $reply=&reply("querysend:".&escape($query),$server);
 7169: 	    $rhash{$server}=$reply;
 7170: 	}
 7171: 	else {
 7172: 	    my $reply=&reply("querysend:".&escape($query).':'.
 7173: 			     &escape($custom).':'.&escape($customshow),
 7174: 			     $server);
 7175: 	    $rhash{$server}=$reply;
 7176: 	}
 7177:     }
 7178:     return \%rhash;
 7179: }
 7180: 
 7181: # ----------------------------------------- Send log queries and wait for reply
 7182: 
 7183: sub log_query {
 7184:     my ($uname,$udom,$query,%filters)=@_;
 7185:     my $uhome=&homeserver($uname,$udom);
 7186:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 7187:     my $uhost=&hostname($uhome);
 7188:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 7189:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 7190:                        $uhome);
 7191:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 7192:     return get_query_reply($queryid);
 7193: }
 7194: 
 7195: # -------------------------- Update MySQL table for portfolio file
 7196: 
 7197: sub update_portfolio_table {
 7198:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 7199:     if ($group ne '') {
 7200:         $file_name =~s /^\Q$group\E//;
 7201:     }
 7202:     my $homeserver = &homeserver($uname,$udom);
 7203:     my $queryid=
 7204:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 7205:                ':'.&escape($file_name).':'.$action,$homeserver);
 7206:     my $reply = &get_query_reply($queryid);
 7207:     return $reply;
 7208: }
 7209: 
 7210: # -------------------------- Update MySQL allusers table
 7211: 
 7212: sub update_allusers_table {
 7213:     my ($uname,$udom,$names) = @_;
 7214:     my $homeserver = &homeserver($uname,$udom);
 7215:     my $queryid=
 7216:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 7217:                'lastname='.&escape($names->{'lastname'}).'%%'.
 7218:                'firstname='.&escape($names->{'firstname'}).'%%'.
 7219:                'middlename='.&escape($names->{'middlename'}).'%%'.
 7220:                'generation='.&escape($names->{'generation'}).'%%'.
 7221:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 7222:                'id='.&escape($names->{'id'}),$homeserver);
 7223:     return;
 7224: }
 7225: 
 7226: # ------- Request retrieval of institutional classlists for course(s)
 7227: 
 7228: sub fetch_enrollment_query {
 7229:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 7230:     my $homeserver;
 7231:     my $maxtries = 1;
 7232:     if ($context eq 'automated') {
 7233:         $homeserver = $perlvar{'lonHostID'};
 7234:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 7235:     } else {
 7236:         $homeserver = &homeserver($cnum,$dom);
 7237:     }
 7238:     my $host=&hostname($homeserver);
 7239:     my $cmd = '';
 7240:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7241:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7242:     }
 7243:     $cmd =~ s/%%$//;
 7244:     $cmd = &escape($cmd);
 7245:     my $query = 'fetchenrollment';
 7246:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 7247:     unless ($queryid=~/^\Q$host\E\_/) { 
 7248:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 7249:         return 'error: '.$queryid;
 7250:     }
 7251:     my $reply = &get_query_reply($queryid);
 7252:     my $tries = 1;
 7253:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7254:         $reply = &get_query_reply($queryid);
 7255:         $tries ++;
 7256:     }
 7257:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7258:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7259:     } else {
 7260:         my @responses = split(/:/,$reply);
 7261:         if ($homeserver eq $perlvar{'lonHostID'}) {
 7262:             foreach my $line (@responses) {
 7263:                 my ($key,$value) = split(/=/,$line,2);
 7264:                 $$replyref{$key} = $value;
 7265:             }
 7266:         } else {
 7267:             my $pathname = LONCAPA::tempdir();
 7268:             foreach my $line (@responses) {
 7269:                 my ($key,$value) = split(/=/,$line);
 7270:                 $$replyref{$key} = $value;
 7271:                 if ($value > 0) {
 7272:                     foreach my $item (@{$$affiliatesref{$key}}) {
 7273:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 7274:                         my $destname = $pathname.'/'.$filename;
 7275:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 7276:                         if ($xml_classlist =~ /^error/) {
 7277:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 7278:                         } else {
 7279:                             if ( open(FILE,">$destname") ) {
 7280:                                 print FILE &unescape($xml_classlist);
 7281:                                 close(FILE);
 7282:                             } else {
 7283:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 7284:                             }
 7285:                         }
 7286:                     }
 7287:                 }
 7288:             }
 7289:         }
 7290:         return 'ok';
 7291:     }
 7292:     return 'error';
 7293: }
 7294: 
 7295: sub get_query_reply {
 7296:     my $queryid=shift;
 7297:     my $replyfile=LONCAPA::tempdir().$queryid;
 7298:     my $reply='';
 7299:     for (1..100) {
 7300: 	sleep 2;
 7301:         if (-e $replyfile.'.end') {
 7302: 	    if (open(my $fh,$replyfile)) {
 7303: 		$reply = join('',<$fh>);
 7304: 		close($fh);
 7305: 	   } else { return 'error: reply_file_error'; }
 7306:            return &unescape($reply);
 7307: 	}
 7308:     }
 7309:     return 'timeout:'.$queryid;
 7310: }
 7311: 
 7312: sub courselog_query {
 7313: #
 7314: # possible filters:
 7315: # url: url or symb
 7316: # username
 7317: # domain
 7318: # action: view, submit, grade
 7319: # start: timestamp
 7320: # end: timestamp
 7321: #
 7322:     my (%filters)=@_;
 7323:     unless ($env{'request.course.id'}) { return 'no_course'; }
 7324:     if ($filters{'url'}) {
 7325: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 7326:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 7327:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 7328:     }
 7329:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7330:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7331:     return &log_query($cname,$cdom,'courselog',%filters);
 7332: }
 7333: 
 7334: sub userlog_query {
 7335: #
 7336: # possible filters:
 7337: # action: log check role
 7338: # start: timestamp
 7339: # end: timestamp
 7340: #
 7341:     my ($uname,$udom,%filters)=@_;
 7342:     return &log_query($uname,$udom,'userlog',%filters);
 7343: }
 7344: 
 7345: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 7346: 
 7347: sub auto_run {
 7348:     my ($cnum,$cdom) = @_;
 7349:     my $response = 0;
 7350:     my $settings;
 7351:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 7352:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 7353:         $settings = $domconfig{'autoenroll'};
 7354:         if ($settings->{'run'} eq '1') {
 7355:             $response = 1;
 7356:         }
 7357:     } else {
 7358:         my $homeserver;
 7359:         if (&is_course($cdom,$cnum)) {
 7360:             $homeserver = &homeserver($cnum,$cdom);
 7361:         } else {
 7362:             $homeserver = &domain($cdom,'primary');
 7363:         }
 7364:         if ($homeserver ne 'no_host') {
 7365:             $response = &reply('autorun:'.$cdom,$homeserver);
 7366:         }
 7367:     }
 7368:     return $response;
 7369: }
 7370: 
 7371: sub auto_get_sections {
 7372:     my ($cnum,$cdom,$inst_coursecode) = @_;
 7373:     my $homeserver;
 7374:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 7375:         $homeserver = &homeserver($cnum,$cdom);
 7376:     }
 7377:     if (!defined($homeserver)) { 
 7378:         if ($cdom =~ /^$match_domain$/) {
 7379:             $homeserver = &domain($cdom,'primary');
 7380:         }
 7381:     }
 7382:     my @secs;
 7383:     if (defined($homeserver)) {
 7384:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 7385:         unless ($response eq 'refused') {
 7386:             @secs = split(/:/,$response);
 7387:         }
 7388:     }
 7389:     return @secs;
 7390: }
 7391: 
 7392: sub auto_new_course {
 7393:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 7394:     my $homeserver = &homeserver($cnum,$cdom);
 7395:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 7396:     return $response;
 7397: }
 7398: 
 7399: sub auto_validate_courseID {
 7400:     my ($cnum,$cdom,$inst_course_id) = @_;
 7401:     my $homeserver = &homeserver($cnum,$cdom);
 7402:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 7403:     return $response;
 7404: }
 7405: 
 7406: sub auto_validate_instcode {
 7407:     my ($cnum,$cdom,$instcode,$owner) = @_;
 7408:     my ($homeserver,$response);
 7409:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7410:         $homeserver = &homeserver($cnum,$cdom);
 7411:     }
 7412:     if (!defined($homeserver)) {
 7413:         if ($cdom =~ /^$match_domain$/) {
 7414:             $homeserver = &domain($cdom,'primary');
 7415:         }
 7416:     }
 7417:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 7418:                         &escape($instcode).':'.&escape($owner),$homeserver));
 7419:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
 7420:     return ($outcome,$description);
 7421: }
 7422: 
 7423: sub auto_create_password {
 7424:     my ($cnum,$cdom,$authparam,$udom) = @_;
 7425:     my ($homeserver,$response);
 7426:     my $create_passwd = 0;
 7427:     my $authchk = '';
 7428:     if ($udom =~ /^$match_domain$/) {
 7429:         $homeserver = &domain($udom,'primary');
 7430:     }
 7431:     if ($homeserver eq '') {
 7432:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7433:             $homeserver = &homeserver($cnum,$cdom);
 7434:         }
 7435:     }
 7436:     if ($homeserver eq '') {
 7437:         $authchk = 'nodomain';
 7438:     } else {
 7439:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 7440:         if ($response eq 'refused') {
 7441:             $authchk = 'refused';
 7442:         } else {
 7443:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 7444:         }
 7445:     }
 7446:     return ($authparam,$create_passwd,$authchk);
 7447: }
 7448: 
 7449: sub auto_photo_permission {
 7450:     my ($cnum,$cdom,$students) = @_;
 7451:     my $homeserver = &homeserver($cnum,$cdom);
 7452:     my ($outcome,$perm_reqd,$conditions) = 
 7453: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 7454:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7455: 	return (undef,undef);
 7456:     }
 7457:     return ($outcome,$perm_reqd,$conditions);
 7458: }
 7459: 
 7460: sub auto_checkphotos {
 7461:     my ($uname,$udom,$pid) = @_;
 7462:     my $homeserver = &homeserver($uname,$udom);
 7463:     my ($result,$resulttype);
 7464:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 7465: 				   &escape($uname).':'.&escape($pid),
 7466: 				   $homeserver));
 7467:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7468: 	return (undef,undef);
 7469:     }
 7470:     if ($outcome) {
 7471:         ($result,$resulttype) = split(/:/,$outcome);
 7472:     } 
 7473:     return ($result,$resulttype);
 7474: }
 7475: 
 7476: sub auto_photochoice {
 7477:     my ($cnum,$cdom) = @_;
 7478:     my $homeserver = &homeserver($cnum,$cdom);
 7479:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 7480: 						       &escape($cdom),
 7481: 						       $homeserver)));
 7482:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7483: 	return (undef,undef);
 7484:     }
 7485:     return ($update,$comment);
 7486: }
 7487: 
 7488: sub auto_photoupdate {
 7489:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 7490:     my $homeserver = &homeserver($cnum,$dom);
 7491:     my $host=&hostname($homeserver);
 7492:     my $cmd = '';
 7493:     my $maxtries = 1;
 7494:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7495:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7496:     }
 7497:     $cmd =~ s/%%$//;
 7498:     $cmd = &escape($cmd);
 7499:     my $query = 'institutionalphotos';
 7500:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 7501:     unless ($queryid=~/^\Q$host\E\_/) {
 7502:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 7503:         return 'error: '.$queryid;
 7504:     }
 7505:     my $reply = &get_query_reply($queryid);
 7506:     my $tries = 1;
 7507:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7508:         $reply = &get_query_reply($queryid);
 7509:         $tries ++;
 7510:     }
 7511:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7512:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7513:     } else {
 7514:         my @responses = split(/:/,$reply);
 7515:         my $outcome = shift(@responses); 
 7516:         foreach my $item (@responses) {
 7517:             my ($key,$value) = split(/=/,$item);
 7518:             $$photo{$key} = $value;
 7519:         }
 7520:         return $outcome;
 7521:     }
 7522:     return 'error';
 7523: }
 7524: 
 7525: sub auto_instcode_format {
 7526:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 7527: 	$cat_order) = @_;
 7528:     my $courses = '';
 7529:     my @homeservers;
 7530:     if ($caller eq 'global') {
 7531: 	my %servers = &get_servers($codedom,'library');
 7532: 	foreach my $tryserver (keys(%servers)) {
 7533: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7534: 		push(@homeservers,$tryserver);
 7535: 	    }
 7536:         }
 7537:     } elsif ($caller eq 'requests') {
 7538:         if ($codedom =~ /^$match_domain$/) {
 7539:             my $chome = &domain($codedom,'primary');
 7540:             unless ($chome eq 'no_host') {
 7541:                 push(@homeservers,$chome);
 7542:             }
 7543:         }
 7544:     } else {
 7545:         push(@homeservers,&homeserver($caller,$codedom));
 7546:     }
 7547:     foreach my $code (keys(%{$instcodes})) {
 7548:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 7549:     }
 7550:     chop($courses);
 7551:     my $ok_response = 0;
 7552:     my $response;
 7553:     while (@homeservers > 0 && $ok_response == 0) {
 7554:         my $server = shift(@homeservers); 
 7555:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 7556:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 7557:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 7558: 		split(/:/,$response);
 7559:             %{$codes} = (%{$codes},&str2hash($codes_str));
 7560:             push(@{$codetitles},&str2array($codetitles_str));
 7561:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 7562:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 7563:             $ok_response = 1;
 7564:         }
 7565:     }
 7566:     if ($ok_response) {
 7567:         return 'ok';
 7568:     } else {
 7569:         return $response;
 7570:     }
 7571: }
 7572: 
 7573: sub auto_instcode_defaults {
 7574:     my ($domain,$returnhash,$code_order) = @_;
 7575:     my @homeservers;
 7576: 
 7577:     my %servers = &get_servers($domain,'library');
 7578:     foreach my $tryserver (keys(%servers)) {
 7579: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7580: 	    push(@homeservers,$tryserver);
 7581: 	}
 7582:     }
 7583: 
 7584:     my $response;
 7585:     foreach my $server (@homeservers) {
 7586:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 7587:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7588: 	
 7589: 	foreach my $pair (split(/\&/,$response)) {
 7590: 	    my ($name,$value)=split(/\=/,$pair);
 7591: 	    if ($name eq 'code_order') {
 7592: 		@{$code_order} = split(/\&/,&unescape($value));
 7593: 	    } else {
 7594: 		$returnhash->{&unescape($name)}=&unescape($value);
 7595: 	    }
 7596: 	}
 7597: 	return 'ok';
 7598:     }
 7599: 
 7600:     return $response;
 7601: }
 7602: 
 7603: sub auto_possible_instcodes {
 7604:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 7605:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 7606:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 7607:         return;
 7608:     }
 7609:     my (@homeservers,$uhome);
 7610:     if (defined(&domain($domain,'primary'))) {
 7611:         $uhome=&domain($domain,'primary');
 7612:         push(@homeservers,&domain($domain,'primary'));
 7613:     } else {
 7614:         my %servers = &get_servers($domain,'library');
 7615:         foreach my $tryserver (keys(%servers)) {
 7616:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7617:                 push(@homeservers,$tryserver);
 7618:             }
 7619:         }
 7620:     }
 7621:     my $response;
 7622:     foreach my $server (@homeservers) {
 7623:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 7624:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7625:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 7626:             split(':',$response);
 7627:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 7628:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 7629:         foreach my $item (split('&',$cat_title)) {   
 7630:             my ($name,$value)=split('=',$item);
 7631:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 7632:         }
 7633:         foreach my $item (split('&',$cat_order)) {
 7634:             my ($name,$value)=split('=',$item);
 7635:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 7636:         }
 7637:         return 'ok';
 7638:     }
 7639:     return $response;
 7640: }
 7641: 
 7642: sub auto_courserequest_checks {
 7643:     my ($dom) = @_;
 7644:     my ($homeserver,%validations);
 7645:     if ($dom =~ /^$match_domain$/) {
 7646:         $homeserver = &domain($dom,'primary');
 7647:     }
 7648:     unless ($homeserver eq 'no_host') {
 7649:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 7650:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 7651:             my @items = split(/&/,$response);
 7652:             foreach my $item (@items) {
 7653:                 my ($key,$value) = split('=',$item);
 7654:                 $validations{&unescape($key)} = &thaw_unescape($value);
 7655:             }
 7656:         }
 7657:     }
 7658:     return %validations; 
 7659: }
 7660: 
 7661: sub auto_courserequest_validation {
 7662:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
 7663:     my ($homeserver,$response);
 7664:     if ($dom =~ /^$match_domain$/) {
 7665:         $homeserver = &domain($dom,'primary');
 7666:     }
 7667:     unless ($homeserver eq 'no_host') {  
 7668:           
 7669:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 7670:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 7671:                                     ':'.&escape($instcode).':'.&escape($instseclist),
 7672:                                     $homeserver));
 7673:     }
 7674:     return $response;
 7675: }
 7676: 
 7677: sub auto_validate_class_sec {
 7678:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 7679:     my $homeserver = &homeserver($cnum,$cdom);
 7680:     my $ownerlist;
 7681:     if (ref($owners) eq 'ARRAY') {
 7682:         $ownerlist = join(',',@{$owners});
 7683:     } else {
 7684:         $ownerlist = $owners;
 7685:     }
 7686:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 7687:                         &escape($ownerlist).':'.$cdom,$homeserver);
 7688:     return $response;
 7689: }
 7690: 
 7691: # ------------------------------------------------------- Course Group routines
 7692: 
 7693: sub get_coursegroups {
 7694:     my ($cdom,$cnum,$group,$namespace) = @_;
 7695:     return(&dump($namespace,$cdom,$cnum,$group));
 7696: }
 7697: 
 7698: sub modify_coursegroup {
 7699:     my ($cdom,$cnum,$groupsettings) = @_;
 7700:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 7701: }
 7702: 
 7703: sub toggle_coursegroup_status {
 7704:     my ($cdom,$cnum,$group,$action) = @_;
 7705:     my ($from_namespace,$to_namespace);
 7706:     if ($action eq 'delete') {
 7707:         $from_namespace = 'coursegroups';
 7708:         $to_namespace = 'deleted_groups';
 7709:     } else {
 7710:         $from_namespace = 'deleted_groups';
 7711:         $to_namespace = 'coursegroups';
 7712:     }
 7713:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 7714:     if (my $tmp = &error(%curr_group)) {
 7715:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 7716:         return ('read error',$tmp);
 7717:     } else {
 7718:         my %savedsettings = %curr_group; 
 7719:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 7720:         my $deloutcome;
 7721:         if ($result eq 'ok') {
 7722:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 7723:         } else {
 7724:             return ('write error',$result);
 7725:         }
 7726:         if ($deloutcome eq 'ok') {
 7727:             return 'ok';
 7728:         } else {
 7729:             return ('delete error',$deloutcome);
 7730:         }
 7731:     }
 7732: }
 7733: 
 7734: sub modify_group_roles {
 7735:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 7736:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 7737:     my $role = 'gr/'.&escape($userprivs);
 7738:     my ($uname,$udom) = split(/:/,$user);
 7739:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 7740:     if ($result eq 'ok') {
 7741:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 7742:     }
 7743:     return $result;
 7744: }
 7745: 
 7746: sub modify_coursegroup_membership {
 7747:     my ($cdom,$cnum,$membership) = @_;
 7748:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 7749:     return $result;
 7750: }
 7751: 
 7752: sub get_active_groups {
 7753:     my ($udom,$uname,$cdom,$cnum) = @_;
 7754:     my $now = time;
 7755:     my %groups = ();
 7756:     foreach my $key (keys(%env)) {
 7757:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 7758:             my ($start,$end) = split(/\./,$env{$key});
 7759:             if (($end!=0) && ($end<$now)) { next; }
 7760:             if (($start!=0) && ($start>$now)) { next; }
 7761:             if ($1 eq $cdom && $2 eq $cnum) {
 7762:                 $groups{$3} = $env{$key} ;
 7763:             }
 7764:         }
 7765:     }
 7766:     return %groups;
 7767: }
 7768: 
 7769: sub get_group_membership {
 7770:     my ($cdom,$cnum,$group) = @_;
 7771:     return(&dump('groupmembership',$cdom,$cnum,$group));
 7772: }
 7773: 
 7774: sub get_users_groups {
 7775:     my ($udom,$uname,$courseid) = @_;
 7776:     my @usersgroups;
 7777:     my $cachetime=1800;
 7778: 
 7779:     my $hashid="$udom:$uname:$courseid";
 7780:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 7781:     if (defined($cached)) {
 7782:         @usersgroups = split(/:/,$grouplist);
 7783:     } else {  
 7784:         $grouplist = '';
 7785:         my $courseurl = &courseid_to_courseurl($courseid);
 7786:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 7787:         my $access_end = $env{'course.'.$courseid.
 7788:                               '.default_enrollment_end_date'};
 7789:         my $now = time;
 7790:         foreach my $key (keys(%roleshash)) {
 7791:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 7792:                 my $group = $1;
 7793:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 7794:                     my $start = $2;
 7795:                     my $end = $1;
 7796:                     if ($start == -1) { next; } # deleted from group
 7797:                     if (($start!=0) && ($start>$now)) { next; }
 7798:                     if (($end!=0) && ($end<$now)) {
 7799:                         if ($access_end && $access_end < $now) {
 7800:                             if ($access_end - $end < 86400) {
 7801:                                 push(@usersgroups,$group);
 7802:                             }
 7803:                         }
 7804:                         next;
 7805:                     }
 7806:                     push(@usersgroups,$group);
 7807:                 }
 7808:             }
 7809:         }
 7810:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 7811:         $grouplist = join(':',@usersgroups);
 7812:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 7813:     }
 7814:     return @usersgroups;
 7815: }
 7816: 
 7817: sub devalidate_getgroups_cache {
 7818:     my ($udom,$uname,$cdom,$cnum)=@_;
 7819:     my $courseid = $cdom.'_'.$cnum;
 7820: 
 7821:     my $hashid="$udom:$uname:$courseid";
 7822:     &devalidate_cache_new('getgroups',$hashid);
 7823: }
 7824: 
 7825: # ------------------------------------------------------------------ Plain Text
 7826: 
 7827: sub plaintext {
 7828:     my ($short,$type,$cid,$forcedefault) = @_;
 7829:     if ($short =~ m{^cr/}) {
 7830: 	return (split('/',$short))[-1];
 7831:     }
 7832:     if (!defined($cid)) {
 7833:         $cid = $env{'request.course.id'};
 7834:     }
 7835:     my %rolenames = (
 7836:                       Course    => 'std',
 7837:                       Community => 'alt1',
 7838:                     );
 7839:     if ($cid ne '') {
 7840:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 7841:             unless ($forcedefault) {
 7842:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 7843:                 &Apache::lonlocal::mt_escape(\$roletext);
 7844:                 return &Apache::lonlocal::mt($roletext);
 7845:             }
 7846:         }
 7847:     }
 7848:     if ((defined($type)) && (defined($rolenames{$type})) &&
 7849:         (defined($rolenames{$type})) && 
 7850:         (defined($prp{$short}{$rolenames{$type}}))) {
 7851:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 7852:     } elsif ($cid ne '') {
 7853:         my $crstype = $env{'course.'.$cid.'.type'};
 7854:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 7855:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 7856:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 7857:         }
 7858:     }
 7859:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 7860: }
 7861: 
 7862: # ----------------------------------------------------------------- Assign Role
 7863: 
 7864: sub assignrole {
 7865:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 7866:         $context)=@_;
 7867:     my $mrole;
 7868:     if ($role =~ /^cr\//) {
 7869:         my $cwosec=$url;
 7870:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 7871: 	unless (&allowed('ccr',$cwosec)) {
 7872:            my $refused = 1;
 7873:            if ($context eq 'requestcourses') {
 7874:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 7875:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 7876:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 7877:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 7878:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7879:                            if ($crsenv{'internal.courseowner'} eq
 7880:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 7881:                                $refused = '';
 7882:                            }
 7883:                        }
 7884:                    }
 7885:                }
 7886:            }
 7887:            if ($refused) {
 7888:                &logthis('Refused custom assignrole: '.
 7889:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 7890:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 7891:                return 'refused';
 7892:            }
 7893:         }
 7894:         $mrole='cr';
 7895:     } elsif ($role =~ /^gr\//) {
 7896:         my $cwogrp=$url;
 7897:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 7898:         unless (&allowed('mdg',$cwogrp)) {
 7899:             &logthis('Refused group assignrole: '.
 7900:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 7901:                     $env{'user.name'}.' at '.$env{'user.domain'});
 7902:             return 'refused';
 7903:         }
 7904:         $mrole='gr';
 7905:     } else {
 7906:         my $cwosec=$url;
 7907:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 7908:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 7909:             my $refused;
 7910:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 7911:                 if (!(&allowed('c'.$role,$url))) {
 7912:                     $refused = 1;
 7913:                 }
 7914:             } else {
 7915:                 $refused = 1;
 7916:             }
 7917:             if ($refused) {
 7918:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 7919:                 if (!$selfenroll && $context eq 'course') {
 7920:                     my %crsenv;
 7921:                     if ($role eq 'cc' || $role eq 'co') {
 7922:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7923:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 7924:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 7925:                                 if ($crsenv{'internal.courseowner'} eq 
 7926:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 7927:                                     $refused = '';
 7928:                                 }
 7929:                             }
 7930:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 7931:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 7932:                                 if ($crsenv{'internal.courseowner'} eq 
 7933:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 7934:                                     $refused = '';
 7935:                                 }
 7936:                             }
 7937:                         }
 7938:                     }
 7939:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7940:                     $refused = '';
 7941:                 } elsif ($context eq 'requestcourses') {
 7942:                     my @possroles = ('st','ta','ep','in','cc','co');
 7943:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 7944:                         my $wrongcc;
 7945:                         if ($cnum =~ /^$match_community$/) {
 7946:                             $wrongcc = 1 if ($role eq 'cc');
 7947:                         } else {
 7948:                             $wrongcc = 1 if ($role eq 'co');
 7949:                         }
 7950:                         unless ($wrongcc) {
 7951:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7952:                             if ($crsenv{'internal.courseowner'} eq 
 7953:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 7954:                                 $refused = '';
 7955:                             }
 7956:                         }
 7957:                     }
 7958:                 } elsif ($context eq 'requestauthor') {
 7959:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
 7960:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 7961:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 7962:                             $refused = '';
 7963:                         } else {
 7964:                             my %domdefaults = &get_domain_defaults($udom);
 7965:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 7966:                                 my $checkbystatus;
 7967:                                 if ($env{'user.adv'}) { 
 7968:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 7969:                                     if ($disposition eq 'automatic') {
 7970:                                         $refused = '';
 7971:                                     } elsif ($disposition eq '') {
 7972:                                         $checkbystatus = 1;
 7973:                                     } 
 7974:                                 } else {
 7975:                                     $checkbystatus = 1;
 7976:                                 }
 7977:                                 if ($checkbystatus) {
 7978:                                     if ($env{'environment.inststatus'}) {
 7979:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 7980:                                         foreach my $type (@inststatuses) {
 7981:                                             if (($type ne '') &&
 7982:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 7983:                                                 $refused = '';
 7984:                                             }
 7985:                                         }
 7986:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 7987:                                         $refused = '';
 7988:                                     }
 7989:                                 }
 7990:                             }
 7991:                         }
 7992:                     }
 7993:                 }
 7994:                 if ($refused) {
 7995:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 7996:                              ' '.$role.' '.$end.' '.$start.' by '.
 7997: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 7998:                     return 'refused';
 7999:                 }
 8000:             }
 8001:         } elsif ($role eq 'au') {
 8002:             if ($url ne '/'.$udom.'/') {
 8003:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 8004:                          ' to assign author role for '.$uname.':'.$udom.
 8005:                          ' in domain: '.$url.' refused (wrong domain).');
 8006:                 return 'refused';
 8007:             }
 8008:         }
 8009:         $mrole=$role;
 8010:     }
 8011:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 8012:                 "$udom:$uname:$url".'_'."$mrole=$role";
 8013:     if ($end) { $command.='_'.$end; }
 8014:     if ($start) {
 8015: 	if ($end) { 
 8016:            $command.='_'.$start; 
 8017:         } else {
 8018:            $command.='_0_'.$start;
 8019:         }
 8020:     }
 8021:     my $origstart = $start;
 8022:     my $origend = $end;
 8023:     my $delflag;
 8024: # actually delete
 8025:     if ($deleteflag) {
 8026: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 8027: # modify command to delete the role
 8028:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 8029:                 "$udom:$uname:$url".'_'."$mrole";
 8030: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 8031: # set start and finish to negative values for userrolelog
 8032:            $start=-1;
 8033:            $end=-1;
 8034:            $delflag = 1;
 8035:         }
 8036:     }
 8037: # send command
 8038:     my $answer=&reply($command,&homeserver($uname,$udom));
 8039: # log new user role if status is ok
 8040:     if ($answer eq 'ok') {
 8041: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 8042: # for course roles, perform group memberships changes triggered by role change.
 8043:         unless ($role =~ /^gr/) {
 8044:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 8045:                                              $origstart,$selfenroll,$context);
 8046:         }
 8047:         if (($role eq 'cc') || ($role eq 'in') ||
 8048:             ($role eq 'ep') || ($role eq 'ad') ||
 8049:             ($role eq 'ta') || ($role eq 'st') ||
 8050:             ($role=~/^cr/) || ($role eq 'gr') ||
 8051:             ($role eq 'co')) {
 8052:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8053:                            $selfenroll,$context);
 8054:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
 8055:                  ($role eq 'au') || ($role eq 'dc')) {
 8056:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8057:                            $context);
 8058:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
 8059:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8060:                              $context); 
 8061:         }
 8062:         if ($role eq 'cc') {
 8063:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 8064:         }
 8065:     }
 8066:     return $answer;
 8067: }
 8068: 
 8069: sub autoupdate_coowners {
 8070:     my ($url,$end,$start,$uname,$udom) = @_;
 8071:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 8072:     if (($cdom ne '') && ($cnum ne '')) {
 8073:         my $now = time;
 8074:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 8075:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 8076:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 8077:             my $instcode = $coursehash{'internal.coursecode'};
 8078:             if ($instcode ne '') {
 8079:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 8080:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 8081:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 8082:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 8083:                         if ($result eq 'valid') {
 8084:                             if ($coursehash{'internal.co-owners'}) {
 8085:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 8086:                                     push(@newcoowners,$coowner);
 8087:                                 }
 8088:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 8089:                                     push(@newcoowners,$uname.':'.$udom);
 8090:                                 }
 8091:                                 @newcoowners = sort(@newcoowners);
 8092:                             } else {
 8093:                                 push(@newcoowners,$uname.':'.$udom);
 8094:                             }
 8095:                         } else {
 8096:                             if ($coursehash{'internal.co-owners'}) {
 8097:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 8098:                                     unless ($coowner eq $uname.':'.$udom) {
 8099:                                         push(@newcoowners,$coowner);
 8100:                                     }
 8101:                                 }
 8102:                                 unless (@newcoowners > 0) {
 8103:                                     $delcoowners = 1;
 8104:                                     $coowners = '';
 8105:                                 }
 8106:                             }
 8107:                         }
 8108:                         if (@newcoowners || $delcoowners) {
 8109:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 8110:                                             $delcoowners,@newcoowners);
 8111:                         }
 8112:                     }
 8113:                 }
 8114:             }
 8115:         }
 8116:     }
 8117: }
 8118: 
 8119: sub store_coowners {
 8120:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 8121:     my $cid = $cdom.'_'.$cnum;
 8122:     my ($coowners,$delresult,$putresult);
 8123:     if (@newcoowners) {
 8124:         $coowners = join(',',@newcoowners);
 8125:         my %coownershash = (
 8126:                             'internal.co-owners' => $coowners,
 8127:                            );
 8128:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 8129:         if ($putresult eq 'ok') {
 8130:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 8131:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 8132:             }
 8133:         }
 8134:     }
 8135:     if ($delcoowners) {
 8136:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 8137:         if ($delresult eq 'ok') {
 8138:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 8139:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 8140:             }
 8141:         }
 8142:     }
 8143:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 8144:         my %crsinfo =
 8145:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 8146:         if (ref($crsinfo{$cid}) eq 'HASH') {
 8147:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 8148:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 8149:         }
 8150:     }
 8151: }
 8152: 
 8153: # -------------------------------------------------- Modify user authentication
 8154: # Overrides without validation
 8155: 
 8156: sub modifyuserauth {
 8157:     my ($udom,$uname,$umode,$upass)=@_;
 8158:     my $uhome=&homeserver($uname,$udom);
 8159:     unless (&allowed('mau',$udom)) { return 'refused'; }
 8160:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 8161:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 8162:              ' in domain '.$env{'request.role.domain'});  
 8163:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 8164: 		     &escape($upass),$uhome);
 8165:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 8166:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 8167:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 8168:     &log($udom,,$uname,$uhome,
 8169:         'Authentication changed by '.$env{'user.domain'}.', '.
 8170:                                      $env{'user.name'}.', '.$umode.
 8171:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 8172:     unless ($reply eq 'ok') {
 8173:         &logthis('Authentication mode error: '.$reply);
 8174: 	return 'error: '.$reply;
 8175:     }   
 8176:     return 'ok';
 8177: }
 8178: 
 8179: # --------------------------------------------------------------- Modify a user
 8180: 
 8181: sub modifyuser {
 8182:     my ($udom,    $uname, $uid,
 8183:         $umode,   $upass, $first,
 8184:         $middle,  $last,  $gene,
 8185:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 8186:     $udom= &LONCAPA::clean_domain($udom);
 8187:     $uname=&LONCAPA::clean_username($uname);
 8188:     my $showcandelete = 'none';
 8189:     if (ref($candelete) eq 'ARRAY') {
 8190:         if (@{$candelete} > 0) {
 8191:             $showcandelete = join(', ',@{$candelete});
 8192:         }
 8193:     }
 8194:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 8195:              $umode.', '.$first.', '.$middle.', '.
 8196: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 8197:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 8198:                                      ' desiredhome not specified'). 
 8199:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 8200:              ' in domain '.$env{'request.role.domain'});
 8201:     my $uhome=&homeserver($uname,$udom,'true');
 8202:     my $newuser;
 8203:     if ($uhome eq 'no_host') {
 8204:         $newuser = 1;
 8205:     }
 8206: # ----------------------------------------------------------------- Create User
 8207:     if (($uhome eq 'no_host') && 
 8208: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 8209:         my $unhome='';
 8210:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 8211:             $unhome = $desiredhome;
 8212: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 8213: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 8214:         } else { # load balancing routine for determining $unhome
 8215:             my $loadm=10000000;
 8216: 	    my %servers = &get_servers($udom,'library');
 8217: 	    foreach my $tryserver (keys(%servers)) {
 8218: 		my $answer=reply('load',$tryserver);
 8219: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 8220: 		    $loadm=$answer;
 8221: 		    $unhome=$tryserver;
 8222: 		}
 8223: 	    }
 8224:         }
 8225:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 8226: 	    return 'error: unable to find a home server for '.$uname.
 8227:                    ' in domain '.$udom;
 8228:         }
 8229:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 8230:                          &escape($upass),$unhome);
 8231: 	unless ($reply eq 'ok') {
 8232:             return 'error: '.$reply;
 8233:         }   
 8234:         $uhome=&homeserver($uname,$udom,'true');
 8235:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 8236: 	    return 'error: unable verify users home machine.';
 8237:         }
 8238:     }   # End of creation of new user
 8239: # ---------------------------------------------------------------------- Add ID
 8240:     if ($uid) {
 8241:        $uid=~tr/A-Z/a-z/;
 8242:        my %uidhash=&idrget($udom,$uname);
 8243:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 8244:          && (!$forceid)) {
 8245: 	  unless ($uid eq $uidhash{$uname}) {
 8246: 	      return 'error: user id "'.$uid.'" does not match '.
 8247:                   'current user id "'.$uidhash{$uname}.'".';
 8248:           }
 8249:        } else {
 8250: 	  &idput($udom,($uname => $uid));
 8251:        }
 8252:     }
 8253: # -------------------------------------------------------------- Add names, etc
 8254:     my @tmp=&get('environment',
 8255: 		   ['firstname','middlename','lastname','generation','id',
 8256:                     'permanentemail','inststatus'],
 8257: 		   $udom,$uname);
 8258:     my (%names,%oldnames);
 8259:     if ($tmp[0] =~ m/^error:.*/) { 
 8260:         %names=(); 
 8261:     } else {
 8262:         %names = @tmp;
 8263:         %oldnames = %names;
 8264:     }
 8265: #
 8266: # If name, email and/or uid are blank (e.g., because an uploaded file
 8267: # of users did not contain them), do not overwrite existing values
 8268: # unless field is in $candelete array ref.  
 8269: #
 8270: 
 8271:     my @fields = ('firstname','middlename','lastname','generation',
 8272:                   'permanentemail','id');
 8273:     my %newvalues;
 8274:     if (ref($candelete) eq 'ARRAY') {
 8275:         foreach my $field (@fields) {
 8276:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 8277:                 if ($field eq 'firstname') {
 8278:                     $names{$field} = $first;
 8279:                 } elsif ($field eq 'middlename') {
 8280:                     $names{$field} = $middle;
 8281:                 } elsif ($field eq 'lastname') {
 8282:                     $names{$field} = $last;
 8283:                 } elsif ($field eq 'generation') { 
 8284:                     $names{$field} = $gene;
 8285:                 } elsif ($field eq 'permanentemail') {
 8286:                     $names{$field} = $email;
 8287:                 } elsif ($field eq 'id') {
 8288:                     $names{$field}  = $uid;
 8289:                 }
 8290:             }
 8291:         }
 8292:     }
 8293:     if ($first)  { $names{'firstname'}  = $first; }
 8294:     if (defined($middle)) { $names{'middlename'} = $middle; }
 8295:     if ($last)   { $names{'lastname'}   = $last; }
 8296:     if (defined($gene))   { $names{'generation'} = $gene; }
 8297:     if ($email) {
 8298:        $email=~s/[^\w\@\.\-\,]//gs;
 8299:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 8300:     }
 8301:     if ($uid) { $names{'id'}  = $uid; }
 8302:     if (defined($inststatus)) {
 8303:         $names{'inststatus'} = '';
 8304:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 8305:         if (ref($usertypes) eq 'HASH') {
 8306:             my @okstatuses; 
 8307:             foreach my $item (split(/:/,$inststatus)) {
 8308:                 if (defined($usertypes->{$item})) {
 8309:                     push(@okstatuses,$item);  
 8310:                 }
 8311:             }
 8312:             if (@okstatuses) {
 8313:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 8314:             }
 8315:         }
 8316:     }
 8317:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 8318:                  $umode.', '.$first.', '.$middle.', '.
 8319:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 8320:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 8321:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 8322:     } else {
 8323:         $logmsg .= ' during self creation';
 8324:     }
 8325:     my $changed;
 8326:     if ($newuser) {
 8327:         $changed = 1;
 8328:     } else {
 8329:         foreach my $field (@fields) {
 8330:             if ($names{$field} ne $oldnames{$field}) {
 8331:                 $changed = 1;
 8332:                 last;
 8333:             }
 8334:         }
 8335:     }
 8336:     unless ($changed) {
 8337:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 8338:         &logthis($logmsg);
 8339:         return 'ok';
 8340:     }
 8341:     my $reply = &put('environment', \%names, $udom,$uname);
 8342:     if ($reply ne 'ok') { 
 8343:         return 'error: '.$reply;
 8344:     }
 8345:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
 8346:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
 8347:     }
 8348:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 8349:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 8350:     $logmsg = 'Success modifying user '.$logmsg;
 8351:     &logthis($logmsg);
 8352:     return 'ok';
 8353: }
 8354: 
 8355: # -------------------------------------------------------------- Modify student
 8356: 
 8357: sub modifystudent {
 8358:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 8359:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 8360:         $selfenroll,$context,$inststatus)=@_;
 8361:     if (!$cid) {
 8362: 	unless ($cid=$env{'request.course.id'}) {
 8363: 	    return 'not_in_class';
 8364: 	}
 8365:     }
 8366: # --------------------------------------------------------------- Make the user
 8367:     my $reply=&modifyuser
 8368: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 8369:          $desiredhome,$email,$inststatus);
 8370:     unless ($reply eq 'ok') { return $reply; }
 8371:     # This will cause &modify_student_enrollment to get the uid from the
 8372:     # students environment
 8373:     $uid = undef if (!$forceid);
 8374:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 8375: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
 8376:     return $reply;
 8377: }
 8378: 
 8379: sub modify_student_enrollment {
 8380:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
 8381:     my ($cdom,$cnum,$chome);
 8382:     if (!$cid) {
 8383: 	unless ($cid=$env{'request.course.id'}) {
 8384: 	    return 'not_in_class';
 8385: 	}
 8386: 	$cdom=$env{'course.'.$cid.'.domain'};
 8387: 	$cnum=$env{'course.'.$cid.'.num'};
 8388:     } else {
 8389: 	($cdom,$cnum)=split(/_/,$cid);
 8390:     }
 8391:     $chome=$env{'course.'.$cid.'.home'};
 8392:     if (!$chome) {
 8393: 	$chome=&homeserver($cnum,$cdom);
 8394:     }
 8395:     if (!$chome) { return 'unknown_course'; }
 8396:     # Make sure the user exists
 8397:     my $uhome=&homeserver($uname,$udom);
 8398:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8399: 	return 'error: no such user';
 8400:     }
 8401:     # Get student data if we were not given enough information
 8402:     if (!defined($first)  || $first  eq '' || 
 8403:         !defined($last)   || $last   eq '' || 
 8404:         !defined($uid)    || $uid    eq '' || 
 8405:         !defined($middle) || $middle eq '' || 
 8406:         !defined($gene)   || $gene   eq '') {
 8407:         # They did not supply us with enough data to enroll the student, so
 8408:         # we need to pick up more information.
 8409:         my %tmp = &get('environment',
 8410:                        ['firstname','middlename','lastname', 'generation','id']
 8411:                        ,$udom,$uname);
 8412: 
 8413:         #foreach my $key (keys(%tmp)) {
 8414:         #    &logthis("key $key = ".$tmp{$key});
 8415:         #}
 8416:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 8417:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 8418:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 8419:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 8420:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 8421:     }
 8422:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 8423:     my $user = "$uname:$udom";
 8424:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
 8425:     my $reply=cput('classlist',
 8426: 		   {$user => 
 8427: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 8428: 		   $cdom,$cnum);
 8429:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
 8430:         &devalidate_getsection_cache($udom,$uname,$cid);
 8431:     } else { 
 8432: 	return 'error: '.$reply;
 8433:     }
 8434:     # Add student role to user
 8435:     my $uurl='/'.$cid;
 8436:     $uurl=~s/\_/\//g;
 8437:     if ($usec) {
 8438: 	$uurl.='/'.$usec;
 8439:     }
 8440:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
 8441:                              $selfenroll,$context);
 8442:     if ($result ne 'ok') {
 8443:         if ($old_entry{$user} ne '') {
 8444:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
 8445:         } else {
 8446:             $reply = &del('classlist',[$user],$cdom,$cnum);
 8447:         }
 8448:     }
 8449:     return $result; 
 8450: }
 8451: 
 8452: sub format_name {
 8453:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 8454:     my $name;
 8455:     if ($first ne 'lastname') {
 8456: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 8457:     } else {
 8458: 	if ($lastname=~/\S/) {
 8459: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 8460: 	    $name=~s/\s+,/,/;
 8461: 	} else {
 8462: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 8463: 	}
 8464:     }
 8465:     $name=~s/^\s+//;
 8466:     $name=~s/\s+$//;
 8467:     $name=~s/\s+/ /g;
 8468:     return $name;
 8469: }
 8470: 
 8471: # ------------------------------------------------- Write to course preferences
 8472: 
 8473: sub writecoursepref {
 8474:     my ($courseid,%prefs)=@_;
 8475:     $courseid=~s/^\///;
 8476:     $courseid=~s/\_/\//g;
 8477:     my ($cdomain,$cnum)=split(/\//,$courseid);
 8478:     my $chome=homeserver($cnum,$cdomain);
 8479:     if (($chome eq '') || ($chome eq 'no_host')) { 
 8480: 	return 'error: no such course';
 8481:     }
 8482:     my $cstring='';
 8483:     foreach my $pref (keys(%prefs)) {
 8484: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 8485:     }
 8486:     $cstring=~s/\&$//;
 8487:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 8488: }
 8489: 
 8490: # ---------------------------------------------------------- Make/modify course
 8491: 
 8492: sub createcourse {
 8493:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 8494:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 8495:     $url=&declutter($url);
 8496:     my $cid='';
 8497:     if ($context eq 'requestcourses') {
 8498:         my $can_create = 0;
 8499:         my ($ownername,$ownerdom) = split(':',$course_owner);
 8500:         if ($udom eq $ownerdom) {
 8501:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 8502:                                   $context)) {
 8503:                 $can_create = 1;
 8504:             }
 8505:         } else {
 8506:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 8507:                                            $category);
 8508:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 8509:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 8510:                 if (@curr > 0) {
 8511:                     my @options = qw(approval validate autolimit);
 8512:                     my $optregex = join('|',@options);
 8513:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 8514:                         $can_create = 1;
 8515:                     }
 8516:                 }
 8517:             }
 8518:         }
 8519:         if ($can_create) {
 8520:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 8521:                 unless (&allowed('ccc',$udom)) {
 8522:                     return 'refused'; 
 8523:                 }
 8524:             }
 8525:         } else {
 8526:             return 'refused';
 8527:         }
 8528:     } elsif (!&allowed('ccc',$udom)) {
 8529:         return 'refused';
 8530:     }
 8531: # --------------------------------------------------------------- Get Unique ID
 8532:     my $uname;
 8533:     if ($cnum =~ /^$match_courseid$/) {
 8534:         my $chome=&homeserver($cnum,$udom,'true');
 8535:         if (($chome eq '') || ($chome eq 'no_host')) {
 8536:             $uname = $cnum;
 8537:         } else {
 8538:             $uname = &generate_coursenum($udom,$crstype);
 8539:         }
 8540:     } else {
 8541:         $uname = &generate_coursenum($udom,$crstype);
 8542:     }
 8543:     return $uname if ($uname =~ /^error/);
 8544: # -------------------------------------------------- Check supplied server name
 8545:     if (!defined($course_server)) {
 8546:         if (defined(&domain($udom,'primary'))) {
 8547:             $course_server = &domain($udom,'primary');
 8548:         } else {
 8549:             $course_server = $env{'user.home'}; 
 8550:         }
 8551:     }
 8552:     my %host_servers =
 8553:         &Apache::lonnet::get_servers($udom,'library');
 8554:     unless ($host_servers{$course_server}) {
 8555:         return 'error: invalid home server for course: '.$course_server;
 8556:     }
 8557: # ------------------------------------------------------------- Make the course
 8558:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 8559:                       $course_server);
 8560:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 8561:     my $uhome=&homeserver($uname,$udom,'true');
 8562:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8563: 	return 'error: no such course';
 8564:     }
 8565: # ----------------------------------------------------------------- Course made
 8566: # log existence
 8567:     my $now = time;
 8568:     my $newcourse = {
 8569:                     $udom.'_'.$uname => {
 8570:                                      description => $description,
 8571:                                      inst_code   => $inst_code,
 8572:                                      owner       => $course_owner,
 8573:                                      type        => $crstype,
 8574:                                      creator     => $env{'user.name'}.':'.
 8575:                                                     $env{'user.domain'},
 8576:                                      created     => $now,
 8577:                                      context     => $context,
 8578:                                                 },
 8579:                     };
 8580:     &courseidput($udom,$newcourse,$uhome,'notime');
 8581: # set toplevel url
 8582:     my $topurl=$url;
 8583:     unless ($nonstandard) {
 8584: # ------------------------------------------ For standard courses, make top url
 8585:         my $mapurl=&clutter($url);
 8586:         if ($mapurl eq '/res/') { $mapurl=''; }
 8587:         $env{'form.initmap'}=(<<ENDINITMAP);
 8588: <map>
 8589: <resource id="1" type="start"></resource>
 8590: <resource id="2" src="$mapurl"></resource>
 8591: <resource id="3" type="finish"></resource>
 8592: <link index="1" from="1" to="2"></link>
 8593: <link index="2" from="2" to="3"></link>
 8594: </map>
 8595: ENDINITMAP
 8596:         $topurl=&declutter(
 8597:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 8598:                           );
 8599:     }
 8600: # ----------------------------------------------------------- Write preferences
 8601:     &writecoursepref($udom.'_'.$uname,
 8602:                      ('description'              => $description,
 8603:                       'url'                      => $topurl,
 8604:                       'internal.creator'         => $env{'user.name'}.':'.
 8605:                                                     $env{'user.domain'},
 8606:                       'internal.created'         => $now,
 8607:                       'internal.creationcontext' => $context)
 8608:                     );
 8609:     return '/'.$udom.'/'.$uname;
 8610: }
 8611: 
 8612: # ------------------------------------------------------------------- Create ID
 8613: sub generate_coursenum {
 8614:     my ($udom,$crstype) = @_;
 8615:     my $domdesc = &domain($udom);
 8616:     return 'error: invalid domain' if ($domdesc eq '');
 8617:     my $first;
 8618:     if ($crstype eq 'Community') {
 8619:         $first = '0';
 8620:     } else {
 8621:         $first = int(1+rand(9)); 
 8622:     } 
 8623:     my $uname=$first.
 8624:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8625:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8626:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8627: # ----------------------------------------------- Make sure that does not exist
 8628:     my $uhome=&homeserver($uname,$udom,'true');
 8629:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8630:         if ($crstype eq 'Community') {
 8631:             $first = '0';
 8632:         } else {
 8633:             $first = int(1+rand(9));
 8634:         }
 8635:         $uname=$first.
 8636:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8637:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8638:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8639:         $uhome=&homeserver($uname,$udom,'true');
 8640:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8641:             return 'error: unable to generate unique course-ID';
 8642:         }
 8643:     }
 8644:     return $uname;
 8645: }
 8646: 
 8647: sub is_course {
 8648:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
 8649:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
 8650: 
 8651:     return unless $cdom and $cnum;
 8652: 
 8653:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
 8654:         '.');
 8655: 
 8656:     return unless exists($courses{$cdom.'_'.$cnum});
 8657:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
 8658: }
 8659: 
 8660: sub store_userdata {
 8661:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
 8662:     my $result;
 8663:     if ($datakey ne '') {
 8664:         if (ref($storehash) eq 'HASH') {
 8665:             if ($udom eq '' || $uname eq '') {
 8666:                 $udom = $env{'user.domain'};
 8667:                 $uname = $env{'user.name'};
 8668:             }
 8669:             my $uhome=&homeserver($uname,$udom);
 8670:             if (($uhome eq '') || ($uhome eq 'no_host')) {
 8671:                 $result = 'error: no_host';
 8672:             } else {
 8673:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
 8674:                 $storehash->{'host'} = $perlvar{'lonHostID'};
 8675: 
 8676:                 my $namevalue='';
 8677:                 foreach my $key (keys(%{$storehash})) {
 8678:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 8679:                 }
 8680:                 $namevalue=~s/\&$//;
 8681:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
 8682:                                   $namevalue,$uhome);
 8683:             }
 8684:         } else {
 8685:             $result = 'error: data to store was not a hash reference'; 
 8686:         }
 8687:     } else {
 8688:         $result= 'error: invalid requestkey'; 
 8689:     }
 8690:     return $result;
 8691: }
 8692: 
 8693: # ---------------------------------------------------------- Assign Custom Role
 8694: 
 8695: sub assigncustomrole {
 8696:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 8697:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 8698:                        $end,$start,$deleteflag,$selfenroll,$context);
 8699: }
 8700: 
 8701: # ----------------------------------------------------------------- Revoke Role
 8702: 
 8703: sub revokerole {
 8704:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 8705:     my $now=time;
 8706:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 8707: }
 8708: 
 8709: # ---------------------------------------------------------- Revoke Custom Role
 8710: 
 8711: sub revokecustomrole {
 8712:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 8713:     my $now=time;
 8714:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 8715:            $deleteflag,$selfenroll,$context);
 8716: }
 8717: 
 8718: # ------------------------------------------------------------ Disk usage
 8719: sub diskusage {
 8720:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 8721:     $directorypath =~ s/\/$//;
 8722:     my $listing=&reply('du2:'.&escape($directorypath).':'
 8723:                        .&escape($getpropath).':'.&escape($uname).':'
 8724:                        .&escape($udom),homeserver($uname,$udom));
 8725:     if ($listing eq 'unknown_cmd') {
 8726:         if ($getpropath) {
 8727:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 8728:         }
 8729:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 8730:     }
 8731:     return $listing;
 8732: }
 8733: 
 8734: sub is_locked {
 8735:     my ($file_name, $domain, $user, $which) = @_;
 8736:     my @check;
 8737:     my $is_locked;
 8738:     push (@check,$file_name);
 8739:     my %locked = &get('file_permissions',\@check,
 8740: 		      $env{'user.domain'},$env{'user.name'});
 8741:     my ($tmp)=keys(%locked);
 8742:     if ($tmp=~/^error:/) { undef(%locked); }
 8743:     
 8744:     if (ref($locked{$file_name}) eq 'ARRAY') {
 8745:         $is_locked = 'false';
 8746:         foreach my $entry (@{$locked{$file_name}}) {
 8747:            if (ref($entry) eq 'ARRAY') {
 8748:                $is_locked = 'true';
 8749:                if (ref($which) eq 'ARRAY') {
 8750:                    push(@{$which},$entry);
 8751:                } else {
 8752:                    last;
 8753:                }
 8754:            }
 8755:        }
 8756:     } else {
 8757:         $is_locked = 'false';
 8758:     }
 8759:     return $is_locked;
 8760: }
 8761: 
 8762: sub declutter_portfile {
 8763:     my ($file) = @_;
 8764:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 8765:     return $file;
 8766: }
 8767: 
 8768: # ------------------------------------------------------------- Mark as Read Only
 8769: 
 8770: sub mark_as_readonly {
 8771:     my ($domain,$user,$files,$what) = @_;
 8772:     my %current_permissions = &dump('file_permissions',$domain,$user);
 8773:     my ($tmp)=keys(%current_permissions);
 8774:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8775:     foreach my $file (@{$files}) {
 8776: 	$file = &declutter_portfile($file);
 8777:         push(@{$current_permissions{$file}},$what);
 8778:     }
 8779:     &put('file_permissions',\%current_permissions,$domain,$user);
 8780:     return;
 8781: }
 8782: 
 8783: # ------------------------------------------------------------Save Selected Files
 8784: 
 8785: sub save_selected_files {
 8786:     my ($user, $path, @files) = @_;
 8787:     my $filename = $user."savedfiles";
 8788:     my @other_files = &files_not_in_path($user, $path);
 8789:     open (OUT, '>'.$tmpdir.$filename);
 8790:     foreach my $file (@files) {
 8791:         print (OUT $env{'form.currentpath'}.$file."\n");
 8792:     }
 8793:     foreach my $file (@other_files) {
 8794:         print (OUT $file."\n");
 8795:     }
 8796:     close (OUT);
 8797:     return 'ok';
 8798: }
 8799: 
 8800: sub clear_selected_files {
 8801:     my ($user) = @_;
 8802:     my $filename = $user."savedfiles";
 8803:     open (OUT, '>'.LONCAPA::tempdir().$filename);
 8804:     print (OUT undef);
 8805:     close (OUT);
 8806:     return ("ok");    
 8807: }
 8808: 
 8809: sub files_in_path {
 8810:     my ($user, $path) = @_;
 8811:     my $filename = $user."savedfiles";
 8812:     my %return_files;
 8813:     open (IN, '<'.LONCAPA::tempdir().$filename);
 8814:     while (my $line_in = <IN>) {
 8815:         chomp ($line_in);
 8816:         my @paths_and_file = split (m!/!, $line_in);
 8817:         my $file_part = pop (@paths_and_file);
 8818:         my $path_part = join ('/', @paths_and_file);
 8819:         $path_part.='/';
 8820:         my $path_and_file = $path_part.$file_part;
 8821:         if ($path_part eq $path) {
 8822:             $return_files{$file_part}= 'selected';
 8823:         }
 8824:     }
 8825:     close (IN);
 8826:     return (\%return_files);
 8827: }
 8828: 
 8829: # called in portfolio select mode, to show files selected NOT in current directory
 8830: sub files_not_in_path {
 8831:     my ($user, $path) = @_;
 8832:     my $filename = $user."savedfiles";
 8833:     my @return_files;
 8834:     my $path_part;
 8835:     open(IN, '<'.LONCAPA::.$filename);
 8836:     while (my $line = <IN>) {
 8837:         #ok, I know it's clunky, but I want it to work
 8838:         my @paths_and_file = split(m|/|, $line);
 8839:         my $file_part = pop(@paths_and_file);
 8840:         chomp($file_part);
 8841:         my $path_part = join('/', @paths_and_file);
 8842:         $path_part .= '/';
 8843:         my $path_and_file = $path_part.$file_part;
 8844:         if ($path_part ne $path) {
 8845:             push(@return_files, ($path_and_file));
 8846:         }
 8847:     }
 8848:     close(OUT);
 8849:     return (@return_files);
 8850: }
 8851: 
 8852: #----------------------------------------------Get portfolio file permissions
 8853: 
 8854: sub get_portfile_permissions {
 8855:     my ($domain,$user) = @_;
 8856:     my %current_permissions = &dump('file_permissions',$domain,$user);
 8857:     my ($tmp)=keys(%current_permissions);
 8858:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8859:     return \%current_permissions;
 8860: }
 8861: 
 8862: #---------------------------------------------Get portfolio file access controls
 8863: 
 8864: sub get_access_controls {
 8865:     my ($current_permissions,$group,$file) = @_;
 8866:     my %access;
 8867:     my $real_file = $file;
 8868:     $file =~ s/\.meta$//;
 8869:     if (defined($file)) {
 8870:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 8871:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 8872:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 8873:             }
 8874:         }
 8875:     } else {
 8876:         foreach my $key (keys(%{$current_permissions})) {
 8877:             if ($key =~ /\0accesscontrol$/) {
 8878:                 if (defined($group)) {
 8879:                     if ($key !~ m-^\Q$group\E/-) {
 8880:                         next;
 8881:                     }
 8882:                 }
 8883:                 my ($fullpath) = split(/\0/,$key);
 8884:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 8885:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 8886:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 8887:                     }
 8888:                 }
 8889:             }
 8890:         }
 8891:     }
 8892:     return %access;
 8893: }
 8894: 
 8895: sub modify_access_controls {
 8896:     my ($file_name,$changes,$domain,$user)=@_;
 8897:     my ($outcome,$deloutcome);
 8898:     my %store_permissions;
 8899:     my %new_values;
 8900:     my %new_control;
 8901:     my %translation;
 8902:     my @deletions = ();
 8903:     my $now = time;
 8904:     if (exists($$changes{'activate'})) {
 8905:         if (ref($$changes{'activate'}) eq 'HASH') {
 8906:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 8907:             my $numnew = scalar(@newitems);
 8908:             for (my $i=0; $i<$numnew; $i++) {
 8909:                 my $newkey = $newitems[$i];
 8910:                 my $newid = &Apache::loncommon::get_cgi_id();
 8911:                 if ($newkey =~ /^\d+:/) { 
 8912:                     $newkey =~ s/^(\d+)/$newid/;
 8913:                     $translation{$1} = $newid;
 8914:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 8915:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 8916:                     $translation{$1} = $newid;
 8917:                 }
 8918:                 $new_values{$file_name."\0".$newkey} = 
 8919:                                           $$changes{'activate'}{$newitems[$i]};
 8920:                 $new_control{$newkey} = $now;
 8921:             }
 8922:         }
 8923:     }
 8924:     my %todelete;
 8925:     my %changed_items;
 8926:     foreach my $action ('delete','update') {
 8927:         if (exists($$changes{$action})) {
 8928:             if (ref($$changes{$action}) eq 'HASH') {
 8929:                 foreach my $key (keys(%{$$changes{$action}})) {
 8930:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 8931:                     if ($action eq 'delete') { 
 8932:                         $todelete{$itemnum} = 1;
 8933:                     } else {
 8934:                         $changed_items{$itemnum} = $key;
 8935:                     }
 8936:                 }
 8937:             }
 8938:         }
 8939:     }
 8940:     # get lock on access controls for file.
 8941:     my $lockhash = {
 8942:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 8943:                                                        ':'.$env{'user.domain'},
 8944:                    }; 
 8945:     my $tries = 0;
 8946:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 8947:    
 8948:     while (($gotlock ne 'ok') && $tries <3) {
 8949:         $tries ++;
 8950:         sleep 1;
 8951:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 8952:     }
 8953:     if ($gotlock eq 'ok') {
 8954:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 8955:         my ($tmp)=keys(%curr_permissions);
 8956:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 8957:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 8958:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 8959:             if (ref($curr_controls) eq 'HASH') {
 8960:                 foreach my $control_item (keys(%{$curr_controls})) {
 8961:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 8962:                     if (defined($todelete{$itemnum})) {
 8963:                         push(@deletions,$file_name."\0".$control_item);
 8964:                     } else {
 8965:                         if (defined($changed_items{$itemnum})) {
 8966:                             $new_control{$changed_items{$itemnum}} = $now;
 8967:                             push(@deletions,$file_name."\0".$control_item);
 8968:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 8969:                         } else {
 8970:                             $new_control{$control_item} = $$curr_controls{$control_item};
 8971:                         }
 8972:                     }
 8973:                 }
 8974:             }
 8975:         }
 8976:         my ($group);
 8977:         if (&is_course($domain,$user)) {
 8978:             ($group,my $file) = split(/\//,$file_name,2);
 8979:         }
 8980:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 8981:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 8982:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 8983:         #  remove lock
 8984:         my @del_lock = ($file_name."\0".'locked_access_records');
 8985:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 8986:         my $sqlresult =
 8987:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 8988:                                     $group);
 8989:     } else {
 8990:         $outcome = "error: could not obtain lockfile\n";  
 8991:     }
 8992:     return ($outcome,$deloutcome,\%new_values,\%translation);
 8993: }
 8994: 
 8995: sub make_public_indefinitely {
 8996:     my ($requrl) = @_;
 8997:     my $now = time;
 8998:     my $action = 'activate';
 8999:     my $aclnum = 0;
 9000:     if (&is_portfolio_url($requrl)) {
 9001:         my (undef,$udom,$unum,$file_name,$group) =
 9002:             &parse_portfolio_url($requrl);
 9003:         my $current_perms = &get_portfile_permissions($udom,$unum);
 9004:         my %access_controls = &get_access_controls($current_perms,
 9005:                                                    $group,$file_name);
 9006:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 9007:             my ($num,$scope,$end,$start) = 
 9008:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 9009:             if ($scope eq 'public') {
 9010:                 if ($start <= $now && $end == 0) {
 9011:                     $action = 'none';
 9012:                 } else {
 9013:                     $action = 'update';
 9014:                     $aclnum = $num;
 9015:                 }
 9016:                 last;
 9017:             }
 9018:         }
 9019:         if ($action eq 'none') {
 9020:              return 'ok';
 9021:         } else {
 9022:             my %changes;
 9023:             my $newend = 0;
 9024:             my $newstart = $now;
 9025:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 9026:             $changes{$action}{$newkey} = {
 9027:                 type => 'public',
 9028:                 time => {
 9029:                     start => $newstart,
 9030:                     end   => $newend,
 9031:                 },
 9032:             };
 9033:             my ($outcome,$deloutcome,$new_values,$translation) =
 9034:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 9035:             return $outcome;
 9036:         }
 9037:     } else {
 9038:         return 'invalid';
 9039:     }
 9040: }
 9041: 
 9042: #------------------------------------------------------Get Marked as Read Only
 9043: 
 9044: sub get_marked_as_readonly {
 9045:     my ($domain,$user,$what,$group) = @_;
 9046:     my $current_permissions = &get_portfile_permissions($domain,$user);
 9047:     my @readonly_files;
 9048:     my $cmp1=$what;
 9049:     if (ref($what)) { $cmp1=join('',@{$what}) };
 9050:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 9051:         if (defined($group)) {
 9052:             if ($file_name !~ m-^\Q$group\E/-) {
 9053:                 next;
 9054:             }
 9055:         }
 9056:         if (ref($value) eq "ARRAY"){
 9057:             foreach my $stored_what (@{$value}) {
 9058:                 my $cmp2=$stored_what;
 9059:                 if (ref($stored_what) eq 'ARRAY') {
 9060:                     $cmp2=join('',@{$stored_what});
 9061:                 }
 9062:                 if ($cmp1 eq $cmp2) {
 9063:                     push(@readonly_files, $file_name);
 9064:                     last;
 9065:                 } elsif (!defined($what)) {
 9066:                     push(@readonly_files, $file_name);
 9067:                     last;
 9068:                 }
 9069:             }
 9070:         }
 9071:     }
 9072:     return @readonly_files;
 9073: }
 9074: #-----------------------------------------------------------Get Marked as Read Only Hash
 9075: 
 9076: sub get_marked_as_readonly_hash {
 9077:     my ($current_permissions,$group,$what) = @_;
 9078:     my %readonly_files;
 9079:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 9080:         if (defined($group)) {
 9081:             if ($file_name !~ m-^\Q$group\E/-) {
 9082:                 next;
 9083:             }
 9084:         }
 9085:         if (ref($value) eq "ARRAY"){
 9086:             foreach my $stored_what (@{$value}) {
 9087:                 if (ref($stored_what) eq 'ARRAY') {
 9088:                     foreach my $lock_descriptor(@{$stored_what}) {
 9089:                         if ($lock_descriptor eq 'graded') {
 9090:                             $readonly_files{$file_name} = 'graded';
 9091:                         } elsif ($lock_descriptor eq 'handback') {
 9092:                             $readonly_files{$file_name} = 'handback';
 9093:                         } else {
 9094:                             if (!exists($readonly_files{$file_name})) {
 9095:                                 $readonly_files{$file_name} = 'locked';
 9096:                             }
 9097:                         }
 9098:                     }
 9099:                 } 
 9100:             }
 9101:         } 
 9102:     }
 9103:     return %readonly_files;
 9104: }
 9105: # ------------------------------------------------------------ Unmark as Read Only
 9106: 
 9107: sub unmark_as_readonly {
 9108:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 9109:     # for portfolio submissions, $what contains [$symb,$crsid] 
 9110:     my ($domain,$user,$what,$file_name,$group) = @_;
 9111:     $file_name = &declutter_portfile($file_name);
 9112:     my $symb_crs = $what;
 9113:     if (ref($what)) { $symb_crs=join('',@$what); }
 9114:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 9115:     my ($tmp)=keys(%current_permissions);
 9116:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9117:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 9118:     foreach my $file (@readonly_files) {
 9119: 	my $clean_file = &declutter_portfile($file);
 9120: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 9121: 	my $current_locks = $current_permissions{$file};
 9122:         my @new_locks;
 9123:         my @del_keys;
 9124:         if (ref($current_locks) eq "ARRAY"){
 9125:             foreach my $locker (@{$current_locks}) {
 9126:                 my $compare=$locker;
 9127:                 if (ref($locker) eq 'ARRAY') {
 9128:                     $compare=join('',@{$locker});
 9129:                     if ($compare ne $symb_crs) {
 9130:                         push(@new_locks, $locker);
 9131:                     }
 9132:                 }
 9133:             }
 9134:             if (scalar(@new_locks) > 0) {
 9135:                 $current_permissions{$file} = \@new_locks;
 9136:             } else {
 9137:                 push(@del_keys, $file);
 9138:                 &del('file_permissions',\@del_keys, $domain, $user);
 9139:                 delete($current_permissions{$file});
 9140:             }
 9141:         }
 9142:     }
 9143:     &put('file_permissions',\%current_permissions,$domain,$user);
 9144:     return;
 9145: }
 9146: 
 9147: # ------------------------------------------------------------ Directory lister
 9148: 
 9149: sub dirlist {
 9150:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 9151:     $uri=~s/^\///;
 9152:     $uri=~s/\/$//;
 9153:     my ($udom, $uname);
 9154:     if ($getuserdir) {
 9155:         $udom = $userdomain;
 9156:         $uname = $username;
 9157:     } else {
 9158:         (undef,$udom,$uname)=split(/\//,$uri);
 9159:         if(defined($userdomain)) {
 9160:             $udom = $userdomain;
 9161:         }
 9162:         if(defined($username)) {
 9163:             $uname = $username;
 9164:         }
 9165:     }
 9166:     my ($dirRoot,$listing,@listing_results);
 9167: 
 9168:     $dirRoot = $perlvar{'lonDocRoot'};
 9169:     if (defined($getpropath)) {
 9170:         $dirRoot = &propath($udom,$uname);
 9171:         $dirRoot =~ s/\/$//;
 9172:     } elsif (defined($getuserdir)) {
 9173:         my $subdir=$uname.'__';
 9174:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 9175:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 9176:                    ."/$udom/$subdir/$uname";
 9177:     } elsif (defined($alternateRoot)) {
 9178:         $dirRoot = $alternateRoot;
 9179:     }
 9180: 
 9181:     if($udom) {
 9182:         if($uname) {
 9183:             my $uhome = &homeserver($uname,$udom);
 9184:             if ($uhome eq 'no_host') {
 9185:                 return ([],'no_host');
 9186:             }
 9187:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 9188:                               .$getuserdir.':'.&escape($dirRoot)
 9189:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
 9190:             if ($listing eq 'unknown_cmd') {
 9191:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
 9192:             } else {
 9193:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 9194:             }
 9195:             if ($listing eq 'unknown_cmd') {
 9196:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
 9197:                 @listing_results = split(/:/,$listing);
 9198:             } else {
 9199:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 9200:             }
 9201:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
 9202:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
 9203:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 9204:                 return ([],$listing);
 9205:             } else {
 9206:                 return (\@listing_results);
 9207:             }
 9208:         } elsif(!$alternateRoot) {
 9209:             my (%allusers,%listerror);
 9210: 	    my %servers = &get_servers($udom,'library');
 9211:  	    foreach my $tryserver (keys(%servers)) {
 9212:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 9213:                                   &escape($udom),$tryserver);
 9214:                 if ($listing eq 'unknown_cmd') {
 9215: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 9216: 				      $udom, $tryserver);
 9217:                 } else {
 9218:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 9219:                 }
 9220: 		if ($listing eq 'unknown_cmd') {
 9221: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 9222: 				      $udom, $tryserver);
 9223: 		    @listing_results = split(/:/,$listing);
 9224: 		} else {
 9225: 		    @listing_results =
 9226: 			map { &unescape($_); } split(/:/,$listing);
 9227: 		}
 9228:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
 9229:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
 9230:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 9231:                     $listerror{$tryserver} = $listing;
 9232:                 } else {
 9233: 		    foreach my $line (@listing_results) {
 9234: 			my ($entry) = split(/&/,$line,2);
 9235: 			$allusers{$entry} = 1;
 9236: 		    }
 9237: 		}
 9238:             }
 9239:             my @alluserslist=();
 9240:             foreach my $user (sort(keys(%allusers))) {
 9241:                 push(@alluserslist,$user.'&user');
 9242:             }
 9243:             return (\@alluserslist);
 9244:         } else {
 9245:             return ([],'missing username');
 9246:         }
 9247:     } elsif(!defined($getpropath)) {
 9248:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
 9249:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
 9250:         return (\@all_domains);
 9251:     } else {
 9252:         return ([],'missing domain');
 9253:     }
 9254: }
 9255: 
 9256: # --------------------------------------------- GetFileTimestamp
 9257: # This function utilizes dirlist and returns the date stamp for
 9258: # when it was last modified.  It will also return an error of -1
 9259: # if an error occurs
 9260: 
 9261: sub GetFileTimestamp {
 9262:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 9263:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 9264:     $studentName   = &LONCAPA::clean_username($studentName);
 9265:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
 9266:                                     undef,$getuserdir);
 9267:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 9268:         return -1;
 9269:     }
 9270:     if (ref($fileref) eq 'ARRAY') {
 9271:         my @stats = split('&',$fileref->[0]);
 9272:         # @stats contains first the filename, then the stat output
 9273:         return $stats[10]; # so this is 10 instead of 9.
 9274:     } else {
 9275:         return -1;
 9276:     }
 9277: }
 9278: 
 9279: sub stat_file {
 9280:     my ($uri) = @_;
 9281:     $uri = &clutter_with_no_wrapper($uri);
 9282: 
 9283:     my ($udom,$uname,$file);
 9284:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 9285: 	($udom,$uname,$file) =
 9286: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 9287: 	$file = 'userfiles/'.$file;
 9288:     }
 9289:     if ($uri =~ m-^/res/-) {
 9290: 	($udom,$uname) = 
 9291: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 9292: 	$file = $uri;
 9293:     }
 9294: 
 9295:     if (!$udom || !$uname || !$file) {
 9296: 	# unable to handle the uri
 9297: 	return ();
 9298:     }
 9299:     my $getpropath;
 9300:     if ($file =~ /^userfiles\//) {
 9301:         $getpropath = 1;
 9302:     }
 9303:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
 9304:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 9305:         return ();
 9306:     } else {
 9307:         if (ref($listref) eq 'ARRAY') {
 9308:             my @stats = split('&',$listref->[0]);
 9309: 	    shift(@stats); #filename is first
 9310: 	    return @stats;
 9311:         }
 9312:     }
 9313:     return ();
 9314: }
 9315: 
 9316: # -------------------------------------------------------- Value of a Condition
 9317: 
 9318: # gets the value of a specific preevaluated condition
 9319: #    stored in the string  $env{user.state.<cid>}
 9320: # or looks up a condition reference in the bighash and if if hasn't
 9321: # already been evaluated recurses into docondval to get the value of
 9322: # the condition, then memoizing it to 
 9323: #   $env{user.state.<cid>.<condition>}
 9324: sub directcondval {
 9325:     my $number=shift;
 9326:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 9327: 	&Apache::lonuserstate::evalstate();
 9328:     }
 9329:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 9330: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 9331:     } elsif ($number =~ /^_/) {
 9332: 	my $sub_condition;
 9333: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9334: 		&GDBM_READER(),0640)) {
 9335: 	    $sub_condition=$bighash{'conditions'.$number};
 9336: 	    untie(%bighash);
 9337: 	}
 9338: 	my $value = &docondval($sub_condition);
 9339: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 9340: 	return $value;
 9341:     }
 9342:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 9343:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 9344:     } else {
 9345:        return 2;
 9346:     }
 9347: }
 9348: 
 9349: # get the collection of conditions for this resource
 9350: sub condval {
 9351:     my $condidx=shift;
 9352:     my $allpathcond='';
 9353:     foreach my $cond (split(/\|/,$condidx)) {
 9354: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 9355: 	    $allpathcond.=
 9356: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 9357: 	}
 9358:     }
 9359:     $allpathcond=~s/\|$//;
 9360:     return &docondval($allpathcond);
 9361: }
 9362: 
 9363: #evaluates an expression of conditions
 9364: sub docondval {
 9365:     my ($allpathcond) = @_;
 9366:     my $result=0;
 9367:     if ($env{'request.course.id'}
 9368: 	&& defined($allpathcond)) {
 9369: 	my $operand='|';
 9370: 	my @stack;
 9371: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 9372: 	    if ($chunk eq '(') {
 9373: 		push @stack,($operand,$result);
 9374: 	    } elsif ($chunk eq ')') {
 9375: 		my $before=pop @stack;
 9376: 		if (pop @stack eq '&') {
 9377: 		    $result=$result>$before?$before:$result;
 9378: 		} else {
 9379: 		    $result=$result>$before?$result:$before;
 9380: 		}
 9381: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 9382: 		$operand=$chunk;
 9383: 	    } else {
 9384: 		my $new=directcondval($chunk);
 9385: 		if ($operand eq '&') {
 9386: 		    $result=$result>$new?$new:$result;
 9387: 		} else {
 9388: 		    $result=$result>$new?$result:$new;
 9389: 		}
 9390: 	    }
 9391: 	}
 9392:     }
 9393:     return $result;
 9394: }
 9395: 
 9396: # ---------------------------------------------------- Devalidate courseresdata
 9397: 
 9398: sub devalidatecourseresdata {
 9399:     my ($coursenum,$coursedomain)=@_;
 9400:     my $hashid=$coursenum.':'.$coursedomain;
 9401:     &devalidate_cache_new('courseres',$hashid);
 9402: }
 9403: 
 9404: 
 9405: # --------------------------------------------------- Course Resourcedata Query
 9406: #
 9407: #  Parameters:
 9408: #      $coursenum    - Number of the course.
 9409: #      $coursedomain - Domain at which the course was created.
 9410: #  Returns:
 9411: #     A hash of the course parameters along (I think) with timestamps
 9412: #     and version info.
 9413: 
 9414: sub get_courseresdata {
 9415:     my ($coursenum,$coursedomain)=@_;
 9416:     my $coursehom=&homeserver($coursenum,$coursedomain);
 9417:     my $hashid=$coursenum.':'.$coursedomain;
 9418:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 9419:     my %dumpreply;
 9420:     unless (defined($cached)) {
 9421: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 9422: 	$result=\%dumpreply;
 9423: 	my ($tmp) = keys(%dumpreply);
 9424: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9425: 	    &do_cache_new('courseres',$hashid,$result,600);
 9426: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 9427: 	    return $tmp;
 9428: 	} elsif ($tmp =~ /^(error)/) {
 9429: 	    $result=undef;
 9430: 	    &do_cache_new('courseres',$hashid,$result,600);
 9431: 	}
 9432:     }
 9433:     return $result;
 9434: }
 9435: 
 9436: sub devalidateuserresdata {
 9437:     my ($uname,$udom)=@_;
 9438:     my $hashid="$udom:$uname";
 9439:     &devalidate_cache_new('userres',$hashid);
 9440: }
 9441: 
 9442: sub get_userresdata {
 9443:     my ($uname,$udom)=@_;
 9444:     #most student don\'t have any data set, check if there is some data
 9445:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 9446: 
 9447:     my $hashid="$udom:$uname";
 9448:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 9449:     if (!defined($cached)) {
 9450: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 9451: 	$result=\%resourcedata;
 9452: 	&do_cache_new('userres',$hashid,$result,600);
 9453:     }
 9454:     my ($tmp)=keys(%$result);
 9455:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 9456: 	return $result;
 9457:     }
 9458:     #error 2 occurs when the .db doesn't exist
 9459:     if ($tmp!~/error: 2 /) {
 9460: 	&logthis("<font color=\"blue\">WARNING:".
 9461: 		 " Trying to get resource data for ".
 9462: 		 $uname." at ".$udom.": ".
 9463: 		 $tmp."</font>");
 9464:     } elsif ($tmp=~/error: 2 /) {
 9465: 	#&EXT_cache_set($udom,$uname);
 9466: 	&do_cache_new('userres',$hashid,undef,600);
 9467: 	undef($tmp); # not really an error so don't send it back
 9468:     }
 9469:     return $tmp;
 9470: }
 9471: #----------------------------------------------- resdata - return resource data
 9472: #  Purpose:
 9473: #    Return resource data for either users or for a course.
 9474: #  Parameters:
 9475: #     $name      - Course/user name.
 9476: #     $domain    - Name of the domain the user/course is registered on.
 9477: #     $type      - Type of thing $name is (must be 'course' or 'user'
 9478: #     @which     - Array of names of resources desired.
 9479: #  Returns:
 9480: #     The value of the first reasource in @which that is found in the
 9481: #     resource hash.
 9482: #  Exceptional Conditions:
 9483: #     If the $type passed in is not valid (not the string 'course' or 
 9484: #     'user', an undefined  reference is returned.
 9485: #     If none of the resources are found, an undef is returned
 9486: sub resdata {
 9487:     my ($name,$domain,$type,@which)=@_;
 9488:     my $result;
 9489:     if ($type eq 'course') {
 9490: 	$result=&get_courseresdata($name,$domain);
 9491:     } elsif ($type eq 'user') {
 9492: 	$result=&get_userresdata($name,$domain);
 9493:     }
 9494:     if (!ref($result)) { return $result; }    
 9495:     foreach my $item (@which) {
 9496: 	if (defined($result->{$item->[0]})) {
 9497: 	    return [$result->{$item->[0]},$item->[1]];
 9498: 	}
 9499:     }
 9500:     return undef;
 9501: }
 9502: 
 9503: #
 9504: # EXT resource caching routines
 9505: #
 9506: 
 9507: sub clear_EXT_cache_status {
 9508:     &delenv('cache.EXT.');
 9509: }
 9510: 
 9511: sub EXT_cache_status {
 9512:     my ($target_domain,$target_user) = @_;
 9513:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 9514:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 9515:         # We know already the user has no data
 9516:         return 1;
 9517:     } else {
 9518:         return 0;
 9519:     }
 9520: }
 9521: 
 9522: sub EXT_cache_set {
 9523:     my ($target_domain,$target_user) = @_;
 9524:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 9525:     #&appenv({$cachename => time});
 9526: }
 9527: 
 9528: # --------------------------------------------------------- Value of a Variable
 9529: sub EXT {
 9530: 
 9531:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 9532:     unless ($varname) { return ''; }
 9533:     #get real user name/domain, courseid and symb
 9534:     my $courseid;
 9535:     my $publicuser;
 9536:     if ($symbparm) {
 9537: 	$symbparm=&get_symb_from_alias($symbparm);
 9538:     }
 9539:     if (!($uname && $udom)) {
 9540:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 9541:       if (!$symbparm) {	$symbparm=$cursymb; }
 9542:     } else {
 9543: 	$courseid=$env{'request.course.id'};
 9544:     }
 9545:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 9546:     my $rest;
 9547:     if (defined($therest[0])) {
 9548:        $rest=join('.',@therest);
 9549:     } else {
 9550:        $rest='';
 9551:     }
 9552: 
 9553:     my $qualifierrest=$qualifier;
 9554:     if ($rest) { $qualifierrest.='.'.$rest; }
 9555:     my $spacequalifierrest=$space;
 9556:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 9557:     if ($realm eq 'user') {
 9558: # --------------------------------------------------------------- user.resource
 9559: 	if ($space eq 'resource') {
 9560: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 9561: 		  || defined($Apache::lonhomework::parsing_a_task))
 9562: 		 &&
 9563: 		 ($symbparm eq &symbread()) ) {	
 9564: 		# if we are in the middle of processing the resource the
 9565: 		# get the value we are planning on committing
 9566:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 9567:                     return $Apache::lonhomework::results{$qualifierrest};
 9568:                 } else {
 9569:                     return $Apache::lonhomework::history{$qualifierrest};
 9570:                 }
 9571: 	    } else {
 9572: 		my %restored;
 9573: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 9574: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 9575: 		} else {
 9576: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 9577: 		}
 9578: 		return $restored{$qualifierrest};
 9579: 	    }
 9580: # ----------------------------------------------------------------- user.access
 9581:         } elsif ($space eq 'access') {
 9582: 	    # FIXME - not supporting calls for a specific user
 9583:             return &allowed($qualifier,$rest);
 9584: # ------------------------------------------ user.preferences, user.environment
 9585:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 9586: 	    if (($uname eq $env{'user.name'}) &&
 9587: 		($udom eq $env{'user.domain'})) {
 9588: 		return $env{join('.',('environment',$qualifierrest))};
 9589: 	    } else {
 9590: 		my %returnhash;
 9591: 		if (!$publicuser) {
 9592: 		    %returnhash=&userenvironment($udom,$uname,
 9593: 						 $qualifierrest);
 9594: 		}
 9595: 		return $returnhash{$qualifierrest};
 9596: 	    }
 9597: # ----------------------------------------------------------------- user.course
 9598:         } elsif ($space eq 'course') {
 9599: 	    # FIXME - not supporting calls for a specific user
 9600:             return $env{join('.',('request.course',$qualifier))};
 9601: # ------------------------------------------------------------------- user.role
 9602:         } elsif ($space eq 'role') {
 9603: 	    # FIXME - not supporting calls for a specific user
 9604:             my ($role,$where)=split(/\./,$env{'request.role'});
 9605:             if ($qualifier eq 'value') {
 9606: 		return $role;
 9607:             } elsif ($qualifier eq 'extent') {
 9608:                 return $where;
 9609:             }
 9610: # ----------------------------------------------------------------- user.domain
 9611:         } elsif ($space eq 'domain') {
 9612:             return $udom;
 9613: # ------------------------------------------------------------------- user.name
 9614:         } elsif ($space eq 'name') {
 9615:             return $uname;
 9616: # ---------------------------------------------------- Any other user namespace
 9617:         } else {
 9618: 	    my %reply;
 9619: 	    if (!$publicuser) {
 9620: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 9621: 	    }
 9622: 	    return $reply{$qualifierrest};
 9623:         }
 9624:     } elsif ($realm eq 'query') {
 9625: # ---------------------------------------------- pull stuff out of query string
 9626:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 9627: 						[$spacequalifierrest]);
 9628: 	return $env{'form.'.$spacequalifierrest}; 
 9629:    } elsif ($realm eq 'request') {
 9630: # ------------------------------------------------------------- request.browser
 9631:         if ($space eq 'browser') {
 9632:             return $env{'browser.'.$qualifier};
 9633: # ------------------------------------------------------------ request.filename
 9634:         } else {
 9635:             return $env{'request.'.$spacequalifierrest};
 9636:         }
 9637:     } elsif ($realm eq 'course') {
 9638: # ---------------------------------------------------------- course.description
 9639:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 9640:     } elsif ($realm eq 'resource') {
 9641: 
 9642: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 9643: 	    if (!$symbparm) { $symbparm=&symbread(); }
 9644: 	}
 9645: 
 9646: 	if ($space eq 'title') {
 9647: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 9648: 	    return &gettitle($symbparm);
 9649: 	}
 9650: 	
 9651: 	if ($space eq 'map') {
 9652: 	    my ($map) = &decode_symb($symbparm);
 9653: 	    return &symbread($map);
 9654: 	}
 9655: 	if ($space eq 'filename') {
 9656: 	    if ($symbparm) {
 9657: 		return &clutter((&decode_symb($symbparm))[2]);
 9658: 	    }
 9659: 	    return &hreflocation('',$env{'request.filename'});
 9660: 	}
 9661: 
 9662: 	my ($section, $group, @groups);
 9663: 	my ($courselevelm,$courselevel);
 9664: 	if ($symbparm && defined($courseid) && 
 9665: 	    $courseid eq $env{'request.course.id'}) {
 9666: 
 9667: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 9668: 
 9669: # ----------------------------------------------------- Cascading lookup scheme
 9670: 	    my $symbp=$symbparm;
 9671: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 9672: 
 9673: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 9674: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 9675: 
 9676: 	    if (($env{'user.name'} eq $uname) &&
 9677: 		($env{'user.domain'} eq $udom)) {
 9678: 		$section=$env{'request.course.sec'};
 9679:                 @groups = split(/:/,$env{'request.course.groups'});  
 9680:                 @groups=&sort_course_groups($courseid,@groups); 
 9681: 	    } else {
 9682: 		if (! defined($usection)) {
 9683: 		    $section=&getsection($udom,$uname,$courseid);
 9684: 		} else {
 9685: 		    $section = $usection;
 9686: 		}
 9687:                 @groups = &get_users_groups($udom,$uname,$courseid);
 9688: 	    }
 9689: 
 9690: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 9691: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 9692: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 9693: 
 9694: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 9695: 	    my $courselevelr=$courseid.'.'.$symbparm;
 9696: 	    $courselevelm=$courseid.'.'.$mapparm;
 9697: 
 9698: # ----------------------------------------------------------- first, check user
 9699: 
 9700: 	    my $userreply=&resdata($uname,$udom,'user',
 9701: 				       ([$courselevelr,'resource'],
 9702: 					[$courselevelm,'map'     ],
 9703: 					[$courselevel, 'course'  ]));
 9704: 	    if (defined($userreply)) { return &get_reply($userreply); }
 9705: 
 9706: # ------------------------------------------------ second, check some of course
 9707:             my $coursereply;
 9708:             if (@groups > 0) {
 9709:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 9710:                                        $mapparm,$spacequalifierrest);
 9711:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 9712:             }
 9713: 
 9714: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 9715: 				  $env{'course.'.$courseid.'.domain'},
 9716: 				  'course',
 9717: 				  ([$seclevelr,   'resource'],
 9718: 				   [$seclevelm,   'map'     ],
 9719: 				   [$seclevel,    'course'  ],
 9720: 				   [$courselevelr,'resource']));
 9721: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 9722: 
 9723: # ------------------------------------------------------ third, check map parms
 9724: 	    my %parmhash=();
 9725: 	    my $thisparm='';
 9726: 	    if (tie(%parmhash,'GDBM_File',
 9727: 		    $env{'request.course.fn'}.'_parms.db',
 9728: 		    &GDBM_READER(),0640)) {
 9729: 		$thisparm=$parmhash{$symbparm};
 9730: 		untie(%parmhash);
 9731: 	    }
 9732: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 9733: 	}
 9734: # ------------------------------------------ fourth, look in resource metadata
 9735: 
 9736: 	$spacequalifierrest=~s/\./\_/;
 9737: 	my $filename;
 9738: 	if (!$symbparm) { $symbparm=&symbread(); }
 9739: 	if ($symbparm) {
 9740: 	    $filename=(&decode_symb($symbparm))[2];
 9741: 	} else {
 9742: 	    $filename=$env{'request.filename'};
 9743: 	}
 9744: 	my $metadata=&metadata($filename,$spacequalifierrest);
 9745: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 9746: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 9747: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 9748: 
 9749: # ---------------------------------------------- fourth, look in rest of course
 9750: 	if ($symbparm && defined($courseid) && 
 9751: 	    $courseid eq $env{'request.course.id'}) {
 9752: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 9753: 				     $env{'course.'.$courseid.'.domain'},
 9754: 				     'course',
 9755: 				     ([$courselevelm,'map'   ],
 9756: 				      [$courselevel, 'course']));
 9757: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 9758: 	}
 9759: # ------------------------------------------------------------------ Cascade up
 9760: 	unless ($space eq '0') {
 9761: 	    my @parts=split(/_/,$space);
 9762: 	    my $id=pop(@parts);
 9763: 	    my $part=join('_',@parts);
 9764: 	    if ($part eq '') { $part='0'; }
 9765: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 9766: 				 $symbparm,$udom,$uname,$section,1);
 9767: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 9768: 	}
 9769: 	if ($recurse) { return undef; }
 9770: 	my $pack_def=&packages_tab_default($filename,$varname);
 9771: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 9772: # ---------------------------------------------------- Any other user namespace
 9773:     } elsif ($realm eq 'environment') {
 9774: # ----------------------------------------------------------------- environment
 9775: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 9776: 	    return $env{'environment.'.$spacequalifierrest};
 9777: 	} else {
 9778: 	    if ($uname eq 'anonymous' && $udom eq '') {
 9779: 		return '';
 9780: 	    }
 9781: 	    my %returnhash=&userenvironment($udom,$uname,
 9782: 					    $spacequalifierrest);
 9783: 	    return $returnhash{$spacequalifierrest};
 9784: 	}
 9785:     } elsif ($realm eq 'system') {
 9786: # ----------------------------------------------------------------- system.time
 9787: 	if ($space eq 'time') {
 9788: 	    return time;
 9789:         }
 9790:     } elsif ($realm eq 'server') {
 9791: # ----------------------------------------------------------------- system.time
 9792: 	if ($space eq 'name') {
 9793: 	    return $ENV{'SERVER_NAME'};
 9794:         }
 9795:     }
 9796:     return '';
 9797: }
 9798: 
 9799: sub get_reply {
 9800:     my ($reply_value) = @_;
 9801:     if (ref($reply_value) eq 'ARRAY') {
 9802:         if (wantarray) {
 9803: 	    return @$reply_value;
 9804:         }
 9805:         return $reply_value->[0];
 9806:     } else {
 9807:         return $reply_value;
 9808:     }
 9809: }
 9810: 
 9811: sub check_group_parms {
 9812:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 9813:     my @groupitems = ();
 9814:     my $resultitem;
 9815:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 9816:     foreach my $group (@{$groups}) {
 9817:         foreach my $level (@levels) {
 9818:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 9819:              push(@groupitems,[$item,$level->[1]]);
 9820:         }
 9821:     }
 9822:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 9823:                             $env{'course.'.$courseid.'.domain'},
 9824:                                      'course',@groupitems);
 9825:     return $coursereply;
 9826: }
 9827: 
 9828: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 9829:     my ($courseid,@groups) = @_;
 9830:     @groups = sort(@groups);
 9831:     return @groups;
 9832: }
 9833: 
 9834: sub packages_tab_default {
 9835:     my ($uri,$varname)=@_;
 9836:     my (undef,$part,$name)=split(/\./,$varname);
 9837: 
 9838:     my (@extension,@specifics,$do_default);
 9839:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 9840: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 9841: 	if ($pack_type eq 'default') {
 9842: 	    $do_default=1;
 9843: 	} elsif ($pack_type eq 'extension') {
 9844: 	    push(@extension,[$package,$pack_type,$pack_part]);
 9845: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 9846: 	    # only look at packages defaults for packages that this id is
 9847: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 9848: 	}
 9849:     }
 9850:     # first look for a package that matches the requested part id
 9851:     foreach my $package (@specifics) {
 9852: 	my (undef,$pack_type,$pack_part)=@{$package};
 9853: 	next if ($pack_part ne $part);
 9854: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9855: 	    return $packagetab{"$pack_type&$name&default"};
 9856: 	}
 9857:     }
 9858:     # look for any possible matching non extension_ package
 9859:     foreach my $package (@specifics) {
 9860: 	my (undef,$pack_type,$pack_part)=@{$package};
 9861: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9862: 	    return $packagetab{"$pack_type&$name&default"};
 9863: 	}
 9864: 	if ($pack_type eq 'part') { $pack_part='0'; }
 9865: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 9866: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 9867: 	}
 9868:     }
 9869:     # look for any posible extension_ match
 9870:     foreach my $package (@extension) {
 9871: 	my ($package,$pack_type)=@{$package};
 9872: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9873: 	    return $packagetab{"$pack_type&$name&default"};
 9874: 	}
 9875: 	if (defined($packagetab{$package."&$name&default"})) {
 9876: 	    return $packagetab{$package."&$name&default"};
 9877: 	}
 9878:     }
 9879:     # look for a global default setting
 9880:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 9881: 	return $packagetab{"default&$name&default"};
 9882:     }
 9883:     return undef;
 9884: }
 9885: 
 9886: sub add_prefix_and_part {
 9887:     my ($prefix,$part)=@_;
 9888:     my $keyroot;
 9889:     if (defined($prefix) && $prefix !~ /^__/) {
 9890: 	# prefix that has a part already
 9891: 	$keyroot=$prefix;
 9892:     } elsif (defined($prefix)) {
 9893: 	# prefix that is missing a part
 9894: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 9895:     } else {
 9896: 	# no prefix at all
 9897: 	if (defined($part)) { $keyroot='_'.$part; }
 9898:     }
 9899:     return $keyroot;
 9900: }
 9901: 
 9902: # ---------------------------------------------------------------- Get metadata
 9903: 
 9904: my %metaentry;
 9905: my %importedpartids;
 9906: sub metadata {
 9907:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 9908:     $uri=&declutter($uri);
 9909:     # if it is a non metadata possible uri return quickly
 9910:     if (($uri eq '') || 
 9911: 	(($uri =~ m|^/*adm/|) && 
 9912: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 9913:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
 9914: 	return undef;
 9915:     }
 9916:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
 9917: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
 9918: 	return undef;
 9919:     }
 9920:     my $filename=$uri;
 9921:     $uri=~s/\.meta$//;
 9922: #
 9923: # Is the metadata already cached?
 9924: # Look at timestamp of caching
 9925: # Everything is cached by the main uri, libraries are never directly cached
 9926: #
 9927:     if (!defined($liburi)) {
 9928: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 9929: 	if (defined($cached)) { return $result->{':'.$what}; }
 9930:     }
 9931:     {
 9932: # Imported parts would go here
 9933:         my %importedids=();
 9934:         my @origfileimportpartids=();
 9935:         my $importedparts=0;
 9936: #
 9937: # Is this a recursive call for a library?
 9938: #
 9939: #	if (! exists($metacache{$uri})) {
 9940: #	    $metacache{$uri}={};
 9941: #	}
 9942: 	my $cachetime = 60*60;
 9943:         if ($liburi) {
 9944: 	    $liburi=&declutter($liburi);
 9945:             $filename=$liburi;
 9946:         } else {
 9947: 	    &devalidate_cache_new('meta',$uri);
 9948: 	    undef(%metaentry);
 9949: 	}
 9950:         my %metathesekeys=();
 9951:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 9952: 	my $metastring;
 9953: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
 9954: 	    my $which = &hreflocation('','/'.($liburi || $uri));
 9955: 	    $metastring = 
 9956: 		&Apache::lonnet::ssi_body($which,
 9957: 					  ('grade_target' => 'meta'));
 9958: 	    $cachetime = 1; # only want this cached in the child not long term
 9959: 	} elsif (($uri !~ m -^(editupload)/-) && 
 9960:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
 9961: 	    my $file=&filelocation('',&clutter($filename));
 9962: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 9963: 	    $metastring=&getfile($file);
 9964: 	}
 9965:         my $parser=HTML::LCParser->new(\$metastring);
 9966:         my $token;
 9967:         undef %metathesekeys;
 9968:         while ($token=$parser->get_token) {
 9969: 	    if ($token->[0] eq 'S') {
 9970: 		if (defined($token->[2]->{'package'})) {
 9971: #
 9972: # This is a package - get package info
 9973: #
 9974: 		    my $package=$token->[2]->{'package'};
 9975: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9976: 		    if (defined($token->[2]->{'id'})) { 
 9977: 			$keyroot.='_'.$token->[2]->{'id'}; 
 9978: 		    }
 9979: 		    if ($metaentry{':packages'}) {
 9980: 			$metaentry{':packages'}.=','.$package.$keyroot;
 9981: 		    } else {
 9982: 			$metaentry{':packages'}=$package.$keyroot;
 9983: 		    }
 9984: 		    foreach my $pack_entry (keys(%packagetab)) {
 9985: 			my $part=$keyroot;
 9986: 			$part=~s/^\_//;
 9987: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 9988: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 9989: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 9990: 			    # ignore package.tab specified default values
 9991:                             # here &package_tab_default() will fetch those
 9992: 			    if ($subp eq 'default') { next; }
 9993: 			    my $value=$packagetab{$pack_entry};
 9994: 			    my $unikey;
 9995: 			    if ($pack =~ /_0$/) {
 9996: 				$unikey='parameter_0_'.$name;
 9997: 				$part=0;
 9998: 			    } else {
 9999: 				$unikey='parameter'.$keyroot.'_'.$name;
10000: 			    }
10001: 			    if ($subp eq 'display') {
10002: 				$value.=' [Part: '.$part.']';
10003: 			    }
10004: 			    $metaentry{':'.$unikey.'.part'}=$part;
10005: 			    $metathesekeys{$unikey}=1;
10006: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10007: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
10008: 			    }
10009: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
10010: 				$metaentry{':'.$unikey}=
10011: 				    $metaentry{':'.$unikey.'.default'};
10012: 			    }
10013: 			}
10014: 		    }
10015: 		} else {
10016: #
10017: # This is not a package - some other kind of start tag
10018: #
10019: 		    my $entry=$token->[1];
10020: 		    my $unikey='';
10021: 
10022: 		    if ($entry eq 'import') {
10023: #
10024: # Importing a library here
10025: #
10026:                         my $location=$parser->get_text('/import');
10027:                         my $dir=$filename;
10028:                         $dir=~s|[^/]*$||;
10029:                         $location=&filelocation($dir,$location);
10030:                        
10031:                         my $importmode=$token->[2]->{'importmode'};
10032:                         if ($importmode eq 'problem') {
10033: # Import as problem/response
10034:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10035:                         } elsif ($importmode eq 'part') {
10036: # Import as part(s)
10037:                            $importedparts=1;
10038: # We need to get the original file and the imported file to get the part order correct
10039: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10040: # Load and inspect original file
10041:                            if ($#origfileimportpartids<0) {
10042:                               undef(%importedpartids);
10043:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10044:                               my $origfile=&getfile($origfilelocation);
10045:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10046:                            }
10047: 
10048: # Load and inspect imported file
10049:                            my $impfile=&getfile($location);
10050:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10051:                            if ($#impfilepartids>=0) {
10052: # This problem had parts
10053:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
10054:                            } else {
10055: # Importing by turning a single problem into a problem part
10056: # It gets the import-tags ID as part-ID
10057:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
10058:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
10059:                            }
10060:                         } else {
10061: # Normal import
10062:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10063:                            if (defined($token->[2]->{'id'})) {
10064:                               $unikey.='_'.$token->[2]->{'id'};
10065:                            }
10066:                         }
10067: 
10068: 			if ($depthcount<20) {
10069: 			    my $metadata = 
10070: 				&metadata($uri,'keys', $location,$unikey,
10071: 					  $depthcount+1);
10072: 			    foreach my $meta (split(',',$metadata)) {
10073: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
10074: 				$metathesekeys{$meta}=1;
10075: 			    }
10076: 			
10077:                         }
10078: 		    } else {
10079: #
10080: # Not importing, some other kind of non-package, non-library start tag
10081: # 
10082:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10083:                         if (defined($token->[2]->{'id'})) {
10084:                             $unikey.='_'.$token->[2]->{'id'};
10085:                         }
10086: 			if (defined($token->[2]->{'name'})) { 
10087: 			    $unikey.='_'.$token->[2]->{'name'}; 
10088: 			}
10089: 			$metathesekeys{$unikey}=1;
10090: 			foreach my $param (@{$token->[3]}) {
10091: 			    $metaentry{':'.$unikey.'.'.$param} =
10092: 				$token->[2]->{$param};
10093: 			}
10094: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
10095: 			my $default=$metaentry{':'.$unikey.'.default'};
10096: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10097: 		 # only ws inside the tag, and not in default, so use default
10098: 		 # as value
10099: 			    $metaentry{':'.$unikey}=$default;
10100: 			} elsif ( $internaltext =~ /\S/ ) {
10101: 		  # something interesting inside the tag
10102: 			    $metaentry{':'.$unikey}=$internaltext;
10103: 			} else {
10104: 		  # no interesting values, don't set a default
10105: 			}
10106: # end of not-a-package not-a-library import
10107: 		    }
10108: # end of not-a-package start tag
10109: 		}
10110: # the next is the end of "start tag"
10111: 	    }
10112: 	}
10113: 	my ($extension) = ($uri =~ /\.(\w+)$/);
10114: 	$extension = lc($extension);
10115: 	if ($extension eq 'htm') { $extension='html'; }
10116: 
10117: 	foreach my $key (keys(%packagetab)) {
10118: 	    #no specific packages #how's our extension
10119: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
10120: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
10121: 					 \%metathesekeys);
10122: 	}
10123: 
10124: 	if (!exists($metaentry{':packages'})
10125: 	    || $packagetab{"import_defaults&extension_$extension"}) {
10126: 	    foreach my $key (keys(%packagetab)) {
10127: 		#no specific packages well let's get default then
10128: 		if ($key!~/^default&/) { next; }
10129: 		&metadata_create_package_def($uri,$key,'default',
10130: 					     \%metathesekeys);
10131: 	    }
10132: 	}
10133: # are there custom rights to evaluate
10134: 	if ($metaentry{':copyright'} eq 'custom') {
10135: 
10136:     #
10137:     # Importing a rights file here
10138:     #
10139: 	    unless ($depthcount) {
10140: 		my $location=$metaentry{':customdistributionfile'};
10141: 		my $dir=$filename;
10142: 		$dir=~s|[^/]*$||;
10143: 		$location=&filelocation($dir,$location);
10144: 		my $rights_metadata =
10145: 		    &metadata($uri,'keys',$location,'_rights',
10146: 			      $depthcount+1);
10147: 		foreach my $rights (split(',',$rights_metadata)) {
10148: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10149: 		    $metathesekeys{$rights}=1;
10150: 		}
10151: 	    }
10152: 	}
10153: 	# uniqifiy package listing
10154: 	my %seen;
10155: 	my @uniq_packages =
10156: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10157: 	$metaentry{':packages'} = join(',',@uniq_packages);
10158: 
10159:         if ($importedparts) {
10160: # We had imported parts and need to rebuild partorder
10161:            $metaentry{':partorder'}='';
10162:            $metathesekeys{'partorder'}=1;
10163:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10164:                if ($origfileimportpartids[$index] eq 'part') {
10165: # original part, part of the problem
10166:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10167:                } else {
10168: # we have imported parts at this position
10169:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10170:                }
10171:            }
10172:            $metaentry{':partorder'}=~s/^\,//;
10173:         }
10174: 
10175: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
10176: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
10177: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
10178: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
10179: # this is the end of "was not already recently cached
10180:     }
10181:     return $metaentry{':'.$what};
10182: }
10183: 
10184: sub metadata_create_package_def {
10185:     my ($uri,$key,$package,$metathesekeys)=@_;
10186:     my ($pack,$name,$subp)=split(/\&/,$key);
10187:     if ($subp eq 'default') { next; }
10188:     
10189:     if (defined($metaentry{':packages'})) {
10190: 	$metaentry{':packages'}.=','.$package;
10191:     } else {
10192: 	$metaentry{':packages'}=$package;
10193:     }
10194:     my $value=$packagetab{$key};
10195:     my $unikey;
10196:     $unikey='parameter_0_'.$name;
10197:     $metaentry{':'.$unikey.'.part'}=0;
10198:     $$metathesekeys{$unikey}=1;
10199:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10200: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
10201:     }
10202:     if (defined($metaentry{':'.$unikey.'.default'})) {
10203: 	$metaentry{':'.$unikey}=
10204: 	    $metaentry{':'.$unikey.'.default'};
10205:     }
10206: }
10207: 
10208: sub metadata_generate_part0 {
10209:     my ($metadata,$metacache,$uri) = @_;
10210:     my %allnames;
10211:     foreach my $metakey (keys(%$metadata)) {
10212: 	if ($metakey=~/^parameter\_(.*)/) {
10213: 	  my $part=$$metacache{':'.$metakey.'.part'};
10214: 	  my $name=$$metacache{':'.$metakey.'.name'};
10215: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
10216: 	    $allnames{$name}=$part;
10217: 	  }
10218: 	}
10219:     }
10220:     foreach my $name (keys(%allnames)) {
10221:       $$metadata{"parameter_0_$name"}=1;
10222:       my $key=":parameter_0_$name";
10223:       $$metacache{"$key.part"}='0';
10224:       $$metacache{"$key.name"}=$name;
10225:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
10226: 					   $allnames{$name}.'_'.$name.
10227: 					   '.type'};
10228:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
10229: 			     '.display'};
10230:       my $expr='[Part: '.$allnames{$name}.']';
10231:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
10232:       $$metacache{"$key.display"}=$olddis;
10233:     }
10234: }
10235: 
10236: # ------------------------------------------------------ Devalidate title cache
10237: 
10238: sub devalidate_title_cache {
10239:     my ($url)=@_;
10240:     if (!$env{'request.course.id'}) { return; }
10241:     my $symb=&symbread($url);
10242:     if (!$symb) { return; }
10243:     my $key=$env{'request.course.id'}."\0".$symb;
10244:     &devalidate_cache_new('title',$key);
10245: }
10246: 
10247: # ------------------------------------------------- Get the title of a course
10248: 
10249: sub current_course_title {
10250:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10251: }
10252: # ------------------------------------------------- Get the title of a resource
10253: 
10254: sub gettitle {
10255:     my $urlsymb=shift;
10256:     my $symb=&symbread($urlsymb);
10257:     if ($symb) {
10258: 	my $key=$env{'request.course.id'}."\0".$symb;
10259: 	my ($result,$cached)=&is_cached_new('title',$key);
10260: 	if (defined($cached)) { 
10261: 	    return $result;
10262: 	}
10263: 	my ($map,$resid,$url)=&decode_symb($symb);
10264: 	my $title='';
10265: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10266: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10267: 	} else {
10268: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10269: 		    &GDBM_READER(),0640)) {
10270: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
10271: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
10272: 		untie(%bighash);
10273: 	    }
10274: 	}
10275: 	$title=~s/\&colon\;/\:/gs;
10276: 	if ($title) {
10277: # Remember both $symb and $title for dynamic metadata
10278:             $accesshash{$symb.'___crstitle'}=$title;
10279:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
10280: # Cache this title and then return it
10281: 	    return &do_cache_new('title',$key,$title,600);
10282: 	}
10283: 	$urlsymb=$url;
10284:     }
10285:     my $title=&metadata($urlsymb,'title');
10286:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
10287:     return $title;
10288: }
10289: 
10290: sub getdocspath {
10291:     my ($symb) = @_;
10292:     my $path;
10293:     if ($symb) {
10294:         my ($mapurl,$id,$resurl) = &decode_symb($symb);
10295:         if ($resurl=~/\.(sequence|page)$/) {
10296:             $mapurl=$resurl;
10297:         } elsif ($resurl eq 'adm/navmaps') {
10298:             $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
10299:         }
10300:         my $mapresobj;
10301:         my $navmap = Apache::lonnavmaps::navmap->new();
10302:         if (ref($navmap)) {
10303:             $mapresobj = $navmap->getResourceByUrl($mapurl);
10304:         }
10305:         $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
10306:         my $type=$2;
10307:         if (ref($mapresobj)) {
10308:             my $pcslist = $mapresobj->map_hierarchy();
10309:             if ($pcslist ne '') {
10310:                 foreach my $pc (split(/,/,$pcslist)) {
10311:                     next if ($pc <= 1);
10312:                     my $res = $navmap->getByMapPc($pc);
10313:                     if (ref($res)) {
10314:                         my $thisurl = $res->src();
10315:                         $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
10316:                         my $thistitle = $res->title();
10317:                         $path .= '&'.
10318:                                  &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
10319:                                  &Apache::lonhtmlcommon::entity_encode($thistitle).
10320:                                  ':'.$res->randompick().
10321:                                  ':'.$res->randomout().
10322:                                  ':'.$res->encrypted().
10323:                                  ':'.$res->randomorder();
10324:                     }
10325:                 }
10326:             }
10327:             $path =~ s/^\&//;
10328:             my $maptitle = $mapresobj->title();
10329:             if ($mapurl eq 'default') {
10330:                 $maptitle = 'Main Course Documents';
10331:             }
10332:             $path .= ($path ne '')? '&' : ''.
10333:                     &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
10334:                     &Apache::lonhtmlcommon::entity_encode($maptitle).
10335:                     ':'.$mapresobj->randompick().
10336:                     ':'.$mapresobj->randomout().
10337:                     ':'.$mapresobj->encrypted().
10338:                     ':'.$mapresobj->randomorder();
10339:         } else {
10340:             my $maptitle = &gettitle($mapurl);
10341:             if ($mapurl eq 'default') {
10342:                 $maptitle = 'Main Course Documents';
10343:             }
10344:             $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
10345:                     &Apache::lonhtmlcommon::entity_encode($maptitle).'::::';
10346:         }
10347:         unless ($mapurl eq 'default') {
10348:             $path = 'default&'.
10349:                     &Apache::lonhtmlcommon::entity_encode('Main Course Documents').
10350:                     '::::&'.$path;
10351:         }
10352:     }
10353:     return $path;
10354: }
10355: 
10356: sub get_slot {
10357:     my ($which,$cnum,$cdom)=@_;
10358:     if (!$cnum || !$cdom) {
10359: 	(undef,my $courseid)=&whichuser();
10360: 	$cdom=$env{'course.'.$courseid.'.domain'};
10361: 	$cnum=$env{'course.'.$courseid.'.num'};
10362:     }
10363:     my $key=join("\0",'slots',$cdom,$cnum,$which);
10364:     my %slotinfo;
10365:     if (exists($remembered{$key})) {
10366: 	$slotinfo{$which} = $remembered{$key};
10367:     } else {
10368: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
10369: 	&Apache::lonhomework::showhash(%slotinfo);
10370: 	my ($tmp)=keys(%slotinfo);
10371: 	if ($tmp=~/^error:/) { return (); }
10372: 	$remembered{$key} = $slotinfo{$which};
10373:     }
10374:     if (ref($slotinfo{$which}) eq 'HASH') {
10375: 	return %{$slotinfo{$which}};
10376:     }
10377:     return $slotinfo{$which};
10378: }
10379: 
10380: sub get_reservable_slots {
10381:     my ($cnum,$cdom,$uname,$udom) = @_;
10382:     my $now = time;
10383:     my $reservable_info;
10384:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10385:     if (exists($remembered{$key})) {
10386:         $reservable_info = $remembered{$key};
10387:     } else {
10388:         my %resv;
10389:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10390:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10391:         $reservable_info = \%resv;
10392:         $remembered{$key} = $reservable_info;
10393:     }
10394:     return $reservable_info;
10395: }
10396: 
10397: sub get_course_slots {
10398:     my ($cnum,$cdom) = @_;
10399:     my $hashid=$cnum.':'.$cdom;
10400:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10401:     if (defined($cached)) {
10402:         if (ref($result) eq 'HASH') {
10403:             return %{$result};
10404:         }
10405:     } else {
10406:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10407:         my ($tmp) = keys(%slots);
10408:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10409:             &Apache::lonnet::do_cache_new('allslots',$hashid,\%slots,600);
10410:             return %slots;
10411:         }
10412:     }
10413:     return;
10414: }
10415: 
10416: sub devalidate_slots_cache {
10417:     my ($cnum,$cdom)=@_;
10418:     my $hashid=$cnum.':'.$cdom;
10419:     &devalidate_cache_new('allslots',$hashid);
10420: }
10421: 
10422: sub get_coursechange {
10423:     my ($cdom,$cnum) = @_;
10424:     if ($cdom eq '' || $cnum eq '') {
10425:         return unless ($env{'request.course.id'});
10426:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10427:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10428:     }
10429:     my $hashid=$cdom.'_'.$cnum;
10430:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
10431:     if ((defined($cached)) && ($change ne '')) {
10432:         return $change;
10433:     } else {
10434:         my %crshash;
10435:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10436:         if ($crshash{'internal.contentchange'} eq '') {
10437:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
10438:             if ($change eq '') {
10439:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
10440:                 $change = $crshash{'internal.created'};
10441:             }
10442:         } else {
10443:             $change = $crshash{'internal.contentchange'};
10444:         }
10445:         my $cachetime = 600;
10446:         &do_cache_new('crschange',$hashid,$change,$cachetime);
10447:     }
10448:     return $change;
10449: }
10450: 
10451: sub devalidate_coursechange_cache {
10452:     my ($cnum,$cdom)=@_;
10453:     my $hashid=$cnum.':'.$cdom;
10454:     &devalidate_cache_new('crschange',$hashid);
10455: }
10456: 
10457: # ------------------------------------------------- Update symbolic store links
10458: 
10459: sub symblist {
10460:     my ($mapname,%newhash)=@_;
10461:     $mapname=&deversion(&declutter($mapname));
10462:     my %hash;
10463:     if (($env{'request.course.fn'}) && (%newhash)) {
10464:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10465:                       &GDBM_WRCREAT(),0640)) {
10466: 	    foreach my $url (keys(%newhash)) {
10467: 		next if ($url eq 'last_known'
10468: 			 && $env{'form.no_update_last_known'});
10469: 		$hash{declutter($url)}=&encode_symb($mapname,
10470: 						    $newhash{$url}->[1],
10471: 						    $newhash{$url}->[0]);
10472:             }
10473:             if (untie(%hash)) {
10474: 		return 'ok';
10475:             }
10476:         }
10477:     }
10478:     return 'error';
10479: }
10480: 
10481: # --------------------------------------------------------------- Verify a symb
10482: 
10483: sub symbverify {
10484:     my ($symb,$thisurl,$encstate)=@_;
10485:     my $thisfn=$thisurl;
10486:     $thisfn=&declutter($thisfn);
10487: # direct jump to resource in page or to a sequence - will construct own symbs
10488:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10489: # check URL part
10490:     my ($map,$resid,$url)=&decode_symb($symb);
10491: 
10492:     unless ($url eq $thisfn) { return 0; }
10493: 
10494:     $symb=&symbclean($symb);
10495:     $thisurl=&deversion($thisurl);
10496:     $thisfn=&deversion($thisfn);
10497: 
10498:     my %bighash;
10499:     my $okay=0;
10500: 
10501:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10502:                             &GDBM_READER(),0640)) {
10503:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10504:             $thisurl =~ s/\?.+$//;
10505:         }
10506:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
10507:         unless ($ids) {
10508:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
10509:             $ids=$bighash{$idkey};
10510:         }
10511:         if ($ids) {
10512: # ------------------------------------------------------------------- Has ID(s)
10513: 	    foreach my $id (split(/\,/,$ids)) {
10514: 	       my ($mapid,$resid)=split(/\./,$id);
10515:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
10516:                    $symb =~ s/\?.+$//;
10517:                }
10518:                if (
10519:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
10520:    eq $symb) {
10521:                    if (ref($encstate)) {
10522:                        $$encstate = $bighash{'encrypted_'.$id};
10523:                    }
10524: 		   if (($env{'request.role.adv'}) ||
10525: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
10526:                        ($thisurl eq '/adm/navmaps')) {
10527: 		       $okay=1;
10528: 		   }
10529: 	       }
10530: 	   }
10531:         }
10532: 	untie(%bighash);
10533:     }
10534:     return $okay;
10535: }
10536: 
10537: # --------------------------------------------------------------- Clean-up symb
10538: 
10539: sub symbclean {
10540:     my $symb=shift;
10541:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10542: # remove version from map
10543:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
10544: 
10545: # remove version from URL
10546:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
10547: 
10548: # remove wrapper
10549: 
10550:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
10551:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
10552:     return $symb;
10553: }
10554: 
10555: # ---------------------------------------------- Split symb to find map and url
10556: 
10557: sub encode_symb {
10558:     my ($map,$resid,$url)=@_;
10559:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
10560: }
10561: 
10562: sub decode_symb {
10563:     my $symb=shift;
10564:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10565:     my ($map,$resid,$url)=split(/___/,$symb);
10566:     return (&fixversion($map),$resid,&fixversion($url));
10567: }
10568: 
10569: sub fixversion {
10570:     my $fn=shift;
10571:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
10572:     my %bighash;
10573:     my $uri=&clutter($fn);
10574:     my $key=$env{'request.course.id'}.'_'.$uri;
10575: # is this cached?
10576:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
10577:     if (defined($cached)) { return $result; }
10578: # unfortunately not cached, or expired
10579:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10580: 	    &GDBM_READER(),0640)) {
10581:  	if ($bighash{'version_'.$uri}) {
10582:  	    my $version=$bighash{'version_'.$uri};
10583:  	    unless (($version eq 'mostrecent') || 
10584: 		    ($version==&getversion($uri))) {
10585:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
10586:  	    }
10587:  	}
10588:  	untie %bighash;
10589:     }
10590:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
10591: }
10592: 
10593: sub deversion {
10594:     my $url=shift;
10595:     $url=~s/\.\d+\.(\w+)$/\.$1/;
10596:     return $url;
10597: }
10598: 
10599: # ------------------------------------------------------ Return symb list entry
10600: 
10601: sub symbread {
10602:     my ($thisfn,$donotrecurse)=@_;
10603:     my $cache_str='request.symbread.cached.'.$thisfn;
10604:     if (defined($env{$cache_str})) {
10605:         if (($thisfn) || ($env{$cache_str} ne '')) {
10606:             return $env{$cache_str};
10607:         }
10608:     }
10609: # no filename provided? try from environment
10610:     unless ($thisfn) {
10611:         if ($env{'request.symb'}) {
10612: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
10613: 	}
10614: 	$thisfn=$env{'request.filename'};
10615:     }
10616:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
10617: # is that filename actually a symb? Verify, clean, and return
10618:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
10619: 	if (&symbverify($thisfn,$1)) {
10620: 	    return $env{$cache_str}=&symbclean($thisfn);
10621: 	}
10622:     }
10623:     $thisfn=declutter($thisfn);
10624:     my %hash;
10625:     my %bighash;
10626:     my $syval='';
10627:     if (($env{'request.course.fn'}) && ($thisfn)) {
10628:         my $targetfn = $thisfn;
10629:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
10630:             $targetfn = 'adm/wrapper/'.$thisfn;
10631:         }
10632: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
10633: 	    $targetfn=$1;
10634: 	}
10635:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10636:                       &GDBM_READER(),0640)) {
10637: 	    $syval=$hash{$targetfn};
10638:             untie(%hash);
10639:         }
10640: # ---------------------------------------------------------- There was an entry
10641:         if ($syval) {
10642: 	    #unless ($syval=~/\_\d+$/) {
10643: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
10644: 		    #&appenv({'request.ambiguous' => $thisfn});
10645: 		    #return $env{$cache_str}='';
10646: 		#}    
10647: 		#$syval.=$1;
10648: 	    #}
10649:         } else {
10650: # ------------------------------------------------------- Was not in symb table
10651:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10652:                             &GDBM_READER(),0640)) {
10653: # ---------------------------------------------- Get ID(s) for current resource
10654:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
10655:               unless ($ids) { 
10656:                  $ids=$bighash{'ids_/'.$thisfn};
10657:               }
10658:               unless ($ids) {
10659: # alias?
10660: 		  $ids=$bighash{'mapalias_'.$thisfn};
10661:               }
10662:               if ($ids) {
10663: # ------------------------------------------------------------------- Has ID(s)
10664:                  my @possibilities=split(/\,/,$ids);
10665:                  if ($#possibilities==0) {
10666: # ----------------------------------------------- There is only one possibility
10667: 		     my ($mapid,$resid)=split(/\./,$ids);
10668: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
10669: 						    $resid,$thisfn);
10670:                  } elsif (!$donotrecurse) {
10671: # ------------------------------------------ There is more than one possibility
10672:                      my $realpossible=0;
10673:                      foreach my $id (@possibilities) {
10674: 			 my $file=$bighash{'src_'.$id};
10675:                          if (&allowed('bre',$file)) {
10676:          		    my ($mapid,$resid)=split(/\./,$id);
10677:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
10678: 				$realpossible++;
10679:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
10680: 						    $resid,$thisfn);
10681:                             }
10682: 			 }
10683:                      }
10684: 		     if ($realpossible!=1) { $syval=''; }
10685:                  } else {
10686:                      $syval='';
10687:                  }
10688: 	      }
10689:               untie(%bighash)
10690:            }
10691:         }
10692:         if ($syval) {
10693: 	    return $env{$cache_str}=$syval;
10694:         }
10695:     }
10696:     &appenv({'request.ambiguous' => $thisfn});
10697:     return $env{$cache_str}='';
10698: }
10699: 
10700: # ---------------------------------------------------------- Return random seed
10701: 
10702: sub numval {
10703:     my $txt=shift;
10704:     $txt=~tr/A-J/0-9/;
10705:     $txt=~tr/a-j/0-9/;
10706:     $txt=~tr/K-T/0-9/;
10707:     $txt=~tr/k-t/0-9/;
10708:     $txt=~tr/U-Z/0-5/;
10709:     $txt=~tr/u-z/0-5/;
10710:     $txt=~s/\D//g;
10711:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
10712:     return int($txt);
10713: }
10714: 
10715: sub numval2 {
10716:     my $txt=shift;
10717:     $txt=~tr/A-J/0-9/;
10718:     $txt=~tr/a-j/0-9/;
10719:     $txt=~tr/K-T/0-9/;
10720:     $txt=~tr/k-t/0-9/;
10721:     $txt=~tr/U-Z/0-5/;
10722:     $txt=~tr/u-z/0-5/;
10723:     $txt=~s/\D//g;
10724:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10725:     my $total;
10726:     foreach my $val (@txts) { $total+=$val; }
10727:     if ($_64bit) { if ($total > 2**32) { return -1; } }
10728:     return int($total);
10729: }
10730: 
10731: sub numval3 {
10732:     use integer;
10733:     my $txt=shift;
10734:     $txt=~tr/A-J/0-9/;
10735:     $txt=~tr/a-j/0-9/;
10736:     $txt=~tr/K-T/0-9/;
10737:     $txt=~tr/k-t/0-9/;
10738:     $txt=~tr/U-Z/0-5/;
10739:     $txt=~tr/u-z/0-5/;
10740:     $txt=~s/\D//g;
10741:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10742:     my $total;
10743:     foreach my $val (@txts) { $total+=$val; }
10744:     if ($_64bit) { $total=(($total<<32)>>32); }
10745:     return $total;
10746: }
10747: 
10748: sub digest {
10749:     my ($data)=@_;
10750:     my $digest=&Digest::MD5::md5($data);
10751:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
10752:     my ($e,$f);
10753:     {
10754:         use integer;
10755:         $e=($a+$b);
10756:         $f=($c+$d);
10757:         if ($_64bit) {
10758:             $e=(($e<<32)>>32);
10759:             $f=(($f<<32)>>32);
10760:         }
10761:     }
10762:     if (wantarray) {
10763: 	return ($e,$f);
10764:     } else {
10765: 	my $g;
10766: 	{
10767: 	    use integer;
10768: 	    $g=($e+$f);
10769: 	    if ($_64bit) {
10770: 		$g=(($g<<32)>>32);
10771: 	    }
10772: 	}
10773: 	return $g;
10774:     }
10775: }
10776: 
10777: sub latest_rnd_algorithm_id {
10778:     return '64bit5';
10779: }
10780: 
10781: sub get_rand_alg {
10782:     my ($courseid)=@_;
10783:     if (!$courseid) { $courseid=(&whichuser())[1]; }
10784:     if ($courseid) {
10785: 	return $env{"course.$courseid.rndseed"};
10786:     }
10787:     return &latest_rnd_algorithm_id();
10788: }
10789: 
10790: sub validCODE {
10791:     my ($CODE)=@_;
10792:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
10793:     return 0;
10794: }
10795: 
10796: sub getCODE {
10797:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
10798:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
10799: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
10800: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
10801: 	return $Apache::lonhomework::history{'resource.CODE'};
10802:     }
10803:     return undef;
10804: }
10805: #
10806: #  Determines the random seed for a specific context:
10807: #
10808: # parameters:
10809: #   symb      - in course context the symb for the seed.
10810: #   course_id - The course id of the form domain_coursenum.
10811: #   domain    - Domain for the user.
10812: #   course    - Course for the user.
10813: #   cenv      - environment of the course.
10814: #
10815: # NOTE:
10816: #   All parameters are picked out of the environment if missing
10817: #   or not defined.
10818: #   If a symb cannot be determined the current time is used instead.
10819: #
10820: #  For a given well defined symb, courside, domain, username,
10821: #  and course environment, the seed is reproducible.
10822: #
10823: sub rndseed {
10824:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
10825:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
10826:     if (!defined($symb)) {
10827: 	unless ($symb=$wsymb) { return time; }
10828:     }
10829:     if (!defined $courseid) { 
10830: 	$courseid=$wcourseid; 
10831:     }
10832:     if (!defined $domain) { $domain=$wdomain; }
10833:     if (!defined $username) { $username=$wusername }
10834: 
10835:     my $which;
10836:     if (defined($cenv->{'rndseed'})) {
10837: 	$which = $cenv->{'rndseed'};
10838:     } else {
10839: 	$which =&get_rand_alg($courseid);
10840:     }
10841:     if (defined(&getCODE())) {
10842: 
10843: 	if ($which eq '64bit5') {
10844: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
10845: 	} elsif ($which eq '64bit4') {
10846: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
10847: 	} else {
10848: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
10849: 	}
10850:     } elsif ($which eq '64bit5') {
10851: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
10852:     } elsif ($which eq '64bit4') {
10853: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
10854:     } elsif ($which eq '64bit3') {
10855: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
10856:     } elsif ($which eq '64bit2') {
10857: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
10858:     } elsif ($which eq '64bit') {
10859: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
10860:     }
10861:     return &rndseed_32bit($symb,$courseid,$domain,$username);
10862: }
10863: 
10864: sub rndseed_32bit {
10865:     my ($symb,$courseid,$domain,$username)=@_;
10866:     {
10867: 	use integer;
10868: 	my $symbchck=unpack("%32C*",$symb) << 27;
10869: 	my $symbseed=numval($symb) << 22;
10870: 	my $namechck=unpack("%32C*",$username) << 17;
10871: 	my $nameseed=numval($username) << 12;
10872: 	my $domainseed=unpack("%32C*",$domain) << 7;
10873: 	my $courseseed=unpack("%32C*",$courseid);
10874: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
10875: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10876: 	#&logthis("rndseed :$num:$symb");
10877: 	if ($_64bit) { $num=(($num<<32)>>32); }
10878: 	return $num;
10879:     }
10880: }
10881: 
10882: sub rndseed_64bit {
10883:     my ($symb,$courseid,$domain,$username)=@_;
10884:     {
10885: 	use integer;
10886: 	my $symbchck=unpack("%32S*",$symb) << 21;
10887: 	my $symbseed=numval($symb) << 10;
10888: 	my $namechck=unpack("%32S*",$username);
10889: 	
10890: 	my $nameseed=numval($username) << 21;
10891: 	my $domainseed=unpack("%32S*",$domain) << 10;
10892: 	my $courseseed=unpack("%32S*",$courseid);
10893: 	
10894: 	my $num1=$symbchck+$symbseed+$namechck;
10895: 	my $num2=$nameseed+$domainseed+$courseseed;
10896: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10897: 	#&logthis("rndseed :$num:$symb");
10898: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10899: 	return "$num1,$num2";
10900:     }
10901: }
10902: 
10903: sub rndseed_64bit2 {
10904:     my ($symb,$courseid,$domain,$username)=@_;
10905:     {
10906: 	use integer;
10907: 	# strings need to be an even # of cahracters long, it it is odd the
10908:         # last characters gets thrown away
10909: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
10910: 	my $symbseed=numval($symb) << 10;
10911: 	my $namechck=unpack("%32S*",$username.' ');
10912: 	
10913: 	my $nameseed=numval($username) << 21;
10914: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
10915: 	my $courseseed=unpack("%32S*",$courseid.' ');
10916: 	
10917: 	my $num1=$symbchck+$symbseed+$namechck;
10918: 	my $num2=$nameseed+$domainseed+$courseseed;
10919: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10920: 	#&logthis("rndseed :$num:$symb");
10921: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10922: 	return "$num1,$num2";
10923:     }
10924: }
10925: 
10926: sub rndseed_64bit3 {
10927:     my ($symb,$courseid,$domain,$username)=@_;
10928:     {
10929: 	use integer;
10930: 	# strings need to be an even # of cahracters long, it it is odd the
10931:         # last characters gets thrown away
10932: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
10933: 	my $symbseed=numval2($symb) << 10;
10934: 	my $namechck=unpack("%32S*",$username.' ');
10935: 	
10936: 	my $nameseed=numval2($username) << 21;
10937: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
10938: 	my $courseseed=unpack("%32S*",$courseid.' ');
10939: 	
10940: 	my $num1=$symbchck+$symbseed+$namechck;
10941: 	my $num2=$nameseed+$domainseed+$courseseed;
10942: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10943: 	#&logthis("rndseed :$num1:$num2:$_64bit");
10944: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10945: 	
10946: 	return "$num1:$num2";
10947:     }
10948: }
10949: 
10950: sub rndseed_64bit4 {
10951:     my ($symb,$courseid,$domain,$username)=@_;
10952:     {
10953: 	use integer;
10954: 	# strings need to be an even # of cahracters long, it it is odd the
10955:         # last characters gets thrown away
10956: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
10957: 	my $symbseed=numval3($symb) << 10;
10958: 	my $namechck=unpack("%32S*",$username.' ');
10959: 	
10960: 	my $nameseed=numval3($username) << 21;
10961: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
10962: 	my $courseseed=unpack("%32S*",$courseid.' ');
10963: 	
10964: 	my $num1=$symbchck+$symbseed+$namechck;
10965: 	my $num2=$nameseed+$domainseed+$courseseed;
10966: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10967: 	#&logthis("rndseed :$num1:$num2:$_64bit");
10968: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10969: 	
10970: 	return "$num1:$num2";
10971:     }
10972: }
10973: 
10974: sub rndseed_64bit5 {
10975:     my ($symb,$courseid,$domain,$username)=@_;
10976:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
10977:     return "$num1:$num2";
10978: }
10979: 
10980: sub rndseed_CODE_64bit {
10981:     my ($symb,$courseid,$domain,$username)=@_;
10982:     {
10983: 	use integer;
10984: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
10985: 	my $symbseed=numval2($symb);
10986: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
10987: 	my $CODEseed=numval(&getCODE());
10988: 	my $courseseed=unpack("%32S*",$courseid.' ');
10989: 	my $num1=$symbseed+$CODEchck;
10990: 	my $num2=$CODEseed+$courseseed+$symbchck;
10991: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
10992: 	#&logthis("rndseed :$num1:$num2:$symb");
10993: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
10994: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
10995: 	return "$num1:$num2";
10996:     }
10997: }
10998: 
10999: sub rndseed_CODE_64bit4 {
11000:     my ($symb,$courseid,$domain,$username)=@_;
11001:     {
11002: 	use integer;
11003: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
11004: 	my $symbseed=numval3($symb);
11005: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11006: 	my $CODEseed=numval3(&getCODE());
11007: 	my $courseseed=unpack("%32S*",$courseid.' ');
11008: 	my $num1=$symbseed+$CODEchck;
11009: 	my $num2=$CODEseed+$courseseed+$symbchck;
11010: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11011: 	#&logthis("rndseed :$num1:$num2:$symb");
11012: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
11013: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
11014: 	return "$num1:$num2";
11015:     }
11016: }
11017: 
11018: sub rndseed_CODE_64bit5 {
11019:     my ($symb,$courseid,$domain,$username)=@_;
11020:     my $code = &getCODE();
11021:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
11022:     return "$num1:$num2";
11023: }
11024: 
11025: sub setup_random_from_rndseed {
11026:     my ($rndseed)=@_;
11027:     if ($rndseed =~/([,:])/) {
11028: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
11029: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
11030:     } else {
11031: 	&Math::Random::random_set_seed_from_phrase($rndseed);
11032:     }
11033: }
11034: 
11035: sub latest_receipt_algorithm_id {
11036:     return 'receipt3';
11037: }
11038: 
11039: sub recunique {
11040:     my $fucourseid=shift;
11041:     my $unique;
11042:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11043: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11044: 	$unique=$env{"course.$fucourseid.internal.encseed"};
11045:     } else {
11046: 	$unique=$perlvar{'lonReceipt'};
11047:     }
11048:     return unpack("%32C*",$unique);
11049: }
11050: 
11051: sub recprefix {
11052:     my $fucourseid=shift;
11053:     my $prefix;
11054:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11055: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11056: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
11057:     } else {
11058: 	$prefix=$perlvar{'lonHostID'};
11059:     }
11060:     return unpack("%32C*",$prefix);
11061: }
11062: 
11063: sub ireceipt {
11064:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
11065: 
11066:     my $return =&recprefix($fucourseid).'-';
11067: 
11068:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11069: 	$env{'request.state'} eq 'construct') {
11070: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11071: 	return $return;
11072:     }
11073: 
11074:     my $cuname=unpack("%32C*",$funame);
11075:     my $cudom=unpack("%32C*",$fudom);
11076:     my $cucourseid=unpack("%32C*",$fucourseid);
11077:     my $cusymb=unpack("%32C*",$fusymb);
11078:     my $cunique=&recunique($fucourseid);
11079:     my $cpart=unpack("%32S*",$part);
11080:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11081: 
11082: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
11083: 			       
11084: 	$return.= ($cunique%$cuname+
11085: 		   $cunique%$cudom+
11086: 		   $cusymb%$cuname+
11087: 		   $cusymb%$cudom+
11088: 		   $cucourseid%$cuname+
11089: 		   $cucourseid%$cudom+
11090: 		   $cpart%$cuname+
11091: 		   $cpart%$cudom);
11092:     } else {
11093: 	$return.= ($cunique%$cuname+
11094: 		   $cunique%$cudom+
11095: 		   $cusymb%$cuname+
11096: 		   $cusymb%$cudom+
11097: 		   $cucourseid%$cuname+
11098: 		   $cucourseid%$cudom);
11099:     }
11100:     return $return;
11101: }
11102: 
11103: sub receipt {
11104:     my ($part)=@_;
11105:     my ($symb,$courseid,$domain,$name) = &whichuser();
11106:     return &ireceipt($name,$domain,$courseid,$symb,$part);
11107: }
11108: 
11109: sub whichuser {
11110:     my ($passedsymb)=@_;
11111:     my ($symb,$courseid,$domain,$name,$publicuser);
11112:     if (defined($env{'form.grade_symb'})) {
11113: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11114: 	my $allowed=&allowed('vgr',$tmp_courseid);
11115: 	if (!$allowed &&
11116: 	    exists($env{'request.course.sec'}) &&
11117: 	    $env{'request.course.sec'} !~ /^\s*$/) {
11118: 	    $allowed=&allowed('vgr',$tmp_courseid.
11119: 			      '/'.$env{'request.course.sec'});
11120: 	}
11121: 	if ($allowed) {
11122: 	    ($symb)=&get_env_multiple('form.grade_symb');
11123: 	    $courseid=$tmp_courseid;
11124: 	    ($domain)=&get_env_multiple('form.grade_domain');
11125: 	    ($name)=&get_env_multiple('form.grade_username');
11126: 	    return ($symb,$courseid,$domain,$name,$publicuser);
11127: 	}
11128:     }
11129:     if (!$passedsymb) {
11130: 	$symb=&symbread();
11131:     } else {
11132: 	$symb=$passedsymb;
11133:     }
11134:     $courseid=$env{'request.course.id'};
11135:     $domain=$env{'user.domain'};
11136:     $name=$env{'user.name'};
11137:     if ($name eq 'public' && $domain eq 'public') {
11138: 	if (!defined($env{'form.username'})) {
11139: 	    $env{'form.username'}.=time.rand(10000000);
11140: 	}
11141: 	$name.=$env{'form.username'};
11142:     }
11143:     return ($symb,$courseid,$domain,$name,$publicuser);
11144: 
11145: }
11146: 
11147: # ------------------------------------------------------------ Serves up a file
11148: # returns either the contents of the file or 
11149: # -1 if the file doesn't exist
11150: #
11151: # if the target is a file that was uploaded via DOCS, 
11152: # a check will be made to see if a current copy exists on the local server,
11153: # if it does this will be served, otherwise a copy will be retrieved from
11154: # the home server for the course and stored in /home/httpd/html/userfiles on
11155: # the local server.   
11156: 
11157: sub getfile {
11158:     my ($file) = @_;
11159:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
11160:     &repcopy($file);
11161:     return &readfile($file);
11162: }
11163: 
11164: sub repcopy_userfile {
11165:     my ($file)=@_;
11166:     my $londocroot = $perlvar{'lonDocRoot'};
11167:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
11168:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
11169:     my ($cdom,$cnum,$filename) = 
11170: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
11171:     my $uri="/uploaded/$cdom/$cnum/$filename";
11172:     if (-e "$file") {
11173: # we already have a local copy, check it out
11174: 	my @fileinfo = stat($file);
11175: 	my $rtncode;
11176: 	my $info;
11177: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
11178: 	if ($lwpresp ne 'ok') {
11179: # there is no such file anymore, even though we had a local copy
11180: 	    if ($rtncode eq '404') {
11181: 		unlink($file);
11182: 	    }
11183: 	    return -1;
11184: 	}
11185: 	if ($info < $fileinfo[9]) {
11186: # nice, the file we have is up-to-date, just say okay
11187: 	    return 'ok';
11188: 	} else {
11189: # the file is outdated, get rid of it
11190: 	    unlink($file);
11191: 	}
11192:     }
11193: # one way or the other, at this point, we don't have the file
11194: # construct the correct path for the file
11195:     my @parts = ($cdom,$cnum); 
11196:     if ($filename =~ m|^(.+)/[^/]+$|) {
11197: 	push @parts, split(/\//,$1);
11198:     }
11199:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11200:     foreach my $part (@parts) {
11201: 	$path .= '/'.$part;
11202: 	if (!-e $path) {
11203: 	    mkdir($path,0770);
11204: 	}
11205:     }
11206: # now the path exists for sure
11207: # get a user agent
11208:     my $ua=new LWP::UserAgent;
11209:     my $transferfile=$file.'.in.transfer';
11210: # FIXME: this should flock
11211:     if (-e $transferfile) { return 'ok'; }
11212:     my $request;
11213:     $uri=~s/^\///;
11214:     my $homeserver = &homeserver($cnum,$cdom);
11215:     my $protocol = $protocol{$homeserver};
11216:     $protocol = 'http' if ($protocol ne 'https');
11217:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
11218:     my $response=$ua->request($request,$transferfile);
11219: # did it work?
11220:     if ($response->is_error()) {
11221: 	unlink($transferfile);
11222: 	&logthis("Userfile repcopy failed for $uri");
11223: 	return -1;
11224:     }
11225: # worked, rename the transfer file
11226:     rename($transferfile,$file);
11227:     return 'ok';
11228: }
11229: 
11230: sub tokenwrapper {
11231:     my $uri=shift;
11232:     $uri=~s|^https?\://([^/]+)||;
11233:     $uri=~s|^/||;
11234:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
11235:     my $token=$1;
11236:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
11237:     if ($udom && $uname && $file) {
11238: 	$file=~s|(\?\.*)*$||;
11239:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
11240:         my $homeserver = &homeserver($uname,$udom);
11241:         my $protocol = $protocol{$homeserver};
11242:         $protocol = 'http' if ($protocol ne 'https');
11243:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
11244:                (($uri=~/\?/)?'&':'?').'token='.$token.
11245:                                '&tokenissued='.$perlvar{'lonHostID'};
11246:     } else {
11247:         return '/adm/notfound.html';
11248:     }
11249: }
11250: 
11251: # call with reqtype HEAD: get last modification time
11252: # call with reqtype GET: get the file contents
11253: # Do not call this with reqtype GET for large files! It loads everything into memory
11254: #
11255: sub getuploaded {
11256:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11257:     $uri=~s/^\///;
11258:     my $homeserver = &homeserver($cnum,$cdom);
11259:     my $protocol = $protocol{$homeserver};
11260:     $protocol = 'http' if ($protocol ne 'https');
11261:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
11262:     my $ua=new LWP::UserAgent;
11263:     my $request=new HTTP::Request($reqtype,$uri);
11264:     my $response=$ua->request($request);
11265:     $$rtncode = $response->code;
11266:     if (! $response->is_success()) {
11267: 	return 'failed';
11268:     }      
11269:     if ($reqtype eq 'HEAD') {
11270: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
11271:     } elsif ($reqtype eq 'GET') {
11272: 	$$info = $response->content;
11273:     }
11274:     return 'ok';
11275: }
11276: 
11277: sub readfile {
11278:     my $file = shift;
11279:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
11280:     my $fh;
11281:     open($fh,"<$file");
11282:     my $a='';
11283:     while (my $line = <$fh>) { $a .= $line; }
11284:     return $a;
11285: }
11286: 
11287: sub filelocation {
11288:     my ($dir,$file) = @_;
11289:     my $location;
11290:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
11291: 
11292:     if ($file =~ m-^/adm/-) {
11293: 	$file=~s-^/adm/wrapper/-/-;
11294: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
11295:     }
11296: 
11297:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
11298:         $location = $file;
11299:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
11300:         my ($udom,$uname,$filename)=
11301:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
11302:         my $home=&homeserver($uname,$udom);
11303:         my $is_me=0;
11304:         my @ids=&current_machine_ids();
11305:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11306:         if ($is_me) {
11307:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
11308:         } else {
11309:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11310:   	      $udom.'/'.$uname.'/'.$filename;
11311:         }
11312:     } elsif ($file =~ m-^/adm/-) {
11313: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
11314:     } else {
11315:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
11316:         $file=~s:^/(res|priv)/:/:;
11317:         my $space=$1;
11318:         if ( !( $file =~ m:^/:) ) {
11319:             $location = $dir. '/'.$file;
11320:         } else {
11321:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
11322:         }
11323:     }
11324:     $location=~s://+:/:g; # remove duplicate /
11325:     while ($location=~m{/\.\./}) {
11326: 	if ($location =~ m{/[^/]+/\.\./}) {
11327: 	    $location=~ s{/[^/]+/\.\./}{/}g;
11328: 	} else {
11329: 	    $location=~ s{/\.\./}{/}g;
11330: 	}
11331:     } #remove dir/..
11332:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11333:     return $location;
11334: }
11335: 
11336: sub hreflocation {
11337:     my ($dir,$file)=@_;
11338:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
11339: 	$file=filelocation($dir,$file);
11340:     } elsif ($file=~m-^/adm/-) {
11341: 	$file=~s-^/adm/wrapper/-/-;
11342: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
11343:     }
11344:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11345: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11346:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
11347: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11348: 	        {/uploaded/$1/$2/}x;
11349:     }
11350:     if ($file=~ m{^/userfiles/}) {
11351: 	$file =~ s{^/userfiles/}{/uploaded/};
11352:     }
11353:     return $file;
11354: }
11355: 
11356: 
11357: 
11358: 
11359: 
11360: sub current_machine_domains {
11361:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
11362: }
11363: 
11364: sub machine_domains {
11365:     my ($hostname) = @_;
11366:     my @domains;
11367:     my %hostname = &all_hostnames();
11368:     while( my($id, $name) = each(%hostname)) {
11369: #	&logthis("-$id-$name-$hostname-");
11370: 	if ($hostname eq $name) {
11371: 	    push(@domains,&host_domain($id));
11372: 	}
11373:     }
11374:     return @domains;
11375: }
11376: 
11377: sub current_machine_ids {
11378:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
11379: }
11380: 
11381: sub machine_ids {
11382:     my ($hostname) = @_;
11383:     $hostname ||= &hostname($perlvar{'lonHostID'});
11384:     my @ids;
11385:     my %name_to_host = &all_names();
11386:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11387: 	return @{ $name_to_host{$hostname} };
11388:     }
11389:     return;
11390: }
11391: 
11392: sub additional_machine_domains {
11393:     my @domains;
11394:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
11395:     while( my $line = <$fh>) {
11396:         $line =~ s/\s//g;
11397:         push(@domains,$line);
11398:     }
11399:     return @domains;
11400: }
11401: 
11402: sub default_login_domain {
11403:     my $domain = $perlvar{'lonDefDomain'};
11404:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
11405:     foreach my $posdom (&current_machine_domains(),
11406:                         &additional_machine_domains()) {
11407:         if (lc($posdom) eq lc($testdomain)) {
11408:             $domain=$posdom;
11409:             last;
11410:         }
11411:     }
11412:     return $domain;
11413: }
11414: 
11415: # ------------------------------------------------------------- Declutters URLs
11416: 
11417: sub declutter {
11418:     my $thisfn=shift;
11419:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
11420:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
11421:     $thisfn=~s/^\///;
11422:     $thisfn=~s|^adm/wrapper/||;
11423:     $thisfn=~s|^adm/coursedocs/showdoc/||;
11424:     $thisfn=~s/^res\///;
11425:     $thisfn=~s/^priv\///;
11426:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
11427:         $thisfn=~s/\?.+$//;
11428:     }
11429:     return $thisfn;
11430: }
11431: 
11432: # ------------------------------------------------------------- Clutter up URLs
11433: 
11434: sub clutter {
11435:     my $thisfn='/'.&declutter(shift);
11436:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
11437: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
11438:        $thisfn='/res'.$thisfn; 
11439:     }
11440:     if ($thisfn !~m|^/adm|) {
11441: 	if ($thisfn =~ m|^/ext/|) {
11442: 	    $thisfn='/adm/wrapper'.$thisfn;
11443: 	} else {
11444: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
11445: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
11446: 	    if ($embstyle eq 'ssi'
11447: 		|| ($embstyle eq 'hdn')
11448: 		|| ($embstyle eq 'rat')
11449: 		|| ($embstyle eq 'prv')
11450: 		|| ($embstyle eq 'ign')) {
11451: 		#do nothing with these
11452: 	    } elsif (($embstyle eq 'img') 
11453: 		|| ($embstyle eq 'emb')
11454: 		|| ($embstyle eq 'wrp')) {
11455: 		$thisfn='/adm/wrapper'.$thisfn;
11456: 	    } elsif ($embstyle eq 'unk'
11457: 		     && $thisfn!~/\.(sequence|page)$/) {
11458: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
11459: 	    } else {
11460: #		&logthis("Got a blank emb style");
11461: 	    }
11462: 	}
11463:     }
11464:     return $thisfn;
11465: }
11466: 
11467: sub clutter_with_no_wrapper {
11468:     my $uri = &clutter(shift);
11469:     if ($uri =~ m-^/adm/-) {
11470: 	$uri =~ s-^/adm/wrapper/-/-;
11471: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
11472:     }
11473:     return $uri;
11474: }
11475: 
11476: sub freeze_escape {
11477:     my ($value)=@_;
11478:     if (ref($value)) {
11479: 	$value=&nfreeze($value);
11480: 	return '__FROZEN__'.&escape($value);
11481:     }
11482:     return &escape($value);
11483: }
11484: 
11485: 
11486: sub thaw_unescape {
11487:     my ($value)=@_;
11488:     if ($value =~ /^__FROZEN__/) {
11489: 	substr($value,0,10,undef);
11490: 	$value=&unescape($value);
11491: 	return &thaw($value);
11492:     }
11493:     return &unescape($value);
11494: }
11495: 
11496: sub correct_line_ends {
11497:     my ($result)=@_;
11498:     $$result =~s/\r\n/\n/mg;
11499:     $$result =~s/\r/\n/mg;
11500: }
11501: # ================================================================ Main Program
11502: 
11503: sub goodbye {
11504:    &logthis("Starting Shut down");
11505: #not converted to using infrastruture and probably shouldn't be
11506:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
11507: #converted
11508: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
11509:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
11510: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
11511: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
11512: #1.1 only
11513: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
11514: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
11515: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
11516: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
11517:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
11518:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
11519:    &logthis(sprintf("%-20s is %s",'hits',$hits));
11520:    &flushcourselogs();
11521:    &logthis("Shutting down");
11522: }
11523: 
11524: sub get_dns {
11525:     my ($url,$func,$ignore_cache) = @_;
11526:     if (!$ignore_cache) {
11527: 	my ($content,$cached)=
11528: 	    &Apache::lonnet::is_cached_new('dns',$url);
11529: 	if ($cached) {
11530: 	    &$func($content);
11531: 	    return;
11532: 	}
11533:     }
11534: 
11535:     my %alldns;
11536:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11537:     foreach my $dns (<$config>) {
11538: 	next if ($dns !~ /^\^(\S*)/x);
11539:         my $line = $1;
11540:         my ($host,$protocol) = split(/:/,$line);
11541:         if ($protocol ne 'https') {
11542:             $protocol = 'http';
11543:         }
11544: 	$alldns{$host} = $protocol;
11545:     }
11546:     while (%alldns) {
11547: 	my ($dns) = keys(%alldns);
11548: 	my $ua=new LWP::UserAgent;
11549:         $ua->timeout(30);
11550: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
11551: 	my $response=$ua->request($request);
11552:         delete($alldns{$dns});
11553: 	next if ($response->is_error());
11554: 	my @content = split("\n",$response->content);
11555: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
11556: 	&$func(\@content);
11557: 	return;
11558:     }
11559:     close($config);
11560:     my $which = (split('/',$url))[3];
11561:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
11562:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
11563:     my @content = <$config>;
11564:     &$func(\@content);
11565:     return;
11566: }
11567: # ------------------------------------------------------------ Read domain file
11568: {
11569:     my $loaded;
11570:     my %domain;
11571: 
11572:     sub parse_domain_tab {
11573: 	my ($lines) = @_;
11574: 	foreach my $line (@$lines) {
11575: 	    next if ($line =~ /^(\#|\s*$ )/x);
11576: 
11577: 	    chomp($line);
11578: 	    my ($name,@elements) = split(/:/,$line,9);
11579: 	    my %this_domain;
11580: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
11581: 			       'lang_def', 'city', 'longi', 'lati',
11582: 			       'primary') {
11583: 		$this_domain{$field} = shift(@elements);
11584: 	    }
11585: 	    $domain{$name} = \%this_domain;
11586: 	}
11587:     }
11588: 
11589:     sub reset_domain_info {
11590: 	undef($loaded);
11591: 	undef(%domain);
11592:     }
11593: 
11594:     sub load_domain_tab {
11595: 	my ($ignore_cache) = @_;
11596: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
11597: 	my $fh;
11598: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
11599: 	    my @lines = <$fh>;
11600: 	    &parse_domain_tab(\@lines);
11601: 	}
11602: 	close($fh);
11603: 	$loaded = 1;
11604:     }
11605: 
11606:     sub domain {
11607: 	&load_domain_tab() if (!$loaded);
11608: 
11609: 	my ($name,$what) = @_;
11610: 	return if ( !exists($domain{$name}) );
11611: 
11612: 	if (!$what) {
11613: 	    return $domain{$name}{'description'};
11614: 	}
11615: 	return $domain{$name}{$what};
11616:     }
11617: 
11618:     sub domain_info {
11619:         &load_domain_tab() if (!$loaded);
11620:         return %domain;
11621:     }
11622: 
11623: }
11624: 
11625: 
11626: # ------------------------------------------------------------- Read hosts file
11627: {
11628:     my %hostname;
11629:     my %hostdom;
11630:     my %libserv;
11631:     my $loaded;
11632:     my %name_to_host;
11633:     my %internetdom;
11634:     my %LC_dns_serv;
11635: 
11636:     sub parse_hosts_tab {
11637: 	my ($file) = @_;
11638: 	foreach my $configline (@$file) {
11639: 	    next if ($configline =~ /^(\#|\s*$ )/x);
11640:             chomp($configline);
11641: 	    if ($configline =~ /^\^/) {
11642:                 if ($configline =~ /^\^([\w.\-]+)/) {
11643:                     $LC_dns_serv{$1} = 1;
11644:                 }
11645:                 next;
11646:             }
11647: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
11648: 	    $name=~s/\s//g;
11649: 	    if ($id && $domain && $role && $name) {
11650: 		$hostname{$id}=$name;
11651: 		push(@{$name_to_host{$name}}, $id);
11652: 		$hostdom{$id}=$domain;
11653: 		if ($role eq 'library') { $libserv{$id}=$name; }
11654:                 if (defined($protocol)) {
11655:                     if ($protocol eq 'https') {
11656:                         $protocol{$id} = $protocol;
11657:                     } else {
11658:                         $protocol{$id} = 'http'; 
11659:                     }
11660:                 } else {
11661:                     $protocol{$id} = 'http';
11662:                 }
11663:                 if (defined($intdom)) {
11664:                     $internetdom{$id} = $intdom;
11665:                 }
11666: 	    }
11667: 	}
11668:     }
11669:     
11670:     sub reset_hosts_info {
11671: 	&purge_remembered();
11672: 	&reset_domain_info();
11673: 	&reset_hosts_ip_info();
11674: 	undef(%name_to_host);
11675: 	undef(%hostname);
11676: 	undef(%hostdom);
11677: 	undef(%libserv);
11678: 	undef($loaded);
11679:     }
11680: 
11681:     sub load_hosts_tab {
11682: 	my ($ignore_cache) = @_;
11683: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
11684: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11685: 	my @config = <$config>;
11686: 	&parse_hosts_tab(\@config);
11687: 	close($config);
11688: 	$loaded=1;
11689:     }
11690: 
11691:     sub hostname {
11692: 	&load_hosts_tab() if (!$loaded);
11693: 
11694: 	my ($lonid) = @_;
11695: 	return $hostname{$lonid};
11696:     }
11697: 
11698:     sub all_hostnames {
11699: 	&load_hosts_tab() if (!$loaded);
11700: 
11701: 	return %hostname;
11702:     }
11703: 
11704:     sub all_names {
11705: 	&load_hosts_tab() if (!$loaded);
11706: 
11707: 	return %name_to_host;
11708:     }
11709: 
11710:     sub all_host_domain {
11711:         &load_hosts_tab() if (!$loaded);
11712:         return %hostdom;
11713:     }
11714: 
11715:     sub is_library {
11716: 	&load_hosts_tab() if (!$loaded);
11717: 
11718: 	return exists($libserv{$_[0]});
11719:     }
11720: 
11721:     sub all_library {
11722: 	&load_hosts_tab() if (!$loaded);
11723: 
11724: 	return %libserv;
11725:     }
11726: 
11727:     sub unique_library {
11728: 	#2x reverse removes all hostnames that appear more than once
11729:         my %unique = reverse &all_library();
11730:         return reverse %unique;
11731:     }
11732: 
11733:     sub get_servers {
11734: 	&load_hosts_tab() if (!$loaded);
11735: 
11736: 	my ($domain,$type) = @_;
11737: 	my %possible_hosts = ($type eq 'library') ? %libserv
11738: 	                                          : %hostname;
11739: 	my %result;
11740: 	if (ref($domain) eq 'ARRAY') {
11741: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
11742: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
11743: 		    $result{$host} = $hostname;
11744: 		}
11745: 	    }
11746: 	} else {
11747: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
11748: 		if ($hostdom{$host} eq $domain) {
11749: 		    $result{$host} = $hostname;
11750: 		}
11751: 	    }
11752: 	}
11753: 	return %result;
11754:     }
11755: 
11756:     sub get_unique_servers {
11757:         my %unique = reverse &get_servers(@_);
11758: 	return reverse %unique;
11759:     }
11760: 
11761:     sub host_domain {
11762: 	&load_hosts_tab() if (!$loaded);
11763: 
11764: 	my ($lonid) = @_;
11765: 	return $hostdom{$lonid};
11766:     }
11767: 
11768:     sub all_domains {
11769: 	&load_hosts_tab() if (!$loaded);
11770: 
11771: 	my %seen;
11772: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
11773: 	return @uniq;
11774:     }
11775: 
11776:     sub internet_dom {
11777:         &load_hosts_tab() if (!$loaded);
11778: 
11779:         my ($lonid) = @_;
11780:         return $internetdom{$lonid};
11781:     }
11782: 
11783:     sub is_LC_dns {
11784:         &load_hosts_tab() if (!$loaded);
11785: 
11786:         my ($hostname) = @_;
11787:         return exists($LC_dns_serv{$hostname});
11788:     }
11789: 
11790: }
11791: 
11792: { 
11793:     my %iphost;
11794:     my %name_to_ip;
11795:     my %lonid_to_ip;
11796: 
11797:     sub get_hosts_from_ip {
11798: 	my ($ip) = @_;
11799: 	my %iphosts = &get_iphost();
11800: 	if (ref($iphosts{$ip})) {
11801: 	    return @{$iphosts{$ip}};
11802: 	}
11803: 	return;
11804:     }
11805:     
11806:     sub reset_hosts_ip_info {
11807: 	undef(%iphost);
11808: 	undef(%name_to_ip);
11809: 	undef(%lonid_to_ip);
11810:     }
11811: 
11812:     sub get_host_ip {
11813: 	my ($lonid) = @_;
11814: 	if (exists($lonid_to_ip{$lonid})) {
11815: 	    return $lonid_to_ip{$lonid};
11816: 	}
11817: 	my $name=&hostname($lonid);
11818:    	my $ip = gethostbyname($name);
11819: 	return if (!$ip || length($ip) ne 4);
11820: 	$ip=inet_ntoa($ip);
11821: 	$name_to_ip{$name}   = $ip;
11822: 	$lonid_to_ip{$lonid} = $ip;
11823: 	return $ip;
11824:     }
11825:     
11826:     sub get_iphost {
11827: 	my ($ignore_cache) = @_;
11828: 
11829: 	if (!$ignore_cache) {
11830: 	    if (%iphost) {
11831: 		return %iphost;
11832: 	    }
11833: 	    my ($ip_info,$cached)=
11834: 		&Apache::lonnet::is_cached_new('iphost','iphost');
11835: 	    if ($cached) {
11836: 		%iphost      = %{$ip_info->[0]};
11837: 		%name_to_ip  = %{$ip_info->[1]};
11838: 		%lonid_to_ip = %{$ip_info->[2]};
11839: 		return %iphost;
11840: 	    }
11841: 	}
11842: 
11843: 	# get yesterday's info for fallback
11844: 	my %old_name_to_ip;
11845: 	my ($ip_info,$cached)=
11846: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
11847: 	if ($cached) {
11848: 	    %old_name_to_ip = %{$ip_info->[1]};
11849: 	}
11850: 
11851: 	my %name_to_host = &all_names();
11852: 	foreach my $name (keys(%name_to_host)) {
11853: 	    my $ip;
11854: 	    if (!exists($name_to_ip{$name})) {
11855: 		$ip = gethostbyname($name);
11856: 		if (!$ip || length($ip) ne 4) {
11857: 		    if (defined($old_name_to_ip{$name})) {
11858: 			$ip = $old_name_to_ip{$name};
11859: 			&logthis("Can't find $name defaulting to old $ip");
11860: 		    } else {
11861: 			&logthis("Name $name no IP found");
11862: 			next;
11863: 		    }
11864: 		} else {
11865: 		    $ip=inet_ntoa($ip);
11866: 		}
11867: 		$name_to_ip{$name} = $ip;
11868: 	    } else {
11869: 		$ip = $name_to_ip{$name};
11870: 	    }
11871: 	    foreach my $id (@{ $name_to_host{$name} }) {
11872: 		$lonid_to_ip{$id} = $ip;
11873: 	    }
11874: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
11875: 	}
11876: 	&Apache::lonnet::do_cache_new('iphost','iphost',
11877: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
11878: 				      48*60*60);
11879: 
11880: 	return %iphost;
11881:     }
11882: 
11883:     #
11884:     #  Given a DNS returns the loncapa host name for that DNS 
11885:     # 
11886:     sub host_from_dns {
11887:         my ($dns) = @_;
11888:         my @hosts;
11889:         my $ip;
11890: 
11891:         if (exists($name_to_ip{$dns})) {
11892:             $ip = $name_to_ip{$dns};
11893:         }
11894:         if (!$ip) {
11895:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
11896:             if (length($ip) == 4) { 
11897: 	        $ip   = &IO::Socket::inet_ntoa($ip);
11898:             }
11899:         }
11900:         if ($ip) {
11901: 	    @hosts = get_hosts_from_ip($ip);
11902: 	    return $hosts[0];
11903:         }
11904:         return undef;
11905:     }
11906: 
11907:     sub get_internet_names {
11908:         my ($lonid) = @_;
11909:         return if ($lonid eq '');
11910:         my ($idnref,$cached)=
11911:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
11912:         if ($cached) {
11913:             return $idnref;
11914:         }
11915:         my $ip = &get_host_ip($lonid);
11916:         my @hosts = &get_hosts_from_ip($ip);
11917:         my %iphost = &get_iphost();
11918:         my (@idns,%seen);
11919:         foreach my $id (@hosts) {
11920:             my $dom = &host_domain($id);
11921:             my $prim_id = &domain($dom,'primary');
11922:             my $prim_ip = &get_host_ip($prim_id);
11923:             next if ($seen{$prim_ip});
11924:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
11925:                 foreach my $id (@{$iphost{$prim_ip}}) {
11926:                     my $intdom = &internet_dom($id);
11927:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
11928:                         push(@idns,$intdom);
11929:                     }
11930:                 }
11931:             }
11932:             $seen{$prim_ip} = 1;
11933:         }
11934:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
11935:     }
11936: 
11937: }
11938: 
11939: sub all_loncaparevs {
11940:     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);
11941: }
11942: 
11943: BEGIN {
11944: 
11945: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
11946:     unless ($readit) {
11947: {
11948:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
11949:     %perlvar = (%perlvar,%{$configvars});
11950: }
11951: 
11952: 
11953: # ------------------------------------------------------ Read spare server file
11954: {
11955:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
11956: 
11957:     while (my $configline=<$config>) {
11958:        chomp($configline);
11959:        if ($configline) {
11960: 	   my ($host,$type) = split(':',$configline,2);
11961: 	   if (!defined($type) || $type eq '') { $type = 'default' };
11962: 	   push(@{ $spareid{$type} }, $host);
11963:        }
11964:     }
11965:     close($config);
11966: }
11967: # ------------------------------------------------------------ Read permissions
11968: {
11969:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
11970: 
11971:     while (my $configline=<$config>) {
11972: 	chomp($configline);
11973: 	if ($configline) {
11974: 	    my ($role,$perm)=split(/ /,$configline);
11975: 	    if ($perm ne '') { $pr{$role}=$perm; }
11976: 	}
11977:     }
11978:     close($config);
11979: }
11980: 
11981: # -------------------------------------------- Read plain texts for permissions
11982: {
11983:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
11984: 
11985:     while (my $configline=<$config>) {
11986: 	chomp($configline);
11987: 	if ($configline) {
11988: 	    my ($short,@plain)=split(/:/,$configline);
11989:             %{$prp{$short}} = ();
11990: 	    if (@plain > 0) {
11991:                 $prp{$short}{'std'} = $plain[0];
11992:                 for (my $i=1; $i<@plain; $i++) {
11993:                     $prp{$short}{'alt'.$i} = $plain[$i];  
11994:                 }
11995:             }
11996: 	}
11997:     }
11998:     close($config);
11999: }
12000: 
12001: # ---------------------------------------------------------- Read package table
12002: {
12003:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
12004: 
12005:     while (my $configline=<$config>) {
12006: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
12007: 	chomp($configline);
12008: 	my ($short,$plain)=split(/:/,$configline);
12009: 	my ($pack,$name)=split(/\&/,$short);
12010: 	if ($plain ne '') {
12011: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
12012: 	    $packagetab{$short}=$plain; 
12013: 	}
12014:     }
12015:     close($config);
12016: }
12017: 
12018: # ---------------------------------------------------------- Read loncaparev table
12019: {
12020:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12021:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12022:             while (my $configline=<$config>) {
12023:                 chomp($configline);
12024:                 my ($hostid,$loncaparev)=split(/:/,$configline);
12025:                 $loncaparevs{$hostid}=$loncaparev;
12026:             }
12027:             close($config);
12028:         }
12029:     }
12030: }
12031: 
12032: # ---------------------------------------------------------- Read serverhostID table
12033: {
12034:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12035:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12036:             while (my $configline=<$config>) {
12037:                 chomp($configline);
12038:                 my ($name,$id)=split(/:/,$configline);
12039:                 $serverhomeIDs{$name}=$id;
12040:             }
12041:             close($config);
12042:         }
12043:     }
12044: }
12045: 
12046: {
12047:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12048:     if (-e $file) {
12049:         my $parser = HTML::LCParser->new($file);
12050:         while (my $token = $parser->get_token()) {
12051:             if ($token->[0] eq 'S') {
12052:                 my $item = $token->[1];
12053:                 my $name = $token->[2]{'name'};
12054:                 my $value = $token->[2]{'value'};
12055:                 if ($item ne '' && $name ne '' && $value ne '') {
12056:                     my $release = $parser->get_text();
12057:                     $release =~ s/(^\s*|\s*$ )//gx;
12058:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
12059:                 }
12060:             }
12061:         }
12062:     }
12063: }
12064: 
12065: # ---------------------------------------------------------- Read managers table
12066: {
12067:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12068:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12069:             while (my $configline=<$config>) {
12070:                 chomp($configline);
12071:                 next if ($configline =~ /^\#/);
12072:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12073:                     $managerstab{$configline} = 1;
12074:                 }
12075:             }
12076:             close($config);
12077:         }
12078:     }
12079: }
12080: 
12081: # ------------- set up temporary directory
12082: {
12083:     $tmpdir = LONCAPA::tempdir();
12084: 
12085: }
12086: 
12087: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
12088: 				'compress_threshold'=> 20_000,
12089:  			        });
12090: 
12091: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
12092: $dumpcount=0;
12093: $locknum=0;
12094: 
12095: &logtouch();
12096: &logthis('<font color="yellow">INFO: Read configuration</font>');
12097: $readit=1;
12098:     {
12099: 	use integer;
12100: 	my $test=(2**32)+1;
12101: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
12102: 	&logthis(" Detected 64bit platform ($_64bit)");
12103:     }
12104: }
12105: }
12106: 
12107: 1;
12108: __END__
12109: 
12110: =pod
12111: 
12112: =head1 NAME
12113: 
12114: Apache::lonnet - Subroutines to ask questions about things in the network.
12115: 
12116: =head1 SYNOPSIS
12117: 
12118: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
12119: 
12120:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12121: 
12122: Common parameters:
12123: 
12124: =over 4
12125: 
12126: =item *
12127: 
12128: $uname : an internal username (if $cname expecting a course Id specifically)
12129: 
12130: =item *
12131: 
12132: $udom : a domain (if $cdom expecting a course's domain specifically)
12133: 
12134: =item *
12135: 
12136: $symb : a resource instance identifier
12137: 
12138: =item *
12139: 
12140: $namespace : the name of a .db file that contains the data needed or
12141: being set.
12142: 
12143: =back
12144: 
12145: =head1 OVERVIEW
12146: 
12147: lonnet provides subroutines which interact with the
12148: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12149: about classes, users, and resources.
12150: 
12151: For many of these objects you can also use this to store data about
12152: them or modify them in various ways.
12153: 
12154: =head2 Symbs
12155: 
12156: To identify a specific instance of a resource, LON-CAPA uses symbols
12157: or "symbs"X<symb>. These identifiers are built from the URL of the
12158: map, the resource number of the resource in the map, and the URL of
12159: the resource itself. The latter is somewhat redundant, but might help
12160: if maps change.
12161: 
12162: An example is
12163: 
12164:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12165: 
12166: The respective map entry is
12167: 
12168:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
12169:   title="Problem 2">
12170:  </resource>
12171: 
12172: Symbs are used by the random number generator, as well as to store and
12173: restore data specific to a certain instance of for example a problem.
12174: 
12175: =head2 Storing And Retrieving Data
12176: 
12177: X<store()>X<cstore()>X<restore()>Three of the most important functions
12178: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12179: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12180: is is the non-critical message twin of cstore. These functions are for
12181: handlers to store a perl hash to a user's permanent data space in an
12182: easy manner, and to retrieve it again on another call. It is expected
12183: that a handler would use this once at the beginning to retrieve data,
12184: and then again once at the end to send only the new data back.
12185: 
12186: The data is stored in the user's data directory on the user's
12187: homeserver under the ID of the course.
12188: 
12189: The hash that is returned by restore will have all of the previous
12190: value for all of the elements of the hash.
12191: 
12192: Example:
12193: 
12194:  #creating a hash
12195:  my %hash;
12196:  $hash{'foo'}='bar';
12197: 
12198:  #storing it
12199:  &Apache::lonnet::cstore(\%hash);
12200: 
12201:  #changing a value
12202:  $hash{'foo'}='notbar';
12203: 
12204:  #adding a new value
12205:  $hash{'bar'}='foo';
12206:  &Apache::lonnet::cstore(\%hash);
12207: 
12208:  #retrieving the hash
12209:  my %history=&Apache::lonnet::restore();
12210: 
12211:  #print the hash
12212:  foreach my $key (sort(keys(%history))) {
12213:    print("\%history{$key} = $history{$key}");
12214:  }
12215: 
12216: Will print out:
12217: 
12218:  %history{1:foo} = bar
12219:  %history{1:keys} = foo:timestamp
12220:  %history{1:timestamp} = 990455579
12221:  %history{2:bar} = foo
12222:  %history{2:foo} = notbar
12223:  %history{2:keys} = foo:bar:timestamp
12224:  %history{2:timestamp} = 990455580
12225:  %history{bar} = foo
12226:  %history{foo} = notbar
12227:  %history{timestamp} = 990455580
12228:  %history{version} = 2
12229: 
12230: Note that the special hash entries C<keys>, C<version> and
12231: C<timestamp> were added to the hash. C<version> will be equal to the
12232: total number of versions of the data that have been stored. The
12233: C<timestamp> attribute will be the UNIX time the hash was
12234: stored. C<keys> is available in every historical section to list which
12235: keys were added or changed at a specific historical revision of a
12236: hash.
12237: 
12238: B<Warning>: do not store the hash that restore returns directly. This
12239: will cause a mess since it will restore the historical keys as if the
12240: were new keys. I.E. 1:foo will become 1:1:foo etc.
12241: 
12242: Calling convention:
12243: 
12244:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
12245:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
12246: 
12247: For more detailed information, see lonnet specific documentation.
12248: 
12249: =head1 RETURN MESSAGES
12250: 
12251: =over 4
12252: 
12253: =item * B<con_lost>: unable to contact remote host
12254: 
12255: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12256: when the connection is brought back up
12257: 
12258: =item * B<con_failed>: unable to contact remote host and unable to save message
12259: for later delivery
12260: 
12261: =item * B<error:>: an error a occurred, a description of the error follows the :
12262: 
12263: =item * B<no_such_host>: unable to fund a host associated with the user/domain
12264: that was requested
12265: 
12266: =back
12267: 
12268: =head1 PUBLIC SUBROUTINES
12269: 
12270: =head2 Session Environment Functions
12271: 
12272: =over 4
12273: 
12274: =item * 
12275: X<appenv()>
12276: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
12277: the user envirnoment file, and will be restored for each access this
12278: user makes during this session, also modifies the %env for the current
12279: process. Optional rolesarrayref - if defined contains a reference to an array
12280: of roles which are exempt from the restriction on modifying user.role entries 
12281: in the user's environment.db and in %env.    
12282: 
12283: =item *
12284: X<delenv()>
12285: B<delenv($delthis,$regexp)>: removes all items from the session
12286: environment file that begin with $delthis. If the 
12287: optional second arg - $regexp - is true, $delthis is treated as a 
12288: regular expression, otherwise \Q$delthis\E is used. 
12289: The values are also deleted from the current processes %env.
12290: 
12291: =item * get_env_multiple($name) 
12292: 
12293: gets $name from the %env hash, it seemlessly handles the cases where multiple
12294: values may be defined and end up as an array ref.
12295: 
12296: returns an array of values
12297: 
12298: =back
12299: 
12300: =head2 User Information
12301: 
12302: =over 4
12303: 
12304: =item *
12305: X<queryauthenticate()>
12306: B<queryauthenticate($uname,$udom)>: try to determine user's current 
12307: authentication scheme
12308: 
12309: =item *
12310: X<authenticate()>
12311: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
12312: authenticate user from domain's lib servers (first use the current
12313: one). C<$upass> should be the users password.
12314: $checkdefauth is optional (value is 1 if a check should be made to
12315:    authenticate user using default authentication method, and allow
12316:    account creation if username does not have account in the domain).
12317: $clientcancheckhost is optional (value is 1 if checking whether the
12318:    server can host will occur on the client side in lonauth.pm).   
12319: 
12320: =item *
12321: X<homeserver()>
12322: B<homeserver($uname,$udom)>: find the server which has
12323: the user's directory and files (there must be only one), this caches
12324: the answer, and also caches if there is a borken connection.
12325: 
12326: =item *
12327: X<idget()>
12328: B<idget($udom,@ids)>: find the usernames behind a list of IDs
12329: (IDs are a unique resource in a domain, there must be only 1 ID per
12330: username, and only 1 username per ID in a specific domain) (returns
12331: hash: id=>name,id=>name)
12332: 
12333: =item *
12334: X<idrget()>
12335: B<idrget($udom,@unames)>: find the IDs behind a list of
12336: usernames (returns hash: name=>id,name=>id)
12337: 
12338: =item *
12339: X<idput()>
12340: B<idput($udom,%ids)>: store away a list of names and associated IDs
12341: 
12342: =item *
12343: X<rolesinit()>
12344: B<rolesinit($udom,$username)>: get user privileges.
12345: returns user role, first access and timer interval hashes
12346: 
12347: =item *
12348: X<privileged()>
12349: B<privileged($username,$domain)>: returns a true if user has a
12350: privileged and active role (i.e. su or dc), false otherwise.
12351: 
12352: =item *
12353: X<getsection()>
12354: B<getsection($udom,$uname,$cname)>: finds the section of student in the
12355: course $cname, return section name/number or '' for "not in course"
12356: and '-1' for "no section"
12357: 
12358: =item *
12359: X<userenvironment()>
12360: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
12361: passed in @what from the requested user's environment, returns a hash
12362: 
12363: =item * 
12364: X<userlog_query()>
12365: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
12366: activity.log file. %filters defines filters applied when parsing the
12367: log file. These can be start or end timestamps, or the type of action
12368: - log to look for Login or Logout events, check for Checkin or
12369: Checkout, role for role selection. The response is in the form
12370: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
12371: escaped strings of the action recorded in the activity.log file.
12372: 
12373: =back
12374: 
12375: =head2 User Roles
12376: 
12377: =over 4
12378: 
12379: =item *
12380: 
12381: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
12382:  F: full access
12383:  U,I,K: authentication modes (cxx only)
12384:  '': forbidden
12385:  1: user needs to choose course
12386:  2: browse allowed
12387:  A: passphrase authentication needed
12388: 
12389: =item *
12390: 
12391: constructaccess($url,$setpriv) : check for access to construction space URL
12392: 
12393: See if the owner domain and name in the URL match those in the
12394: expected environment.  If so, return three element list
12395: ($ownername,$ownerdomain,$ownerhome).
12396: 
12397: Otherwise return the null string.
12398: 
12399: If second argument 'setpriv' is true, it assigns the privileges,
12400: and returns the same three element list, unless the owner has
12401: blocked "ad hoc" Domain Coordinator access to the Author Space,
12402: in which case the null string is returned.
12403: 
12404: =item *
12405: 
12406: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
12407: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
12408: and course level
12409: 
12410: =item *
12411: 
12412: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
12413: (rolesplain.tab); plain text explanation of a user role term.
12414: $type is Course (default) or Community.
12415: If $forcedefault evaluates to true, text returned will be default 
12416: text for $type. Otherwise, if this is a course, the text returned 
12417: will be a custom name for the role (if defined in the course's 
12418: environment).  If no custom name is defined the default is returned.
12419:    
12420: =item *
12421: 
12422: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
12423: All arguments are optional. Returns a hash of a roles, either for
12424: co-author/assistant author roles for a user's Construction Space
12425: (default), or if $context is 'userroles', roles for the user himself,
12426: In the hash, keys are set to colon-separated $uname,$udom,$role, and
12427: (optionally) if $withsec is true, a fourth colon-separated item - $section.
12428: For each key, value is set to colon-separated start and end times for
12429: the role.  If no username and domain are specified, will default to
12430: current user/domain. Types, roles, and roledoms are references to arrays
12431: of role statuses (active, future or previous), roles 
12432: (e.g., cc,in, st etc.) and domains of the roles which can be used
12433: to restrict the list of roles reported. If no array ref is 
12434: provided for types, will default to return only active roles.
12435: 
12436: =item *
12437: 
12438: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
12439: user: $uname:$udom has a role in the course: $cdom_$cnum. 
12440: 
12441: Additional optional arguments are: $type (if role checking is to be restricted 
12442: to certain user status types -- previous (expired roles), active (currently
12443: available roles) or future (roles available in the future), and
12444: $hideprivileged -- if true will not report course roles for users who
12445: have active Domain Coordinator or Super User roles.
12446: 
12447: =back
12448: 
12449: =head2 User Modification
12450: 
12451: =over 4
12452: 
12453: =item *
12454: 
12455: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
12456: user for the level given by URL.  Optional start and end dates (leave empty
12457: string or zero for "no date")
12458: 
12459: =item *
12460: 
12461: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
12462: change a users, password, possible return values are: ok,
12463: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
12464: refused
12465: 
12466: =item *
12467: 
12468: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
12469: 
12470: =item *
12471: 
12472: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
12473:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
12474: 
12475: will update user information (firstname,middlename,lastname,generation,
12476: permanentemail), and if forceid is true, student/employee ID also.
12477: A user's institutional affiliation(s) can also be updated.
12478: User information fields will not be overwritten with empty entries 
12479: unless the field is included in the $candelete array reference.
12480: This array is included when a single user is modified via "Manage Users",
12481: or when Autoupdate.pl is run by cron in a domain.
12482: 
12483: =item *
12484: 
12485: modifystudent
12486: 
12487: modify a student's enrollment and identification information.
12488: The course id is resolved based on the current users environment.  
12489: This means the envoking user must be a course coordinator or otherwise
12490: associated with a course.
12491: 
12492: This call is essentially a wrapper for lonnet::modifyuser and
12493: lonnet::modify_student_enrollment
12494: 
12495: Inputs: 
12496: 
12497: =over 4
12498: 
12499: =item B<$udom> Student's loncapa domain
12500: 
12501: =item B<$uname> Student's loncapa login name
12502: 
12503: =item B<$uid> Student/Employee ID
12504: 
12505: =item B<$umode> Student's authentication mode
12506: 
12507: =item B<$upass> Student's password
12508: 
12509: =item B<$first> Student's first name
12510: 
12511: =item B<$middle> Student's middle name
12512: 
12513: =item B<$last> Student's last name
12514: 
12515: =item B<$gene> Student's generation
12516: 
12517: =item B<$usec> Student's section in course
12518: 
12519: =item B<$end> Unix time of the roles expiration
12520: 
12521: =item B<$start> Unix time of the roles start date
12522: 
12523: =item B<$forceid> If defined, allow $uid to be changed
12524: 
12525: =item B<$desiredhome> server to use as home server for student
12526: 
12527: =item B<$email> Student's permanent e-mail address
12528: 
12529: =item B<$type> Type of enrollment (auto or manual)
12530: 
12531: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
12532: 
12533: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
12534: 
12535: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
12536: 
12537: =item B<$context> role change context (shown in User Management Logs display in a course)
12538: 
12539: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
12540: 
12541: =back
12542: 
12543: =item *
12544: 
12545: modify_student_enrollment
12546: 
12547: Change a students enrollment status in a class.  The environment variable
12548: 'role.request.course' must be defined for this function to proceed.
12549: 
12550: Inputs:
12551: 
12552: =over 4
12553: 
12554: =item $udom, students domain
12555: 
12556: =item $uname, students name
12557: 
12558: =item $uid, students user id
12559: 
12560: =item $first, students first name
12561: 
12562: =item $middle
12563: 
12564: =item $last
12565: 
12566: =item $gene
12567: 
12568: =item $usec
12569: 
12570: =item $end
12571: 
12572: =item $start
12573: 
12574: =item $type
12575: 
12576: =item $locktype
12577: 
12578: =item $cid
12579: 
12580: =item $selfenroll
12581: 
12582: =item $context
12583: 
12584: =back
12585: 
12586: 
12587: =item *
12588: 
12589: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
12590: custom role; give a custom role to a user for the level given by URL.  Specify
12591: name and domain of role author, and role name
12592: 
12593: =item *
12594: 
12595: revokerole($udom,$uname,$url,$role) : revoke a role for url
12596: 
12597: =item *
12598: 
12599: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
12600: 
12601: =back
12602: 
12603: =head2 Course Infomation
12604: 
12605: =over 4
12606: 
12607: =item *
12608: 
12609: coursedescription($courseid,$options) : returns a hash of information about the
12610: specified course id, including all environment settings for the
12611: course, the description of the course will be in the hash under the
12612: key 'description'
12613: 
12614: $options is an optional parameter that if supplied is a hash reference that controls
12615: what how this function works.  It has the following key/values:
12616: 
12617: =over 4
12618: 
12619: =item freshen_cache
12620: 
12621: If defined, and the environment cache for the course is valid, it is 
12622: returned in the returned hash.
12623: 
12624: =item one_time
12625: 
12626: If defined, the last cache time is set to _now_
12627: 
12628: =item user
12629: 
12630: If defined, the supplied username is used instead of the current user.
12631: 
12632: 
12633: =back
12634: 
12635: =item *
12636: 
12637: resdata($name,$domain,$type,@which) : request for current parameter
12638: setting for a specific $type, where $type is either 'course' or 'user',
12639: @what should be a list of parameters to ask about. This routine caches
12640: answers for 5 minutes.
12641: 
12642: =item *
12643: 
12644: get_courseresdata($courseid, $domain) : dump the entire course resource
12645: data base, returning a hash that is keyed by the resource name and has
12646: values that are the resource value.  I believe that the timestamps and
12647: versions are also returned.
12648: 
12649: =back
12650: 
12651: =head2 Course Modification
12652: 
12653: =over 4
12654: 
12655: =item *
12656: 
12657: writecoursepref($courseid,%prefs) : write preferences (environment
12658: database) for a course
12659: 
12660: =item *
12661: 
12662: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
12663: 
12664: =item *
12665: 
12666: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
12667: 
12668: =item *
12669: 
12670: is_course($courseid), is_course($cdom, $cnum)
12671: 
12672: Accepts either a combined $courseid (in the form of domain_courseid) or the
12673: two component version $cdom, $cnum. It checks if the specified course exists.
12674: 
12675: Returns:
12676:     undef if the course doesn't exist, otherwise
12677:     in scalar context the combined courseid.
12678:     in list context the two components of the course identifier, domain and 
12679:     courseid.    
12680: 
12681: =back
12682: 
12683: =head2 Resource Subroutines
12684: 
12685: =over 4
12686: 
12687: =item *
12688: 
12689: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
12690: 
12691: =item *
12692: 
12693: repcopy($filename) : subscribes to the requested file, and attempts to
12694: replicate from the owning library server, Might return
12695: 'unavailable', 'not_found', 'forbidden', 'ok', or
12696: 'bad_request', also attempts to grab the metadata for the
12697: resource. Expects the local filesystem pathname
12698: (/home/httpd/html/res/....)
12699: 
12700: =back
12701: 
12702: =head2 Resource Information
12703: 
12704: =over 4
12705: 
12706: =item *
12707: 
12708: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
12709: a vairety of different possible values, $varname should be a request
12710: string, and the other parameters can be used to specify who and what
12711: one is asking about.
12712: 
12713: Possible values for $varname are environment.lastname (or other item
12714: from the envirnment hash), user.name (or someother aspect about the
12715: user), resource.0.maxtries (or some other part and parameter of a
12716: resource)
12717: 
12718: =item *
12719: 
12720: directcondval($number) : get current value of a condition; reads from a state
12721: string
12722: 
12723: =item *
12724: 
12725: condval($condidx) : value of condition index based on state
12726: 
12727: =item *
12728: 
12729: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
12730: resource's metadata, $what should be either a specific key, or either
12731: 'keys' (to get a list of possible keys) or 'packages' to get a list of
12732: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
12733: 
12734: this function automatically caches all requests
12735: 
12736: =item *
12737: 
12738: metadata_query($query,$custom,$customshow) : make a metadata query against the
12739: network of library servers; returns file handle of where SQL and regex results
12740: will be stored for query
12741: 
12742: =item *
12743: 
12744: symbread($filename) : return symbolic list entry (filename argument optional);
12745: returns the data handle
12746: 
12747: =item *
12748: 
12749: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
12750: and is a possible symb for the URL in $thisfn, and if is an encrypted
12751: resource that the user accessed using /enc/ returns a 1 on success, 0
12752: on failure, user must be in a course, as it assumes the existence of
12753: the course initial hash, and uses $env('request.course.id'}.  The third
12754: arg is an optional reference to a scalar.  If this arg is passed in the 
12755: call to symbverify, it will be set to 1 if the symb has been set to be 
12756: encrypted; otherwise it will be null.  
12757: 
12758: =item *
12759: 
12760: symbclean($symb) : removes versions numbers from a symb, returns the
12761: cleaned symb
12762: 
12763: =item *
12764: 
12765: is_on_map($uri) : checks if the $uri is somewhere on the current
12766: course map, user must be in a course for it to work.
12767: 
12768: =item *
12769: 
12770: numval($salt) : return random seed value (addend for rndseed)
12771: 
12772: =item *
12773: 
12774: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
12775: a random seed, all arguments are optional, if they aren't sent it uses the
12776: environment to derive them. Note: if symb isn't sent and it can't get one
12777: from &symbread it will use the current time as its return value
12778: 
12779: =item *
12780: 
12781: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
12782: unfakeable, receipt
12783: 
12784: =item *
12785: 
12786: receipt() : API to ireceipt working off of env values; given out to users
12787: 
12788: =item *
12789: 
12790: countacc($url) : count the number of accesses to a given URL
12791: 
12792: =item *
12793: 
12794: 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
12795: 
12796: =item *
12797: 
12798: 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)
12799: 
12800: =item *
12801: 
12802: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
12803: 
12804: =item *
12805: 
12806: devalidate($symb) : devalidate temporary spreadsheet calculations,
12807: forcing spreadsheet to reevaluate the resource scores next time.
12808: 
12809: =item * 
12810: 
12811: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
12812: when viewing in course context.
12813: 
12814:  input: six args -- filename (decluttered), course number, course domain,
12815:                     url, symb (if registered) and group (if this is a 
12816:                     group item -- e.g., bulletin board, group page etc.).
12817: 
12818:  output: array of five scalars --
12819:          $cfile -- url for file editing if editable on current server
12820:          $home -- homeserver of resource (i.e., for author if published,
12821:                                           or course if uploaded.).
12822:          $switchserver --  1 if server switch will be needed.
12823:          $forceedit -- 1 if icon/link should be to go to edit mode 
12824:          $forceview -- 1 if icon/link should be to go to view mode
12825: 
12826: =item *
12827: 
12828: is_course_upload($file,$cnum,$cdom)
12829: 
12830: Used in course context to determine if current file was uploaded to 
12831: the course (i.e., would be found in /userfiles/docs on the course's 
12832: homeserver.
12833: 
12834:   input: 3 args -- filename (decluttered), course number and course domain.
12835:   output: boolean -- 1 if file was uploaded.
12836: 
12837: =back
12838: 
12839: =head2 Storing/Retreiving Data
12840: 
12841: =over 4
12842: 
12843: =item *
12844: 
12845: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
12846: for this url; hashref needs to be given and should be a \%hashname; the
12847: remaining args aren't required and if they aren't passed or are '' they will
12848: be derived from the env
12849: 
12850: =item *
12851: 
12852: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
12853: uses critical subroutine
12854: 
12855: =item *
12856: 
12857: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
12858: all args are optional
12859: 
12860: =item *
12861: 
12862: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
12863: dumps the complete (or key matching regexp) namespace into a hash
12864: ($udom, $uname, $regexp, $range are optional) for a namespace that is
12865: normally &store()ed into
12866: 
12867: $range should be either an integer '100' (give me the first 100
12868:                                            matching records)
12869:               or be  two integers sperated by a - with no spaces
12870:                  '30-50' (give me the 30th through the 50th matching
12871:                           records)
12872: 
12873: 
12874: =item *
12875: 
12876: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
12877: replaces a &store() version of data with a replacement set of data
12878: for a particular resource in a namespace passed in the $storehash hash 
12879: reference
12880: 
12881: =item *
12882: 
12883: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
12884: works very similar to store/cstore, but all data is stored in a
12885: temporary location and can be reset using tmpreset, $storehash should
12886: be a hash reference, returns nothing on success
12887: 
12888: =item *
12889: 
12890: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
12891: similar to restore, but all data is stored in a temporary location and
12892: can be reset using tmpreset. Returns a hash of values on success,
12893: error string otherwise.
12894: 
12895: =item *
12896: 
12897: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
12898: deltes all keys for $symb form the temporary storage hash.
12899: 
12900: =item *
12901: 
12902: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
12903: reference filled in from namesp ($udom and $uname are optional)
12904: 
12905: =item *
12906: 
12907: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
12908: namesp ($udom and $uname are optional)
12909: 
12910: =item *
12911: 
12912: dump($namespace,$udom,$uname,$regexp,$range) : 
12913: dumps the complete (or key matching regexp) namespace into a hash
12914: ($udom, $uname, $regexp, $range are optional)
12915: 
12916: $range should be either an integer '100' (give me the first 100
12917:                                            matching records)
12918:               or be  two integers sperated by a - with no spaces
12919:                  '30-50' (give me the 30th through the 50th matching
12920:                           records)
12921: =item *
12922: 
12923: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
12924: $store can be a scalar, an array reference, or if the amount to be 
12925: incremented is > 1, a hash reference.
12926: 
12927: ($udom and $uname are optional)
12928: 
12929: =item *
12930: 
12931: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
12932: ($udom and $uname are optional)
12933: 
12934: =item *
12935: 
12936: cput($namespace,$storehash,$udom,$uname) : critical put
12937: ($udom and $uname are optional)
12938: 
12939: =item *
12940: 
12941: newput($namespace,$storehash,$udom,$uname) :
12942: 
12943: Attempts to store the items in the $storehash, but only if they don't
12944: currently exist, if this succeeds you can be certain that you have 
12945: successfully created a new key value pair in the $namespace db.
12946: 
12947: 
12948: Args:
12949:  $namespace: name of database to store values to
12950:  $storehash: hashref to store to the db
12951:  $udom: (optional) domain of user containing the db
12952:  $uname: (optional) name of user caontaining the db
12953: 
12954: Returns:
12955:  'ok' -> succeeded in storing all keys of $storehash
12956:  'key_exists: <key>' -> failed to anything out of $storehash, as at
12957:                         least <key> already existed in the db (other
12958:                         requested keys may also already exist)
12959:  'error: <msg>' -> unable to tie the DB or other error occurred
12960:  'con_lost' -> unable to contact request server
12961:  'refused' -> action was not allowed by remote machine
12962: 
12963: 
12964: =item *
12965: 
12966: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
12967: reference filled in from namesp (encrypts the return communication)
12968: ($udom and $uname are optional)
12969: 
12970: =item *
12971: 
12972: log($udom,$name,$home,$message) : write to permanent log for user; use
12973: critical subroutine
12974: 
12975: =item *
12976: 
12977: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
12978: array reference filled in from namespace found in domain level on either
12979: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
12980: 
12981: =item *
12982: 
12983: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
12984: domain level either on specified domain server ($uhome) or primary domain 
12985: server ($udom and $uhome are optional)
12986: 
12987: =item * 
12988: 
12989: get_domain_defaults($target_domain) : returns hash with defaults for
12990: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
12991: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
12992: or localauth), initial password or a kerberos realm, language (e.g., en-us).
12993: Values are retrieved from cache (if current), or from domain's configuration.db
12994: (if available), or lastly from values in lonTabs/dns_domain,tab, 
12995: or lonTabs/domain.tab. 
12996: 
12997: %domdefaults = &get_auth_defaults($target_domain);
12998: 
12999: =back
13000: 
13001: =head2 Network Status Functions
13002: 
13003: =over 4
13004: 
13005: =item *
13006: 
13007: dirlist() : return directory list based on URI (first arg).
13008: 
13009: Inputs: 1 required, 5 optional.
13010: 
13011: =over
13012: 
13013: =item 
13014: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13015: 
13016: =item
13017: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
13018: 
13019: =item
13020: $username -  username of user/course to be listed. Extracted from $uri if absent. 
13021: 
13022: =item
13023: $getpropath - boolean: 1 if prepend path using &propath(). 
13024: 
13025: =item
13026: $getuserdir - boolean: 1 if prepend path for "userfiles".
13027: 
13028: =item 
13029: $alternateRoot - path to prepend in place of path from $uri.
13030: 
13031: =back
13032: 
13033: Returns: Array of up to two items.
13034: 
13035: =over
13036: 
13037: a reference to an array of files/subdirectories
13038: 
13039: =over
13040: 
13041: Each element in the array of files/subdirectories is a & separated list of
13042: item name and the result of running stat on the item.  If dirlist was requested
13043: for a file instead of a directory, the item name will be ''. For a directory 
13044: listing, if the item is a metadata file, the element will end &N&M 
13045: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13046: default copyright set (1).  
13047: 
13048: =back
13049: 
13050: a scalar containing error condition (if encountered).
13051: 
13052: =over
13053: 
13054: =item 
13055: no_host (no homeserver identified for $username:$domain).
13056: 
13057: =item 
13058: no_such_host (server contacted for listing not identified as valid host).
13059: 
13060: =item 
13061: con_lost (connection to remote server failed).
13062: 
13063: =item 
13064: refused (invalid $username:$domain received on lond side).
13065: 
13066: =item 
13067: no_such_dir (directory at specified path on lond side does not exist). 
13068: 
13069: =item 
13070: empty (directory at specified path on lond side is empty).
13071: 
13072: =over
13073: 
13074: This is currently not encountered because the &ls3, &ls2, 
13075: &ls (_handler) routines on the lond side do not filter out
13076: . and .. from a directory listing. 
13077: 
13078: =back
13079: 
13080: =back
13081: 
13082: =back
13083: 
13084: =item *
13085: 
13086: spareserver() : find server with least workload from spare.tab
13087: 
13088: 
13089: =item *
13090: 
13091: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13092: if there is no corresponding loncapa host.
13093: 
13094: =back
13095: 
13096: 
13097: =head2 Apache Request
13098: 
13099: =over 4
13100: 
13101: =item *
13102: 
13103: ssi($url,%hash) : server side include, does a complete request cycle on url to
13104: localhost, posts hash
13105: 
13106: =back
13107: 
13108: =head2 Data to String to Data
13109: 
13110: =over 4
13111: 
13112: =item *
13113: 
13114: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13115: and '&' separators, supports elements that are arrayrefs and hashrefs
13116: 
13117: =item *
13118: 
13119: hashref2str($hashref) : convert a hashref into a string complete with
13120: escaping and '=' and '&' separators, supports elements that are
13121: arrayrefs and hashrefs
13122: 
13123: =item *
13124: 
13125: arrayref2str($arrayref) : convert an arrayref into a string complete
13126: with escaping and '&' separators, supports elements that are arrayrefs
13127: and hashrefs
13128: 
13129: =item *
13130: 
13131: str2hash($string) : convert string to hash using unescaping and
13132: splitting on '=' and '&', supports elements that are arrayrefs and
13133: hashrefs
13134: 
13135: =item *
13136: 
13137: str2array($string) : convert string to hash using unescaping and
13138: splitting on '&', supports elements that are arrayrefs and hashrefs
13139: 
13140: =back
13141: 
13142: =head2 Logging Routines
13143: 
13144: 
13145: These routines allow one to make log messages in the lonnet.log and
13146: lonnet.perm logfiles.
13147: 
13148: =over 4
13149: 
13150: =item *
13151: 
13152: logtouch() : make sure the logfile, lonnet.log, exists
13153: 
13154: =item *
13155: 
13156: logthis() : append message to the normal lonnet.log file, it gets
13157: preiodically rolled over and deleted.
13158: 
13159: =item *
13160: 
13161: logperm() : append a permanent message to lonnet.perm.log, this log
13162: file never gets deleted by any automated portion of the system, only
13163: messages of critical importance should go in here.
13164: 
13165: 
13166: =back
13167: 
13168: =head2 General File Helper Routines
13169: 
13170: =over 4
13171: 
13172: =item *
13173: 
13174: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
13175: (a) files in /uploaded
13176:   (i) If a local copy of the file exists - 
13177:       compares modification date of local copy with last-modified date for 
13178:       definitive version stored on home server for course. If local copy is 
13179:       stale, requests a new version from the home server and stores it. 
13180:       If the original has been removed from the home server, then local copy 
13181:       is unlinked.
13182:   (ii) If local copy does not exist -
13183:       requests the file from the home server and stores it. 
13184:   
13185:   If $caller is 'uploadrep':  
13186:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
13187:     for request for files originally uploaded via DOCS. 
13188:      - returns 'ok' if fresh local copy now available, -1 otherwise.
13189:   
13190:   Otherwise:
13191:      This indicates a call from the content generation phase of the request.
13192:      -  returns the entire contents of the file or -1.
13193:      
13194: (b) files in /res
13195:    - returns the entire contents of a file or -1; 
13196:    it properly subscribes to and replicates the file if neccessary.
13197: 
13198: 
13199: =item *
13200: 
13201: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
13202:                   reference
13203: 
13204: returns either a stat() list of data about the file or an empty list
13205: if the file doesn't exist or couldn't find out about it (connection
13206: problems or user unknown)
13207: 
13208: =item *
13209: 
13210: filelocation($dir,$file) : returns file system location of a file
13211: based on URI; meant to be "fairly clean" absolute reference, $dir is a
13212: directory that relative $file lookups are to looked in ($dir of /a/dir
13213: and a file of ../bob will become /a/bob)
13214: 
13215: =item *
13216: 
13217: hreflocation($dir,$file) : returns file system location or a URL; same as
13218: filelocation except for hrefs
13219: 
13220: =item *
13221: 
13222: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
13223: 
13224: =back
13225: 
13226: =head2 Usererfile file routines (/uploaded*)
13227: 
13228: =over 4
13229: 
13230: =item *
13231: 
13232: userfileupload(): main rotine for putting a file in a user or course's
13233:                   filespace, arguments are,
13234: 
13235:  formname - required - this is the name of the element in $env where the
13236:            filename, and the contents of the file to create/modifed exist
13237:            the filename is in $env{'form.'.$formname.'.filename'} and the
13238:            contents of the file is located in $env{'form.'.$formname}
13239:  context - if coursedoc, store the file in the course of the active role
13240:              of the current user; 
13241:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
13242:            if 'canceloverwrite': delete file in tmp/overwrites directory
13243:  subdir - required - subdirectory to put the file in under ../userfiles/
13244:          if undefined, it will be placed in "unknown"
13245: 
13246:  (This routine calls clean_filename() to remove any dangerous
13247:  characters from the filename, and then calls finuserfileupload() to
13248:  complete the transaction)
13249: 
13250:  returns either the url of the uploaded file (/uploaded/....) if successful
13251:  and /adm/notfound.html if unsuccessful
13252: 
13253: =item *
13254: 
13255: clean_filename(): routine for cleaing a filename up for storage in
13256:                  userfile space, argument is:
13257: 
13258:  filename - proposed filename
13259: 
13260: returns: the new clean filename
13261: 
13262: =item *
13263: 
13264: finishuserfileupload(): routine that creates and sends the file to
13265: userspace, probably shouldn't be called directly
13266: 
13267:   docuname: username or courseid of destination for the file
13268:   docudom: domain of user/course of destination for the file
13269:   formname: same as for userfileupload()
13270:   fname: filename (including subdirectories) for the file
13271:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
13272:   allfiles: reference to hash used to store objects found by parser
13273:   codebase: reference to hash used for codebases of java objects found by parser
13274:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
13275:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
13276:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
13277:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
13278:   context: if 'overwrite', will move the uploaded file from its temporary location to
13279:             userfiles to facilitate overwriting a previously uploaded file with same name.
13280:   mimetype: reference to scalar to accommodate mime type determined
13281:             from File::MMagic if $parser = parse.
13282: 
13283:  returns either the url of the uploaded file (/uploaded/....) if successful
13284:  and /adm/notfound.html if unsuccessful (or an error message if context 
13285:  was 'overwrite').
13286:  
13287: 
13288: =item *
13289: 
13290: renameuserfile(): renames an existing userfile to a new name
13291: 
13292:   Args:
13293:    docuname: username or courseid of destination for the file
13294:    docudom: domain of user/course of destination for the file
13295:    old: current file name (including any subdirs under userfiles)
13296:    new: desired file name (including any subdirs under userfiles)
13297: 
13298: =item *
13299: 
13300: mkdiruserfile(): creates a directory is a userfiles dir
13301: 
13302:   Args:
13303:    docuname: username or courseid of destination for the file
13304:    docudom: domain of user/course of destination for the file
13305:    dir: dir to create (including any subdirs under userfiles)
13306: 
13307: =item *
13308: 
13309: removeuserfile(): removes a file that exists in userfiles
13310: 
13311:   Args:
13312:    docuname: username or courseid of destination for the file
13313:    docudom: domain of user/course of destination for the file
13314:    fname: filname to delete (including any subdirs under userfiles)
13315: 
13316: =item *
13317: 
13318: removeuploadedurl(): convience function for removeuserfile()
13319: 
13320:   Args:
13321:    url:  a full /uploaded/... url to delete
13322: 
13323: =item * 
13324: 
13325: get_portfile_permissions():
13326:   Args:
13327:     domain: domain of user or course contain the portfolio files
13328:     user: name of user or num of course contain the portfolio files
13329:   Returns:
13330:     hashref of a dump of the proper file_permissions.db
13331:    
13332: 
13333: =item * 
13334: 
13335: get_access_controls():
13336: 
13337: Args:
13338:   current_permissions: the hash ref returned from get_portfile_permissions()
13339:   group: (optional) the group you want the files associated with
13340:   file: (optional) the file you want access info on
13341: 
13342: Returns:
13343:     a hash (keys are file names) of hashes containing
13344:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
13345:         values are XML containing access control settings (see below) 
13346: 
13347: Internal notes:
13348: 
13349:  access controls are stored in file_permissions.db as key=value pairs.
13350:     key -> path to file/file_name\0uniqueID:scope_end_start
13351:         where scope -> public,guest,course,group,domains or users.
13352:               end -> UNIX time for end of access (0 -> no end date)
13353:               start -> UNIX time for start of access
13354: 
13355:     value -> XML description of access control
13356:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
13357:             <start></start>
13358:             <end></end>
13359: 
13360:             <password></password>  for scope type = guest
13361: 
13362:             <domain></domain>     for scope type = course or group
13363:             <number></number>
13364:             <roles id="">
13365:              <role></role>
13366:              <access></access>
13367:              <section></section>
13368:              <group></group>
13369:             </roles>
13370: 
13371:             <dom></dom>         for scope type = domains
13372: 
13373:             <users>             for scope type = users
13374:              <user>
13375:               <uname></uname>
13376:               <udom></udom>
13377:              </user>
13378:             </users>
13379:            </scope> 
13380:               
13381:  Access data is also aggregated for each file in an additional key=value pair:
13382:  key -> path to file/file_name\0accesscontrol 
13383:  value -> reference to hash
13384:           hash contains key = value pairs
13385:           where key = uniqueID:scope_end_start
13386:                 value = UNIX time record was last updated
13387: 
13388:           Used to improve speed of look-ups of access controls for each file.  
13389:  
13390:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
13391: 
13392: =item *
13393: 
13394: modify_access_controls():
13395: 
13396: Modifies access controls for a portfolio file
13397: Args
13398: 1. file name
13399: 2. reference to hash of required changes,
13400: 3. domain
13401: 4. username
13402:   where domain,username are the domain of the portfolio owner 
13403:   (either a user or a course) 
13404: 
13405: Returns:
13406: 1. result of additions or updates ('ok' or 'error', with error message). 
13407: 2. result of deletions ('ok' or 'error', with error message).
13408: 3. reference to hash of any new or updated access controls.
13409: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
13410:    key = integer (inbound ID)
13411:    value = uniqueID
13412: 
13413: =item *
13414: 
13415: get_timebased_id():
13416: 
13417: Attempts to get a unique timestamp-based suffix for use with items added to a 
13418: course via the Course Editor (e.g., folders, composite pages, 
13419: group bulletin boards).
13420: 
13421: Args: (first three required; six others optional)
13422: 
13423: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
13424:    docssequence, or name of group
13425: 
13426: 2. keyid (alphanumeric): name of temporary locking key in hash,
13427:    e.g., num, boardids
13428: 
13429: 3. namespace: name of gdbm file used to store suffixes already assigned;  
13430:    file will be named nohist_namespace.db
13431: 
13432: 4. cdom: domain of course; default is current course domain from %env
13433: 
13434: 5. cnum: course number; default is current course number from %env
13435: 
13436: 6. idtype: set to concat if an additional digit is to be appended to the 
13437:    unix timestamp to form the suffix, if the plain timestamp is already
13438:    in use.  Default is to not do this, but simply increment the unix 
13439:    timestamp by 1 until a unique key is obtained.
13440: 
13441: 7. who: holder of locking key; defaults to user:domain for user.
13442: 
13443: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
13444:    retrying); default is 3.
13445: 
13446: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
13447: 
13448: Returns:
13449: 
13450: 1. suffix obtained (numeric)
13451: 
13452: 2. result of deleting locking key (ok if deleted, or lock never obtained)
13453: 
13454: 3. error: contains (localized) error message if an error occurred.
13455: 
13456: 
13457: =back
13458: 
13459: =head2 HTTP Helper Routines
13460: 
13461: =over 4
13462: 
13463: =item *
13464: 
13465: escape() : unpack non-word characters into CGI-compatible hex codes
13466: 
13467: =item *
13468: 
13469: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
13470: 
13471: =back
13472: 
13473: =head1 PRIVATE SUBROUTINES
13474: 
13475: =head2 Underlying communication routines (Shouldn't call)
13476: 
13477: =over 4
13478: 
13479: =item *
13480: 
13481: subreply() : tries to pass a message to lonc, returns con_lost if incapable
13482: 
13483: =item *
13484: 
13485: reply() : uses subreply to send a message to remote machine, logs all failures
13486: 
13487: =item *
13488: 
13489: critical() : passes a critical message to another server; if cannot
13490: get through then place message in connection buffer directory and
13491: returns con_delayed, if incapable of saving message, returns
13492: con_failed
13493: 
13494: =item *
13495: 
13496: reconlonc() : tries to reconnect lonc client processes.
13497: 
13498: =back
13499: 
13500: =head2 Resource Access Logging
13501: 
13502: =over 4
13503: 
13504: =item *
13505: 
13506: flushcourselogs() : flush (save) buffer logs and access logs
13507: 
13508: =item *
13509: 
13510: courselog($what) : save message for course in hash
13511: 
13512: =item *
13513: 
13514: courseacclog($what) : save message for course using &courselog().  Perform
13515: special processing for specific resource types (problems, exams, quizzes, etc).
13516: 
13517: =item *
13518: 
13519: goodbye() : flush course logs and log shutting down; it is called in srm.conf
13520: as a PerlChildExitHandler
13521: 
13522: =back
13523: 
13524: =head2 Other
13525: 
13526: =over 4
13527: 
13528: =item *
13529: 
13530: symblist($mapname,%newhash) : update symbolic storage links
13531: 
13532: =back
13533: 
13534: =cut
13535: 

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