File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1147: download - view: text, annotated - select for diffs
Mon Dec 5 01:14:21 2011 UTC (12 years, 7 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Include portal_def in %domdefaults.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1147 2011/12/05 01:14:21 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: =pod
   31: 
   32: =head1 NAME
   33: 
   34: Apache::lonnet.pm
   35: 
   36: =head1 SYNOPSIS
   37: 
   38: This file is an interface to the lonc processes of
   39: the LON-CAPA network as well as set of elaborated functions for handling information
   40: necessary for navigating through a given cluster of LON-CAPA machines within a
   41: domain. There are over 40 specialized functions in this module which handle the
   42: reading and transmission of metadata, user information (ids, names, environments, roles,
   43: logs), file information (storage, reading, directories, extensions, replication, embedded
   44: styles and descriptors), educational resources (course descriptions, section names and
   45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
   46: and from more descriptive phrases or explanations.
   47: 
   48: This is part of the LearningOnline Network with CAPA project
   49: described at http://www.lon-capa.org.
   50: 
   51: =head1 Package Variables
   52: 
   53: These are largely undocumented, so if you decipher one please note it here.
   54: 
   55: =over 4
   56: 
   57: =item $processmarker
   58: 
   59: Contains the time this process was started and this servers host id.
   60: 
   61: =item $dumpcount
   62: 
   63: Counts the number of times a message log flush has been attempted (regardless
   64: of success) by this process.  Used as part of the filename when messages are
   65: delayed.
   66: 
   67: =back
   68: 
   69: =cut
   70: 
   71: package Apache::lonnet;
   72: 
   73: use strict;
   74: use LWP::UserAgent();
   75: use HTTP::Date;
   76: use Image::Magick;
   77: 
   78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
   79:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
   80:             %managerstab);
   81: 
   82: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   83:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   84:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   85:     %courseownerbuf, %coursetypebuf,$locknum);
   86: 
   87: use IO::Socket;
   88: use GDBM_File;
   89: use HTML::LCParser;
   90: use Fcntl qw(:flock);
   91: use Storable qw(thaw nfreeze);
   92: use Time::HiRes qw( gettimeofday tv_interval );
   93: use Cache::Memcached;
   94: use Digest::MD5;
   95: use Math::Random;
   96: use File::MMagic;
   97: use LONCAPA qw(:DEFAULT :match);
   98: use LONCAPA::Configuration;
   99: 
  100: use File::Copy;
  101: 
  102: my $readit;
  103: my $max_connection_retries = 10;     # Or some such value.
  104: 
  105: require Exporter;
  106: 
  107: our @ISA = qw (Exporter);
  108: our @EXPORT = qw(%env);
  109: 
  110: 
  111: # --------------------------------------------------------------------- Logging
  112: {
  113:     my $logid;
  114:     sub instructor_log {
  115: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  116:         if (($cnum eq '') || ($cdom eq '')) {
  117:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  118:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  119:         }
  120: 	$logid++;
  121:         my $now = time();
  122: 	my $id=$now.'00000'.$$.'00000'.$logid;
  123: 	return &Apache::lonnet::put('nohist_'.$hash_name,
  124: 				    { $id => {
  125: 					'exe_uname' => $env{'user.name'},
  126: 					'exe_udom'  => $env{'user.domain'},
  127: 					'exe_time'  => $now,
  128: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
  129: 					'delflag'   => $delflag,
  130: 					'logentry'  => $storehash,
  131: 					'uname'     => $uname,
  132: 					'udom'      => $udom,
  133: 				    }
  134: 				  },$cdom,$cnum);
  135:     }
  136: }
  137: 
  138: sub logtouch {
  139:     my $execdir=$perlvar{'lonDaemons'};
  140:     unless (-e "$execdir/logs/lonnet.log") {	
  141: 	open(my $fh,">>$execdir/logs/lonnet.log");
  142: 	close $fh;
  143:     }
  144:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  145:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  146: }
  147: 
  148: sub logthis {
  149:     my $message=shift;
  150:     my $execdir=$perlvar{'lonDaemons'};
  151:     my $now=time;
  152:     my $local=localtime($now);
  153:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  154: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  155: 	print $fh $logstring;
  156: 	close($fh);
  157:     }
  158:     return 1;
  159: }
  160: 
  161: sub logperm {
  162:     my $message=shift;
  163:     my $execdir=$perlvar{'lonDaemons'};
  164:     my $now=time;
  165:     my $local=localtime($now);
  166:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  167: 	print $fh "$now:$message:$local\n";
  168: 	close($fh);
  169:     }
  170:     return 1;
  171: }
  172: 
  173: sub create_connection {
  174:     my ($hostname,$lonid) = @_;
  175:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  176: 				     Type    => SOCK_STREAM,
  177: 				     Timeout => 10);
  178:     return 0 if (!$client);
  179:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  180:     my $result = <$client>;
  181:     chomp($result);
  182:     return 1 if ($result eq 'done');
  183:     return 0;
  184: }
  185: 
  186: sub get_server_timezone {
  187:     my ($cnum,$cdom) = @_;
  188:     my $home=&homeserver($cnum,$cdom);
  189:     if ($home ne 'no_host') {
  190:         my $cachetime = 24*3600;
  191:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  192:         if (defined($cached)) {
  193:             return $timezone;
  194:         } else {
  195:             my $timezone = &reply('servertimezone',$home);
  196:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  197:         }
  198:     }
  199: }
  200: 
  201: sub get_server_distarch {
  202:     my ($lonhost,$ignore_cache) = @_;
  203:     if (defined($lonhost)) {
  204:         if (!defined(&hostname($lonhost))) {
  205:             return;
  206:         }
  207:         my $cachetime = 12*3600;
  208:         if (!$ignore_cache) {
  209:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  210:             if (defined($cached)) {
  211:                 return $distarch;
  212:             }
  213:         }
  214:         my $rep = &reply('serverdistarch',$lonhost);
  215:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  216:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  217:                 $rep eq '') {
  218:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  219:         }
  220:     }
  221:     return;
  222: }
  223: 
  224: sub get_server_loncaparev {
  225:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  226:     if (defined($lonhost)) {
  227:         if (!defined(&hostname($lonhost))) {
  228:             undef($lonhost);
  229:         }
  230:     }
  231:     if (!defined($lonhost)) {
  232:         if (defined(&domain($dom,'primary'))) {
  233:             $lonhost=&domain($dom,'primary');
  234:             if ($lonhost eq 'no_host') {
  235:                 undef($lonhost);
  236:             }
  237:         }
  238:     }
  239:     if (defined($lonhost)) {
  240:         my $cachetime = 12*3600;
  241:         if (!$ignore_cache) {
  242:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  243:             if (defined($cached)) {
  244:                 return $loncaparev;
  245:             }
  246:         }
  247:         my ($answer,$loncaparev);
  248:         my @ids=&current_machine_ids();
  249:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  250:             $answer = $perlvar{'lonVersion'};
  251:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  252:                 $loncaparev = $1;
  253:             }
  254:         } else {
  255:             $answer = &reply('serverloncaparev',$lonhost);
  256:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  257:                 if ($caller eq 'loncron') {
  258:                     my $ua=new LWP::UserAgent;
  259:                     $ua->timeout(4);
  260:                     my $protocol = $protocol{$lonhost};
  261:                     $protocol = 'http' if ($protocol ne 'https');
  262:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
  263:                     my $request=new HTTP::Request('GET',$url);
  264:                     my $response=$ua->request($request);
  265:                     unless ($response->is_error()) {
  266:                         my $content = $response->content;
  267:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  268:                             $loncaparev = $1;
  269:                         }
  270:                     }
  271:                 } else {
  272:                     $loncaparev = $loncaparevs{$lonhost};
  273:                 }
  274:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  275:                 $loncaparev = $1;
  276:             }
  277:         }
  278:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  279:     }
  280: }
  281: 
  282: sub get_server_homeID {
  283:     my ($hostname,$ignore_cache,$caller) = @_;
  284:     unless ($ignore_cache) {
  285:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  286:         if (defined($cached)) {
  287:             return $serverhomeID;
  288:         }
  289:     }
  290:     my $cachetime = 12*3600;
  291:     my $serverhomeID;
  292:     if ($caller eq 'loncron') { 
  293:         my @machine_ids = &machine_ids($hostname);
  294:         foreach my $id (@machine_ids) {
  295:             my $response = &reply('serverhomeID',$id);
  296:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  297:                 $serverhomeID = $response;
  298:                 last;
  299:             }
  300:         }
  301:         if ($serverhomeID eq '') {
  302:             $serverhomeID = $machine_ids[-1];
  303:         }
  304:     } else {
  305:         $serverhomeID = $serverhomeIDs{$hostname};
  306:     }
  307:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  308: }
  309: 
  310: sub get_remote_globals {
  311:     my ($lonhost,$whathash,$ignore_cache) = @_;
  312:     my ($result,%returnhash,%whatneeded);
  313:     if (ref($whathash) eq 'HASH') {
  314:         foreach my $what (sort(keys(%{$whathash}))) {
  315:             my $hashid = $lonhost.'-'.$what;
  316:             my ($response,$cached);
  317:             unless ($ignore_cache) {
  318:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  319:             }
  320:             if (defined($cached)) {
  321:                 $returnhash{$what} = $response;
  322:             } else {
  323:                 $whatneeded{$what} = 1;
  324:             }
  325:         }
  326:         if (keys(%whatneeded) == 0) {
  327:             $result = 'ok';
  328:         } else {
  329:             my $requested = &freeze_escape(\%whatneeded);
  330:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  331:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  332:                 ($rep eq 'unknown_cmd')) {
  333:                 $result = $rep;
  334:             } else {
  335:                 $result = 'ok';
  336:                 my @pairs=split(/\&/,$rep);
  337:                 foreach my $item (@pairs) {
  338:                     my ($key,$value)=split(/=/,$item,2);
  339:                     my $what = &unescape($key);
  340:                     my $hashid = $lonhost.'-'.$what;
  341:                     $returnhash{$what}=&thaw_unescape($value);
  342:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  343:                 }
  344:             }
  345:         }
  346:     }
  347:     return ($result,\%returnhash);
  348: }
  349: 
  350: sub remote_devalidate_cache {
  351:     my ($lonhost,$name,$id) = @_;
  352:     my $response = &reply('devalidatecache:'.&escape($name).':'.&escape($id),$lonhost);
  353:     return $response;
  354: }
  355: 
  356: # -------------------------------------------------- Non-critical communication
  357: sub subreply {
  358:     my ($cmd,$server)=@_;
  359:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  360:     #
  361:     #  With loncnew process trimming, there's a timing hole between lonc server
  362:     #  process exit and the master server picking up the listen on the AF_UNIX
  363:     #  socket.  In that time interval, a lock file will exist:
  364: 
  365:     my $lockfile=$peerfile.".lock";
  366:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  367: 	sleep(1);
  368:     }
  369:     # At this point, either a loncnew parent is listening or an old lonc
  370:     # or loncnew child is listening so we can connect or everything's dead.
  371:     #
  372:     #   We'll give the connection a few tries before abandoning it.  If
  373:     #   connection is not possible, we'll con_lost back to the client.
  374:     #   
  375:     my $client;
  376:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  377: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  378: 				      Type    => SOCK_STREAM,
  379: 				      Timeout => 10);
  380: 	if ($client) {
  381: 	    last;		# Connected!
  382: 	} else {
  383: 	    &create_connection(&hostname($server),$server);
  384: 	}
  385:         sleep(1);		# Try again later if failed connection.
  386:     }
  387:     my $answer;
  388:     if ($client) {
  389: 	print $client "sethost:$server:$cmd\n";
  390: 	$answer=<$client>;
  391: 	if (!$answer) { $answer="con_lost"; }
  392: 	chomp($answer);
  393:     } else {
  394: 	$answer = 'con_lost';	# Failed connection.
  395:     }
  396:     return $answer;
  397: }
  398: 
  399: sub reply {
  400:     my ($cmd,$server)=@_;
  401:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  402:     my $answer=subreply($cmd,$server);
  403:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  404:        &logthis("<font color=\"blue\">WARNING:".
  405:                 " $cmd to $server returned $answer</font>");
  406:     }
  407:     return $answer;
  408: }
  409: 
  410: # ----------------------------------------------------------- Send USR1 to lonc
  411: 
  412: sub reconlonc {
  413:     my ($lonid) = @_;
  414:     my $hostname = &hostname($lonid);
  415:     if ($lonid) {
  416: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  417: 	if ($hostname && -e $peerfile) {
  418: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  419: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  420: 					     Type    => SOCK_STREAM,
  421: 					     Timeout => 10);
  422: 	    if ($client) {
  423: 		print $client ("reset_retries\n");
  424: 		my $answer=<$client>;
  425: 		#reset just this one.
  426: 	    }
  427: 	}
  428: 	return;
  429:     }
  430: 
  431:     &logthis("Trying to reconnect lonc");
  432:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  433:     if (open(my $fh,"<$loncfile")) {
  434: 	my $loncpid=<$fh>;
  435:         chomp($loncpid);
  436:         if (kill 0 => $loncpid) {
  437: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  438:             kill USR1 => $loncpid;
  439:             sleep 1;
  440:          } else {
  441: 	    &logthis(
  442:                "<font color=\"blue\">WARNING:".
  443:                " lonc at pid $loncpid not responding, giving up</font>");
  444:         }
  445:     } else {
  446: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  447:     }
  448: }
  449: 
  450: # ------------------------------------------------------ Critical communication
  451: 
  452: sub critical {
  453:     my ($cmd,$server)=@_;
  454:     unless (&hostname($server)) {
  455:         &logthis("<font color=\"blue\">WARNING:".
  456:                " Critical message to unknown server ($server)</font>");
  457:         return 'no_such_host';
  458:     }
  459:     my $answer=reply($cmd,$server);
  460:     if ($answer eq 'con_lost') {
  461: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  462: 	my $answer=reply($cmd,$server);
  463:         if ($answer eq 'con_lost') {
  464:             my $now=time;
  465:             my $middlename=$cmd;
  466:             $middlename=substr($middlename,0,16);
  467:             $middlename=~s/\W//g;
  468:             my $dfilename=
  469:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  470:             $dumpcount++;
  471:             {
  472: 		my $dfh;
  473: 		if (open($dfh,">$dfilename")) {
  474: 		    print $dfh "$cmd\n"; 
  475: 		    close($dfh);
  476: 		}
  477:             }
  478:             sleep 2;
  479:             my $wcmd='';
  480:             {
  481: 		my $dfh;
  482: 		if (open($dfh,"<$dfilename")) {
  483: 		    $wcmd=<$dfh>; 
  484: 		    close($dfh);
  485: 		}
  486:             }
  487:             chomp($wcmd);
  488:             if ($wcmd eq $cmd) {
  489: 		&logthis("<font color=\"blue\">WARNING: ".
  490:                          "Connection buffer $dfilename: $cmd</font>");
  491:                 &logperm("D:$server:$cmd");
  492: 	        return 'con_delayed';
  493:             } else {
  494:                 &logthis("<font color=\"red\">CRITICAL:"
  495:                         ." Critical connection failed: $server $cmd</font>");
  496:                 &logperm("F:$server:$cmd");
  497:                 return 'con_failed';
  498:             }
  499:         }
  500:     }
  501:     return $answer;
  502: }
  503: 
  504: # ------------------------------------------- check if return value is an error
  505: 
  506: sub error {
  507:     my ($result) = @_;
  508:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  509: 	if ($2 == 2) { return undef; }
  510: 	return $1;
  511:     }
  512:     return undef;
  513: }
  514: 
  515: sub convert_and_load_session_env {
  516:     my ($lonidsdir,$handle)=@_;
  517:     my @profile;
  518:     {
  519: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  520: 	if (!$opened) {
  521: 	    return 0;
  522: 	}
  523: 	flock($idf,LOCK_SH);
  524: 	@profile=<$idf>;
  525: 	close($idf);
  526:     }
  527:     my %temp_env;
  528:     foreach my $line (@profile) {
  529: 	if ($line !~ m/=/) {
  530: 	    return 0;
  531: 	}
  532: 	chomp($line);
  533: 	my ($envname,$envvalue)=split(/=/,$line,2);
  534: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  535:     }
  536:     unlink("$lonidsdir/$handle.id");
  537:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  538: 	    0640)) {
  539: 	%disk_env = %temp_env;
  540: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  541: 	untie(%disk_env);
  542:     }
  543:     return 1;
  544: }
  545: 
  546: # ------------------------------------------- Transfer profile into environment
  547: my $env_loaded;
  548: sub transfer_profile_to_env {
  549:     my ($lonidsdir,$handle,$force_transfer) = @_;
  550:     if (!$force_transfer && $env_loaded) { return; } 
  551: 
  552:     if (!defined($lonidsdir)) {
  553: 	$lonidsdir = $perlvar{'lonIDsDir'};
  554:     }
  555:     if (!defined($handle)) {
  556:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  557:     }
  558: 
  559:     my $convert;
  560:     {
  561:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  562: 	if (!$opened) {
  563: 	    return;
  564: 	}
  565: 	flock($idf,LOCK_SH);
  566: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  567: 		&GDBM_READER(),0640)) {
  568: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  569: 	    untie(%disk_env);
  570: 	} else {
  571: 	    $convert = 1;
  572: 	}
  573:     }
  574:     if ($convert) {
  575: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  576: 	    &logthis("Failed to load session, or convert session.");
  577: 	}
  578:     }
  579: 
  580:     my %remove;
  581:     while ( my $envname = each(%env) ) {
  582:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  583:             if ($time < time-300) {
  584:                 $remove{$key}++;
  585:             }
  586:         }
  587:     }
  588: 
  589:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  590:     $env_loaded=1;
  591:     foreach my $expired_key (keys(%remove)) {
  592:         &delenv($expired_key);
  593:     }
  594: }
  595: 
  596: # ---------------------------------------------------- Check for valid session 
  597: sub check_for_valid_session {
  598:     my ($r) = @_;
  599:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  600:     my $lonid=$cookies{'lonID'};
  601:     return undef if (!$lonid);
  602: 
  603:     my $handle=&LONCAPA::clean_handle($lonid->value);
  604:     my $lonidsdir=$r->dir_config('lonIDsDir');
  605:     return undef if (!-e "$lonidsdir/$handle.id");
  606: 
  607:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  608:     return undef if (!$opened);
  609: 
  610:     flock($idf,LOCK_SH);
  611:     my %disk_env;
  612:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  613: 	    &GDBM_READER(),0640)) {
  614: 	return undef;	
  615:     }
  616: 
  617:     if (!defined($disk_env{'user.name'})
  618: 	|| !defined($disk_env{'user.domain'})) {
  619: 	return undef;
  620:     }
  621:     return $handle;
  622: }
  623: 
  624: sub timed_flock {
  625:     my ($file,$lock_type) = @_;
  626:     my $failed=0;
  627:     eval {
  628: 	local $SIG{__DIE__}='DEFAULT';
  629: 	local $SIG{ALRM}=sub {
  630: 	    $failed=1;
  631: 	    die("failed lock");
  632: 	};
  633: 	alarm(13);
  634: 	flock($file,$lock_type);
  635: 	alarm(0);
  636:     };
  637:     if ($failed) {
  638: 	return undef;
  639:     } else {
  640: 	return 1;
  641:     }
  642: }
  643: 
  644: # ---------------------------------------------------------- Append Environment
  645: 
  646: sub appenv {
  647:     my ($newenv,$roles) = @_;
  648:     if (ref($newenv) eq 'HASH') {
  649:         foreach my $key (keys(%{$newenv})) {
  650:             my $refused = 0;
  651: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  652:                 $refused = 1;
  653:                 if (ref($roles) eq 'ARRAY') {
  654:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
  655:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  656:                         $refused = 0;
  657:                     }
  658:                 }
  659:             }
  660:             if ($refused) {
  661:                 &logthis("<font color=\"blue\">WARNING: ".
  662:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  663:                          .'</font>');
  664: 	        delete($newenv->{$key});
  665:             } else {
  666:                 $env{$key}=$newenv->{$key};
  667:             }
  668:         }
  669:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  670:         if ($opened
  671: 	    && &timed_flock($env_file,LOCK_EX)
  672: 	    &&
  673: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  674: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  675: 	    while (my ($key,$value) = each(%{$newenv})) {
  676: 	        $disk_env{$key} = $value;
  677: 	    }
  678: 	    untie(%disk_env);
  679:         }
  680:     }
  681:     return 'ok';
  682: }
  683: # ----------------------------------------------------- Delete from Environment
  684: 
  685: sub delenv {
  686:     my ($delthis,$regexp,$roles) = @_;
  687:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  688:         my $refused = 1;
  689:         if (ref($roles) eq 'ARRAY') {
  690:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  691:             if (grep(/^\Q$role\E$/,@{$roles})) {
  692:                 $refused = 0;
  693:             }
  694:         }
  695:         if ($refused) {
  696:             &logthis("<font color=\"blue\">WARNING: ".
  697:                      "Attempt to delete from environment ".$delthis);
  698:             return 'error';
  699:         }
  700:     }
  701:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  702:     if ($opened
  703: 	&& &timed_flock($env_file,LOCK_EX)
  704: 	&&
  705: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  706: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  707: 	foreach my $key (keys(%disk_env)) {
  708: 	    if ($regexp) {
  709:                 if ($key=~/^$delthis/) {
  710:                     delete($env{$key});
  711:                     delete($disk_env{$key});
  712:                 } 
  713:             } else {
  714:                 if ($key=~/^\Q$delthis\E/) {
  715: 		    delete($env{$key});
  716: 		    delete($disk_env{$key});
  717: 	        }
  718:             }
  719: 	}
  720: 	untie(%disk_env);
  721:     }
  722:     return 'ok';
  723: }
  724: 
  725: sub get_env_multiple {
  726:     my ($name) = @_;
  727:     my @values;
  728:     if (defined($env{$name})) {
  729:         # exists is it an array
  730:         if (ref($env{$name})) {
  731:             @values=@{ $env{$name} };
  732:         } else {
  733:             $values[0]=$env{$name};
  734:         }
  735:     }
  736:     return(@values);
  737: }
  738: 
  739: # ------------------------------------------------------------------- Locking
  740: 
  741: sub set_lock {
  742:     my ($text)=@_;
  743:     $locknum++;
  744:     my $id=$$.'-'.$locknum;
  745:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  746:              'session.lock.'.$id => $text});
  747:     return $id;
  748: }
  749: 
  750: sub get_locks {
  751:     my $num=0;
  752:     my %texts=();
  753:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  754:        if ($lock=~/\w/) {
  755:           $num++;
  756:           $texts{$lock}=$env{'session.lock.'.$lock};
  757:        }
  758:    }
  759:    return ($num,%texts);
  760: }
  761: 
  762: sub remove_lock {
  763:     my ($id)=@_;
  764:     my $newlocks='';
  765:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  766:        if (($lock=~/\w/) && ($lock ne $id)) {
  767:           $newlocks.=','.$lock;
  768:        }
  769:     }
  770:     &appenv({'session.locks' => $newlocks});
  771:     &delenv('session.lock.'.$id);
  772: }
  773: 
  774: sub remove_all_locks {
  775:     my $activelocks=$env{'session.locks'};
  776:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  777:        if ($lock=~/\w/) {
  778:           &remove_lock($lock);
  779:        }
  780:     }
  781: }
  782: 
  783: 
  784: # ------------------------------------------ Find out current server userload
  785: sub userload {
  786:     my $numusers=0;
  787:     {
  788: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  789: 	my $filename;
  790: 	my $curtime=time;
  791: 	while ($filename=readdir(LONIDS)) {
  792: 	    next if ($filename eq '.' || $filename eq '..');
  793: 	    next if ($filename =~ /publicuser_\d+\.id/);
  794: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  795: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  796: 	}
  797: 	closedir(LONIDS);
  798:     }
  799:     my $userloadpercent=0;
  800:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  801:     if ($maxuserload) {
  802: 	$userloadpercent=100*$numusers/$maxuserload;
  803:     }
  804:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  805:     return $userloadpercent;
  806: }
  807: 
  808: # ------------------------------ Find server with least workload from spare.tab
  809: 
  810: sub spareserver {
  811:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  812:     my $spare_server;
  813:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  814:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  815:                                                      :  $userloadpercent;
  816:     my ($uint_dom,$remotesessions);
  817:     if (($udom ne '') && (&domain($udom) ne '')) {
  818:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  819:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  820:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  821:         $remotesessions = $udomdefaults{'remotesessions'};
  822:     }
  823:     my $spareshash = &this_host_spares($udom);
  824:     if (ref($spareshash) eq 'HASH') {
  825:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  826:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  827:                 if ($uint_dom) {
  828:                     next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  829:                                                  $try_server));
  830:                 }
  831: 	        ($spare_server, $lowest_load) =
  832: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  833:             }
  834:         }
  835: 
  836:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
  837: 
  838:         if (!$found_server) {
  839:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
  840: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
  841:                     if ($uint_dom) {
  842:                         next unless (&spare_can_host($udom,$uint_dom,
  843:                                                      $remotesessions,$try_server));
  844:                     }
  845: 	            ($spare_server, $lowest_load) =
  846: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
  847:                 }
  848: 	    }
  849:         }
  850:     }
  851: 
  852:     if (!$want_server_name) {
  853:         my $protocol = 'http';
  854:         if ($protocol{$spare_server} eq 'https') {
  855:             $protocol = $protocol{$spare_server};
  856:         }
  857:         if (defined($spare_server)) {
  858:             my $hostname = &hostname($spare_server);
  859:             if (defined($hostname)) {
  860: 	        $spare_server = $protocol.'://'.$hostname;
  861:             }
  862:         }
  863:     }
  864:     return $spare_server;
  865: }
  866: 
  867: sub compare_server_load {
  868:     my ($try_server, $spare_server, $lowest_load) = @_;
  869: 
  870:     my $loadans     = &reply('load',    $try_server);
  871:     my $userloadans = &reply('userload',$try_server);
  872: 
  873:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  874: 	return ($spare_server, $lowest_load); #didn't get a number from the server
  875:     }
  876: 
  877:     my $load;
  878:     if ($loadans =~ /\d/) {
  879: 	if ($userloadans =~ /\d/) {
  880: 	    #both are numbers, pick the bigger one
  881: 	    $load = ($loadans > $userloadans) ? $loadans 
  882: 		                              : $userloadans;
  883: 	} else {
  884: 	    $load = $loadans;
  885: 	}
  886:     } else {
  887: 	$load = $userloadans;
  888:     }
  889: 
  890:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  891: 	$spare_server = $try_server;
  892: 	$lowest_load  = $load;
  893:     }
  894:     return ($spare_server,$lowest_load);
  895: }
  896: 
  897: # --------------------------- ask offload servers if user already has a session
  898: sub find_existing_session {
  899:     my ($udom,$uname) = @_;
  900:     my $spareshash = &this_host_spares($udom);
  901:     if (ref($spareshash) eq 'HASH') {
  902:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  903:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  904:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  905:             }
  906:         }
  907:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
  908:             foreach my $try_server (@{ $spareshash->{'default'} }) {
  909:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  910:             }
  911:         }
  912:     }
  913:     return;
  914: }
  915: 
  916: # -------------------------------- ask if server already has a session for user
  917: sub has_user_session {
  918:     my ($lonid,$udom,$uname) = @_;
  919:     my $result = &reply(join(':','userhassession',
  920: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  921:     return 1 if ($result eq 'ok');
  922: 
  923:     return 0;
  924: }
  925: 
  926: # --------- determine least loaded server in a user's domain which allows login
  927: 
  928: sub choose_server {
  929:     my ($udom,$checkloginvia) = @_;
  930:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
  931:     my %servers = &get_servers($udom);
  932:     my $lowest_load = 30000;
  933:     my ($login_host,$hostname,$portal_path);
  934:     foreach my $lonhost (keys(%servers)) {
  935:         my $loginvia;
  936:         if ($checkloginvia) {
  937:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
  938:             if ($loginvia) {
  939:                 my ($server,$path) = split(/:/,$loginvia);
  940:                 ($login_host, $lowest_load) =
  941:                     &compare_server_load($server, $login_host, $lowest_load);
  942:                 if ($login_host eq $server) {
  943:                     $portal_path = $path;
  944:                 }
  945:             } else {
  946:                 ($login_host, $lowest_load) =
  947:                     &compare_server_load($lonhost, $login_host, $lowest_load);
  948:                 if ($login_host eq $lonhost) {
  949:                     $portal_path = '';
  950:                 }
  951:             }
  952:         } else {
  953:             ($login_host, $lowest_load) =
  954:                 &compare_server_load($lonhost, $login_host, $lowest_load);
  955:         }
  956:     }
  957:     if ($login_host ne '') {
  958:         $hostname = &hostname($login_host);
  959:     }
  960:     return ($login_host,$hostname,$portal_path);
  961: }
  962: 
  963: # --------------------------------------------- Try to change a user's password
  964: 
  965: sub changepass {
  966:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  967:     $currentpass = &escape($currentpass);
  968:     $newpass     = &escape($newpass);
  969:     my $lonhost = $perlvar{'lonHostID'};
  970:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
  971: 		       $server);
  972:     if (! $answer) {
  973: 	&logthis("No reply on password change request to $server ".
  974: 		 "by $uname in domain $udom.");
  975:     } elsif ($answer =~ "^ok") {
  976:         &logthis("$uname in $udom successfully changed their password ".
  977: 		 "on $server.");
  978:     } elsif ($answer =~ "^pwchange_failure") {
  979: 	&logthis("$uname in $udom was unable to change their password ".
  980: 		 "on $server.  The action was blocked by either lcpasswd ".
  981: 		 "or pwchange");
  982:     } elsif ($answer =~ "^non_authorized") {
  983:         &logthis("$uname in $udom did not get their password correct when ".
  984: 		 "attempting to change it on $server.");
  985:     } elsif ($answer =~ "^auth_mode_error") {
  986:         &logthis("$uname in $udom attempted to change their password despite ".
  987: 		 "not being locally or internally authenticated on $server.");
  988:     } elsif ($answer =~ "^unknown_user") {
  989:         &logthis("$uname in $udom attempted to change their password ".
  990: 		 "on $server but were unable to because $server is not ".
  991: 		 "their home server.");
  992:     } elsif ($answer =~ "^refused") {
  993: 	&logthis("$server refused to change $uname in $udom password because ".
  994: 		 "it was sent an unencrypted request to change the password.");
  995:     } elsif ($answer =~ "invalid_client") {
  996:         &logthis("$server refused to change $uname in $udom password because ".
  997:                  "it was a reset by e-mail originating from an invalid server.");
  998:     }
  999:     return $answer;
 1000: }
 1001: 
 1002: # ----------------------- Try to determine user's current authentication scheme
 1003: 
 1004: sub queryauthenticate {
 1005:     my ($uname,$udom)=@_;
 1006:     my $uhome=&homeserver($uname,$udom);
 1007:     if (!$uhome) {
 1008: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1009: 	return 'no_host';
 1010:     }
 1011:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1012:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1013: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1014:     }
 1015:     return $answer;
 1016: }
 1017: 
 1018: # --------- Try to authenticate user from domain's lib servers (first this one)
 1019: 
 1020: sub authenticate {
 1021:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1022:     $upass=&escape($upass);
 1023:     $uname= &LONCAPA::clean_username($uname);
 1024:     my $uhome=&homeserver($uname,$udom,1);
 1025:     my $newhome;
 1026:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1027: # Maybe the machine was offline and only re-appeared again recently?
 1028:         &reconlonc();
 1029: # One more
 1030: 	$uhome=&homeserver($uname,$udom,1);
 1031:         if (($uhome eq 'no_host') && $checkdefauth) {
 1032:             if (defined(&domain($udom,'primary'))) {
 1033:                 $newhome=&domain($udom,'primary');
 1034:             }
 1035:             if ($newhome ne '') {
 1036:                 $uhome = $newhome;
 1037:             }
 1038:         }
 1039: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1040: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1041: 	    return 'no_host';
 1042:         }
 1043:     }
 1044:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1045:     if ($answer eq 'authorized') {
 1046:         if ($newhome) {
 1047:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1048:             return 'no_account_on_host'; 
 1049:         } else {
 1050:             &logthis("User $uname at $udom authorized by $uhome");
 1051:             return $uhome;
 1052:         }
 1053:     }
 1054:     if ($answer eq 'non_authorized') {
 1055: 	&logthis("User $uname at $udom rejected by $uhome");
 1056: 	return 'no_host'; 
 1057:     }
 1058:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1059:     return 'no_host';
 1060: }
 1061: 
 1062: sub can_host_session {
 1063:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1064:     my $canhost = 1;
 1065:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1066:     if (ref($remotesessions) eq 'HASH') {
 1067:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1068:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1069:                 $canhost = 0;
 1070:             } else {
 1071:                 $canhost = 1;
 1072:             }
 1073:         }
 1074:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1075:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1076:                 $canhost = 1;
 1077:             } else {
 1078:                 $canhost = 0;
 1079:             }
 1080:         }
 1081:         if ($canhost) {
 1082:             if ($remotesessions->{'version'} ne '') {
 1083:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1084:                 if ($reqmajor ne '' && $reqminor ne '') {
 1085:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1086:                         my $major = $1;
 1087:                         my $minor = $2;
 1088:                         if (($major < $reqmajor ) ||
 1089:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1090:                             $canhost = 0;
 1091:                         }
 1092:                     } else {
 1093:                         $canhost = 0;
 1094:                     }
 1095:                 }
 1096:             }
 1097:         }
 1098:     }
 1099:     if ($canhost) {
 1100:         if (ref($hostedsessions) eq 'HASH') {
 1101:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1102:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1103:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1104:                 if (($uint_dom ne '') && 
 1105:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1106:                     $canhost = 0;
 1107:                 } else {
 1108:                     $canhost = 1;
 1109:                 }
 1110:             }
 1111:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1112:                 if (($uint_dom ne '') && 
 1113:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1114:                     $canhost = 1;
 1115:                 } else {
 1116:                     $canhost = 0;
 1117:                 }
 1118:             }
 1119:         }
 1120:     }
 1121:     return $canhost;
 1122: }
 1123: 
 1124: sub spare_can_host {
 1125:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1126:     my $canhost=1;
 1127:     my @intdoms;
 1128:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
 1129:     if (ref($internet_names) eq 'ARRAY') {
 1130:         @intdoms = @{$internet_names};
 1131:     }
 1132:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1133:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
 1134:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
 1135:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
 1136:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
 1137:         $canhost = &can_host_session($udom,$try_server,$remoterev,
 1138:                                      $remotesessions,
 1139:                                      $defdomdefaults{'hostedsessions'});
 1140:     }
 1141:     return $canhost;
 1142: }
 1143: 
 1144: sub this_host_spares {
 1145:     my ($dom) = @_;
 1146:     my ($dom_in_use,$lonhost_in_use,$result);
 1147:     my @hosts = &current_machine_ids();
 1148:     foreach my $lonhost (@hosts) {
 1149:         if (&host_domain($lonhost) eq $dom) {
 1150:             $dom_in_use = $dom;
 1151:             $lonhost_in_use = $lonhost;
 1152:             last;
 1153:         }
 1154:     }
 1155:     if ($dom_in_use ne '') {
 1156:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1157:     }
 1158:     if (ref($result) ne 'HASH') {
 1159:         $lonhost_in_use = $perlvar{'lonHostID'};
 1160:         $dom_in_use = &host_domain($lonhost_in_use);
 1161:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1162:         if (ref($result) ne 'HASH') {
 1163:             $result = \%spareid;
 1164:         }
 1165:     }
 1166:     return $result;
 1167: }
 1168: 
 1169: sub spares_for_offload  {
 1170:     my ($dom_in_use,$lonhost_in_use) = @_;
 1171:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1172:     if (defined($cached)) {
 1173:         return $result;
 1174:     } else {
 1175:         my $cachetime = 60*60*24;
 1176:         my %domconfig =
 1177:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1178:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1179:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1180:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1181:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1182:                 }
 1183:             }
 1184:         }
 1185:     }
 1186:     return;
 1187: }
 1188: 
 1189: sub get_lonbalancer_config {
 1190:     my ($servers) = @_;
 1191:     my ($currbalancer,$currtargets);
 1192:     if (ref($servers) eq 'HASH') {
 1193:         foreach my $server (keys(%{$servers})) {
 1194:             my %what = (
 1195:                          spareid => 1,
 1196:                          perlvar => 1,
 1197:                        );
 1198:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1199:             if ($result eq 'ok') {
 1200:                 if (ref($returnhash) eq 'HASH') {
 1201:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1202:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1203:                             $currbalancer = $server;
 1204:                             $currtargets = {};
 1205:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1206:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1207:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1208:                                 }
 1209:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1210:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1211:                                 }
 1212:                             }
 1213:                             last;
 1214:                         }
 1215:                     }
 1216:                 }
 1217:             }
 1218:         }
 1219:     }
 1220:     return ($currbalancer,$currtargets);
 1221: }
 1222: 
 1223: sub check_loadbalancing {
 1224:     my ($uname,$udom) = @_;
 1225:     my ($is_balancer,$dom_in_use,$homeintdom,$rule_in_effect,
 1226:         $offloadto,$otherserver);
 1227:     my $lonhost = $perlvar{'lonHostID'};
 1228:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1229:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1230:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1231:     my $serverhomedom = &host_domain($lonhost);
 1232: 
 1233:     my $cachetime = 60*60*24;
 1234: 
 1235:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1236:         $dom_in_use = $udom;
 1237:         $homeintdom = 1;
 1238:     } else {
 1239:         $dom_in_use = $serverhomedom;
 1240:     }
 1241:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1242:     unless (defined($cached)) {
 1243:         my %domconfig =
 1244:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1245:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1246:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1247:         }
 1248:     }
 1249:     if (ref($result) eq 'HASH') {
 1250:         my $currbalancer = $result->{'lonhost'};
 1251:         my $currtargets = $result->{'targets'};
 1252:         my $currrules = $result->{'rules'};
 1253:         if ($currbalancer ne '') {
 1254:             my @hosts = &current_machine_ids();
 1255:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1256:                 $is_balancer = 1;
 1257:             }
 1258:         }
 1259:         if ($is_balancer) {
 1260:             if (ref($currrules) eq 'HASH') {
 1261:                 if ($homeintdom) {
 1262:                     if ($uname ne '') {
 1263:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1264:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1265:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1266:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1267:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1268:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1269:                             }
 1270:                         }
 1271:                         if ($rule_in_effect eq '') {
 1272:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1273:                             if ($userenv{'inststatus'} ne '') {
 1274:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1275:                                 my ($othertitle,$usertypes,$types) =
 1276:                                     &Apache::loncommon::sorted_inst_types($udom);
 1277:                                 if (ref($types) eq 'ARRAY') {
 1278:                                     foreach my $type (@{$types}) {
 1279:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1280:                                             if (exists($currrules->{$type})) {
 1281:                                                 $rule_in_effect = $currrules->{$type};
 1282:                                             }
 1283:                                         }
 1284:                                     }
 1285:                                 }
 1286:                             } else {
 1287:                                 if (exists($currrules->{'default'})) {
 1288:                                     $rule_in_effect = $currrules->{'default'};
 1289:                                 }
 1290:                             }
 1291:                         }
 1292:                     } else {
 1293:                         if (exists($currrules->{'default'})) {
 1294:                             $rule_in_effect = $currrules->{'default'};
 1295:                         }
 1296:                     }
 1297:                 } else {
 1298:                     if ($currrules->{'_LC_external'} ne '') {
 1299:                         $rule_in_effect = $currrules->{'_LC_external'};
 1300:                     }
 1301:                 }
 1302:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1303:                                                        $uname,$udom);
 1304:             }
 1305:         }
 1306:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1307:         my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1308:         unless (defined($cached)) {
 1309:             my %domconfig =
 1310:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1311:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1312:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1313:             }
 1314:         }
 1315:         if (ref($result) eq 'HASH') {
 1316:             my $currbalancer = $result->{'lonhost'};
 1317:             my $currtargets = $result->{'targets'};
 1318:             my $currrules = $result->{'rules'};
 1319: 
 1320:             if ($currbalancer eq $lonhost) {
 1321:                 $is_balancer = 1;
 1322:                 if (ref($currrules) eq 'HASH') {
 1323:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1324:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1325:                     }
 1326:                 }
 1327:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1328:                                                        $uname,$udom);
 1329:             }
 1330:         } else {
 1331:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1332:                 $is_balancer = 1;
 1333:                 $offloadto = &this_host_spares($dom_in_use);
 1334:             }
 1335:         }
 1336:     } else {
 1337:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1338:             $is_balancer = 1;
 1339:             $offloadto = &this_host_spares($dom_in_use);
 1340:         }
 1341:     }
 1342:     my $lowest_load = 30000;
 1343:     if (ref($offloadto) eq 'HASH') {
 1344:         if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1345:             foreach my $try_server (@{$offloadto->{'primary'}}) {
 1346:                 ($otherserver,$lowest_load) =
 1347:                     &compare_server_load($try_server,$otherserver,$lowest_load);
 1348:             }
 1349:         }
 1350:         my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1351: 
 1352:         if (!$found_server) {
 1353:             if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1354:                 foreach my $try_server (@{$offloadto->{'default'}}) {
 1355:                     ($otherserver,$lowest_load) =
 1356:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1357:                 }
 1358:             }
 1359:         }
 1360:     } elsif (ref($offloadto) eq 'ARRAY') {
 1361:         if (@{$offloadto} == 1) {
 1362:             $otherserver = $offloadto->[0];
 1363:         } elsif (@{$offloadto} > 1) {
 1364:             foreach my $try_server (@{$offloadto}) {
 1365:                 ($otherserver,$lowest_load) =
 1366:                     &compare_server_load($try_server,$otherserver,$lowest_load);
 1367:             }
 1368:         }
 1369:     }
 1370:     return ($is_balancer,$otherserver);
 1371: }
 1372: 
 1373: sub get_loadbalancer_targets {
 1374:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1375:     my $offloadto;
 1376:     if ($rule_in_effect eq '') {
 1377:         $offloadto = $currtargets;
 1378:     } else {
 1379:         if ($rule_in_effect eq 'homeserver') {
 1380:             my $homeserver = &homeserver($uname,$udom);
 1381:             if ($homeserver ne 'no_host') {
 1382:                 $offloadto = [$homeserver];
 1383:             }
 1384:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1385:             my %domconfig =
 1386:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1387:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1388:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1389:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1390:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1391:                     }
 1392:                 }
 1393:             } else {
 1394:                 my %servers = &dom_servers($udom);
 1395:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1396:                 if (&hostname($remotebalancer) ne '') {
 1397:                     $offloadto = [$remotebalancer];
 1398:                 }
 1399:             }
 1400:         } elsif (&hostname($rule_in_effect) ne '') {
 1401:             $offloadto = [$rule_in_effect];
 1402:         }
 1403:     }
 1404:     return $offloadto;
 1405: }
 1406: 
 1407: sub internet_dom_servers {
 1408:     my ($dom) = @_;
 1409:     my (%uniqservers,%servers);
 1410:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1411:     my @machinedoms = &machine_domains($primaryserver);
 1412:     foreach my $mdom (@machinedoms) {
 1413:         my %currservers = %servers;
 1414:         my %server = &get_servers($mdom);
 1415:         %servers = (%currservers,%server);
 1416:     }
 1417:     my %by_hostname;
 1418:     foreach my $id (keys(%servers)) {
 1419:         push(@{$by_hostname{$servers{$id}}},$id);
 1420:     }
 1421:     foreach my $hostname (sort(keys(%by_hostname))) {
 1422:         if (@{$by_hostname{$hostname}} > 1) {
 1423:             my $match = 0;
 1424:             foreach my $id (@{$by_hostname{$hostname}}) {
 1425:                 if (&host_domain($id) eq $dom) {
 1426:                     $uniqservers{$id} = $hostname;
 1427:                     $match = 1;
 1428:                 }
 1429:             }
 1430:             unless ($match) {
 1431:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1432:             }
 1433:         } else {
 1434:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1435:         }
 1436:     }
 1437:     return %uniqservers;
 1438: }
 1439: 
 1440: # ---------------------- Find the homebase for a user from domain's lib servers
 1441: 
 1442: my %homecache;
 1443: sub homeserver {
 1444:     my ($uname,$udom,$ignoreBadCache)=@_;
 1445:     my $index="$uname:$udom";
 1446: 
 1447:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1448: 
 1449:     my %servers = &get_servers($udom,'library');
 1450:     foreach my $tryserver (keys(%servers)) {
 1451:         next if ($ignoreBadCache ne 'true' && 
 1452: 		 exists($badServerCache{$tryserver}));
 1453: 
 1454: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1455: 	if ($answer eq 'found') {
 1456: 	    delete($badServerCache{$tryserver}); 
 1457: 	    return $homecache{$index}=$tryserver;
 1458: 	} elsif ($answer eq 'no_host') {
 1459: 	    $badServerCache{$tryserver}=1;
 1460: 	}
 1461:     }    
 1462:     return 'no_host';
 1463: }
 1464: 
 1465: # ------------------------------------- Find the usernames behind a list of IDs
 1466: 
 1467: sub idget {
 1468:     my ($udom,@ids)=@_;
 1469:     my %returnhash=();
 1470:     
 1471:     my %servers = &get_servers($udom,'library');
 1472:     foreach my $tryserver (keys(%servers)) {
 1473: 	my $idlist=join('&',@ids);
 1474: 	$idlist=~tr/A-Z/a-z/; 
 1475: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1476: 	my @answer=();
 1477: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1478: 	    @answer=split(/\&/,$reply);
 1479: 	}                    ;
 1480: 	my $i;
 1481: 	for ($i=0;$i<=$#ids;$i++) {
 1482: 	    if ($answer[$i]) {
 1483: 		$returnhash{$ids[$i]}=$answer[$i];
 1484: 	    } 
 1485: 	}
 1486:     } 
 1487:     return %returnhash;
 1488: }
 1489: 
 1490: # ------------------------------------- Find the IDs behind a list of usernames
 1491: 
 1492: sub idrget {
 1493:     my ($udom,@unames)=@_;
 1494:     my %returnhash=();
 1495:     foreach my $uname (@unames) {
 1496:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1497:     }
 1498:     return %returnhash;
 1499: }
 1500: 
 1501: # ------------------------------- Store away a list of names and associated IDs
 1502: 
 1503: sub idput {
 1504:     my ($udom,%ids)=@_;
 1505:     my %servers=();
 1506:     foreach my $uname (keys(%ids)) {
 1507: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1508:         my $uhom=&homeserver($uname,$udom);
 1509:         if ($uhom ne 'no_host') {
 1510:             my $id=&escape($ids{$uname});
 1511:             $id=~tr/A-Z/a-z/;
 1512:             my $esc_unam=&escape($uname);
 1513: 	    if ($servers{$uhom}) {
 1514: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
 1515:             } else {
 1516:                 $servers{$uhom}=$id.'='.$esc_unam;
 1517:             }
 1518:         }
 1519:     }
 1520:     foreach my $server (keys(%servers)) {
 1521:         &critical('idput:'.$udom.':'.$servers{$server},$server);
 1522:     }
 1523: }
 1524: 
 1525: # ------------------------------dump from db file owned by domainconfig user
 1526: sub dump_dom {
 1527:     my ($namespace,$udom,$regexp,$range)=@_;
 1528:     if (!$udom) {
 1529:         $udom=$env{'user.domain'};
 1530:     }
 1531:     my %returnhash;
 1532:     if ($udom) {
 1533:         my $uname = &get_domainconfiguser($udom);
 1534:         %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
 1535:     }
 1536:     return %returnhash;
 1537: }
 1538: 
 1539: # ------------------------------------------ get items from domain db files   
 1540: 
 1541: sub get_dom {
 1542:     my ($namespace,$storearr,$udom,$uhome)=@_;
 1543:     my $items='';
 1544:     foreach my $item (@$storearr) {
 1545:         $items.=&escape($item).'&';
 1546:     }
 1547:     $items=~s/\&$//;
 1548:     if (!$udom) {
 1549:         $udom=$env{'user.domain'};
 1550:         if (defined(&domain($udom,'primary'))) {
 1551:             $uhome=&domain($udom,'primary');
 1552:         } else {
 1553:             undef($uhome);
 1554:         }
 1555:     } else {
 1556:         if (!$uhome) {
 1557:             if (defined(&domain($udom,'primary'))) {
 1558:                 $uhome=&domain($udom,'primary');
 1559:             }
 1560:         }
 1561:     }
 1562:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1563:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 1564:         my %returnhash;
 1565:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 1566:             return %returnhash;
 1567:         }
 1568:         my @pairs=split(/\&/,$rep);
 1569:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1570:             return @pairs;
 1571:         }
 1572:         my $i=0;
 1573:         foreach my $item (@$storearr) {
 1574:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 1575:             $i++;
 1576:         }
 1577:         return %returnhash;
 1578:     } else {
 1579:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1580:     }
 1581: }
 1582: 
 1583: # -------------------------------------------- put items in domain db files 
 1584: 
 1585: sub put_dom {
 1586:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1587:     if (!$udom) {
 1588:         $udom=$env{'user.domain'};
 1589:         if (defined(&domain($udom,'primary'))) {
 1590:             $uhome=&domain($udom,'primary');
 1591:         } else {
 1592:             undef($uhome);
 1593:         }
 1594:     } else {
 1595:         if (!$uhome) {
 1596:             if (defined(&domain($udom,'primary'))) {
 1597:                 $uhome=&domain($udom,'primary');
 1598:             }
 1599:         }
 1600:     } 
 1601:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1602:         my $items='';
 1603:         foreach my $item (keys(%$storehash)) {
 1604:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 1605:         }
 1606:         $items=~s/\&$//;
 1607:         return &reply("putdom:$udom:$namespace:$items",$uhome);
 1608:     } else {
 1609:         &logthis("put_dom failed - no homeserver and/or domain");
 1610:     }
 1611: }
 1612: 
 1613: # --------------------- newput for items in db file owned by domainconfig user
 1614: sub newput_dom {
 1615:     my ($namespace,$storehash,$udom) = @_;
 1616:     my $result;
 1617:     if (!$udom) {
 1618:         $udom=$env{'user.domain'};
 1619:     }
 1620:     if ($udom) {
 1621:         my $uname = &get_domainconfiguser($udom);
 1622:         $result = &newput($namespace,$storehash,$udom,$uname);
 1623:     }
 1624:     return $result;
 1625: }
 1626: 
 1627: # --------------------- delete for items in db file owned by domainconfig user
 1628: sub del_dom {
 1629:     my ($namespace,$storearr,$udom)=@_;
 1630:     if (ref($storearr) eq 'ARRAY') {
 1631:         if (!$udom) {
 1632:             $udom=$env{'user.domain'};
 1633:         }
 1634:         if ($udom) {
 1635:             my $uname = &get_domainconfiguser($udom); 
 1636:             return &del($namespace,$storearr,$udom,$uname);
 1637:         }
 1638:     }
 1639: }
 1640: 
 1641: # ----------------------------------construct domainconfig user for a domain 
 1642: sub get_domainconfiguser {
 1643:     my ($udom) = @_;
 1644:     return $udom.'-domainconfig';
 1645: }
 1646: 
 1647: sub retrieve_inst_usertypes {
 1648:     my ($udom) = @_;
 1649:     my (%returnhash,@order);
 1650:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 1651:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 1652:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 1653:         %returnhash = %{$domdefs{'inststatustypes'}};
 1654:         @order = @{$domdefs{'inststatusorder'}};
 1655:     } else {
 1656:         if (defined(&domain($udom,'primary'))) {
 1657:             my $uhome=&domain($udom,'primary');
 1658:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 1659:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 1660:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
 1661:                 return (\%returnhash,\@order);
 1662:             }
 1663:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 1664:             my @pairs=split(/\&/,$hashitems);
 1665:             foreach my $item (@pairs) {
 1666:                 my ($key,$value)=split(/=/,$item,2);
 1667:                 $key = &unescape($key);
 1668:                 next if ($key =~ /^error: 2 /);
 1669:                 $returnhash{$key}=&thaw_unescape($value);
 1670:             }
 1671:             my @esc_order = split(/\&/,$orderitems);
 1672:             foreach my $item (@esc_order) {
 1673:                 push(@order,&unescape($item));
 1674:             }
 1675:         } else {
 1676:             &logthis("get_dom failed - no primary domain server for $udom");
 1677:         }
 1678:     }
 1679:     return (\%returnhash,\@order);
 1680: }
 1681: 
 1682: sub is_domainimage {
 1683:     my ($url) = @_;
 1684:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1685:         if (&domain($1) ne '') {
 1686:             return '1';
 1687:         }
 1688:     }
 1689:     return;
 1690: }
 1691: 
 1692: sub inst_directory_query {
 1693:     my ($srch) = @_;
 1694:     my $udom = $srch->{'srchdomain'};
 1695:     my %results;
 1696:     my $homeserver = &domain($udom,'primary');
 1697:     my $outcome;
 1698:     if ($homeserver ne '') {
 1699: 	my $queryid=&reply("querysend:instdirsearch:".
 1700: 			   &escape($srch->{'srchby'}).':'.
 1701: 			   &escape($srch->{'srchterm'}).':'.
 1702: 			   &escape($srch->{'srchtype'}),$homeserver);
 1703: 	my $host=&hostname($homeserver);
 1704: 	if ($queryid !~/^\Q$host\E\_/) {
 1705: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1706: 	    return;
 1707: 	}
 1708: 	my $response = &get_query_reply($queryid);
 1709: 	my $maxtries = 5;
 1710: 	my $tries = 1;
 1711: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1712: 	    $response = &get_query_reply($queryid);
 1713: 	    $tries ++;
 1714: 	}
 1715: 
 1716:         if (!&error($response) && $response ne 'refused') {
 1717:             if ($response eq 'unavailable') {
 1718:                 $outcome = $response;
 1719:             } else {
 1720:                 $outcome = 'ok';
 1721:                 my @matches = split(/\n/,$response);
 1722:                 foreach my $match (@matches) {
 1723:                     my ($key,$value) = split(/=/,$match);
 1724:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1725:                 }
 1726:             }
 1727:         }
 1728:     }
 1729:     return ($outcome,%results);
 1730: }
 1731: 
 1732: sub usersearch {
 1733:     my ($srch) = @_;
 1734:     my $dom = $srch->{'srchdomain'};
 1735:     my %results;
 1736:     my %libserv = &all_library();
 1737:     my $query = 'usersearch';
 1738:     foreach my $tryserver (keys(%libserv)) {
 1739:         if (&host_domain($tryserver) eq $dom) {
 1740:             my $host=&hostname($tryserver);
 1741:             my $queryid=
 1742:                 &reply("querysend:".&escape($query).':'.
 1743:                        &escape($srch->{'srchby'}).':'.
 1744:                        &escape($srch->{'srchtype'}).':'.
 1745:                        &escape($srch->{'srchterm'}),$tryserver);
 1746:             if ($queryid !~/^\Q$host\E\_/) {
 1747:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1748:                 next;
 1749:             }
 1750:             my $reply = &get_query_reply($queryid);
 1751:             my $maxtries = 1;
 1752:             my $tries = 1;
 1753:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1754:                 $reply = &get_query_reply($queryid);
 1755:                 $tries ++;
 1756:             }
 1757:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1758:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1759:             } else {
 1760:                 my @matches;
 1761:                 if ($reply =~ /\n/) {
 1762:                     @matches = split(/\n/,$reply);
 1763:                 } else {
 1764:                     @matches = split(/\&/,$reply);
 1765:                 }
 1766:                 foreach my $match (@matches) {
 1767:                     my ($uname,$udom,%userhash);
 1768:                     foreach my $entry (split(/:/,$match)) {
 1769:                         my ($key,$value) =
 1770:                             map {&unescape($_);} split(/=/,$entry);
 1771:                         $userhash{$key} = $value;
 1772:                         if ($key eq 'username') {
 1773:                             $uname = $value;
 1774:                         } elsif ($key eq 'domain') {
 1775:                             $udom = $value;
 1776:                         }
 1777:                     }
 1778:                     $results{$uname.':'.$udom} = \%userhash;
 1779:                 }
 1780:             }
 1781:         }
 1782:     }
 1783:     return %results;
 1784: }
 1785: 
 1786: sub get_instuser {
 1787:     my ($udom,$uname,$id) = @_;
 1788:     my $homeserver = &domain($udom,'primary');
 1789:     my ($outcome,%results);
 1790:     if ($homeserver ne '') {
 1791:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1792:                            &escape($id).':'.&escape($udom),$homeserver);
 1793:         my $host=&hostname($homeserver);
 1794:         if ($queryid !~/^\Q$host\E\_/) {
 1795:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1796:             return;
 1797:         }
 1798:         my $response = &get_query_reply($queryid);
 1799:         my $maxtries = 5;
 1800:         my $tries = 1;
 1801:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1802:             $response = &get_query_reply($queryid);
 1803:             $tries ++;
 1804:         }
 1805:         if (!&error($response) && $response ne 'refused') {
 1806:             if ($response eq 'unavailable') {
 1807:                 $outcome = $response;
 1808:             } else {
 1809:                 $outcome = 'ok';
 1810:                 my @matches = split(/\n/,$response);
 1811:                 foreach my $match (@matches) {
 1812:                     my ($key,$value) = split(/=/,$match);
 1813:                     $results{&unescape($key)} = &thaw_unescape($value);
 1814:                 }
 1815:             }
 1816:         }
 1817:     }
 1818:     my %userinfo;
 1819:     if (ref($results{$uname}) eq 'HASH') {
 1820:         %userinfo = %{$results{$uname}};
 1821:     } 
 1822:     return ($outcome,%userinfo);
 1823: }
 1824: 
 1825: sub inst_rulecheck {
 1826:     my ($udom,$uname,$id,$item,$rules) = @_;
 1827:     my %returnhash;
 1828:     if ($udom ne '') {
 1829:         if (ref($rules) eq 'ARRAY') {
 1830:             @{$rules} = map {&escape($_);} (@{$rules});
 1831:             my $rulestr = join(':',@{$rules});
 1832:             my $homeserver=&domain($udom,'primary');
 1833:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1834:                 my $response;
 1835:                 if ($item eq 'username') {                
 1836:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1837:                                               ':'.&escape($uname).':'.$rulestr,
 1838:                                               $homeserver));
 1839:                 } elsif ($item eq 'id') {
 1840:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1841:                                               ':'.&escape($id).':'.$rulestr,
 1842:                                               $homeserver));
 1843:                 } elsif ($item eq 'selfcreate') {
 1844:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1845:                                                &escape($udom).':'.&escape($uname).
 1846:                                               ':'.$rulestr,$homeserver));
 1847:                 }
 1848:                 if ($response ne 'refused') {
 1849:                     my @pairs=split(/\&/,$response);
 1850:                     foreach my $item (@pairs) {
 1851:                         my ($key,$value)=split(/=/,$item,2);
 1852:                         $key = &unescape($key);
 1853:                         next if ($key =~ /^error: 2 /);
 1854:                         $returnhash{$key}=&thaw_unescape($value);
 1855:                     }
 1856:                 }
 1857:             }
 1858:         }
 1859:     }
 1860:     return %returnhash;
 1861: }
 1862: 
 1863: sub inst_userrules {
 1864:     my ($udom,$check) = @_;
 1865:     my (%ruleshash,@ruleorder);
 1866:     if ($udom ne '') {
 1867:         my $homeserver=&domain($udom,'primary');
 1868:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1869:             my $response;
 1870:             if ($check eq 'id') {
 1871:                 $response=&reply('instidrules:'.&escape($udom),
 1872:                                  $homeserver);
 1873:             } elsif ($check eq 'email') {
 1874:                 $response=&reply('instemailrules:'.&escape($udom),
 1875:                                  $homeserver);
 1876:             } else {
 1877:                 $response=&reply('instuserrules:'.&escape($udom),
 1878:                                  $homeserver);
 1879:             }
 1880:             if (($response ne 'refused') && ($response ne 'error') && 
 1881:                 ($response ne 'unknown_cmd') && 
 1882:                 ($response ne 'no_such_host')) {
 1883:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1884:                 my @pairs=split(/\&/,$hashitems);
 1885:                 foreach my $item (@pairs) {
 1886:                     my ($key,$value)=split(/=/,$item,2);
 1887:                     $key = &unescape($key);
 1888:                     next if ($key =~ /^error: 2 /);
 1889:                     $ruleshash{$key}=&thaw_unescape($value);
 1890:                 }
 1891:                 my @esc_order = split(/\&/,$orderitems);
 1892:                 foreach my $item (@esc_order) {
 1893:                     push(@ruleorder,&unescape($item));
 1894:                 }
 1895:             }
 1896:         }
 1897:     }
 1898:     return (\%ruleshash,\@ruleorder);
 1899: }
 1900: 
 1901: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 1902: 
 1903: sub get_domain_defaults {
 1904:     my ($domain) = @_;
 1905:     my $cachetime = 60*60*24;
 1906:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 1907:     if (defined($cached)) {
 1908:         if (ref($result) eq 'HASH') {
 1909:             return %{$result};
 1910:         }
 1911:     }
 1912:     my %domdefaults;
 1913:     my %domconfig =
 1914:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 1915:                                   'requestcourses','inststatus',
 1916:                                   'coursedefaults','usersessions'],$domain);
 1917:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 1918:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 1919:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 1920:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 1921:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 1922:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 1923:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 1924:     } else {
 1925:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 1926:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 1927:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 1928:     }
 1929:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 1930:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 1931:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 1932:         } else {
 1933:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 1934:         } 
 1935:         my @usertools = ('aboutme','blog','portfolio');
 1936:         foreach my $item (@usertools) {
 1937:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 1938:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 1939:             }
 1940:         }
 1941:     }
 1942:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 1943:         foreach my $item ('official','unofficial','community') {
 1944:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 1945:         }
 1946:     }
 1947:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 1948:         foreach my $item ('inststatustypes','inststatusorder') {
 1949:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 1950:         }
 1951:     }
 1952:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 1953:         foreach my $item ('canuse_pdfforms') {
 1954:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
 1955:         }
 1956:     }
 1957:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1958:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 1959:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 1960:         }
 1961:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 1962:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 1963:         }
 1964:     }
 1965:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
 1966:                                   $cachetime);
 1967:     return %domdefaults;
 1968: }
 1969: 
 1970: # --------------------------------------------------- Assign a key to a student
 1971: 
 1972: sub assign_access_key {
 1973: #
 1974: # a valid key looks like uname:udom#comments
 1975: # comments are being appended
 1976: #
 1977:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 1978:     $kdom=
 1979:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 1980:     $knum=
 1981:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 1982:     $cdom=
 1983:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1984:     $cnum=
 1985:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1986:     $udom=$env{'user.name'} unless (defined($udom));
 1987:     $uname=$env{'user.domain'} unless (defined($uname));
 1988:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 1989:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 1990:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 1991:                                                   # assigned to this person
 1992:                                                   # - this should not happen,
 1993:                                                   # unless something went wrong
 1994:                                                   # the first time around
 1995: # ready to assign
 1996:         $logentry=$1.'; '.$logentry;
 1997:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 1998:                                                  $kdom,$knum) eq 'ok') {
 1999: # key now belongs to user
 2000: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2001:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2002:                 &appenv({'environment.'.$envkey => $ckey});
 2003:                 return 'ok';
 2004:             } else {
 2005:                 return 
 2006:   'error: Count not permanently assign key, will need to be re-entered later.';
 2007: 	    }
 2008:         } else {
 2009:             return 'error: Could not assign key, try again later.';
 2010:         }
 2011:     } elsif (!$existing{$ckey}) {
 2012: # the key does not exist
 2013: 	return 'error: The key does not exist';
 2014:     } else {
 2015: # the key is somebody else's
 2016: 	return 'error: The key is already in use';
 2017:     }
 2018: }
 2019: 
 2020: # ------------------------------------------ put an additional comment on a key
 2021: 
 2022: sub comment_access_key {
 2023: #
 2024: # a valid key looks like uname:udom#comments
 2025: # comments are being appended
 2026: #
 2027:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2028:     $cdom=
 2029:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2030:     $cnum=
 2031:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2032:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2033:     if ($existing{$ckey}) {
 2034:         $existing{$ckey}.='; '.$logentry;
 2035: # ready to assign
 2036:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2037:                                                  $cdom,$cnum) eq 'ok') {
 2038: 	    return 'ok';
 2039:         } else {
 2040: 	    return 'error: Count not store comment.';
 2041:         }
 2042:     } else {
 2043: # the key does not exist
 2044: 	return 'error: The key does not exist';
 2045:     }
 2046: }
 2047: 
 2048: # ------------------------------------------------------ Generate a set of keys
 2049: 
 2050: sub generate_access_keys {
 2051:     my ($number,$cdom,$cnum,$logentry)=@_;
 2052:     $cdom=
 2053:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2054:     $cnum=
 2055:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2056:     unless (&allowed('mky',$cdom)) { return 0; }
 2057:     unless (($cdom) && ($cnum)) { return 0; }
 2058:     if ($number>10000) { return 0; }
 2059:     sleep(2); # make sure don't get same seed twice
 2060:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2061:     my $total=0;
 2062:     for (my $i=1;$i<=$number;$i++) {
 2063:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2064:                   sprintf("%lx",int(100000*rand)).'-'.
 2065:                   sprintf("%lx",int(100000*rand));
 2066:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2067:        $newkey=~s/0/h/g; # and also 0 and O
 2068:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2069:        if ($existing{$newkey}) {
 2070:            $i--;
 2071:        } else {
 2072: 	  if (&put('accesskeys',
 2073:               { $newkey => '# generated '.localtime().
 2074:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2075:                            '; '.$logentry },
 2076: 		   $cdom,$cnum) eq 'ok') {
 2077:               $total++;
 2078: 	  }
 2079:        }
 2080:     }
 2081:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2082:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2083:     return $total;
 2084: }
 2085: 
 2086: # ------------------------------------------------------- Validate an accesskey
 2087: 
 2088: sub validate_access_key {
 2089:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2090:     $cdom=
 2091:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2092:     $cnum=
 2093:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2094:     $udom=$env{'user.domain'} unless (defined($udom));
 2095:     $uname=$env{'user.name'} unless (defined($uname));
 2096:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2097:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2098: }
 2099: 
 2100: # ------------------------------------- Find the section of student in a course
 2101: sub devalidate_getsection_cache {
 2102:     my ($udom,$unam,$courseid)=@_;
 2103:     my $hashid="$udom:$unam:$courseid";
 2104:     &devalidate_cache_new('getsection',$hashid);
 2105: }
 2106: 
 2107: sub courseid_to_courseurl {
 2108:     my ($courseid) = @_;
 2109:     #already url style courseid
 2110:     return $courseid if ($courseid =~ m{^/});
 2111: 
 2112:     if (exists($env{'course.'.$courseid.'.num'})) {
 2113: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2114: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2115: 	return "/$cdom/$cnum";
 2116:     }
 2117: 
 2118:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2119:     if (exists($courseinfo{'num'})) {
 2120: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2121:     }
 2122: 
 2123:     return undef;
 2124: }
 2125: 
 2126: sub getsection {
 2127:     my ($udom,$unam,$courseid)=@_;
 2128:     my $cachetime=1800;
 2129: 
 2130:     my $hashid="$udom:$unam:$courseid";
 2131:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2132:     if (defined($cached)) { return $result; }
 2133: 
 2134:     my %Pending; 
 2135:     my %Expired;
 2136:     #
 2137:     # Each role can either have not started yet (pending), be active, 
 2138:     #    or have expired.
 2139:     #
 2140:     # If there is an active role, we are done.
 2141:     #
 2142:     # If there is more than one role which has not started yet, 
 2143:     #     choose the one which will start sooner
 2144:     # If there is one role which has not started yet, return it.
 2145:     #
 2146:     # If there is more than one expired role, choose the one which ended last.
 2147:     # If there is a role which has expired, return it.
 2148:     #
 2149:     $courseid = &courseid_to_courseurl($courseid);
 2150:     my $extra = &freeze_escape({'skipcheck' => 1});
 2151:     my %roleshash = &dump('roles',$udom,$unam,$courseid,undef,$extra);
 2152:     foreach my $key (keys(%roleshash)) {
 2153:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2154:         my $section=$1;
 2155:         if ($key eq $courseid.'_st') { $section=''; }
 2156:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2157:         my $now=time;
 2158:         if (defined($end) && $end && ($now > $end)) {
 2159:             $Expired{$end}=$section;
 2160:             next;
 2161:         }
 2162:         if (defined($start) && $start && ($now < $start)) {
 2163:             $Pending{$start}=$section;
 2164:             next;
 2165:         }
 2166:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2167:     }
 2168:     #
 2169:     # Presumedly there will be few matching roles from the above
 2170:     # loop and the sorting time will be negligible.
 2171:     if (scalar(keys(%Pending))) {
 2172:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2173:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2174:     } 
 2175:     if (scalar(keys(%Expired))) {
 2176:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2177:         my $time = pop(@sorted);
 2178:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2179:     }
 2180:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2181: }
 2182: 
 2183: sub save_cache {
 2184:     &purge_remembered();
 2185:     #&Apache::loncommon::validate_page();
 2186:     undef(%env);
 2187:     undef($env_loaded);
 2188: }
 2189: 
 2190: my $to_remember=-1;
 2191: my %remembered;
 2192: my %accessed;
 2193: my $kicks=0;
 2194: my $hits=0;
 2195: sub make_key {
 2196:     my ($name,$id) = @_;
 2197:     if (length($id) > 65 
 2198: 	&& length(&escape($id)) > 200) {
 2199: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2200:     }
 2201:     return &escape($name.':'.$id);
 2202: }
 2203: 
 2204: sub devalidate_cache_new {
 2205:     my ($name,$id,$debug) = @_;
 2206:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2207:     $id=&make_key($name,$id);
 2208:     $memcache->delete($id);
 2209:     delete($remembered{$id});
 2210:     delete($accessed{$id});
 2211: }
 2212: 
 2213: sub is_cached_new {
 2214:     my ($name,$id,$debug) = @_;
 2215:     $id=&make_key($name,$id);
 2216:     if (exists($remembered{$id})) {
 2217: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
 2218: 	$accessed{$id}=[&gettimeofday()];
 2219: 	$hits++;
 2220: 	return ($remembered{$id},1);
 2221:     }
 2222:     my $value = $memcache->get($id);
 2223:     if (!(defined($value))) {
 2224: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2225: 	return (undef,undef);
 2226:     }
 2227:     if ($value eq '__undef__') {
 2228: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2229: 	$value=undef;
 2230:     }
 2231:     &make_room($id,$value,$debug);
 2232:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2233:     return ($value,1);
 2234: }
 2235: 
 2236: sub do_cache_new {
 2237:     my ($name,$id,$value,$time,$debug) = @_;
 2238:     $id=&make_key($name,$id);
 2239:     my $setvalue=$value;
 2240:     if (!defined($setvalue)) {
 2241: 	$setvalue='__undef__';
 2242:     }
 2243:     if (!defined($time) ) {
 2244: 	$time=600;
 2245:     }
 2246:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 2247:     my $result = $memcache->set($id,$setvalue,$time);
 2248:     if (! $result) {
 2249: 	&logthis("caching of id -> $id  failed");
 2250: 	$memcache->disconnect_all();
 2251:     }
 2252:     # need to make a copy of $value
 2253:     &make_room($id,$value,$debug);
 2254:     return $value;
 2255: }
 2256: 
 2257: sub make_room {
 2258:     my ($id,$value,$debug)=@_;
 2259: 
 2260:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 2261:                                     : $value;
 2262:     if ($to_remember<0) { return; }
 2263:     $accessed{$id}=[&gettimeofday()];
 2264:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 2265:     my $to_kick;
 2266:     my $max_time=0;
 2267:     foreach my $other (keys(%accessed)) {
 2268: 	if (&tv_interval($accessed{$other}) > $max_time) {
 2269: 	    $to_kick=$other;
 2270: 	    $max_time=&tv_interval($accessed{$other});
 2271: 	}
 2272:     }
 2273:     delete($remembered{$to_kick});
 2274:     delete($accessed{$to_kick});
 2275:     $kicks++;
 2276:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 2277:     return;
 2278: }
 2279: 
 2280: sub purge_remembered {
 2281:     #&logthis("Tossing ".scalar(keys(%remembered)));
 2282:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 2283:     undef(%remembered);
 2284:     undef(%accessed);
 2285: }
 2286: # ------------------------------------- Read an entry from a user's environment
 2287: 
 2288: sub userenvironment {
 2289:     my ($udom,$unam,@what)=@_;
 2290:     my $items;
 2291:     foreach my $item (@what) {
 2292:         $items.=&escape($item).'&';
 2293:     }
 2294:     $items=~s/\&$//;
 2295:     my %returnhash=();
 2296:     my $uhome = &homeserver($unam,$udom);
 2297:     unless ($uhome eq 'no_host') {
 2298:         my @answer=split(/\&/, 
 2299:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 2300:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 2301:             return %returnhash;
 2302:         }
 2303:         my $i;
 2304:         for ($i=0;$i<=$#what;$i++) {
 2305: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 2306:         }
 2307:     }
 2308:     return %returnhash;
 2309: }
 2310: 
 2311: # ---------------------------------------------------------- Get a studentphoto
 2312: sub studentphoto {
 2313:     my ($udom,$unam,$ext) = @_;
 2314:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2315:     if (defined($env{'request.course.id'})) {
 2316:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 2317:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 2318:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 2319:             } else {
 2320:                 my ($result,$perm_reqd)=
 2321: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2322:                 if ($result eq 'ok') {
 2323:                     if (!($perm_reqd eq 'yes')) {
 2324:                         return(&retrievestudentphoto($udom,$unam,$ext));
 2325:                     }
 2326:                 }
 2327:             }
 2328:         }
 2329:     } else {
 2330:         my ($result,$perm_reqd) = 
 2331: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2332:         if ($result eq 'ok') {
 2333:             if (!($perm_reqd eq 'yes')) {
 2334:                 return(&retrievestudentphoto($udom,$unam,$ext));
 2335:             }
 2336:         }
 2337:     }
 2338:     return '/adm/lonKaputt/lonlogo_broken.gif';
 2339: }
 2340: 
 2341: sub retrievestudentphoto {
 2342:     my ($udom,$unam,$ext,$type) = @_;
 2343:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2344:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 2345:     if ($ret eq 'ok') {
 2346:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 2347:         if ($type eq 'thumbnail') {
 2348:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 2349:         }
 2350:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 2351:         return $tokenurl;
 2352:     } else {
 2353:         if ($type eq 'thumbnail') {
 2354:             return '/adm/lonKaputt/genericstudent_tn.gif';
 2355:         } else { 
 2356:             return '/adm/lonKaputt/lonlogo_broken.gif';
 2357:         }
 2358:     }
 2359: }
 2360: 
 2361: # -------------------------------------------------------------------- New chat
 2362: 
 2363: sub chatsend {
 2364:     my ($newentry,$anon,$group)=@_;
 2365:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 2366:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2367:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 2368:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 2369: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 2370: 		   &escape($newentry)).':'.$group,$chome);
 2371: }
 2372: 
 2373: # ------------------------------------------ Find current version of a resource
 2374: 
 2375: sub getversion {
 2376:     my $fname=&clutter(shift);
 2377:     unless ($fname=~/^\/res\//) { return -1; }
 2378:     return &currentversion(&filelocation('',$fname));
 2379: }
 2380: 
 2381: sub currentversion {
 2382:     my $fname=shift;
 2383:     my $author=$fname;
 2384:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2385:     my ($udom,$uname)=split(/\//,$author);
 2386:     my $home=&homeserver($uname,$udom);
 2387:     if ($home eq 'no_host') { 
 2388:         return -1; 
 2389:     }
 2390:     my $answer=&reply("currentversion:$fname",$home);
 2391:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2392: 	return -1;
 2393:     }
 2394:     return $answer;
 2395: }
 2396: 
 2397: #
 2398: # Return special version number of resource if set by override, empty otherwise
 2399: #
 2400: sub usedversion {
 2401:     my $fname=shift;
 2402:     unless ($fname) { $fname=$env{'request.uri'}; }
 2403:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 2404:     if ($urlversion) { return $urlversion; }
 2405:     return '';
 2406: }
 2407: 
 2408: # ----------------------------- Subscribe to a resource, return URL if possible
 2409: 
 2410: sub subscribe {
 2411:     my $fname=shift;
 2412:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 2413:     $fname=~s/[\n\r]//g;
 2414:     my $author=$fname;
 2415:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2416:     my ($udom,$uname)=split(/\//,$author);
 2417:     my $home=homeserver($uname,$udom);
 2418:     if ($home eq 'no_host') {
 2419:         return 'not_found';
 2420:     }
 2421:     my $answer=reply("sub:$fname",$home);
 2422:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2423: 	$answer.=' by '.$home;
 2424:     }
 2425:     return $answer;
 2426: }
 2427:     
 2428: # -------------------------------------------------------------- Replicate file
 2429: 
 2430: sub repcopy {
 2431:     my $filename=shift;
 2432:     $filename=~s/\/+/\//g;
 2433:     my $londocroot = $perlvar{'lonDocRoot'};
 2434:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 2435:     if ($filename=~m{^\Q$londocroot/lonUsers/\E}) { return 'ok'; }
 2436:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 2437: 	$filename=~m{^/*(uploaded|editupload)/}) {
 2438: 	return &repcopy_userfile($filename);
 2439:     }
 2440:     $filename=~s/[\n\r]//g;
 2441:     my $transname="$filename.in.transfer";
 2442: # FIXME: this should flock
 2443:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 2444:     my $remoteurl=subscribe($filename);
 2445:     if ($remoteurl =~ /^con_lost by/) {
 2446: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2447:            return 'unavailable';
 2448:     } elsif ($remoteurl eq 'not_found') {
 2449: 	   #&logthis("Subscribe returned not_found: $filename");
 2450: 	   return 'not_found';
 2451:     } elsif ($remoteurl =~ /^rejected by/) {
 2452: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2453:            return 'forbidden';
 2454:     } elsif ($remoteurl eq 'directory') {
 2455:            return 'ok';
 2456:     } else {
 2457:         my $author=$filename;
 2458:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2459:         my ($udom,$uname)=split(/\//,$author);
 2460:         my $home=homeserver($uname,$udom);
 2461:         unless ($home eq $perlvar{'lonHostID'}) {
 2462:            my @parts=split(/\//,$filename);
 2463:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 2464:            if ($path ne "$londocroot/res") {
 2465:                &logthis("Malconfiguration for replication: $filename");
 2466: 	       return 'bad_request';
 2467:            }
 2468:            my $count;
 2469:            for ($count=5;$count<$#parts;$count++) {
 2470:                $path.="/$parts[$count]";
 2471:                if ((-e $path)!=1) {
 2472: 		   mkdir($path,0777);
 2473:                }
 2474:            }
 2475:            my $ua=new LWP::UserAgent;
 2476:            my $request=new HTTP::Request('GET',"$remoteurl");
 2477:            my $response=$ua->request($request,$transname);
 2478:            if ($response->is_error()) {
 2479: 	       unlink($transname);
 2480:                my $message=$response->status_line;
 2481:                &logthis("<font color=\"blue\">WARNING:"
 2482:                        ." LWP get: $message: $filename</font>");
 2483:                return 'unavailable';
 2484:            } else {
 2485: 	       if ($remoteurl!~/\.meta$/) {
 2486:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 2487:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 2488:                   if ($mresponse->is_error()) {
 2489: 		      unlink($filename.'.meta');
 2490:                       &logthis(
 2491:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 2492:                   }
 2493: 	       }
 2494:                rename($transname,$filename);
 2495:                return 'ok';
 2496:            }
 2497:        }
 2498:     }
 2499: }
 2500: 
 2501: # ------------------------------------------------ Get server side include body
 2502: sub ssi_body {
 2503:     my ($filelink,%form)=@_;
 2504:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 2505:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 2506:     }
 2507:     my $output='';
 2508:     my $response;
 2509:     if ($filelink=~/^https?\:/) {
 2510:        ($output,$response)=&externalssi($filelink);
 2511:     } else {
 2512:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 2513:        $filelink .= 'inhibitmenu=yes';
 2514:        ($output,$response)=&ssi($filelink,%form);
 2515:     }
 2516:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 2517:     $output=~s/^.*?\<body[^\>]*\>//si;
 2518:     $output=~s/\<\/body\s*\>.*?$//si;
 2519:     if (wantarray) {
 2520:         return ($output, $response);
 2521:     } else {
 2522:         return $output;
 2523:     }
 2524: }
 2525: 
 2526: # --------------------------------------------------------- Server Side Include
 2527: 
 2528: sub absolute_url {
 2529:     my ($host_name) = @_;
 2530:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 2531:     if ($host_name eq '') {
 2532: 	$host_name = $ENV{'SERVER_NAME'};
 2533:     }
 2534:     return $protocol.$host_name;
 2535: }
 2536: 
 2537: #
 2538: #   Server side include.
 2539: # Parameters:
 2540: #  fn     Possibly encrypted resource name/id.
 2541: #  form   Hash that describes how the rendering should be done
 2542: #         and other things.
 2543: # Returns:
 2544: #   Scalar context: The content of the response.
 2545: #   Array context:  2 element list of the content and the full response object.
 2546: #     
 2547: sub ssi {
 2548: 
 2549:     my ($fn,%form)=@_;
 2550:     my $ua=new LWP::UserAgent;
 2551:     my $request;
 2552: 
 2553:     $form{'no_update_last_known'}=1;
 2554:     &Apache::lonenc::check_encrypt(\$fn);
 2555:     if (%form) {
 2556:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 2557:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
 2558:     } else {
 2559:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 2560:     }
 2561: 
 2562:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 2563:     my $response=$ua->request($request);
 2564: 
 2565:     if (wantarray) {
 2566: 	return ($response->content, $response);
 2567:     } else {
 2568: 	return $response->content;
 2569:     }
 2570: }
 2571: 
 2572: sub externalssi {
 2573:     my ($url)=@_;
 2574:     my $ua=new LWP::UserAgent;
 2575:     my $request=new HTTP::Request('GET',$url);
 2576:     my $response=$ua->request($request);
 2577:     if (wantarray) {
 2578:         return ($response->content, $response);
 2579:     } else {
 2580:         return $response->content;
 2581:     }
 2582: }
 2583: 
 2584: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 2585: 
 2586: sub allowuploaded {
 2587:     my ($srcurl,$url)=@_;
 2588:     $url=&clutter(&declutter($url));
 2589:     my $dir=$url;
 2590:     $dir=~s/\/[^\/]+$//;
 2591:     my %httpref=();
 2592:     my $httpurl=&hreflocation('',$url);
 2593:     $httpref{'httpref.'.$httpurl}=$srcurl;
 2594:     &Apache::lonnet::appenv(\%httpref);
 2595: }
 2596: 
 2597: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 2598: # input: action, courseID, current domain, intended
 2599: #        path to file, source of file, instruction to parse file for objects,
 2600: #        ref to hash for embedded objects,
 2601: #        ref to hash for codebase of java objects.
 2602: #        reference to scalar to accommodate mime type determined
 2603: #          from File::MMagic if $parser = parse.
 2604: #
 2605: # output: url to file (if action was uploaddoc), 
 2606: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 2607: #
 2608: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 2609: # course.
 2610: #
 2611: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2612: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 2613: #          course's home server.
 2614: #
 2615: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 2616: #          be copied from $source (current location) to 
 2617: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2618: #         and will then be copied to
 2619: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 2620: #         course's home server.
 2621: #
 2622: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2623: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 2624: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2625: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 2626: #         in course's home server.
 2627: #
 2628: 
 2629: sub process_coursefile {
 2630:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 2631:         $mimetype)=@_;
 2632:     my $fetchresult;
 2633:     my $home=&homeserver($docuname,$docudom);
 2634:     if ($action eq 'propagate') {
 2635:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2636: 			     $home);
 2637:     } else {
 2638:         my $fpath = '';
 2639:         my $fname = $file;
 2640:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2641:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2642:         my $filepath = &build_filepath($fpath);
 2643:         if ($action eq 'copy') {
 2644:             if ($source eq '') {
 2645:                 $fetchresult = 'no source file';
 2646:                 return $fetchresult;
 2647:             } else {
 2648:                 my $destination = $filepath.'/'.$fname;
 2649:                 rename($source,$destination);
 2650:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2651:                                  $home);
 2652:             }
 2653:         } elsif ($action eq 'uploaddoc') {
 2654:             open(my $fh,'>'.$filepath.'/'.$fname);
 2655:             print $fh $env{'form.'.$source};
 2656:             close($fh);
 2657:             if ($parser eq 'parse') {
 2658:                 my $mm = new File::MMagic;
 2659:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 2660:                 if ($type eq 'text/html') {
 2661:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 2662:                     unless ($parse_result eq 'ok') {
 2663:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 2664:                     }
 2665:                 }
 2666:                 if (ref($mimetype)) {
 2667:                     $$mimetype = $type;
 2668:                 } 
 2669:             }
 2670:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2671:                                  $home);
 2672:             if ($fetchresult eq 'ok') {
 2673:                 return '/uploaded/'.$fpath.'/'.$fname;
 2674:             } else {
 2675:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2676:                         ' to host '.$home.': '.$fetchresult);
 2677:                 return '/adm/notfound.html';
 2678:             }
 2679:         }
 2680:     }
 2681:     unless ( $fetchresult eq 'ok') {
 2682:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2683:              ' to host '.$home.': '.$fetchresult);
 2684:     }
 2685:     return $fetchresult;
 2686: }
 2687: 
 2688: sub build_filepath {
 2689:     my ($fpath) = @_;
 2690:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 2691:     unless ($fpath eq '') {
 2692:         my @parts=split('/',$fpath);
 2693:         foreach my $part (@parts) {
 2694:             $filepath.= '/'.$part;
 2695:             if ((-e $filepath)!=1) {
 2696:                 mkdir($filepath,0777);
 2697:             }
 2698:         }
 2699:     }
 2700:     return $filepath;
 2701: }
 2702: 
 2703: sub store_edited_file {
 2704:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 2705:     my $file = $primary_url;
 2706:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 2707:     my $fpath = '';
 2708:     my $fname = $file;
 2709:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2710:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2711:     my $filepath = &build_filepath($fpath);
 2712:     open(my $fh,'>'.$filepath.'/'.$fname);
 2713:     print $fh $content;
 2714:     close($fh);
 2715:     my $home=&homeserver($docuname,$docudom);
 2716:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2717: 			  $home);
 2718:     if ($$fetchresult eq 'ok') {
 2719:         return '/uploaded/'.$fpath.'/'.$fname;
 2720:     } else {
 2721:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2722: 		 ' to host '.$home.': '.$$fetchresult);
 2723:         return '/adm/notfound.html';
 2724:     }
 2725: }
 2726: 
 2727: sub clean_filename {
 2728:     my ($fname,$args)=@_;
 2729: # Replace Windows backslashes by forward slashes
 2730:     $fname=~s/\\/\//g;
 2731:     if (!$args->{'keep_path'}) {
 2732:         # Get rid of everything but the actual filename
 2733: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 2734:     }
 2735: # Replace spaces by underscores
 2736:     $fname=~s/\s+/\_/g;
 2737: # Replace all other weird characters by nothing
 2738:     $fname=~s{[^/\w\.\-]}{}g;
 2739: # Replace all .\d. sequences with _\d. so they no longer look like version
 2740: # numbers
 2741:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 2742:     return $fname;
 2743: }
 2744: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 2745: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 2746: # image with the same aspect ratio as the original, but with dimensions which do 
 2747: # not exceed $resizewidth and $resizeheight.
 2748:  
 2749: sub resizeImage {
 2750:     my ($img_path,$resizewidth,$resizeheight) = @_;
 2751:     my $ima = Image::Magick->new;
 2752:     my $resized;
 2753:     if (-e $img_path) {
 2754:         $ima->Read($img_path);
 2755:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 2756:             my $width = $ima->Get('width');
 2757:             my $height = $ima->Get('height');
 2758:             if ($width > $resizewidth) {
 2759: 	        my $factor = $width/$resizewidth;
 2760:                 my $newheight = $height/$factor;
 2761:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 2762:                 $resized = 1;
 2763:             }
 2764:         }
 2765:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 2766:             my $width = $ima->Get('width');
 2767:             my $height = $ima->Get('height');
 2768:             if ($height > $resizeheight) {
 2769:                 my $factor = $height/$resizeheight;
 2770:                 my $newwidth = $width/$factor;
 2771:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 2772:                 $resized = 1;
 2773:             }
 2774:         }
 2775:         if ($resized) {
 2776:             $ima->Write($img_path);
 2777:         }
 2778:     }
 2779:     return;
 2780: }
 2781: 
 2782: # --------------- Take an uploaded file and put it into the userfiles directory
 2783: # input: $formname - the contents of the file are in $env{"form.$formname"}
 2784: #                    the desired filename is in $env{"form.$formname.filename"}
 2785: #        $context - possible values: coursedoc, existingfile, overwrite, 
 2786: #                                    canceloverwrite, or ''. 
 2787: #                   if 'coursedoc': upload to the current course
 2788: #                   if 'existingfile': write file to tmp/overwrites directory 
 2789: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 2790: #                   $context is passed as argument to &finishuserfileupload
 2791: #        $subdir - directory in userfile to store the file into
 2792: #        $parser - instruction to parse file for objects ($parser = parse)    
 2793: #        $allfiles - reference to hash for embedded objects
 2794: #        $codebase - reference to hash for codebase of java objects
 2795: #        $desuname - username for permanent storage of uploaded file
 2796: #        $dsetudom - domain for permanaent storage of uploaded file
 2797: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 2798: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 2799: #        $resizewidth - width (pixels) to which to resize uploaded image
 2800: #        $resizeheight - height (pixels) to which to resize uploaded image
 2801: #        $mimetype - reference to scalar to accommodate mime type determined
 2802: #                    from File::MMagic if $parser = parse.
 2803: # 
 2804: # output: url of file in userspace, or error: <message> 
 2805: #             or /adm/notfound.html if failure to upload occurse
 2806: 
 2807: sub userfileupload {
 2808:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 2809:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 2810:     if (!defined($subdir)) { $subdir='unknown'; }
 2811:     my $fname=$env{'form.'.$formname.'.filename'};
 2812:     $fname=&clean_filename($fname);
 2813:     # See if there is anything left
 2814:     unless ($fname) { return 'error: no uploaded file'; }
 2815:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 2816:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 2817:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 2818:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 2819:         my $now = time;
 2820:         my $filepath;
 2821:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 2822:              $filepath = 'tmp/helprequests/'.$now;
 2823:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 2824:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 2825:                          '_'.$env{'user.domain'}.'/pending';
 2826:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 2827:             my ($docuname,$docudom);
 2828:             if ($destudom) {
 2829:                 $docudom = $destudom;
 2830:             } else {
 2831:                 $docudom = $env{'user.domain'};
 2832:             }
 2833:             if ($destuname) {
 2834:                 $docuname = $destuname;
 2835:             } else {
 2836:                 $docuname = $env{'user.name'};
 2837:             }
 2838:             if (exists($env{'form.group'})) {
 2839:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2840:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2841:             }
 2842:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 2843:             if ($context eq 'canceloverwrite') {
 2844:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 2845:                 if (-e  $tempfile) {
 2846:                     my @info = stat($tempfile);
 2847:                     if ($info[9] eq $env{'form.timestamp'}) {
 2848:                         unlink($tempfile);
 2849:                     }
 2850:                 }
 2851:                 return;
 2852:             }
 2853:         }
 2854:         # Create the directory if not present
 2855:         my @parts=split(/\//,$filepath);
 2856:         my $fullpath = $perlvar{'lonDaemons'};
 2857:         for (my $i=0;$i<@parts;$i++) {
 2858:             $fullpath .= '/'.$parts[$i];
 2859:             if ((-e $fullpath)!=1) {
 2860:                 mkdir($fullpath,0777);
 2861:             }
 2862:         }
 2863:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2864:         print $fh $env{'form.'.$formname};
 2865:         close($fh);
 2866:         if ($context eq 'existingfile') {
 2867:             my @info = stat($fullpath.'/'.$fname);
 2868:             return ($fullpath.'/'.$fname,$info[9]);
 2869:         } else {
 2870:             return $fullpath.'/'.$fname;
 2871:         }
 2872:     }
 2873:     if ($subdir eq 'scantron') {
 2874:         $fname = 'scantron_orig_'.$fname;
 2875:     } else {
 2876:         $fname="$subdir/$fname";
 2877:     }
 2878:     if ($context eq 'coursedoc') {
 2879: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2880: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2881:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 2882:             return &finishuserfileupload($docuname,$docudom,
 2883: 					 $formname,$fname,$parser,$allfiles,
 2884: 					 $codebase,$thumbwidth,$thumbheight,
 2885:                                          $resizewidth,$resizeheight,$context,$mimetype);
 2886:         } else {
 2887:             $fname=$env{'form.folder'}.'/'.$fname;
 2888:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 2889: 				       $fname,$formname,$parser,
 2890: 				       $allfiles,$codebase,$mimetype);
 2891:         }
 2892:     } elsif (defined($destuname)) {
 2893:         my $docuname=$destuname;
 2894:         my $docudom=$destudom;
 2895: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2896: 				     $parser,$allfiles,$codebase,
 2897:                                      $thumbwidth,$thumbheight,
 2898:                                      $resizewidth,$resizeheight,$context,$mimetype);
 2899:     } else {
 2900:         my $docuname=$env{'user.name'};
 2901:         my $docudom=$env{'user.domain'};
 2902:         if (exists($env{'form.group'})) {
 2903:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2904:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2905:         }
 2906: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2907: 				     $parser,$allfiles,$codebase,
 2908:                                      $thumbwidth,$thumbheight,
 2909:                                      $resizewidth,$resizeheight,$context,$mimetype);
 2910:     }
 2911: }
 2912: 
 2913: sub finishuserfileupload {
 2914:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 2915:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 2916:     my $path=$docudom.'/'.$docuname.'/';
 2917:     my $filepath=$perlvar{'lonDocRoot'};
 2918:   
 2919:     my ($fnamepath,$file,$fetchthumb);
 2920:     $file=$fname;
 2921:     if ($fname=~m|/|) {
 2922:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 2923: 	$path.=$fnamepath.'/';
 2924:     }
 2925:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 2926:     my $count;
 2927:     for ($count=4;$count<=$#parts;$count++) {
 2928:         $filepath.="/$parts[$count]";
 2929:         if ((-e $filepath)!=1) {
 2930: 	    mkdir($filepath,0777);
 2931:         }
 2932:     }
 2933: 
 2934: # Save the file
 2935:     {
 2936: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 2937: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 2938: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 2939: 	    return '/adm/notfound.html';
 2940: 	}
 2941:         if ($context eq 'overwrite') {
 2942:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 2943:             my $target = $filepath.'/'.$file;
 2944:             if (-e $source) {
 2945:                 my @info = stat($source);
 2946:                 if ($info[9] eq $env{'form.timestamp'}) {   
 2947:                     unless (&File::Copy::move($source,$target)) {
 2948:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 2949:                         return "Moving from $source failed";
 2950:                     }
 2951:                 } else {
 2952:                     return "Temporary file: $source had unexpected date/time for last modification";
 2953:                 }
 2954:             } else {
 2955:                 return "Temporary file: $source missing";
 2956:             }
 2957:         } elsif (!print FH ($env{'form.'.$formname})) {
 2958: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 2959: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 2960: 	    return '/adm/notfound.html';
 2961: 	}
 2962: 	close(FH);
 2963:         if ($resizewidth && $resizeheight) {
 2964:             my $mm = new File::MMagic;
 2965:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 2966:             if ($mime_type =~ m{^image/}) {
 2967: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 2968:             }  
 2969: 	}
 2970:     }
 2971:     if ($parser eq 'parse') {
 2972:         my $mm = new File::MMagic;
 2973:         my $type = $mm->checktype_filename($filepath.'/'.$file);
 2974:         if ($type eq 'text/html') {
 2975:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 2976:                                                        $allfiles,$codebase);
 2977:             unless ($parse_result eq 'ok') {
 2978:                 &logthis('Failed to parse '.$filepath.$file.
 2979: 	   	         ' for embedded media: '.$parse_result); 
 2980:             }
 2981:         }
 2982:         if (ref($mimetype)) {
 2983:             $$mimetype = $type;
 2984:         }
 2985:     }
 2986:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 2987:         my $input = $filepath.'/'.$file;
 2988:         my $output = $filepath.'/'.'tn-'.$file;
 2989:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 2990:         system("convert -sample $thumbsize $input $output");
 2991:         if (-e $filepath.'/'.'tn-'.$file) {
 2992:             $fetchthumb  = 1; 
 2993:         }
 2994:     }
 2995:  
 2996: # Notify homeserver to grep it
 2997: #
 2998:     my $docuhome=&homeserver($docuname,$docudom);	
 2999:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 3000:     if ($fetchresult eq 'ok') {
 3001:         if ($fetchthumb) {
 3002:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 3003:             if ($thumbresult ne 'ok') {
 3004:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 3005:                          $docuhome.': '.$thumbresult);
 3006:             }
 3007:         }
 3008: #
 3009: # Return the URL to it
 3010:         return '/uploaded/'.$path.$file;
 3011:     } else {
 3012:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 3013: 		 ': '.$fetchresult);
 3014:         return '/adm/notfound.html';
 3015:     }
 3016: }
 3017: 
 3018: sub extract_embedded_items {
 3019:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 3020:     my @state = ();
 3021:     my %javafiles = (
 3022:                       codebase => '',
 3023:                       code => '',
 3024:                       archive => ''
 3025:                     );
 3026:     my %mediafiles = (
 3027:                       src => '',
 3028:                       movie => '',
 3029:                      );
 3030:     my $p;
 3031:     if ($content) {
 3032:         $p = HTML::LCParser->new($content);
 3033:     } else {
 3034:         $p = HTML::LCParser->new($fullpath);
 3035:     }
 3036:     while (my $t=$p->get_token()) {
 3037: 	if ($t->[0] eq 'S') {
 3038: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 3039: 	    push(@state, $tagname);
 3040:             if (lc($tagname) eq 'allow') {
 3041:                 &add_filetype($allfiles,$attr->{'src'},'src');
 3042:             }
 3043: 	    if (lc($tagname) eq 'img') {
 3044: 		&add_filetype($allfiles,$attr->{'src'},'src');
 3045: 	    }
 3046: 	    if (lc($tagname) eq 'a') {
 3047: 		&add_filetype($allfiles,$attr->{'href'},'href');
 3048: 	    }
 3049:             if (lc($tagname) eq 'script') {
 3050:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 3051:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 3052:                 } else {
 3053:                     &add_filetype($allfiles,$attr->{'src'},'src');
 3054:                 }
 3055:             }
 3056:             if (lc($tagname) eq 'link') {
 3057:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 3058:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3059:                 }
 3060:             }
 3061: 	    if (lc($tagname) eq 'object' ||
 3062: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 3063: 		foreach my $item (keys(%javafiles)) {
 3064: 		    $javafiles{$item} = '';
 3065: 		}
 3066: 	    }
 3067: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 3068: 		my $name = lc($attr->{'name'});
 3069: 		foreach my $item (keys(%javafiles)) {
 3070: 		    if ($name eq $item) {
 3071: 			$javafiles{$item} = $attr->{'value'};
 3072: 			last;
 3073: 		    }
 3074: 		}
 3075: 		foreach my $item (keys(%mediafiles)) {
 3076: 		    if ($name eq $item) {
 3077: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 3078: 			last;
 3079: 		    }
 3080: 		}
 3081: 	    }
 3082: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 3083: 		foreach my $item (keys(%javafiles)) {
 3084: 		    if ($attr->{$item}) {
 3085: 			$javafiles{$item} = $attr->{$item};
 3086: 			last;
 3087: 		    }
 3088: 		}
 3089: 		foreach my $item (keys(%mediafiles)) {
 3090: 		    if ($attr->{$item}) {
 3091: 			&add_filetype($allfiles,$attr->{$item},$item);
 3092: 			last;
 3093: 		    }
 3094: 		}
 3095: 	    }
 3096: 	} elsif ($t->[0] eq 'E') {
 3097: 	    my ($tagname) = ($t->[1]);
 3098: 	    if ($javafiles{'codebase'} ne '') {
 3099: 		$javafiles{'codebase'} .= '/';
 3100: 	    }  
 3101: 	    if (lc($tagname) eq 'applet' ||
 3102: 		lc($tagname) eq 'object' ||
 3103: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 3104: 		) {
 3105: 		foreach my $item (keys(%javafiles)) {
 3106: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 3107: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 3108: 			&add_filetype($allfiles,$file,$item);
 3109: 		    }
 3110: 		}
 3111: 	    } 
 3112: 	    pop @state;
 3113: 	}
 3114:     }
 3115:     return 'ok';
 3116: }
 3117: 
 3118: sub add_filetype {
 3119:     my ($allfiles,$file,$type)=@_;
 3120:     if (exists($allfiles->{$file})) {
 3121: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 3122: 	    push(@{$allfiles->{$file}}, &escape($type));
 3123: 	}
 3124:     } else {
 3125: 	@{$allfiles->{$file}} = (&escape($type));
 3126:     }
 3127: }
 3128: 
 3129: sub removeuploadedurl {
 3130:     my ($url)=@_;	
 3131:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 3132:     return &removeuserfile($uname,$udom,$fname);
 3133: }
 3134: 
 3135: sub removeuserfile {
 3136:     my ($docuname,$docudom,$fname)=@_;
 3137:     my $home=&homeserver($docuname,$docudom);    
 3138:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 3139:     if ($result eq 'ok') {	
 3140:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 3141:             my $metafile = $fname.'.meta';
 3142:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 3143: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 3144:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 3145:             my $sqlresult = 
 3146:                 &update_portfolio_table($docuname,$docudom,$file,
 3147:                                         'portfolio_metadata',$group,
 3148:                                         'delete');
 3149:         }
 3150:     }
 3151:     return $result;
 3152: }
 3153: 
 3154: sub mkdiruserfile {
 3155:     my ($docuname,$docudom,$dir)=@_;
 3156:     my $home=&homeserver($docuname,$docudom);
 3157:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 3158: }
 3159: 
 3160: sub renameuserfile {
 3161:     my ($docuname,$docudom,$old,$new)=@_;
 3162:     my $home=&homeserver($docuname,$docudom);
 3163:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 3164:                         &escape("$old").':'.&escape("$new"),$home);
 3165:     if ($result eq 'ok') {
 3166:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 3167:             my $oldmeta = $old.'.meta';
 3168:             my $newmeta = $new.'.meta';
 3169:             my $metaresult = 
 3170:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 3171: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 3172:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 3173:             my $sqlresult = 
 3174:                 &update_portfolio_table($docuname,$docudom,$file,
 3175:                                         'portfolio_metadata',$group,
 3176:                                         'delete');
 3177:         }
 3178:     }
 3179:     return $result;
 3180: }
 3181: 
 3182: # ------------------------------------------------------------------------- Log
 3183: 
 3184: sub log {
 3185:     my ($dom,$nam,$hom,$what)=@_;
 3186:     return critical("log:$dom:$nam:$what",$hom);
 3187: }
 3188: 
 3189: # ------------------------------------------------------------------ Course Log
 3190: #
 3191: # This routine flushes several buffers of non-mission-critical nature
 3192: #
 3193: 
 3194: sub flushcourselogs {
 3195:     &logthis('Flushing log buffers');
 3196: #
 3197: # course logs
 3198: # This is a log of all transactions in a course, which can be used
 3199: # for data mining purposes
 3200: #
 3201: # It also collects the courseid database, which lists last transaction
 3202: # times and course titles for all courseids
 3203: #
 3204:     my %courseidbuffer=();
 3205:     foreach my $crsid (keys(%courselogs)) {
 3206:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 3207: 		          &escape($courselogs{$crsid}),
 3208: 		          $coursehombuf{$crsid}) eq 'ok') {
 3209: 	    delete $courselogs{$crsid};
 3210:         } else {
 3211:             &logthis('Failed to flush log buffer for '.$crsid);
 3212:             if (length($courselogs{$crsid})>40000) {
 3213:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 3214:                         " exceeded maximum size, deleting.</font>");
 3215:                delete $courselogs{$crsid};
 3216:             }
 3217:         }
 3218:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 3219:             'description' => $coursedescrbuf{$crsid},
 3220:             'inst_code'    => $courseinstcodebuf{$crsid},
 3221:             'type'        => $coursetypebuf{$crsid},
 3222:             'owner'       => $courseownerbuf{$crsid},
 3223:         };
 3224:     }
 3225: #
 3226: # Write course id database (reverse lookup) to homeserver of courses 
 3227: # Is used in pickcourse
 3228: #
 3229:     foreach my $crs_home (keys(%courseidbuffer)) {
 3230:         my $response = &courseidput(&host_domain($crs_home),
 3231:                                     $courseidbuffer{$crs_home},
 3232:                                     $crs_home,'timeonly');
 3233:     }
 3234: #
 3235: # File accesses
 3236: # Writes to the dynamic metadata of resources to get hit counts, etc.
 3237: #
 3238:     foreach my $entry (keys(%accesshash)) {
 3239:         if ($entry =~ /___count$/) {
 3240:             my ($dom,$name);
 3241:             ($dom,$name,undef)=
 3242: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 3243:             if (! defined($dom) || $dom eq '' || 
 3244:                 ! defined($name) || $name eq '') {
 3245:                 my $cid = $env{'request.course.id'};
 3246:                 $dom  = $env{'request.'.$cid.'.domain'};
 3247:                 $name = $env{'request.'.$cid.'.num'};
 3248:             }
 3249:             my $value = $accesshash{$entry};
 3250:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 3251:             my %temphash=($url => $value);
 3252:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 3253:             if ($result eq 'ok') {
 3254:                 delete $accesshash{$entry};
 3255:             } elsif ($result eq 'unknown_cmd') {
 3256:                 # Target server has old code running on it.
 3257:                 my %temphash=($entry => $value);
 3258:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 3259:                     delete $accesshash{$entry};
 3260:                 }
 3261:             }
 3262:         } else {
 3263:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 3264:             my %temphash=($entry => $accesshash{$entry});
 3265:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 3266:                 delete $accesshash{$entry};
 3267:             }
 3268:         }
 3269:     }
 3270: #
 3271: # Roles
 3272: # Reverse lookup of user roles for course faculty/staff and co-authorship
 3273: #
 3274:     foreach my $entry (keys(%userrolehash)) {
 3275:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 3276: 	    split(/\:/,$entry);
 3277:         if (&Apache::lonnet::put('nohist_userroles',
 3278:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 3279:                 $rudom,$runame) eq 'ok') {
 3280: 	    delete $userrolehash{$entry};
 3281:         }
 3282:     }
 3283: #
 3284: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 3285: #
 3286:     my %domrolebuffer = ();
 3287:     foreach my $entry (keys(%domainrolehash)) {
 3288:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 3289:         if ($domrolebuffer{$rudom}) {
 3290:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 3291:                       '='.&escape($domainrolehash{$entry});
 3292:         } else {
 3293:             $domrolebuffer{$rudom}.=&escape($entry).
 3294:                       '='.&escape($domainrolehash{$entry});
 3295:         }
 3296:         delete $domainrolehash{$entry};
 3297:     }
 3298:     foreach my $dom (keys(%domrolebuffer)) {
 3299: 	my %servers = &get_servers($dom,'library');
 3300: 	foreach my $tryserver (keys(%servers)) {
 3301: 	    unless (&reply('domroleput:'.$dom.':'.
 3302: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 3303: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 3304: 	    }
 3305:         }
 3306:     }
 3307:     $dumpcount++;
 3308: }
 3309: 
 3310: sub courselog {
 3311:     my $what=shift;
 3312:     $what=time.':'.$what;
 3313:     unless ($env{'request.course.id'}) { return ''; }
 3314:     $coursedombuf{$env{'request.course.id'}}=
 3315:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 3316:     $coursenumbuf{$env{'request.course.id'}}=
 3317:        $env{'course.'.$env{'request.course.id'}.'.num'};
 3318:     $coursehombuf{$env{'request.course.id'}}=
 3319:        $env{'course.'.$env{'request.course.id'}.'.home'};
 3320:     $coursedescrbuf{$env{'request.course.id'}}=
 3321:        $env{'course.'.$env{'request.course.id'}.'.description'};
 3322:     $courseinstcodebuf{$env{'request.course.id'}}=
 3323:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 3324:     $courseownerbuf{$env{'request.course.id'}}=
 3325:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 3326:     $coursetypebuf{$env{'request.course.id'}}=
 3327:        $env{'course.'.$env{'request.course.id'}.'.type'};
 3328:     if (defined $courselogs{$env{'request.course.id'}}) {
 3329: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 3330:     } else {
 3331: 	$courselogs{$env{'request.course.id'}}.=$what;
 3332:     }
 3333:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 3334: 	&flushcourselogs();
 3335:     }
 3336: }
 3337: 
 3338: sub courseacclog {
 3339:     my $fnsymb=shift;
 3340:     unless ($env{'request.course.id'}) { return ''; }
 3341:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 3342:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 3343:         $what.=':POST';
 3344:         # FIXME: Probably ought to escape things....
 3345: 	foreach my $key (keys(%env)) {
 3346:             if ($key=~/^form\.(.*)/) {
 3347:                 my $formitem = $1;
 3348:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 3349:                     $what.=':'.$formitem.'='.$env{$key};
 3350:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 3351:                     $what.=':'.$formitem.'='.$env{$key};
 3352:                 }
 3353:             }
 3354:         }
 3355:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 3356:         # FIXME: We should not be depending on a form parameter that someone
 3357:         # editing lonsearchcat.pm might change in the future.
 3358:         if ($env{'form.phase'} eq 'course_search') {
 3359:             $what.= ':POST';
 3360:             # FIXME: Probably ought to escape things....
 3361:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 3362:                                  'crsdiscuss') {
 3363:                 $what.=':'.$element.'='.$env{'form.'.$element};
 3364:             }
 3365:         }
 3366:     }
 3367:     &courselog($what);
 3368: }
 3369: 
 3370: sub countacc {
 3371:     my $url=&declutter(shift);
 3372:     return if (! defined($url) || $url eq '');
 3373:     unless ($env{'request.course.id'}) { return ''; }
 3374:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 3375:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 3376:     $accesshash{$key}++;
 3377: }
 3378: 
 3379: sub linklog {
 3380:     my ($from,$to)=@_;
 3381:     $from=&declutter($from);
 3382:     $to=&declutter($to);
 3383:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 3384:     $accesshash{$to.'___'.$from.'___goto'}=1;
 3385: }
 3386:   
 3387: sub userrolelog {
 3388:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 3389:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 3390:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 3391:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 3392:         ($trole=~/^ta/) || ($trole=~/^co/)) {
 3393:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3394:        $userrolehash
 3395:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3396:                     =$tend.':'.$tstart;
 3397:     }
 3398:     if (($env{'request.role'} =~ /dc\./) &&
 3399: 	(($trole=~/^au/) || ($trole=~/^in/) ||
 3400: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
 3401: 	 ($trole=~/^cr/) || ($trole=~/^ta/) ||
 3402:          ($trole=~/^co/))) {
 3403:        $userrolehash
 3404:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 3405:                     =$tend.':'.$tstart;
 3406:     }
 3407:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 3408:         ($trole=~/^li/) || ($trole=~/^li/) ||
 3409:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 3410:         ($trole=~/^sc/)) {
 3411:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3412:        $domainrolehash
 3413:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3414:                     = $tend.':'.$tstart;
 3415:     }
 3416: }
 3417: 
 3418: sub courserolelog {
 3419:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 3420:     if (($trole eq 'cc') || ($trole eq 'in') ||
 3421:         ($trole eq 'ep') || ($trole eq 'ad') ||
 3422:         ($trole eq 'ta') || ($trole eq 'st') ||
 3423:         ($trole=~/^cr/) || ($trole eq 'gr') ||
 3424:         ($trole eq 'co')) {
 3425:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 3426:             my $cdom = $1;
 3427:             my $cnum = $2;
 3428:             my $sec = $3;
 3429:             my $namespace = 'rolelog';
 3430:             my %storehash = (
 3431:                                role    => $trole,
 3432:                                start   => $tstart,
 3433:                                end     => $tend,
 3434:                                selfenroll => $selfenroll,
 3435:                                context    => $context,
 3436:                             );
 3437:             if ($trole eq 'gr') {
 3438:                 $namespace = 'groupslog';
 3439:                 $storehash{'group'} = $sec;
 3440:             } else {
 3441:                 $storehash{'section'} = $sec;
 3442:             }
 3443:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
 3444:             if (($trole ne 'st') || ($sec ne '')) {
 3445:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 3446:             }
 3447:         }
 3448:     }
 3449:     return;
 3450: }
 3451: 
 3452: sub get_course_adv_roles {
 3453:     my ($cid,$codes) = @_;
 3454:     $cid=$env{'request.course.id'} unless (defined($cid));
 3455:     my %coursehash=&coursedescription($cid);
 3456:     my $crstype = &Apache::loncommon::course_type($cid);
 3457:     my %nothide=();
 3458:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3459:         if ($user !~ /:/) {
 3460: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 3461:         } else {
 3462:             $nothide{$user}=1;
 3463:         }
 3464:     }
 3465:     my %returnhash=();
 3466:     my %dumphash=
 3467:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 3468:     my $now=time;
 3469:     my %privileged;
 3470:     foreach my $entry (keys(%dumphash)) {
 3471: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 3472:         if (($tstart) && ($tstart<0)) { next; }
 3473:         if (($tend) && ($tend<$now)) { next; }
 3474:         if (($tstart) && ($now<$tstart)) { next; }
 3475:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 3476: 	if ($username eq '' || $domain eq '') { next; }
 3477:         unless (ref($privileged{$domain}) eq 'HASH') {
 3478:             my %dompersonnel =
 3479:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 3480:             $privileged{$domain} = {};
 3481:             foreach my $server (keys(%dompersonnel)) {
 3482:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 3483:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
 3484:                         my ($trole,$uname,$udom) = split(/:/,$user);
 3485:                         $privileged{$udom}{$uname} = 1;
 3486:                     }
 3487:                 }
 3488:             }
 3489:         }
 3490:         if ((exists($privileged{$domain}{$username})) && 
 3491:             (!$nothide{$username.':'.$domain})) { next; }
 3492: 	if ($role eq 'cr') { next; }
 3493:         if ($codes) {
 3494:             if ($section) { $role .= ':'.$section; }
 3495:             if ($returnhash{$role}) {
 3496:                 $returnhash{$role}.=','.$username.':'.$domain;
 3497:             } else {
 3498:                 $returnhash{$role}=$username.':'.$domain;
 3499:             }
 3500:         } else {
 3501:             my $key=&plaintext($role,$crstype);
 3502:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 3503:             if ($returnhash{$key}) {
 3504: 	        $returnhash{$key}.=','.$username.':'.$domain;
 3505:             } else {
 3506:                 $returnhash{$key}=$username.':'.$domain;
 3507:             }
 3508:         }
 3509:     }
 3510:     return %returnhash;
 3511: }
 3512: 
 3513: sub get_my_roles {
 3514:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 3515:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 3516:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 3517:     my (%dumphash,%nothide);
 3518:     if ($context eq 'userroles') {
 3519:         my $extra = &freeze_escape({'skipcheck' => 1});
 3520:         %dumphash = &dump('roles',$udom,$uname,'.',undef,$extra);
 3521:     } else {
 3522:         %dumphash=
 3523:             &dump('nohist_userroles',$udom,$uname);
 3524:         if ($hidepriv) {
 3525:             my %coursehash=&coursedescription($udom.'_'.$uname);
 3526:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3527:                 if ($user !~ /:/) {
 3528:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 3529:                 } else {
 3530:                     $nothide{$user} = 1;
 3531:                 }
 3532:             }
 3533:         }
 3534:     }
 3535:     my %returnhash=();
 3536:     my $now=time;
 3537:     my %privileged;
 3538:     foreach my $entry (keys(%dumphash)) {
 3539:         my ($role,$tend,$tstart);
 3540:         if ($context eq 'userroles') {
 3541: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 3542:         } else {
 3543:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 3544:         }
 3545:         if (($tstart) && ($tstart<0)) { next; }
 3546:         my $status = 'active';
 3547:         if (($tend) && ($tend<=$now)) {
 3548:             $status = 'previous';
 3549:         } 
 3550:         if (($tstart) && ($now<$tstart)) {
 3551:             $status = 'future';
 3552:         }
 3553:         if (ref($types) eq 'ARRAY') {
 3554:             if (!grep(/^\Q$status\E$/,@{$types})) {
 3555:                 next;
 3556:             } 
 3557:         } else {
 3558:             if ($status ne 'active') {
 3559:                 next;
 3560:             }
 3561:         }
 3562:         my ($rolecode,$username,$domain,$section,$area);
 3563:         if ($context eq 'userroles') {
 3564:             ($area,$rolecode) = split(/_/,$entry);
 3565:             (undef,$domain,$username,$section) = split(/\//,$area);
 3566:         } else {
 3567:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 3568:         }
 3569:         if (ref($roledoms) eq 'ARRAY') {
 3570:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 3571:                 next;
 3572:             }
 3573:         }
 3574:         if (ref($roles) eq 'ARRAY') {
 3575:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 3576:                 if ($role =~ /^cr\//) {
 3577:                     if (!grep(/^cr$/,@{$roles})) {
 3578:                         next;
 3579:                     }
 3580:                 } elsif ($role =~ /^gr\//) {
 3581:                     if (!grep(/^gr$/,@{$roles})) {
 3582:                         next;
 3583:                     }
 3584:                 } else {
 3585:                     next;
 3586:                 }
 3587:             }
 3588:         }
 3589:         if ($hidepriv) {
 3590:             if ($context eq 'userroles') {
 3591:                 if ((&privileged($username,$domain)) &&
 3592:                     (!$nothide{$username.':'.$domain})) {
 3593:                     next;
 3594:                 }
 3595:             } else {
 3596:                 unless (ref($privileged{$domain}) eq 'HASH') {
 3597:                     my %dompersonnel =
 3598:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 3599:                     $privileged{$domain} = {};
 3600:                     if (keys(%dompersonnel)) {
 3601:                         foreach my $server (keys(%dompersonnel)) {
 3602:                             if (ref($dompersonnel{$server}) eq 'HASH') {
 3603:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
 3604:                                     my ($trole,$uname,$udom) = split(/:/,$user);
 3605:                                     $privileged{$udom}{$uname} = $trole;
 3606:                                 }
 3607:                             }
 3608:                         }
 3609:                     }
 3610:                 }
 3611:                 if (exists($privileged{$domain}{$username})) {
 3612:                     if (!$nothide{$username.':'.$domain}) {
 3613:                         next;
 3614:                     }
 3615:                 }
 3616:             }
 3617:         }
 3618:         if ($withsec) {
 3619:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 3620:                 $tstart.':'.$tend;
 3621:         } else {
 3622:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 3623:         }
 3624:     }
 3625:     return %returnhash;
 3626: }
 3627: 
 3628: # ----------------------------------------------------- Frontpage Announcements
 3629: #
 3630: #
 3631: 
 3632: sub postannounce {
 3633:     my ($server,$text)=@_;
 3634:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 3635:     unless ($text=~/\w/) { $text=''; }
 3636:     return &reply('setannounce:'.&escape($text),$server);
 3637: }
 3638: 
 3639: sub getannounce {
 3640: 
 3641:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 3642: 	my $announcement='';
 3643: 	while (my $line = <$fh>) { $announcement .= $line; }
 3644: 	close($fh);
 3645: 	if ($announcement=~/\w/) { 
 3646: 	    return 
 3647:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 3648:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 3649: 	} else {
 3650: 	    return '';
 3651: 	}
 3652:     } else {
 3653: 	return '';
 3654:     }
 3655: }
 3656: 
 3657: # ---------------------------------------------------------- Course ID routines
 3658: # Deal with domain's nohist_courseid.db files
 3659: #
 3660: 
 3661: sub courseidput {
 3662:     my ($domain,$storehash,$coursehome,$caller) = @_;
 3663:     return unless (ref($storehash) eq 'HASH');
 3664:     my $outcome;
 3665:     if ($caller eq 'timeonly') {
 3666:         my $cids = '';
 3667:         foreach my $item (keys(%$storehash)) {
 3668:             $cids.=&escape($item).'&';
 3669:         }
 3670:         $cids=~s/\&$//;
 3671:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 3672:                           $coursehome);       
 3673:     } else {
 3674:         my $items = '';
 3675:         foreach my $item (keys(%$storehash)) {
 3676:             $items.= &escape($item).'='.
 3677:                      &freeze_escape($$storehash{$item}).'&';
 3678:         }
 3679:         $items=~s/\&$//;
 3680:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 3681:                           $coursehome);
 3682:     }
 3683:     if ($outcome eq 'unknown_cmd') {
 3684:         my $what;
 3685:         foreach my $cid (keys(%$storehash)) {
 3686:             $what .= &escape($cid).'=';
 3687:             foreach my $item ('description','inst_code','owner','type') {
 3688:                 $what .= &escape($storehash->{$cid}{$item}).':';
 3689:             }
 3690:             $what =~ s/\:$/&/;
 3691:         }
 3692:         $what =~ s/\&$//;  
 3693:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 3694:     } else {
 3695:         return $outcome;
 3696:     }
 3697: }
 3698: 
 3699: sub courseiddump {
 3700:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 3701:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 3702:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 3703:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
 3704:     my $as_hash = 1;
 3705:     my %returnhash;
 3706:     if (!$domfilter) { $domfilter=''; }
 3707:     my %libserv = &all_library();
 3708:     foreach my $tryserver (keys(%libserv)) {
 3709:         if ( (  $hostidflag == 1 
 3710: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 3711: 	     || (!defined($hostidflag)) ) {
 3712: 
 3713: 	    if (($domfilter eq '') ||
 3714: 		(&host_domain($tryserver) eq $domfilter)) {
 3715:                 my $rep = 
 3716:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
 3717:                          $sincefilter.':'.&escape($descfilter).':'.
 3718:                          &escape($instcodefilter).':'.&escape($ownerfilter).
 3719:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
 3720:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
 3721:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
 3722:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
 3723:                          &escape($cc_clone).':'.$cloneonly.':'.
 3724:                          &escape($createdbefore).':'.&escape($createdafter).':'.
 3725:                          &escape($creationcontext).':'.$domcloner,
 3726:                          $tryserver);
 3727:                 my @pairs=split(/\&/,$rep);
 3728:                 foreach my $item (@pairs) {
 3729:                     my ($key,$value)=split(/\=/,$item,2);
 3730:                     $key = &unescape($key);
 3731:                     next if ($key =~ /^error: 2 /);
 3732:                     my $result = &thaw_unescape($value);
 3733:                     if (ref($result) eq 'HASH') {
 3734:                         $returnhash{$key}=$result;
 3735:                     } else {
 3736:                         my @responses = split(/:/,$value);
 3737:                         my @items = ('description','inst_code','owner','type');
 3738:                         for (my $i=0; $i<@responses; $i++) {
 3739:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 3740:                         }
 3741:                     }
 3742:                 }
 3743:             }
 3744:         }
 3745:     }
 3746:     return %returnhash;
 3747: }
 3748: 
 3749: sub courselastaccess {
 3750:     my ($cdom,$cnum,$hostidref) = @_;
 3751:     my %returnhash;
 3752:     if ($cdom && $cnum) {
 3753:         my $chome = &homeserver($cnum,$cdom);
 3754:         if ($chome ne 'no_host') {
 3755:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 3756:             &extract_lastaccess(\%returnhash,$rep);
 3757:         }
 3758:     } else {
 3759:         if (!$cdom) { $cdom=''; }
 3760:         my %libserv = &all_library();
 3761:         foreach my $tryserver (keys(%libserv)) {
 3762:             if (ref($hostidref) eq 'ARRAY') {
 3763:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 3764:             } 
 3765:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 3766:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 3767:                 &extract_lastaccess(\%returnhash,$rep);
 3768:             }
 3769:         }
 3770:     }
 3771:     return %returnhash;
 3772: }
 3773: 
 3774: sub extract_lastaccess {
 3775:     my ($returnhash,$rep) = @_;
 3776:     if (ref($returnhash) eq 'HASH') {
 3777:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 3778:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 3779:                  $rep eq '') {
 3780:             my @pairs=split(/\&/,$rep);
 3781:             foreach my $item (@pairs) {
 3782:                 my ($key,$value)=split(/\=/,$item,2);
 3783:                 $key = &unescape($key);
 3784:                 next if ($key =~ /^error: 2 /);
 3785:                 $returnhash->{$key} = &thaw_unescape($value);
 3786:             }
 3787:         }
 3788:     }
 3789:     return;
 3790: }
 3791: 
 3792: # ---------------------------------------------------------- DC e-mail
 3793: 
 3794: sub dcmailput {
 3795:     my ($domain,$msgid,$message,$server)=@_;
 3796:     my $status = &Apache::lonnet::critical(
 3797:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 3798:        &escape($message),$server);
 3799:     return $status;
 3800: }
 3801: 
 3802: sub dcmaildump {
 3803:     my ($dom,$startdate,$enddate,$senders) = @_;
 3804:     my %returnhash=();
 3805: 
 3806:     if (defined(&domain($dom,'primary'))) {
 3807:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 3808:                                                          &escape($enddate).':';
 3809: 	my @esc_senders=map { &escape($_)} @$senders;
 3810: 	$cmd.=&escape(join('&',@esc_senders));
 3811: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 3812:             my ($key,$value) = split(/\=/,$line,2);
 3813:             if (($key) && ($value)) {
 3814:                 $returnhash{&unescape($key)} = &unescape($value);
 3815:             }
 3816:         }
 3817:     }
 3818:     return %returnhash;
 3819: }
 3820: # ---------------------------------------------------------- Domain roles
 3821: 
 3822: sub get_domain_roles {
 3823:     my ($dom,$roles,$startdate,$enddate)=@_;
 3824:     if ((!defined($startdate)) || ($startdate eq '')) {
 3825:         $startdate = '.';
 3826:     }
 3827:     if ((!defined($enddate)) || ($enddate eq '')) {
 3828:         $enddate = '.';
 3829:     }
 3830:     my $rolelist;
 3831:     if (ref($roles) eq 'ARRAY') {
 3832:         $rolelist = join(':',@{$roles});
 3833:     }
 3834:     my %personnel = ();
 3835: 
 3836:     my %servers = &get_servers($dom,'library');
 3837:     foreach my $tryserver (keys(%servers)) {
 3838: 	%{$personnel{$tryserver}}=();
 3839: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 3840: 					    &escape($startdate).':'.
 3841: 					    &escape($enddate).':'.
 3842: 					    &escape($rolelist), $tryserver))) {
 3843: 	    my ($key,$value) = split(/\=/,$line,2);
 3844: 	    if (($key) && ($value)) {
 3845: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 3846: 	    }
 3847: 	}
 3848:     }
 3849:     return %personnel;
 3850: }
 3851: 
 3852: # ----------------------------------------------------------- Interval timing 
 3853: 
 3854: sub get_first_access {
 3855:     my ($type,$argsymb)=@_;
 3856:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 3857:     if ($argsymb) { $symb=$argsymb; }
 3858:     my ($map,$id,$res)=&decode_symb($symb);
 3859:     if ($type eq 'course') {
 3860: 	$res='course';
 3861:     } elsif ($type eq 'map') {
 3862: 	$res=&symbread($map);
 3863:     } else {
 3864: 	$res=$symb;
 3865:     }
 3866:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 3867:     return $times{"$courseid\0$res"};
 3868: }
 3869: 
 3870: sub set_first_access {
 3871:     my ($type)=@_;
 3872:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 3873:     my ($map,$id,$res)=&decode_symb($symb);
 3874:     if ($type eq 'course') {
 3875: 	$res='course';
 3876:     } elsif ($type eq 'map') {
 3877: 	$res=&symbread($map);
 3878:     } else {
 3879: 	$res=$symb;
 3880:     }
 3881:     my $firstaccess=&get_first_access($type,$symb);
 3882:     if (!$firstaccess) {
 3883: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 3884:     }
 3885:     return 'already_set';
 3886: }
 3887: 
 3888: # --------------------------------------------- Set Expire Date for Spreadsheet
 3889: 
 3890: sub expirespread {
 3891:     my ($uname,$udom,$stype,$usymb)=@_;
 3892:     my $cid=$env{'request.course.id'}; 
 3893:     if ($cid) {
 3894:        my $now=time;
 3895:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 3896:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 3897:                             $env{'course.'.$cid.'.num'}.
 3898: 	        	    ':nohist_expirationdates:'.
 3899:                             &escape($key).'='.$now,
 3900:                             $env{'course.'.$cid.'.home'})
 3901:     }
 3902:     return 'ok';
 3903: }
 3904: 
 3905: # ----------------------------------------------------- Devalidate Spreadsheets
 3906: 
 3907: sub devalidate {
 3908:     my ($symb,$uname,$udom)=@_;
 3909:     my $cid=$env{'request.course.id'}; 
 3910:     if ($cid) {
 3911:         # delete the stored spreadsheets for
 3912:         # - the student level sheet of this user in course's homespace
 3913:         # - the assessment level sheet for this resource 
 3914:         #   for this user in user's homespace
 3915: 	# - current conditional state info
 3916: 	my $key=$uname.':'.$udom.':';
 3917:         my $status=
 3918: 	    &del('nohist_calculatedsheets',
 3919: 		 [$key.'studentcalc:'],
 3920: 		 $env{'course.'.$cid.'.domain'},
 3921: 		 $env{'course.'.$cid.'.num'})
 3922: 		.' '.
 3923: 	    &del('nohist_calculatedsheets_'.$cid,
 3924: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 3925:         unless ($status eq 'ok ok') {
 3926:            &logthis('Could not devalidate spreadsheet '.
 3927:                     $uname.' at '.$udom.' for '.
 3928: 		    $symb.': '.$status);
 3929:         }
 3930: 	&delenv('user.state.'.$cid);
 3931:     }
 3932: }
 3933: 
 3934: sub get_scalar {
 3935:     my ($string,$end) = @_;
 3936:     my $value;
 3937:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 3938: 	$value = $1;
 3939:     } elsif ($$string =~ s/^([^&]*?)&//) {
 3940: 	$value = $1;
 3941:     }
 3942:     return &unescape($value);
 3943: }
 3944: 
 3945: sub array2str {
 3946:   my (@array) = @_;
 3947:   my $result=&arrayref2str(\@array);
 3948:   $result=~s/^__ARRAY_REF__//;
 3949:   $result=~s/__END_ARRAY_REF__$//;
 3950:   return $result;
 3951: }
 3952: 
 3953: sub arrayref2str {
 3954:   my ($arrayref) = @_;
 3955:   my $result='__ARRAY_REF__';
 3956:   foreach my $elem (@$arrayref) {
 3957:     if(ref($elem) eq 'ARRAY') {
 3958:       $result.=&arrayref2str($elem).'&';
 3959:     } elsif(ref($elem) eq 'HASH') {
 3960:       $result.=&hashref2str($elem).'&';
 3961:     } elsif(ref($elem)) {
 3962:       #print("Got a ref of ".(ref($elem))." skipping.");
 3963:     } else {
 3964:       $result.=&escape($elem).'&';
 3965:     }
 3966:   }
 3967:   $result=~s/\&$//;
 3968:   $result .= '__END_ARRAY_REF__';
 3969:   return $result;
 3970: }
 3971: 
 3972: sub hash2str {
 3973:   my (%hash) = @_;
 3974:   my $result=&hashref2str(\%hash);
 3975:   $result=~s/^__HASH_REF__//;
 3976:   $result=~s/__END_HASH_REF__$//;
 3977:   return $result;
 3978: }
 3979: 
 3980: sub hashref2str {
 3981:   my ($hashref)=@_;
 3982:   my $result='__HASH_REF__';
 3983:   foreach my $key (sort(keys(%$hashref))) {
 3984:     if (ref($key) eq 'ARRAY') {
 3985:       $result.=&arrayref2str($key).'=';
 3986:     } elsif (ref($key) eq 'HASH') {
 3987:       $result.=&hashref2str($key).'=';
 3988:     } elsif (ref($key)) {
 3989:       $result.='=';
 3990:       #print("Got a ref of ".(ref($key))." skipping.");
 3991:     } else {
 3992: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 3993:     }
 3994: 
 3995:     if(ref($hashref->{$key}) eq 'ARRAY') {
 3996:       $result.=&arrayref2str($hashref->{$key}).'&';
 3997:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 3998:       $result.=&hashref2str($hashref->{$key}).'&';
 3999:     } elsif(ref($hashref->{$key})) {
 4000:        $result.='&';
 4001:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 4002:     } else {
 4003:       $result.=&escape($hashref->{$key}).'&';
 4004:     }
 4005:   }
 4006:   $result=~s/\&$//;
 4007:   $result .= '__END_HASH_REF__';
 4008:   return $result;
 4009: }
 4010: 
 4011: sub str2hash {
 4012:     my ($string)=@_;
 4013:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 4014:     return %$hash;
 4015: }
 4016: 
 4017: sub str2hashref {
 4018:   my ($string) = @_;
 4019: 
 4020:   my %hash;
 4021: 
 4022:   if($string !~ /^__HASH_REF__/) {
 4023:       if (! ($string eq '' || !defined($string))) {
 4024: 	  $hash{'error'}='Not hash reference';
 4025:       }
 4026:       return (\%hash, $string);
 4027:   }
 4028: 
 4029:   $string =~ s/^__HASH_REF__//;
 4030: 
 4031:   while($string !~ /^__END_HASH_REF__/) {
 4032:       #key
 4033:       my $key='';
 4034:       if($string =~ /^__HASH_REF__/) {
 4035:           ($key, $string)=&str2hashref($string);
 4036:           if(defined($key->{'error'})) {
 4037:               $hash{'error'}='Bad data';
 4038:               return (\%hash, $string);
 4039:           }
 4040:       } elsif($string =~ /^__ARRAY_REF__/) {
 4041:           ($key, $string)=&str2arrayref($string);
 4042:           if($key->[0] eq 'Array reference error') {
 4043:               $hash{'error'}='Bad data';
 4044:               return (\%hash, $string);
 4045:           }
 4046:       } else {
 4047:           $string =~ s/^(.*?)=//;
 4048: 	  $key=&unescape($1);
 4049:       }
 4050:       $string =~ s/^=//;
 4051: 
 4052:       #value
 4053:       my $value='';
 4054:       if($string =~ /^__HASH_REF__/) {
 4055:           ($value, $string)=&str2hashref($string);
 4056:           if(defined($value->{'error'})) {
 4057:               $hash{'error'}='Bad data';
 4058:               return (\%hash, $string);
 4059:           }
 4060:       } elsif($string =~ /^__ARRAY_REF__/) {
 4061:           ($value, $string)=&str2arrayref($string);
 4062:           if($value->[0] eq 'Array reference error') {
 4063:               $hash{'error'}='Bad data';
 4064:               return (\%hash, $string);
 4065:           }
 4066:       } else {
 4067: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 4068:       }
 4069:       $string =~ s/^&//;
 4070: 
 4071:       $hash{$key}=$value;
 4072:   }
 4073: 
 4074:   $string =~ s/^__END_HASH_REF__//;
 4075: 
 4076:   return (\%hash, $string);
 4077: }
 4078: 
 4079: sub str2array {
 4080:     my ($string)=@_;
 4081:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 4082:     return @$array;
 4083: }
 4084: 
 4085: sub str2arrayref {
 4086:   my ($string) = @_;
 4087:   my @array;
 4088: 
 4089:   if($string !~ /^__ARRAY_REF__/) {
 4090:       if (! ($string eq '' || !defined($string))) {
 4091: 	  $array[0]='Array reference error';
 4092:       }
 4093:       return (\@array, $string);
 4094:   }
 4095: 
 4096:   $string =~ s/^__ARRAY_REF__//;
 4097: 
 4098:   while($string !~ /^__END_ARRAY_REF__/) {
 4099:       my $value='';
 4100:       if($string =~ /^__HASH_REF__/) {
 4101:           ($value, $string)=&str2hashref($string);
 4102:           if(defined($value->{'error'})) {
 4103:               $array[0] ='Array reference error';
 4104:               return (\@array, $string);
 4105:           }
 4106:       } elsif($string =~ /^__ARRAY_REF__/) {
 4107:           ($value, $string)=&str2arrayref($string);
 4108:           if($value->[0] eq 'Array reference error') {
 4109:               $array[0] ='Array reference error';
 4110:               return (\@array, $string);
 4111:           }
 4112:       } else {
 4113: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 4114:       }
 4115:       $string =~ s/^&//;
 4116: 
 4117:       push(@array, $value);
 4118:   }
 4119: 
 4120:   $string =~ s/^__END_ARRAY_REF__//;
 4121: 
 4122:   return (\@array, $string);
 4123: }
 4124: 
 4125: # -------------------------------------------------------------------Temp Store
 4126: 
 4127: sub tmpreset {
 4128:   my ($symb,$namespace,$domain,$stuname) = @_;
 4129:   if (!$symb) {
 4130:     $symb=&symbread();
 4131:     if (!$symb) { $symb= $env{'request.url'}; }
 4132:   }
 4133:   $symb=escape($symb);
 4134: 
 4135:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4136:   $namespace=~s/\//\_/g;
 4137:   $namespace=~s/\W//g;
 4138: 
 4139:   if (!$domain) { $domain=$env{'user.domain'}; }
 4140:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4141:   if ($domain eq 'public' && $stuname eq 'public') {
 4142:       $stuname=$ENV{'REMOTE_ADDR'};
 4143:   }
 4144:   my $path=LONCAPA::tempdir();
 4145:   my %hash;
 4146:   if (tie(%hash,'GDBM_File',
 4147: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4148: 	  &GDBM_WRCREAT(),0640)) {
 4149:     foreach my $key (keys(%hash)) {
 4150:       if ($key=~ /:$symb/) {
 4151: 	delete($hash{$key});
 4152:       }
 4153:     }
 4154:   }
 4155: }
 4156: 
 4157: sub tmpstore {
 4158:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4159: 
 4160:   if (!$symb) {
 4161:     $symb=&symbread();
 4162:     if (!$symb) { $symb= $env{'request.url'}; }
 4163:   }
 4164:   $symb=escape($symb);
 4165: 
 4166:   if (!$namespace) {
 4167:     # I don't think we would ever want to store this for a course.
 4168:     # it seems this will only be used if we don't have a course.
 4169:     #$namespace=$env{'request.course.id'};
 4170:     #if (!$namespace) {
 4171:       $namespace=$env{'request.state'};
 4172:     #}
 4173:   }
 4174:   $namespace=~s/\//\_/g;
 4175:   $namespace=~s/\W//g;
 4176:   if (!$domain) { $domain=$env{'user.domain'}; }
 4177:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4178:   if ($domain eq 'public' && $stuname eq 'public') {
 4179:       $stuname=$ENV{'REMOTE_ADDR'};
 4180:   }
 4181:   my $now=time;
 4182:   my %hash;
 4183:   my $path=LONCAPA::tempdir();
 4184:   if (tie(%hash,'GDBM_File',
 4185: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4186: 	  &GDBM_WRCREAT(),0640)) {
 4187:     $hash{"version:$symb"}++;
 4188:     my $version=$hash{"version:$symb"};
 4189:     my $allkeys=''; 
 4190:     foreach my $key (keys(%$storehash)) {
 4191:       $allkeys.=$key.':';
 4192:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 4193:     }
 4194:     $hash{"$version:$symb:timestamp"}=$now;
 4195:     $allkeys.='timestamp';
 4196:     $hash{"$version:keys:$symb"}=$allkeys;
 4197:     if (untie(%hash)) {
 4198:       return 'ok';
 4199:     } else {
 4200:       return "error:$!";
 4201:     }
 4202:   } else {
 4203:     return "error:$!";
 4204:   }
 4205: }
 4206: 
 4207: # -----------------------------------------------------------------Temp Restore
 4208: 
 4209: sub tmprestore {
 4210:   my ($symb,$namespace,$domain,$stuname) = @_;
 4211: 
 4212:   if (!$symb) {
 4213:     $symb=&symbread();
 4214:     if (!$symb) { $symb= $env{'request.url'}; }
 4215:   }
 4216:   $symb=escape($symb);
 4217: 
 4218:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4219: 
 4220:   if (!$domain) { $domain=$env{'user.domain'}; }
 4221:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4222:   if ($domain eq 'public' && $stuname eq 'public') {
 4223:       $stuname=$ENV{'REMOTE_ADDR'};
 4224:   }
 4225:   my %returnhash;
 4226:   $namespace=~s/\//\_/g;
 4227:   $namespace=~s/\W//g;
 4228:   my %hash;
 4229:   my $path=LONCAPA::tempdir();
 4230:   if (tie(%hash,'GDBM_File',
 4231: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4232: 	  &GDBM_READER(),0640)) {
 4233:     my $version=$hash{"version:$symb"};
 4234:     $returnhash{'version'}=$version;
 4235:     my $scope;
 4236:     for ($scope=1;$scope<=$version;$scope++) {
 4237:       my $vkeys=$hash{"$scope:keys:$symb"};
 4238:       my @keys=split(/:/,$vkeys);
 4239:       my $key;
 4240:       $returnhash{"$scope:keys"}=$vkeys;
 4241:       foreach $key (@keys) {
 4242: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4243: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4244:       }
 4245:     }
 4246:     if (!(untie(%hash))) {
 4247:       return "error:$!";
 4248:     }
 4249:   } else {
 4250:     return "error:$!";
 4251:   }
 4252:   return %returnhash;
 4253: }
 4254: 
 4255: # ----------------------------------------------------------------------- Store
 4256: 
 4257: sub store {
 4258:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4259:     my $home='';
 4260: 
 4261:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4262: 
 4263:     $symb=&symbclean($symb);
 4264:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4265: 
 4266:     if (!$domain) { $domain=$env{'user.domain'}; }
 4267:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4268: 
 4269:     &devalidate($symb,$stuname,$domain);
 4270: 
 4271:     $symb=escape($symb);
 4272:     if (!$namespace) { 
 4273:        unless ($namespace=$env{'request.course.id'}) { 
 4274:           return ''; 
 4275:        } 
 4276:     }
 4277:     if (!$home) { $home=$env{'user.home'}; }
 4278: 
 4279:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4280:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4281: 
 4282:     my $namevalue='';
 4283:     foreach my $key (keys(%$storehash)) {
 4284:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4285:     }
 4286:     $namevalue=~s/\&$//;
 4287:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 4288:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4289: }
 4290: 
 4291: # -------------------------------------------------------------- Critical Store
 4292: 
 4293: sub cstore {
 4294:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4295:     my $home='';
 4296: 
 4297:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4298: 
 4299:     $symb=&symbclean($symb);
 4300:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4301: 
 4302:     if (!$domain) { $domain=$env{'user.domain'}; }
 4303:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4304: 
 4305:     &devalidate($symb,$stuname,$domain);
 4306: 
 4307:     $symb=escape($symb);
 4308:     if (!$namespace) { 
 4309:        unless ($namespace=$env{'request.course.id'}) { 
 4310:           return ''; 
 4311:        } 
 4312:     }
 4313:     if (!$home) { $home=$env{'user.home'}; }
 4314: 
 4315:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4316:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4317: 
 4318:     my $namevalue='';
 4319:     foreach my $key (keys(%$storehash)) {
 4320:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4321:     }
 4322:     $namevalue=~s/\&$//;
 4323:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 4324:     return critical
 4325:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4326: }
 4327: 
 4328: # --------------------------------------------------------------------- Restore
 4329: 
 4330: sub restore {
 4331:     my ($symb,$namespace,$domain,$stuname) = @_;
 4332:     my $home='';
 4333: 
 4334:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4335: 
 4336:     if (!$symb) {
 4337:       unless ($symb=escape(&symbread())) { return ''; }
 4338:     } else {
 4339:       $symb=&escape(&symbclean($symb));
 4340:     }
 4341:     if (!$namespace) { 
 4342:        unless ($namespace=$env{'request.course.id'}) { 
 4343:           return ''; 
 4344:        } 
 4345:     }
 4346:     if (!$domain) { $domain=$env{'user.domain'}; }
 4347:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4348:     if (!$home) { $home=$env{'user.home'}; }
 4349:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 4350: 
 4351:     my %returnhash=();
 4352:     foreach my $line (split(/\&/,$answer)) {
 4353: 	my ($name,$value)=split(/\=/,$line);
 4354:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 4355:     }
 4356:     my $version;
 4357:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 4358:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 4359:           $returnhash{$item}=$returnhash{$version.':'.$item};
 4360:        }
 4361:     }
 4362:     return %returnhash;
 4363: }
 4364: 
 4365: # ---------------------------------------------------------- Course Description
 4366: #
 4367: #  
 4368: 
 4369: sub coursedescription {
 4370:     my ($courseid,$args)=@_;
 4371:     $courseid=~s/^\///;
 4372:     $courseid=~s/\_/\//g;
 4373:     my ($cdomain,$cnum)=split(/\//,$courseid);
 4374:     my $chome=&homeserver($cnum,$cdomain);
 4375:     my $normalid=$cdomain.'_'.$cnum;
 4376:     # need to always cache even if we get errors otherwise we keep 
 4377:     # trying and trying and trying to get the course description.
 4378:     my %envhash=();
 4379:     my %returnhash=();
 4380:     
 4381:     my $expiretime=600;
 4382:     if ($env{'request.course.id'} eq $normalid) {
 4383: 	$expiretime=120;
 4384:     }
 4385: 
 4386:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 4387:     if (!$args->{'freshen_cache'}
 4388: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 4389: 	foreach my $key (keys(%env)) {
 4390: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 4391: 	    my ($setting) = $1;
 4392: 	    $returnhash{$setting} = $env{$key};
 4393: 	}
 4394: 	return %returnhash;
 4395:     }
 4396: 
 4397:     # get the data again
 4398: 
 4399:     if (!$args->{'one_time'}) {
 4400: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 4401:     }
 4402: 
 4403:     if ($chome ne 'no_host') {
 4404:        %returnhash=&dump('environment',$cdomain,$cnum);
 4405:        if (!exists($returnhash{'con_lost'})) {
 4406: 	   my $username = $env{'user.name'}; # Defult username
 4407: 	   if(defined $args->{'user'}) {
 4408: 	       $username = $args->{'user'};
 4409: 	   }
 4410:            $returnhash{'home'}= $chome;
 4411: 	   $returnhash{'domain'} = $cdomain;
 4412: 	   $returnhash{'num'} = $cnum;
 4413:            if (!defined($returnhash{'type'})) {
 4414:                $returnhash{'type'} = 'Course';
 4415:            }
 4416:            while (my ($name,$value) = each %returnhash) {
 4417:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 4418:            }
 4419:            $returnhash{'url'}=&clutter($returnhash{'url'});
 4420:            $returnhash{'fn'}=LONCAPA::tempdir() .
 4421: 	       $username.'_'.$cdomain.'_'.$cnum;
 4422:            $envhash{'course.'.$normalid.'.home'}=$chome;
 4423:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 4424:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 4425:        }
 4426:     }
 4427:     if (!$args->{'one_time'}) {
 4428: 	&appenv(\%envhash);
 4429:     }
 4430:     return %returnhash;
 4431: }
 4432: 
 4433: sub update_released_required {
 4434:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 4435:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 4436:         $cid = $env{'request.course.id'};
 4437:         $cdom = $env{'course.'.$cid.'.domain'};
 4438:         $cnum = $env{'course.'.$cid.'.num'};
 4439:         $chome = $env{'course.'.$cid.'.home'};
 4440:     }
 4441:     if ($needsrelease) {
 4442:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 4443:         my $needsupdate;
 4444:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 4445:             $needsupdate = 1;
 4446:         } else {
 4447:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 4448:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 4449:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 4450:                 $needsupdate = 1;
 4451:             }
 4452:         }
 4453:         if ($needsupdate) {
 4454:             my %needshash = (
 4455:                              'internal.releaserequired' => $needsrelease,
 4456:                             );
 4457:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 4458:             if ($putresult eq 'ok') {
 4459:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 4460:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 4461:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 4462:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 4463:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 4464:                 }
 4465:             }
 4466:         }
 4467:     }
 4468:     return;
 4469: }
 4470: 
 4471: # -------------------------------------------------See if a user is privileged
 4472: 
 4473: sub privileged {
 4474:     my ($username,$domain)=@_;
 4475:     my $rolesdump=&reply("dump:$domain:$username:roles",
 4476: 			&homeserver($username,$domain));
 4477:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
 4478:         ($rolesdump =~ /^error:/)) {
 4479:         return 0;
 4480:     }
 4481:     my $now=time;
 4482:     if ($rolesdump ne '') {
 4483:         foreach my $entry (split(/&/,$rolesdump)) {
 4484: 	    if ($entry!~/^rolesdef_/) {
 4485: 		my ($area,$role)=split(/=/,$entry);
 4486: 		$area=~s/\_\w\w$//;
 4487: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 4488: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 4489: 		    my $active=1;
 4490: 		    if ($tend) {
 4491: 			if ($tend<$now) { $active=0; }
 4492: 		    }
 4493: 		    if ($tstart) {
 4494: 			if ($tstart>$now) { $active=0; }
 4495: 		    }
 4496: 		    if ($active) { return 1; }
 4497: 		}
 4498: 	    }
 4499: 	}
 4500:     }
 4501:     return 0;
 4502: }
 4503: 
 4504: # -------------------------------------------------------- Get user privileges
 4505: 
 4506: sub rolesinit {
 4507:     my ($domain,$username,$authhost)=@_;
 4508:     my $now=time;
 4509:     my %userroles = ('user.login.time' => $now);
 4510:     my $extra = &freeze_escape({'skipcheck' => 1});
 4511:     my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
 4512:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
 4513:         ($rolesdump =~ /^error:/)) {
 4514:         return \%userroles;
 4515:     }
 4516:     my %allroles=();
 4517:     my %allgroups=();   
 4518: 
 4519:     if ($rolesdump ne '') {
 4520:         foreach my $entry (split(/&/,$rolesdump)) {
 4521: 	  if ($entry!~/^rolesdef_/) {
 4522:             my ($area,$role)=split(/=/,$entry);
 4523: 	    $area=~s/\_\w\w$//;
 4524:             my ($trole,$tend,$tstart,$group_privs);
 4525: 	    if ($role=~/^cr/) { 
 4526: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 4527: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
 4528: 		    ($tend,$tstart)=split('_',$trest);
 4529: 		} else {
 4530: 		    $trole=$role;
 4531: 		}
 4532:             } elsif ($role =~ m|^gr/|) {
 4533:                 ($trole,$tend,$tstart) = split(/_/,$role);
 4534:                 next if ($tstart eq '-1');
 4535:                 ($trole,$group_privs) = split(/\//,$trole);
 4536:                 $group_privs = &unescape($group_privs);
 4537: 	    } else {
 4538: 		($trole,$tend,$tstart)=split(/_/,$role);
 4539: 	    }
 4540: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 4541: 					 $username);
 4542: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 4543:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 4544:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 4545:             if (($area ne '') && ($trole ne '')) {
 4546: 		my $spec=$trole.'.'.$area;
 4547: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 4548: 		if ($trole =~ /^cr\//) {
 4549:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 4550:                 } elsif ($trole eq 'gr') {
 4551:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 4552: 		} else {
 4553:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 4554: 		}
 4555:             }
 4556:           }
 4557:         }
 4558:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 4559:         $userroles{'user.adv'}    = $adv;
 4560: 	$userroles{'user.author'} = $author;
 4561:         $env{'user.adv'}=$adv;
 4562:     }
 4563:     return \%userroles;  
 4564: }
 4565: 
 4566: sub set_arearole {
 4567:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 4568: # log the associated role with the area
 4569:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 4570:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 4571: }
 4572: 
 4573: sub custom_roleprivs {
 4574:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 4575:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 4576:     my $homsvr=homeserver($rauthor,$rdomain);
 4577:     if (&hostname($homsvr) ne '') {
 4578:         my ($rdummy,$roledef)=
 4579:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 4580:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4581:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 4582:             if (defined($syspriv)) {
 4583:                 if ($trest =~ /^$match_community$/) {
 4584:                     $syspriv =~ s/bre\&S//; 
 4585:                 }
 4586:                 $$allroles{'cm./'}.=':'.$syspriv;
 4587:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 4588:             }
 4589:             if ($tdomain ne '') {
 4590:                 if (defined($dompriv)) {
 4591:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 4592:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 4593:                 }
 4594:                 if (($trest ne '') && (defined($coursepriv))) {
 4595:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 4596:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 4597:                 }
 4598:             }
 4599:         }
 4600:     }
 4601: }
 4602: 
 4603: sub group_roleprivs {
 4604:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 4605:     my $access = 1;
 4606:     my $now = time;
 4607:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 4608:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 4609:     if ($access) {
 4610:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 4611:         $$allgroups{$course}{$group} .=':'.$group_privs;
 4612:     }
 4613: }
 4614: 
 4615: sub standard_roleprivs {
 4616:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 4617:     if (defined($pr{$trole.':s'})) {
 4618:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 4619:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 4620:     }
 4621:     if ($tdomain ne '') {
 4622:         if (defined($pr{$trole.':d'})) {
 4623:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 4624:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 4625:         }
 4626:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 4627:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 4628:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 4629:         }
 4630:     }
 4631: }
 4632: 
 4633: sub set_userprivs {
 4634:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 4635:     my $author=0;
 4636:     my $adv=0;
 4637:     my %grouproles = ();
 4638:     if (keys(%{$allgroups}) > 0) {
 4639:         my @groupkeys; 
 4640:         foreach my $role (keys(%{$allroles})) {
 4641:             push(@groupkeys,$role);
 4642:         }
 4643:         if (ref($groups_roles) eq 'HASH') {
 4644:             foreach my $key (keys(%{$groups_roles})) {
 4645:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 4646:                     push(@groupkeys,$key);
 4647:                 }
 4648:             }
 4649:         }
 4650:         if (@groupkeys > 0) {
 4651:             foreach my $role (@groupkeys) {
 4652:                 my ($trole,$area,$sec,$extendedarea);
 4653:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 4654:                     $trole = $1;
 4655:                     $area = $2;
 4656:                     $sec = $3;
 4657:                     $extendedarea = $area.$sec;
 4658:                     if (exists($$allgroups{$area})) {
 4659:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 4660:                             my $spec = $trole.'.'.$extendedarea;
 4661:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 4662:                                                 $$allgroups{$area}{$group};
 4663:                         }
 4664:                     }
 4665:                 }
 4666:             }
 4667:         }
 4668:     }
 4669:     foreach my $group (keys(%grouproles)) {
 4670:         $$allroles{$group} = $grouproles{$group};
 4671:     }
 4672:     foreach my $role (keys(%{$allroles})) {
 4673:         my %thesepriv;
 4674:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 4675:         foreach my $item (split(/:/,$$allroles{$role})) {
 4676:             if ($item ne '') {
 4677:                 my ($privilege,$restrictions)=split(/&/,$item);
 4678:                 if ($restrictions eq '') {
 4679:                     $thesepriv{$privilege}='F';
 4680:                 } elsif ($thesepriv{$privilege} ne 'F') {
 4681:                     $thesepriv{$privilege}.=$restrictions;
 4682:                 }
 4683:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 4684:             }
 4685:         }
 4686:         my $thesestr='';
 4687:         foreach my $priv (sort(keys(%thesepriv))) {
 4688: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 4689: 	}
 4690:         $userroles->{'user.priv.'.$role} = $thesestr;
 4691:     }
 4692:     return ($author,$adv);
 4693: }
 4694: 
 4695: sub role_status {
 4696:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 4697:     my @pwhere = ();
 4698:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 4699:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
 4700:         unless (!defined($$role) || $$role eq '') {
 4701:             $$where=join('.',@pwhere);
 4702:             $$trolecode=$$role.'.'.$$where;
 4703:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 4704:             $$tstatus='is';
 4705:             if ($$tstart && $$tstart>$update) {
 4706:                 $$tstatus='future';
 4707:                 if ($$tstart<$now) {
 4708:                     if ($$tstart && $$tstart>$refresh) {
 4709:                         if (($$where ne '') && ($$role ne '')) {
 4710:                             my (%allroles,%allgroups,$group_privs,
 4711:                                 %groups_roles,@rolecodes);
 4712:                             my %userroles = (
 4713:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 4714:                             );
 4715:                             @rolecodes = ('cm'); 
 4716:                             my $spec=$$role.'.'.$$where;
 4717:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 4718:                             if ($$role =~ /^cr\//) {
 4719:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 4720:                                 push(@rolecodes,'cr');
 4721:                             } elsif ($$role eq 'gr') {
 4722:                                 push(@rolecodes,$$role);
 4723:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 4724:                                                     $env{'user.name'});
 4725:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 4726:                                 (undef,my $group_privs) = split(/\//,$trole);
 4727:                                 $group_privs = &unescape($group_privs);
 4728:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 4729:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 4730:                                 &get_groups_roles($tdomain,$trest,
 4731:                                                   \%course_roles,\@rolecodes,
 4732:                                                   \%groups_roles);
 4733:                             } else {
 4734:                                 push(@rolecodes,$$role);
 4735:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 4736:                             }
 4737:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
 4738:                             &appenv(\%userroles,\@rolecodes);
 4739:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 4740:                         }
 4741:                     }
 4742:                     $$tstatus = 'is';
 4743:                 }
 4744:             }
 4745:             if ($$tend) {
 4746:                 if ($$tend<$update) {
 4747:                     $$tstatus='expired';
 4748:                 } elsif ($$tend<$now) {
 4749:                     $$tstatus='will_not';
 4750:                 }
 4751:             }
 4752:         }
 4753:     }
 4754: }
 4755: 
 4756: sub get_groups_roles {
 4757:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 4758:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 4759:                   (ref($rolecodes) eq 'ARRAY') && 
 4760:                   (ref($groups_roles) eq 'HASH')); 
 4761:     if (keys(%{$cdom_courseroles}) > 0) {
 4762:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 4763:         if ($cdom ne '' && $cnum ne '') {
 4764:             foreach my $key (keys(%{$cdom_courseroles})) {
 4765:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 4766:                     my $crsrole = $1;
 4767:                     my $crssec = $2;
 4768:                     if ($crsrole =~ /^cr/) {
 4769:                         unless (grep(/^cr$/,@{$rolecodes})) {
 4770:                             push(@{$rolecodes},'cr');
 4771:                         }
 4772:                     } else {
 4773:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 4774:                             push(@{$rolecodes},$crsrole);
 4775:                         }
 4776:                     }
 4777:                     my $rolekey = "$crsrole./$cdom/$cnum";
 4778:                     if ($crssec ne '') {
 4779:                         $rolekey .= "/$crssec";
 4780:                     }
 4781:                     $rolekey .= './';
 4782:                     $groups_roles->{$rolekey} = $rolecodes;
 4783:                 }
 4784:             }
 4785:         }
 4786:     }
 4787:     return;
 4788: }
 4789: 
 4790: sub delete_env_groupprivs {
 4791:     my ($where,$courseroles,$possroles) = @_;
 4792:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 4793:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 4794:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 4795:         %{$courseroles->{$udom}} =
 4796:             &get_my_roles('','','userroles',['active'],
 4797:                           $possroles,[$udom],1);
 4798:     }
 4799:     if (ref($courseroles->{$udom}) eq 'HASH') {
 4800:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 4801:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 4802:             my $area = '/'.$cdom.'/'.$cnum;
 4803:             my $privkey = "user.priv.$crsrole.$area";
 4804:             if ($crssec ne '') {
 4805:                 $privkey .= '/'.$crssec;
 4806:             }
 4807:             $privkey .= ".$area/$group";
 4808:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 4809:         }
 4810:     }
 4811:     return;
 4812: }
 4813: 
 4814: sub check_adhoc_privs {
 4815:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
 4816:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 4817:     if ($env{$cckey}) {
 4818:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 4819:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 4820:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 4821:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 4822:         }
 4823:     } else {
 4824:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 4825:     }
 4826: }
 4827: 
 4828: sub set_adhoc_privileges {
 4829: # role can be cc or ca
 4830:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
 4831:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 4832:     my $spec = $role.'.'.$area;
 4833:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 4834:                                   $env{'user.name'});
 4835:     my %ccrole = ();
 4836:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
 4837:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
 4838:     &appenv(\%userroles,[$role,'cm']);
 4839:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 4840:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 4841:         &appenv( {'request.role'        => $spec,
 4842:                   'request.role.domain' => $dcdom,
 4843:                   'request.course.sec'  => ''
 4844:                  }
 4845:                );
 4846:         my $tadv=0;
 4847:         if (&allowed('adv') eq 'F') { $tadv=1; }
 4848:         &appenv({'request.role.adv'    => $tadv});
 4849:     }
 4850: }
 4851: 
 4852: # --------------------------------------------------------------- get interface
 4853: 
 4854: sub get {
 4855:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4856:    my $items='';
 4857:    foreach my $item (@$storearr) {
 4858:        $items.=&escape($item).'&';
 4859:    }
 4860:    $items=~s/\&$//;
 4861:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4862:    if (!$uname) { $uname=$env{'user.name'}; }
 4863:    my $uhome=&homeserver($uname,$udomain);
 4864: 
 4865:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 4866:    my @pairs=split(/\&/,$rep);
 4867:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 4868:      return @pairs;
 4869:    }
 4870:    my %returnhash=();
 4871:    my $i=0;
 4872:    foreach my $item (@$storearr) {
 4873:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 4874:       $i++;
 4875:    }
 4876:    return %returnhash;
 4877: }
 4878: 
 4879: # --------------------------------------------------------------- del interface
 4880: 
 4881: sub del {
 4882:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4883:    my $items='';
 4884:    foreach my $item (@$storearr) {
 4885:        $items.=&escape($item).'&';
 4886:    }
 4887: 
 4888:    $items=~s/\&$//;
 4889:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4890:    if (!$uname) { $uname=$env{'user.name'}; }
 4891:    my $uhome=&homeserver($uname,$udomain);
 4892:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 4893: }
 4894: 
 4895: # -------------------------------------------------------------- dump interface
 4896: 
 4897: sub dump {
 4898:     my ($namespace,$udomain,$uname,$regexp,$range,$extra)=@_;
 4899:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4900:     if (!$uname) { $uname=$env{'user.name'}; }
 4901:     my $uhome=&homeserver($uname,$udomain);
 4902:     if ($regexp) {
 4903: 	$regexp=&escape($regexp);
 4904:     } else {
 4905: 	$regexp='.';
 4906:     }
 4907:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range:$extra",$uhome);
 4908:     my @pairs=split(/\&/,$rep);
 4909:     my %returnhash=();
 4910:     if (!($rep =~ /^error/ )) {
 4911: 	foreach my $item (@pairs) {
 4912: 	    my ($key,$value)=split(/=/,$item,2);
 4913: 	    $key = &unescape($key);
 4914: 	    next if ($key =~ /^error: 2 /);
 4915: 	    $returnhash{$key}=&thaw_unescape($value);
 4916: 	}
 4917:     }
 4918:     return %returnhash;
 4919: }
 4920: 
 4921: 
 4922: # --------------------------------------------------------- dumpstore interface
 4923: 
 4924: sub dumpstore {
 4925:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 4926:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4927:    if (!$uname) { $uname=$env{'user.name'}; }
 4928:    my $uhome=&homeserver($uname,$udomain);
 4929:    if ($regexp) {
 4930:        $regexp=&escape($regexp);
 4931:    } else {
 4932:        $regexp='.';
 4933:    }
 4934:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 4935:    my @pairs=split(/\&/,$rep);
 4936:    my %returnhash=();
 4937:    foreach my $item (@pairs) {
 4938:        my ($key,$value)=split(/=/,$item,2);
 4939:        next if ($key =~ /^error: 2 /);
 4940:        $returnhash{$key}=&thaw_unescape($value);
 4941:    }
 4942:    return %returnhash;
 4943: }
 4944: 
 4945: # -------------------------------------------------------------- keys interface
 4946: 
 4947: sub getkeys {
 4948:    my ($namespace,$udomain,$uname)=@_;
 4949:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4950:    if (!$uname) { $uname=$env{'user.name'}; }
 4951:    my $uhome=&homeserver($uname,$udomain);
 4952:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 4953:    my @keyarray=();
 4954:    foreach my $key (split(/\&/,$rep)) {
 4955:       next if ($key =~ /^error: 2 /);
 4956:       push(@keyarray,&unescape($key));
 4957:    }
 4958:    return @keyarray;
 4959: }
 4960: 
 4961: # --------------------------------------------------------------- currentdump
 4962: sub currentdump {
 4963:    my ($courseid,$sdom,$sname)=@_;
 4964:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 4965:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 4966:    $sname    = $env{'user.name'}         if (! defined($sname));
 4967:    my $uhome = &homeserver($sname,$sdom);
 4968:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 4969:    return if ($rep =~ /^(error:|no_such_host)/);
 4970:    #
 4971:    my %returnhash=();
 4972:    #
 4973:    if ($rep eq "unknown_cmd") { 
 4974:        # an old lond will not know currentdump
 4975:        # Do a dump and make it look like a currentdump
 4976:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 4977:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 4978:        my %hash = @tmp;
 4979:        @tmp=();
 4980:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 4981:    } else {
 4982:        my @pairs=split(/\&/,$rep);
 4983:        foreach my $pair (@pairs) {
 4984:            my ($key,$value)=split(/=/,$pair,2);
 4985:            my ($symb,$param) = split(/:/,$key);
 4986:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 4987:                                                         &thaw_unescape($value);
 4988:        }
 4989:    }
 4990:    return %returnhash;
 4991: }
 4992: 
 4993: sub convert_dump_to_currentdump{
 4994:     my %hash = %{shift()};
 4995:     my %returnhash;
 4996:     # Code ripped from lond, essentially.  The only difference
 4997:     # here is the unescaping done by lonnet::dump().  Conceivably
 4998:     # we might run in to problems with parameter names =~ /^v\./
 4999:     while (my ($key,$value) = each(%hash)) {
 5000:         my ($v,$symb,$param) = split(/:/,$key);
 5001: 	$symb  = &unescape($symb);
 5002: 	$param = &unescape($param);
 5003:         next if ($v eq 'version' || $symb eq 'keys');
 5004:         next if (exists($returnhash{$symb}) &&
 5005:                  exists($returnhash{$symb}->{$param}) &&
 5006:                  $returnhash{$symb}->{'v.'.$param} > $v);
 5007:         $returnhash{$symb}->{$param}=$value;
 5008:         $returnhash{$symb}->{'v.'.$param}=$v;
 5009:     }
 5010:     #
 5011:     # Remove all of the keys in the hashes which keep track of
 5012:     # the version of the parameter.
 5013:     while (my ($symb,$param_hash) = each(%returnhash)) {
 5014:         # use a foreach because we are going to delete from the hash.
 5015:         foreach my $key (keys(%$param_hash)) {
 5016:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 5017:         }
 5018:     }
 5019:     return \%returnhash;
 5020: }
 5021: 
 5022: # ------------------------------------------------------ critical inc interface
 5023: 
 5024: sub cinc {
 5025:     return &inc(@_,'critical');
 5026: }
 5027: 
 5028: # --------------------------------------------------------------- inc interface
 5029: 
 5030: sub inc {
 5031:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 5032:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5033:     if (!$uname) { $uname=$env{'user.name'}; }
 5034:     my $uhome=&homeserver($uname,$udomain);
 5035:     my $items='';
 5036:     if (! ref($store)) {
 5037:         # got a single value, so use that instead
 5038:         $items = &escape($store).'=&';
 5039:     } elsif (ref($store) eq 'SCALAR') {
 5040:         $items = &escape($$store).'=&';        
 5041:     } elsif (ref($store) eq 'ARRAY') {
 5042:         $items = join('=&',map {&escape($_);} @{$store});
 5043:     } elsif (ref($store) eq 'HASH') {
 5044:         while (my($key,$value) = each(%{$store})) {
 5045:             $items.= &escape($key).'='.&escape($value).'&';
 5046:         }
 5047:     }
 5048:     $items=~s/\&$//;
 5049:     if ($critical) {
 5050: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 5051:     } else {
 5052: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 5053:     }
 5054: }
 5055: 
 5056: # --------------------------------------------------------------- put interface
 5057: 
 5058: sub put {
 5059:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5060:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5061:    if (!$uname) { $uname=$env{'user.name'}; }
 5062:    my $uhome=&homeserver($uname,$udomain);
 5063:    my $items='';
 5064:    foreach my $item (keys(%$storehash)) {
 5065:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5066:    }
 5067:    $items=~s/\&$//;
 5068:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5069: }
 5070: 
 5071: # ------------------------------------------------------------ newput interface
 5072: 
 5073: sub newput {
 5074:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5075:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5076:    if (!$uname) { $uname=$env{'user.name'}; }
 5077:    my $uhome=&homeserver($uname,$udomain);
 5078:    my $items='';
 5079:    foreach my $key (keys(%$storehash)) {
 5080:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5081:    }
 5082:    $items=~s/\&$//;
 5083:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 5084: }
 5085: 
 5086: # ---------------------------------------------------------  putstore interface
 5087: 
 5088: sub putstore {
 5089:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5090:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5091:    if (!$uname) { $uname=$env{'user.name'}; }
 5092:    my $uhome=&homeserver($uname,$udomain);
 5093:    my $items='';
 5094:    foreach my $key (keys(%$storehash)) {
 5095:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 5096:    }
 5097:    $items=~s/\&$//;
 5098:    my $esc_symb=&escape($symb);
 5099:    my $esc_v=&escape($version);
 5100:    my $reply =
 5101:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 5102: 	      $uhome);
 5103:    if ($reply eq 'unknown_cmd') {
 5104:        # gfall back to way things use to be done
 5105:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 5106: 			    $uname);
 5107:    }
 5108:    return $reply;
 5109: }
 5110: 
 5111: sub old_putstore {
 5112:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5113:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5114:     if (!$uname) { $uname=$env{'user.name'}; }
 5115:     my $uhome=&homeserver($uname,$udomain);
 5116:     my %newstorehash;
 5117:     foreach my $item (keys(%$storehash)) {
 5118: 	my $key = $version.':'.&escape($symb).':'.$item;
 5119: 	$newstorehash{$key} = $storehash->{$item};
 5120:     }
 5121:     my $items='';
 5122:     my %allitems = ();
 5123:     foreach my $item (keys(%newstorehash)) {
 5124: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 5125: 	    my $key = $1.':keys:'.$2;
 5126: 	    $allitems{$key} .= $3.':';
 5127: 	}
 5128: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 5129:     }
 5130:     foreach my $item (keys(%allitems)) {
 5131: 	$allitems{$item} =~ s/\:$//;
 5132: 	$items.= $item.'='.$allitems{$item}.'&';
 5133:     }
 5134:     $items=~s/\&$//;
 5135:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5136: }
 5137: 
 5138: # ------------------------------------------------------ critical put interface
 5139: 
 5140: sub cput {
 5141:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5142:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5143:    if (!$uname) { $uname=$env{'user.name'}; }
 5144:    my $uhome=&homeserver($uname,$udomain);
 5145:    my $items='';
 5146:    foreach my $item (keys(%$storehash)) {
 5147:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5148:    }
 5149:    $items=~s/\&$//;
 5150:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 5151: }
 5152: 
 5153: # -------------------------------------------------------------- eget interface
 5154: 
 5155: sub eget {
 5156:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5157:    my $items='';
 5158:    foreach my $item (@$storearr) {
 5159:        $items.=&escape($item).'&';
 5160:    }
 5161:    $items=~s/\&$//;
 5162:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5163:    if (!$uname) { $uname=$env{'user.name'}; }
 5164:    my $uhome=&homeserver($uname,$udomain);
 5165:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 5166:    my @pairs=split(/\&/,$rep);
 5167:    my %returnhash=();
 5168:    my $i=0;
 5169:    foreach my $item (@$storearr) {
 5170:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5171:       $i++;
 5172:    }
 5173:    return %returnhash;
 5174: }
 5175: 
 5176: # ------------------------------------------------------------ tmpput interface
 5177: sub tmpput {
 5178:     my ($storehash,$server,$context)=@_;
 5179:     my $items='';
 5180:     foreach my $item (keys(%$storehash)) {
 5181: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5182:     }
 5183:     $items=~s/\&$//;
 5184:     if (defined($context)) {
 5185:         $items .= ':'.&escape($context);
 5186:     }
 5187:     return &reply("tmpput:$items",$server);
 5188: }
 5189: 
 5190: # ------------------------------------------------------------ tmpget interface
 5191: sub tmpget {
 5192:     my ($token,$server)=@_;
 5193:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5194:     my $rep=&reply("tmpget:$token",$server);
 5195:     my %returnhash;
 5196:     foreach my $item (split(/\&/,$rep)) {
 5197: 	my ($key,$value)=split(/=/,$item);
 5198:         next if ($key =~ /^error: 2 /);
 5199: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 5200:     }
 5201:     return %returnhash;
 5202: }
 5203: 
 5204: # ------------------------------------------------------------ tmpdel interface
 5205: sub tmpdel {
 5206:     my ($token,$server)=@_;
 5207:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5208:     return &reply("tmpdel:$token",$server);
 5209: }
 5210: 
 5211: # -------------------------------------------------- portfolio access checking
 5212: 
 5213: sub portfolio_access {
 5214:     my ($requrl) = @_;
 5215:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 5216:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 5217:     if ($result) {
 5218:         my %setters;
 5219:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 5220:             my ($startblock,$endblock) =
 5221:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 5222:             if ($startblock && $endblock) {
 5223:                 return 'B';
 5224:             }
 5225:         } else {
 5226:             my ($startblock,$endblock) =
 5227:                 &Apache::loncommon::blockcheck(\%setters,'port');
 5228:             if ($startblock && $endblock) {
 5229:                 return 'B';
 5230:             }
 5231:         }
 5232:     }
 5233:     if ($result eq 'ok') {
 5234:        return 'F';
 5235:     } elsif ($result =~ /^[^:]+:guest_/) {
 5236:        return 'A';
 5237:     }
 5238:     return '';
 5239: }
 5240: 
 5241: sub get_portfolio_access {
 5242:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 5243: 
 5244:     if (!ref($access_hash)) {
 5245: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 5246: 	my %access_controls = &get_access_controls($current_perms,$group,
 5247: 						   $file_name);
 5248: 	$access_hash = $access_controls{$file_name};
 5249:     }
 5250: 
 5251:     my ($public,$guest,@domains,@users,@courses,@groups);
 5252:     my $now = time;
 5253:     if (ref($access_hash) eq 'HASH') {
 5254:         foreach my $key (keys(%{$access_hash})) {
 5255:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 5256:             if ($start > $now) {
 5257:                 next;
 5258:             }
 5259:             if ($end && $end<$now) {
 5260:                 next;
 5261:             }
 5262:             if ($scope eq 'public') {
 5263:                 $public = $key;
 5264:                 last;
 5265:             } elsif ($scope eq 'guest') {
 5266:                 $guest = $key;
 5267:             } elsif ($scope eq 'domains') {
 5268:                 push(@domains,$key);
 5269:             } elsif ($scope eq 'users') {
 5270:                 push(@users,$key);
 5271:             } elsif ($scope eq 'course') {
 5272:                 push(@courses,$key);
 5273:             } elsif ($scope eq 'group') {
 5274:                 push(@groups,$key);
 5275:             }
 5276:         }
 5277:         if ($public) {
 5278:             return 'ok';
 5279:         }
 5280:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 5281:             if ($guest) {
 5282:                 return $guest;
 5283:             }
 5284:         } else {
 5285:             if (@domains > 0) {
 5286:                 foreach my $domkey (@domains) {
 5287:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 5288:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 5289:                             return 'ok';
 5290:                         }
 5291:                     }
 5292:                 }
 5293:             }
 5294:             if (@users > 0) {
 5295:                 foreach my $userkey (@users) {
 5296:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 5297:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 5298:                             if (ref($item) eq 'HASH') {
 5299:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 5300:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 5301:                                     return 'ok';
 5302:                                 }
 5303:                             }
 5304:                         }
 5305:                     } 
 5306:                 }
 5307:             }
 5308:             my %roleshash;
 5309:             my @courses_and_groups = @courses;
 5310:             push(@courses_and_groups,@groups); 
 5311:             if (@courses_and_groups > 0) {
 5312:                 my (%allgroups,%allroles); 
 5313:                 my ($start,$end,$role,$sec,$group);
 5314:                 foreach my $envkey (%env) {
 5315:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 5316:                         my $cid = $2.'_'.$3; 
 5317:                         if ($1 eq 'gr') {
 5318:                             $group = $4;
 5319:                             $allgroups{$cid}{$group} = $env{$envkey};
 5320:                         } else {
 5321:                             if ($4 eq '') {
 5322:                                 $sec = 'none';
 5323:                             } else {
 5324:                                 $sec = $4;
 5325:                             }
 5326:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 5327:                         }
 5328:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 5329:                         my $cid = $2.'_'.$3;
 5330:                         if ($4 eq '') {
 5331:                             $sec = 'none';
 5332:                         } else {
 5333:                             $sec = $4;
 5334:                         }
 5335:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 5336:                     }
 5337:                 }
 5338:                 if (keys(%allroles) == 0) {
 5339:                     return;
 5340:                 }
 5341:                 foreach my $key (@courses_and_groups) {
 5342:                     my %content = %{$$access_hash{$key}};
 5343:                     my $cnum = $content{'number'};
 5344:                     my $cdom = $content{'domain'};
 5345:                     my $cid = $cdom.'_'.$cnum;
 5346:                     if (!exists($allroles{$cid})) {
 5347:                         next;
 5348:                     }    
 5349:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 5350:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 5351:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 5352:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 5353:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 5354:                         foreach my $role (keys(%{$allroles{$cid}})) {
 5355:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 5356:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 5357:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 5358:                                         if (grep/^all$/,@sections) {
 5359:                                             return 'ok';
 5360:                                         } else {
 5361:                                             if (grep/^$sec$/,@sections) {
 5362:                                                 return 'ok';
 5363:                                             }
 5364:                                         }
 5365:                                     }
 5366:                                 }
 5367:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 5368:                                     if (grep/^none$/,@groups) {
 5369:                                         return 'ok';
 5370:                                     }
 5371:                                 } else {
 5372:                                     if (grep/^all$/,@groups) {
 5373:                                         return 'ok';
 5374:                                     } 
 5375:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 5376:                                         if (grep/^$group$/,@groups) {
 5377:                                             return 'ok';
 5378:                                         }
 5379:                                     }
 5380:                                 } 
 5381:                             }
 5382:                         }
 5383:                     }
 5384:                 }
 5385:             }
 5386:             if ($guest) {
 5387:                 return $guest;
 5388:             }
 5389:         }
 5390:     }
 5391:     return;
 5392: }
 5393: 
 5394: sub course_group_datechecker {
 5395:     my ($dates,$now,$status) = @_;
 5396:     my ($start,$end) = split(/\./,$dates);
 5397:     if (!$start && !$end) {
 5398:         return 'ok';
 5399:     }
 5400:     if (grep/^active$/,@{$status}) {
 5401:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 5402:             return 'ok';
 5403:         }
 5404:     }
 5405:     if (grep/^previous$/,@{$status}) {
 5406:         if ($end > $now ) {
 5407:             return 'ok';
 5408:         }
 5409:     }
 5410:     if (grep/^future$/,@{$status}) {
 5411:         if ($start > $now) {
 5412:             return 'ok';
 5413:         }
 5414:     }
 5415:     return; 
 5416: }
 5417: 
 5418: sub parse_portfolio_url {
 5419:     my ($url) = @_;
 5420: 
 5421:     my ($type,$udom,$unum,$group,$file_name);
 5422:     
 5423:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 5424: 	$type = 1;
 5425:         $udom = $1;
 5426:         $unum = $2;
 5427:         $file_name = $3;
 5428:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 5429: 	$type = 2;
 5430:         $udom = $1;
 5431:         $unum = $2;
 5432:         $group = $3;
 5433:         $file_name = $3.'/'.$4;
 5434:     }
 5435:     if (wantarray) {
 5436: 	return ($type,$udom,$unum,$file_name,$group);
 5437:     }
 5438:     return $type;
 5439: }
 5440: 
 5441: sub is_portfolio_url {
 5442:     my ($url) = @_;
 5443:     return scalar(&parse_portfolio_url($url));
 5444: }
 5445: 
 5446: sub is_portfolio_file {
 5447:     my ($file) = @_;
 5448:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 5449:         return 1;
 5450:     }
 5451:     return;
 5452: }
 5453: 
 5454: sub usertools_access {
 5455:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 5456:     my ($access,%tools);
 5457:     if ($context eq '') {
 5458:         $context = 'tools';
 5459:     }
 5460:     if ($context eq 'requestcourses') {
 5461:         %tools = (
 5462:                       official   => 1,
 5463:                       unofficial => 1,
 5464:                       community  => 1,
 5465:                  );
 5466:     } else {
 5467:         %tools = (
 5468:                       aboutme   => 1,
 5469:                       blog      => 1,
 5470:                       portfolio => 1,
 5471:                  );
 5472:     }
 5473:     return if (!defined($tools{$tool}));
 5474: 
 5475:     if ((!defined($udom)) || (!defined($uname))) {
 5476:         $udom = $env{'user.domain'};
 5477:         $uname = $env{'user.name'};
 5478:     }
 5479: 
 5480:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 5481:         if ($action ne 'reload') {
 5482:             if ($context eq 'requestcourses') {
 5483:                 return $env{'environment.canrequest.'.$tool};
 5484:             } else {
 5485:                 return $env{'environment.availabletools.'.$tool};
 5486:             }
 5487:         }
 5488:     }
 5489: 
 5490:     my ($toolstatus,$inststatus);
 5491: 
 5492:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 5493:          ($action ne 'reload')) {
 5494:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
 5495:         $inststatus = $env{'environment.inststatus'};
 5496:     } else {
 5497:         if (ref($userenvref) eq 'HASH') {
 5498:             $toolstatus = $userenvref->{$context.'.'.$tool};
 5499:             $inststatus = $userenvref->{'inststatus'};
 5500:         } else {
 5501:             my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
 5502:             $toolstatus = $userenv{$context.'.'.$tool};
 5503:             $inststatus = $userenv{'inststatus'};
 5504:         }
 5505:     }
 5506: 
 5507:     if ($toolstatus ne '') {
 5508:         if ($toolstatus) {
 5509:             $access = 1;
 5510:         } else {
 5511:             $access = 0;
 5512:         }
 5513:         return $access;
 5514:     }
 5515: 
 5516:     my ($is_adv,%domdef);
 5517:     if (ref($is_advref) eq 'HASH') {
 5518:         $is_adv = $is_advref->{'is_adv'};
 5519:     } else {
 5520:         $is_adv = &is_advanced_user($udom,$uname);
 5521:     }
 5522:     if (ref($domdefref) eq 'HASH') {
 5523:         %domdef = %{$domdefref};
 5524:     } else {
 5525:         %domdef = &get_domain_defaults($udom);
 5526:     }
 5527:     if (ref($domdef{$tool}) eq 'HASH') {
 5528:         if ($is_adv) {
 5529:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 5530:                 if ($domdef{$tool}{'_LC_adv'}) { 
 5531:                     $access = 1;
 5532:                 } else {
 5533:                     $access = 0;
 5534:                 }
 5535:                 return $access;
 5536:             }
 5537:         }
 5538:         if ($inststatus ne '') {
 5539:             my ($hasaccess,$hasnoaccess);
 5540:             foreach my $affiliation (split(/:/,$inststatus)) {
 5541:                 if ($domdef{$tool}{$affiliation} ne '') { 
 5542:                     if ($domdef{$tool}{$affiliation}) {
 5543:                         $hasaccess = 1;
 5544:                     } else {
 5545:                         $hasnoaccess = 1;
 5546:                     }
 5547:                 }
 5548:             }
 5549:             if ($hasaccess || $hasnoaccess) {
 5550:                 if ($hasaccess) {
 5551:                     $access = 1;
 5552:                 } elsif ($hasnoaccess) {
 5553:                     $access = 0; 
 5554:                 }
 5555:                 return $access;
 5556:             }
 5557:         } else {
 5558:             if ($domdef{$tool}{'default'} ne '') {
 5559:                 if ($domdef{$tool}{'default'}) {
 5560:                     $access = 1;
 5561:                 } elsif ($domdef{$tool}{'default'} == 0) {
 5562:                     $access = 0;
 5563:                 }
 5564:                 return $access;
 5565:             }
 5566:         }
 5567:     } else {
 5568:         if ($context eq 'tools') {
 5569:             $access = 1;
 5570:         } else {
 5571:             $access = 0;
 5572:         }
 5573:         return $access;
 5574:     }
 5575: }
 5576: 
 5577: sub is_course_owner {
 5578:     my ($cdom,$cnum,$udom,$uname) = @_;
 5579:     if (($udom eq '') || ($uname eq '')) {
 5580:         $udom = $env{'user.domain'};
 5581:         $uname = $env{'user.name'};
 5582:     }
 5583:     unless (($udom eq '') || ($uname eq '')) {
 5584:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 5585:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 5586:                 return 1;
 5587:             } else {
 5588:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 5589:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 5590:                     return 1;
 5591:                 }
 5592:             }
 5593:         }
 5594:     }
 5595:     return;
 5596: }
 5597: 
 5598: sub is_advanced_user {
 5599:     my ($udom,$uname) = @_;
 5600:     if ($udom ne '' && $uname ne '') {
 5601:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 5602:             if (wantarray) {
 5603:                 return ($env{'user.adv'},$env{'user.author'});
 5604:             } else {
 5605:                 return $env{'user.adv'};
 5606:             }
 5607:         }
 5608:     }
 5609:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 5610:     my %allroles;
 5611:     my ($is_adv,$is_author);
 5612:     foreach my $role (keys(%roleshash)) {
 5613:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 5614:         my $area = '/'.$tdomain.'/'.$trest;
 5615:         if ($sec ne '') {
 5616:             $area .= '/'.$sec;
 5617:         }
 5618:         if (($area ne '') && ($trole ne '')) {
 5619:             my $spec=$trole.'.'.$area;
 5620:             if ($trole =~ /^cr\//) {
 5621:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 5622:             } elsif ($trole ne 'gr') {
 5623:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 5624:             }
 5625:             if ($trole eq 'au') {
 5626:                 $is_author = 1;
 5627:             }
 5628:         }
 5629:     }
 5630:     foreach my $role (keys(%allroles)) {
 5631:         last if ($is_adv);
 5632:         foreach my $item (split(/:/,$allroles{$role})) {
 5633:             if ($item ne '') {
 5634:                 my ($privilege,$restrictions)=split(/&/,$item);
 5635:                 if ($privilege eq 'adv') {
 5636:                     $is_adv = 1;
 5637:                     last;
 5638:                 }
 5639:             }
 5640:         }
 5641:     }
 5642:     if (wantarray) {
 5643:         return ($is_adv,$is_author);
 5644:     }
 5645:     return $is_adv;
 5646: }
 5647: 
 5648: sub check_can_request {
 5649:     my ($dom,$can_request,$request_domains) = @_;
 5650:     my $canreq = 0;
 5651:     my ($types,$typename) = &Apache::loncommon::course_types();
 5652:     my @options = ('approval','validate','autolimit');
 5653:     my $optregex = join('|',@options);
 5654:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 5655:         foreach my $type (@{$types}) {
 5656:             if (&usertools_access($env{'user.name'},
 5657:                                   $env{'user.domain'},
 5658:                                   $type,undef,'requestcourses')) {
 5659:                 $canreq ++;
 5660:                 if (ref($request_domains) eq 'HASH') {
 5661:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 5662:                 }
 5663:                 if ($dom eq $env{'user.domain'}) {
 5664:                     $can_request->{$type} = 1;
 5665:                 }
 5666:             }
 5667:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 5668:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 5669:                 if (@curr > 0) {
 5670:                     foreach my $item (@curr) {
 5671:                         if (ref($request_domains) eq 'HASH') {
 5672:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 5673:                             if ($otherdom ne '') {
 5674:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 5675:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 5676:                                         push(@{$request_domains->{$type}},$otherdom);
 5677:                                     }
 5678:                                 } else {
 5679:                                     push(@{$request_domains->{$type}},$otherdom);
 5680:                                 }
 5681:                             }
 5682:                         }
 5683:                     }
 5684:                     unless($dom eq $env{'user.domain'}) {
 5685:                         $canreq ++;
 5686:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 5687:                             $can_request->{$type} = 1;
 5688:                         }
 5689:                     }
 5690:                 }
 5691:             }
 5692:         }
 5693:     }
 5694:     return $canreq;
 5695: }
 5696: 
 5697: # ---------------------------------------------- Custom access rule evaluation
 5698: 
 5699: sub customaccess {
 5700:     my ($priv,$uri)=@_;
 5701:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 5702:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 5703:     $udom = &LONCAPA::clean_domain($udom);
 5704:     $ucrs = &LONCAPA::clean_username($ucrs);
 5705:     my $access=0;
 5706:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 5707: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 5708: 	if ($type eq 'user') {
 5709: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 5710: 		my ($tdom,$tuname)=split(m{/},$scope);
 5711: 		if ($tdom) {
 5712: 		    if ($tdom ne $env{'user.domain'}) { next; }
 5713: 		}
 5714: 		if ($tuname) {
 5715: 		    if ($tuname ne $env{'user.name'}) { next; }
 5716: 		}
 5717: 		$access=($effect eq 'allow');
 5718: 		last;
 5719: 	    }
 5720: 	} else {
 5721: 	    if ($role) {
 5722: 		if ($role ne $urole) { next; }
 5723: 	    }
 5724: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 5725: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 5726: 		if ($tdom) {
 5727: 		    if ($tdom ne $udom) { next; }
 5728: 		}
 5729: 		if ($tcrs) {
 5730: 		    if ($tcrs ne $ucrs) { next; }
 5731: 		}
 5732: 		if ($tsec) {
 5733: 		    if ($tsec ne $usec) { next; }
 5734: 		}
 5735: 		$access=($effect eq 'allow');
 5736: 		last;
 5737: 	    }
 5738: 	    if ($realm eq '' && $role eq '') {
 5739: 		$access=($effect eq 'allow');
 5740: 	    }
 5741: 	}
 5742:     }
 5743:     return $access;
 5744: }
 5745: 
 5746: # ------------------------------------------------- Check for a user privilege
 5747: 
 5748: sub allowed {
 5749:     my ($priv,$uri,$symb,$role)=@_;
 5750:     my $ver_orguri=$uri;
 5751:     $uri=&deversion($uri);
 5752:     my $orguri=$uri;
 5753:     $uri=&declutter($uri);
 5754: 
 5755:     if ($priv eq 'evb') {
 5756: # Evade communication block restrictions for specified role in a course
 5757:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 5758:             return $1;
 5759:         } else {
 5760:             return;
 5761:         }
 5762:     }
 5763: 
 5764:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 5765: # Free bre access to adm and meta resources
 5766:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 5767: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 5768: 	&& ($priv eq 'bre')) {
 5769: 	return 'F';
 5770:     }
 5771: 
 5772: # Free bre access to user's own portfolio contents
 5773:     my ($space,$domain,$name,@dir)=split('/',$uri);
 5774:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 5775: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 5776:         my %setters;
 5777:         my ($startblock,$endblock) = 
 5778:             &Apache::loncommon::blockcheck(\%setters,'port');
 5779:         if ($startblock && $endblock) {
 5780:             return 'B';
 5781:         } else {
 5782:             return 'F';
 5783:         }
 5784:     }
 5785: 
 5786: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 5787:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 5788:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 5789:         if (exists($env{'request.course.id'})) {
 5790:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5791:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5792:             if (($domain eq $cdom) && ($name eq $cnum)) {
 5793:                 my $courseprivid=$env{'request.course.id'};
 5794:                 $courseprivid=~s/\_/\//;
 5795:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 5796:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 5797:                     return $1; 
 5798:                 } else {
 5799:                     if ($env{'request.course.sec'}) {
 5800:                         $courseprivid.='/'.$env{'request.course.sec'};
 5801:                     }
 5802:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 5803:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 5804:                         return $2;
 5805:                     }
 5806:                 }
 5807:             }
 5808:         }
 5809:     }
 5810: 
 5811: # Free bre to public access
 5812: 
 5813:     if ($priv eq 'bre') {
 5814:         my $copyright=&metadata($uri,'copyright');
 5815: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 5816:            return 'F'; 
 5817:         }
 5818:         if ($copyright eq 'priv') {
 5819:             $uri=~/([^\/]+)\/([^\/]+)\//;
 5820: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 5821: 		return '';
 5822:             }
 5823:         }
 5824:         if ($copyright eq 'domain') {
 5825:             $uri=~/([^\/]+)\/([^\/]+)\//;
 5826: 	    unless (($env{'user.domain'} eq $1) ||
 5827:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 5828: 		return '';
 5829:             }
 5830:         }
 5831:         if ($env{'request.role'}=~ /li\.\//) {
 5832:             # Library role, so allow browsing of resources in this domain.
 5833:             return 'F';
 5834:         }
 5835:         if ($copyright eq 'custom') {
 5836: 	    unless (&customaccess($priv,$uri)) { return ''; }
 5837:         }
 5838:     }
 5839:     # Domain coordinator is trying to create a course
 5840:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 5841:         # uri is the requested domain in this case.
 5842:         # comparison to 'request.role.domain' shows if the user has selected
 5843:         # a role of dc for the domain in question.
 5844:         return 'F' if ($uri eq $env{'request.role.domain'});
 5845:     }
 5846: 
 5847:     my $thisallowed='';
 5848:     my $statecond=0;
 5849:     my $courseprivid='';
 5850: 
 5851:     my $ownaccess;
 5852:     # Community Coordinator or Assistant Co-author browsing resource space.
 5853:     if (($priv eq 'bro') && ($env{'user.author'})) {
 5854:         if ($uri eq '') {
 5855:             $ownaccess = 1;
 5856:         } else {
 5857:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 5858:                 my $udom = $env{'user.domain'};
 5859:                 my $uname = $env{'user.name'};
 5860:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 5861:                     $ownaccess = 1;
 5862:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 5863:                     unless ($uri =~ m{\.\./}) {
 5864:                         $ownaccess = 1;
 5865:                     }
 5866:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 5867:                     my $now = time;
 5868:                     if ($uri =~ m{^([^/]+)/?$}) {
 5869:                         my $adom = $1;
 5870:                         foreach my $key (keys(%env)) {
 5871:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 5872:                                 my ($start,$end) = split('.',$env{$key});
 5873:                                 if (($now >= $start) && (!$end || $end < $now)) {
 5874:                                     $ownaccess = 1;
 5875:                                     last;
 5876:                                 }
 5877:                             }
 5878:                         }
 5879:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 5880:                         my $adom = $1;
 5881:                         my $aname = $2;
 5882:                         foreach my $role ('ca','aa') { 
 5883:                             if ($env{"user.role.$role./$adom/$aname"}) {
 5884:                                 my ($start,$end) =
 5885:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 5886:                                 if (($now >= $start) && (!$end || $end < $now)) {
 5887:                                     $ownaccess = 1;
 5888:                                     last;
 5889:                                 }
 5890:                             }
 5891:                         }
 5892:                     }
 5893:                 }
 5894:             }
 5895:         }
 5896:     }
 5897: 
 5898: # Course
 5899: 
 5900:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 5901:         unless (($priv eq 'bro') && (!$ownaccess)) {
 5902:             $thisallowed.=$1;
 5903:         }
 5904:     }
 5905: 
 5906: # Domain
 5907: 
 5908:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 5909:        =~/\Q$priv\E\&([^\:]*)/) {
 5910:         unless (($priv eq 'bro') && (!$ownaccess)) {
 5911:             $thisallowed.=$1;
 5912:         }
 5913:     }
 5914: 
 5915: # User who is not author or co-author might still be able to edit
 5916: # resource of an author in the domain (e.g., if Domain Coordinator).
 5917:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 5918:         (&allowed('mdc',$env{'request.course.id'}))) {
 5919:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 5920:             $thisallowed.=$1;
 5921:         }
 5922:     }
 5923: 
 5924: # Course: uri itself is a course
 5925:     my $courseuri=$uri;
 5926:     $courseuri=~s/\_(\d)/\/$1/;
 5927:     $courseuri=~s/^([^\/])/\/$1/;
 5928: 
 5929:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 5930:        =~/\Q$priv\E\&([^\:]*)/) {
 5931:         unless (($priv eq 'bro') && (!$ownaccess)) {
 5932:             $thisallowed.=$1;
 5933:         }
 5934:     }
 5935: 
 5936: # URI is an uploaded document for this course, default permissions don't matter
 5937: # not allowing 'edit' access (editupload) to uploaded course docs
 5938:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 5939: 	$thisallowed='';
 5940:         my ($match)=&is_on_map($uri);
 5941:         if ($match) {
 5942:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 5943:                   =~/\Q$priv\E\&([^\:]*)/) {
 5944:                 $thisallowed.=$1;
 5945:             }
 5946:         } else {
 5947:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 5948:             if ($refuri) {
 5949:                 if ($refuri =~ m|^/adm/|) {
 5950:                     $thisallowed='F';
 5951:                 } else {
 5952:                     $refuri=&declutter($refuri);
 5953:                     my ($match) = &is_on_map($refuri);
 5954:                     if ($match) {
 5955:                         $thisallowed='F';
 5956:                     }
 5957:                 }
 5958:             }
 5959:         }
 5960:     }
 5961: 
 5962:     if ($priv eq 'bre'
 5963: 	&& $thisallowed ne 'F' 
 5964: 	&& $thisallowed ne '2'
 5965: 	&& &is_portfolio_url($uri)) {
 5966: 	$thisallowed = &portfolio_access($uri);
 5967:     }
 5968:     
 5969: # Full access at system, domain or course-wide level? Exit.
 5970:     if ($thisallowed=~/F/) {
 5971: 	return 'F';
 5972:     }
 5973: 
 5974: # If this is generating or modifying users, exit with special codes
 5975: 
 5976:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 5977: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 5978: 	    my ($audom,$auname)=split('/',$uri);
 5979: # no author name given, so this just checks on the general right to make a co-author in this domain
 5980: 	    unless ($auname) { return $thisallowed; }
 5981: # an author name is given, so we are about to actually make a co-author for a certain account
 5982: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 5983: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 5984: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 5985: 	}
 5986: 	return $thisallowed;
 5987:     }
 5988: #
 5989: # Gathered so far: system, domain and course wide privileges
 5990: #
 5991: # Course: See if uri or referer is an individual resource that is part of 
 5992: # the course
 5993: 
 5994:     if ($env{'request.course.id'}) {
 5995: 
 5996:        $courseprivid=$env{'request.course.id'};
 5997:        if ($env{'request.course.sec'}) {
 5998:           $courseprivid.='/'.$env{'request.course.sec'};
 5999:        }
 6000:        $courseprivid=~s/\_/\//;
 6001:        my $checkreferer=1;
 6002:        my ($match,$cond)=&is_on_map($uri);
 6003:        if ($match) {
 6004:            $statecond=$cond;
 6005:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6006:                =~/\Q$priv\E\&([^\:]*)/) {
 6007:                $thisallowed.=$1;
 6008:                $checkreferer=0;
 6009:            }
 6010:        }
 6011:        
 6012:        if ($checkreferer) {
 6013: 	  my $refuri=$env{'httpref.'.$orguri};
 6014:             unless ($refuri) {
 6015:                 foreach my $key (keys(%env)) {
 6016: 		    if ($key=~/^httpref\..*\*/) {
 6017: 			my $pattern=$key;
 6018:                         $pattern=~s/^httpref\.\/res\///;
 6019:                         $pattern=~s/\*/\[\^\/\]\+/g;
 6020:                         $pattern=~s/\//\\\//g;
 6021:                         if ($orguri=~/$pattern/) {
 6022: 			    $refuri=$env{$key};
 6023:                         }
 6024:                     }
 6025:                 }
 6026:             }
 6027: 
 6028:          if ($refuri) { 
 6029: 	  $refuri=&declutter($refuri);
 6030:           my ($match,$cond)=&is_on_map($refuri);
 6031:             if ($match) {
 6032:               my $refstatecond=$cond;
 6033:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6034:                   =~/\Q$priv\E\&([^\:]*)/) {
 6035:                   $thisallowed.=$1;
 6036:                   $uri=$refuri;
 6037:                   $statecond=$refstatecond;
 6038:               }
 6039:           }
 6040:         }
 6041:        }
 6042:    }
 6043: 
 6044: #
 6045: # Gathered now: all privileges that could apply, and condition number
 6046: # 
 6047: #
 6048: # Full or no access?
 6049: #
 6050: 
 6051:     if ($thisallowed=~/F/) {
 6052: 	return 'F';
 6053:     }
 6054: 
 6055:     unless ($thisallowed) {
 6056:         return '';
 6057:     }
 6058: 
 6059: # Restrictions exist, deal with them
 6060: #
 6061: #   C:according to course preferences
 6062: #   R:according to resource settings
 6063: #   L:unless locked
 6064: #   X:according to user session state
 6065: #
 6066: 
 6067: # Possibly locked functionality, check all courses
 6068: # Locks might take effect only after 10 minutes cache expiration for other
 6069: # courses, and 2 minutes for current course
 6070: 
 6071:     my $envkey;
 6072:     if ($thisallowed=~/L/) {
 6073:         foreach $envkey (keys(%env)) {
 6074:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 6075:                my $courseid=$2;
 6076:                my $roleid=$1.'.'.$2;
 6077:                $courseid=~s/^\///;
 6078:                my $expiretime=600;
 6079:                if ($env{'request.role'} eq $roleid) {
 6080: 		  $expiretime=120;
 6081:                }
 6082: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 6083:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 6084:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 6085: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 6086:                }
 6087:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6088:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 6089: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 6090:                        &log($env{'user.domain'},$env{'user.name'},
 6091:                             $env{'user.home'},
 6092:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 6093:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6094:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6095: 		       return '';
 6096:                    }
 6097:                }
 6098:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6099:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 6100: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 6101:                        &log($env{'user.domain'},$env{'user.name'},
 6102:                             $env{'user.home'},
 6103:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 6104:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6105:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6106: 		       return '';
 6107:                    }
 6108:                }
 6109: 	   }
 6110:        }
 6111:     }
 6112:    
 6113: #
 6114: # Rest of the restrictions depend on selected course
 6115: #
 6116: 
 6117:     unless ($env{'request.course.id'}) {
 6118: 	if ($thisallowed eq 'A') {
 6119: 	    return 'A';
 6120:         } elsif ($thisallowed eq 'B') {
 6121:             return 'B';
 6122: 	} else {
 6123: 	    return '1';
 6124: 	}
 6125:     }
 6126: 
 6127: #
 6128: # Now user is definitely in a course
 6129: #
 6130: 
 6131: 
 6132: # Course preferences
 6133: 
 6134:    if ($thisallowed=~/C/) {
 6135:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6136:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 6137:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 6138: 	   =~/\Q$rolecode\E/) {
 6139: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6140: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6141: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 6142: 			$env{'request.course.id'});
 6143: 	   }
 6144:            return '';
 6145:        }
 6146: 
 6147:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 6148: 	   =~/\Q$unamedom\E/) {
 6149: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6150: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 6151: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 6152: 			$env{'request.course.id'});
 6153: 	   }
 6154:            return '';
 6155:        }
 6156:    }
 6157: 
 6158: # Resource preferences
 6159: 
 6160:    if ($thisallowed=~/R/) {
 6161:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6162:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 6163: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6164: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6165: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 6166: 	   }
 6167: 	   return '';
 6168:        }
 6169:    }
 6170: 
 6171: # Restricted by state or randomout?
 6172: 
 6173:    if ($thisallowed=~/X/) {
 6174:       if ($env{'acc.randomout'}) {
 6175: 	 if (!$symb) { $symb=&symbread($uri,1); }
 6176:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 6177:             return ''; 
 6178:          }
 6179:       }
 6180:       if (&condval($statecond)) {
 6181: 	 return '2';
 6182:       } else {
 6183:          return '';
 6184:       }
 6185:    }
 6186: 
 6187:     if ($thisallowed eq 'A') {
 6188: 	return 'A';
 6189:     } elsif ($thisallowed eq 'B') {
 6190:         return 'B';
 6191:     }
 6192:    return 'F';
 6193: }
 6194: #
 6195: #   Removes the versino from a URI and
 6196: #   splits it in to its filename and path to the filename.
 6197: #   Seems like File::Basename could have done this more clearly.
 6198: #   Parameters:
 6199: #      $uri   - input URI
 6200: #   Returns:
 6201: #     Two element list consisting of 
 6202: #     $pathname  - the URI up to and excluding the trailing /
 6203: #     $filename  - The part of the URI following the last /
 6204: #  NOTE:
 6205: #    Another realization of this is simply:
 6206: #    use File::Basename;
 6207: #    ...
 6208: #    $uri = shift;
 6209: #    $filename = basename($uri);
 6210: #    $path     = dirname($uri);
 6211: #    return ($filename, $path);
 6212: #
 6213: #     The implementation below is probably faster however.
 6214: #
 6215: sub split_uri_for_cond {
 6216:     my $uri=&deversion(&declutter(shift));
 6217:     my @uriparts=split(/\//,$uri);
 6218:     my $filename=pop(@uriparts);
 6219:     my $pathname=join('/',@uriparts);
 6220:     return ($pathname,$filename);
 6221: }
 6222: # --------------------------------------------------- Is a resource on the map?
 6223: 
 6224: sub is_on_map {
 6225:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 6226:     #Trying to find the conditional for the file
 6227:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 6228: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 6229:     if ($match) {
 6230: 	return (1,$1);
 6231:     } else {
 6232: 	return (0,0);
 6233:     }
 6234: }
 6235: 
 6236: # --------------------------------------------------------- Get symb from alias
 6237: 
 6238: sub get_symb_from_alias {
 6239:     my $symb=shift;
 6240:     my ($map,$resid,$url)=&decode_symb($symb);
 6241: # Already is a symb
 6242:     if ($url) { return $symb; }
 6243: # Must be an alias
 6244:     my $aliassymb='';
 6245:     my %bighash;
 6246:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6247:                             &GDBM_READER(),0640)) {
 6248:         my $rid=$bighash{'mapalias_'.$symb};
 6249: 	if ($rid) {
 6250: 	    my ($mapid,$resid)=split(/\./,$rid);
 6251: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 6252: 				    $resid,$bighash{'src_'.$rid});
 6253: 	}
 6254:         untie %bighash;
 6255:     }
 6256:     return $aliassymb;
 6257: }
 6258: 
 6259: # ----------------------------------------------------------------- Define Role
 6260: 
 6261: sub definerole {
 6262:   if (allowed('mcr','/')) {
 6263:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 6264:     foreach my $role (split(':',$sysrole)) {
 6265: 	my ($crole,$cqual)=split(/\&/,$role);
 6266:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 6267:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 6268: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 6269:                return "refused:s:$crole&$cqual"; 
 6270:             }
 6271:         }
 6272:     }
 6273:     foreach my $role (split(':',$domrole)) {
 6274: 	my ($crole,$cqual)=split(/\&/,$role);
 6275:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 6276:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 6277: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 6278:                return "refused:d:$crole&$cqual"; 
 6279:             }
 6280:         }
 6281:     }
 6282:     foreach my $role (split(':',$courole)) {
 6283: 	my ($crole,$cqual)=split(/\&/,$role);
 6284:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 6285:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 6286: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 6287:                return "refused:c:$crole&$cqual"; 
 6288:             }
 6289:         }
 6290:     }
 6291:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 6292:                 "$env{'user.domain'}:$env{'user.name'}:".
 6293: 	        "rolesdef_$rolename=".
 6294:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 6295:     return reply($command,$env{'user.home'});
 6296:   } else {
 6297:     return 'refused';
 6298:   }
 6299: }
 6300: 
 6301: # ---------------- Make a metadata query against the network of library servers
 6302: 
 6303: sub metadata_query {
 6304:     my ($query,$custom,$customshow,$server_array)=@_;
 6305:     my %rhash;
 6306:     my %libserv = &all_library();
 6307:     my @server_list = (defined($server_array) ? @$server_array
 6308:                                               : keys(%libserv) );
 6309:     for my $server (@server_list) {
 6310: 	unless ($custom or $customshow) {
 6311: 	    my $reply=&reply("querysend:".&escape($query),$server);
 6312: 	    $rhash{$server}=$reply;
 6313: 	}
 6314: 	else {
 6315: 	    my $reply=&reply("querysend:".&escape($query).':'.
 6316: 			     &escape($custom).':'.&escape($customshow),
 6317: 			     $server);
 6318: 	    $rhash{$server}=$reply;
 6319: 	}
 6320:     }
 6321:     return \%rhash;
 6322: }
 6323: 
 6324: # ----------------------------------------- Send log queries and wait for reply
 6325: 
 6326: sub log_query {
 6327:     my ($uname,$udom,$query,%filters)=@_;
 6328:     my $uhome=&homeserver($uname,$udom);
 6329:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 6330:     my $uhost=&hostname($uhome);
 6331:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 6332:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 6333:                        $uhome);
 6334:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 6335:     return get_query_reply($queryid);
 6336: }
 6337: 
 6338: # -------------------------- Update MySQL table for portfolio file
 6339: 
 6340: sub update_portfolio_table {
 6341:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 6342:     if ($group ne '') {
 6343:         $file_name =~s /^\Q$group\E//;
 6344:     }
 6345:     my $homeserver = &homeserver($uname,$udom);
 6346:     my $queryid=
 6347:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 6348:                ':'.&escape($file_name).':'.$action,$homeserver);
 6349:     my $reply = &get_query_reply($queryid);
 6350:     return $reply;
 6351: }
 6352: 
 6353: # -------------------------- Update MySQL allusers table
 6354: 
 6355: sub update_allusers_table {
 6356:     my ($uname,$udom,$names) = @_;
 6357:     my $homeserver = &homeserver($uname,$udom);
 6358:     my $queryid=
 6359:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 6360:                'lastname='.&escape($names->{'lastname'}).'%%'.
 6361:                'firstname='.&escape($names->{'firstname'}).'%%'.
 6362:                'middlename='.&escape($names->{'middlename'}).'%%'.
 6363:                'generation='.&escape($names->{'generation'}).'%%'.
 6364:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 6365:                'id='.&escape($names->{'id'}),$homeserver);
 6366:     return;
 6367: }
 6368: 
 6369: # ------- Request retrieval of institutional classlists for course(s)
 6370: 
 6371: sub fetch_enrollment_query {
 6372:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 6373:     my $homeserver;
 6374:     my $maxtries = 1;
 6375:     if ($context eq 'automated') {
 6376:         $homeserver = $perlvar{'lonHostID'};
 6377:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 6378:     } else {
 6379:         $homeserver = &homeserver($cnum,$dom);
 6380:     }
 6381:     my $host=&hostname($homeserver);
 6382:     my $cmd = '';
 6383:     foreach my $affiliate (keys(%{$affiliatesref})) {
 6384:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 6385:     }
 6386:     $cmd =~ s/%%$//;
 6387:     $cmd = &escape($cmd);
 6388:     my $query = 'fetchenrollment';
 6389:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 6390:     unless ($queryid=~/^\Q$host\E\_/) { 
 6391:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 6392:         return 'error: '.$queryid;
 6393:     }
 6394:     my $reply = &get_query_reply($queryid);
 6395:     my $tries = 1;
 6396:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 6397:         $reply = &get_query_reply($queryid);
 6398:         $tries ++;
 6399:     }
 6400:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 6401:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 6402:     } else {
 6403:         my @responses = split(/:/,$reply);
 6404:         if ($homeserver eq $perlvar{'lonHostID'}) {
 6405:             foreach my $line (@responses) {
 6406:                 my ($key,$value) = split(/=/,$line,2);
 6407:                 $$replyref{$key} = $value;
 6408:             }
 6409:         } else {
 6410:             my $pathname = LONCAPA::tempdir();
 6411:             foreach my $line (@responses) {
 6412:                 my ($key,$value) = split(/=/,$line);
 6413:                 $$replyref{$key} = $value;
 6414:                 if ($value > 0) {
 6415:                     foreach my $item (@{$$affiliatesref{$key}}) {
 6416:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 6417:                         my $destname = $pathname.'/'.$filename;
 6418:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 6419:                         if ($xml_classlist =~ /^error/) {
 6420:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 6421:                         } else {
 6422:                             if ( open(FILE,">$destname") ) {
 6423:                                 print FILE &unescape($xml_classlist);
 6424:                                 close(FILE);
 6425:                             } else {
 6426:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 6427:                             }
 6428:                         }
 6429:                     }
 6430:                 }
 6431:             }
 6432:         }
 6433:         return 'ok';
 6434:     }
 6435:     return 'error';
 6436: }
 6437: 
 6438: sub get_query_reply {
 6439:     my $queryid=shift;
 6440:     my $replyfile=LONCAPA::tempdir().$queryid;
 6441:     my $reply='';
 6442:     for (1..100) {
 6443: 	sleep 2;
 6444:         if (-e $replyfile.'.end') {
 6445: 	    if (open(my $fh,$replyfile)) {
 6446: 		$reply = join('',<$fh>);
 6447: 		close($fh);
 6448: 	   } else { return 'error: reply_file_error'; }
 6449:            return &unescape($reply);
 6450: 	}
 6451:     }
 6452:     return 'timeout:'.$queryid;
 6453: }
 6454: 
 6455: sub courselog_query {
 6456: #
 6457: # possible filters:
 6458: # url: url or symb
 6459: # username
 6460: # domain
 6461: # action: view, submit, grade
 6462: # start: timestamp
 6463: # end: timestamp
 6464: #
 6465:     my (%filters)=@_;
 6466:     unless ($env{'request.course.id'}) { return 'no_course'; }
 6467:     if ($filters{'url'}) {
 6468: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 6469:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 6470:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 6471:     }
 6472:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6473:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6474:     return &log_query($cname,$cdom,'courselog',%filters);
 6475: }
 6476: 
 6477: sub userlog_query {
 6478: #
 6479: # possible filters:
 6480: # action: log check role
 6481: # start: timestamp
 6482: # end: timestamp
 6483: #
 6484:     my ($uname,$udom,%filters)=@_;
 6485:     return &log_query($uname,$udom,'userlog',%filters);
 6486: }
 6487: 
 6488: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 6489: 
 6490: sub auto_run {
 6491:     my ($cnum,$cdom) = @_;
 6492:     my $response = 0;
 6493:     my $settings;
 6494:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 6495:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 6496:         $settings = $domconfig{'autoenroll'};
 6497:         if ($settings->{'run'} eq '1') {
 6498:             $response = 1;
 6499:         }
 6500:     } else {
 6501:         my $homeserver;
 6502:         if (&is_course($cdom,$cnum)) {
 6503:             $homeserver = &homeserver($cnum,$cdom);
 6504:         } else {
 6505:             $homeserver = &domain($cdom,'primary');
 6506:         }
 6507:         if ($homeserver ne 'no_host') {
 6508:             $response = &reply('autorun:'.$cdom,$homeserver);
 6509:         }
 6510:     }
 6511:     return $response;
 6512: }
 6513: 
 6514: sub auto_get_sections {
 6515:     my ($cnum,$cdom,$inst_coursecode) = @_;
 6516:     my $homeserver;
 6517:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 6518:         $homeserver = &homeserver($cnum,$cdom);
 6519:     }
 6520:     if (!defined($homeserver)) { 
 6521:         if ($cdom =~ /^$match_domain$/) {
 6522:             $homeserver = &domain($cdom,'primary');
 6523:         }
 6524:     }
 6525:     my @secs;
 6526:     if (defined($homeserver)) {
 6527:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 6528:         unless ($response eq 'refused') {
 6529:             @secs = split(/:/,$response);
 6530:         }
 6531:     }
 6532:     return @secs;
 6533: }
 6534: 
 6535: sub auto_new_course {
 6536:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 6537:     my $homeserver = &homeserver($cnum,$cdom);
 6538:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 6539:     return $response;
 6540: }
 6541: 
 6542: sub auto_validate_courseID {
 6543:     my ($cnum,$cdom,$inst_course_id) = @_;
 6544:     my $homeserver = &homeserver($cnum,$cdom);
 6545:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 6546:     return $response;
 6547: }
 6548: 
 6549: sub auto_validate_instcode {
 6550:     my ($cnum,$cdom,$instcode,$owner) = @_;
 6551:     my ($homeserver,$response);
 6552:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 6553:         $homeserver = &homeserver($cnum,$cdom);
 6554:     }
 6555:     if (!defined($homeserver)) {
 6556:         if ($cdom =~ /^$match_domain$/) {
 6557:             $homeserver = &domain($cdom,'primary');
 6558:         }
 6559:     }
 6560:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 6561:                         &escape($instcode).':'.&escape($owner),$homeserver));
 6562:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
 6563:     return ($outcome,$description);
 6564: }
 6565: 
 6566: sub auto_create_password {
 6567:     my ($cnum,$cdom,$authparam,$udom) = @_;
 6568:     my ($homeserver,$response);
 6569:     my $create_passwd = 0;
 6570:     my $authchk = '';
 6571:     if ($udom =~ /^$match_domain$/) {
 6572:         $homeserver = &domain($udom,'primary');
 6573:     }
 6574:     if ($homeserver eq '') {
 6575:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 6576:             $homeserver = &homeserver($cnum,$cdom);
 6577:         }
 6578:     }
 6579:     if ($homeserver eq '') {
 6580:         $authchk = 'nodomain';
 6581:     } else {
 6582:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 6583:         if ($response eq 'refused') {
 6584:             $authchk = 'refused';
 6585:         } else {
 6586:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 6587:         }
 6588:     }
 6589:     return ($authparam,$create_passwd,$authchk);
 6590: }
 6591: 
 6592: sub auto_photo_permission {
 6593:     my ($cnum,$cdom,$students) = @_;
 6594:     my $homeserver = &homeserver($cnum,$cdom);
 6595:     my ($outcome,$perm_reqd,$conditions) = 
 6596: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 6597:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 6598: 	return (undef,undef);
 6599:     }
 6600:     return ($outcome,$perm_reqd,$conditions);
 6601: }
 6602: 
 6603: sub auto_checkphotos {
 6604:     my ($uname,$udom,$pid) = @_;
 6605:     my $homeserver = &homeserver($uname,$udom);
 6606:     my ($result,$resulttype);
 6607:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 6608: 				   &escape($uname).':'.&escape($pid),
 6609: 				   $homeserver));
 6610:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 6611: 	return (undef,undef);
 6612:     }
 6613:     if ($outcome) {
 6614:         ($result,$resulttype) = split(/:/,$outcome);
 6615:     } 
 6616:     return ($result,$resulttype);
 6617: }
 6618: 
 6619: sub auto_photochoice {
 6620:     my ($cnum,$cdom) = @_;
 6621:     my $homeserver = &homeserver($cnum,$cdom);
 6622:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 6623: 						       &escape($cdom),
 6624: 						       $homeserver)));
 6625:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 6626: 	return (undef,undef);
 6627:     }
 6628:     return ($update,$comment);
 6629: }
 6630: 
 6631: sub auto_photoupdate {
 6632:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 6633:     my $homeserver = &homeserver($cnum,$dom);
 6634:     my $host=&hostname($homeserver);
 6635:     my $cmd = '';
 6636:     my $maxtries = 1;
 6637:     foreach my $affiliate (keys(%{$affiliatesref})) {
 6638:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 6639:     }
 6640:     $cmd =~ s/%%$//;
 6641:     $cmd = &escape($cmd);
 6642:     my $query = 'institutionalphotos';
 6643:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 6644:     unless ($queryid=~/^\Q$host\E\_/) {
 6645:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 6646:         return 'error: '.$queryid;
 6647:     }
 6648:     my $reply = &get_query_reply($queryid);
 6649:     my $tries = 1;
 6650:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 6651:         $reply = &get_query_reply($queryid);
 6652:         $tries ++;
 6653:     }
 6654:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 6655:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 6656:     } else {
 6657:         my @responses = split(/:/,$reply);
 6658:         my $outcome = shift(@responses); 
 6659:         foreach my $item (@responses) {
 6660:             my ($key,$value) = split(/=/,$item);
 6661:             $$photo{$key} = $value;
 6662:         }
 6663:         return $outcome;
 6664:     }
 6665:     return 'error';
 6666: }
 6667: 
 6668: sub auto_instcode_format {
 6669:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 6670: 	$cat_order) = @_;
 6671:     my $courses = '';
 6672:     my @homeservers;
 6673:     if ($caller eq 'global') {
 6674: 	my %servers = &get_servers($codedom,'library');
 6675: 	foreach my $tryserver (keys(%servers)) {
 6676: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 6677: 		push(@homeservers,$tryserver);
 6678: 	    }
 6679:         }
 6680:     } elsif ($caller eq 'requests') {
 6681:         if ($codedom =~ /^$match_domain$/) {
 6682:             my $chome = &domain($codedom,'primary');
 6683:             unless ($chome eq 'no_host') {
 6684:                 push(@homeservers,$chome);
 6685:             }
 6686:         }
 6687:     } else {
 6688:         push(@homeservers,&homeserver($caller,$codedom));
 6689:     }
 6690:     foreach my $code (keys(%{$instcodes})) {
 6691:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 6692:     }
 6693:     chop($courses);
 6694:     my $ok_response = 0;
 6695:     my $response;
 6696:     while (@homeservers > 0 && $ok_response == 0) {
 6697:         my $server = shift(@homeservers); 
 6698:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 6699:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 6700:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 6701: 		split(/:/,$response);
 6702:             %{$codes} = (%{$codes},&str2hash($codes_str));
 6703:             push(@{$codetitles},&str2array($codetitles_str));
 6704:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 6705:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 6706:             $ok_response = 1;
 6707:         }
 6708:     }
 6709:     if ($ok_response) {
 6710:         return 'ok';
 6711:     } else {
 6712:         return $response;
 6713:     }
 6714: }
 6715: 
 6716: sub auto_instcode_defaults {
 6717:     my ($domain,$returnhash,$code_order) = @_;
 6718:     my @homeservers;
 6719: 
 6720:     my %servers = &get_servers($domain,'library');
 6721:     foreach my $tryserver (keys(%servers)) {
 6722: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 6723: 	    push(@homeservers,$tryserver);
 6724: 	}
 6725:     }
 6726: 
 6727:     my $response;
 6728:     foreach my $server (@homeservers) {
 6729:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 6730:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 6731: 	
 6732: 	foreach my $pair (split(/\&/,$response)) {
 6733: 	    my ($name,$value)=split(/\=/,$pair);
 6734: 	    if ($name eq 'code_order') {
 6735: 		@{$code_order} = split(/\&/,&unescape($value));
 6736: 	    } else {
 6737: 		$returnhash->{&unescape($name)}=&unescape($value);
 6738: 	    }
 6739: 	}
 6740: 	return 'ok';
 6741:     }
 6742: 
 6743:     return $response;
 6744: }
 6745: 
 6746: sub auto_possible_instcodes {
 6747:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 6748:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 6749:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 6750:         return;
 6751:     }
 6752:     my (@homeservers,$uhome);
 6753:     if (defined(&domain($domain,'primary'))) {
 6754:         $uhome=&domain($domain,'primary');
 6755:         push(@homeservers,&domain($domain,'primary'));
 6756:     } else {
 6757:         my %servers = &get_servers($domain,'library');
 6758:         foreach my $tryserver (keys(%servers)) {
 6759:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 6760:                 push(@homeservers,$tryserver);
 6761:             }
 6762:         }
 6763:     }
 6764:     my $response;
 6765:     foreach my $server (@homeservers) {
 6766:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 6767:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 6768:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 6769:             split(':',$response);
 6770:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 6771:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 6772:         foreach my $item (split('&',$cat_title)) {   
 6773:             my ($name,$value)=split('=',$item);
 6774:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 6775:         }
 6776:         foreach my $item (split('&',$cat_order)) {
 6777:             my ($name,$value)=split('=',$item);
 6778:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 6779:         }
 6780:         return 'ok';
 6781:     }
 6782:     return $response;
 6783: }
 6784: 
 6785: sub auto_courserequest_checks {
 6786:     my ($dom) = @_;
 6787:     my ($homeserver,%validations);
 6788:     if ($dom =~ /^$match_domain$/) {
 6789:         $homeserver = &domain($dom,'primary');
 6790:     }
 6791:     unless ($homeserver eq 'no_host') {
 6792:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 6793:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 6794:             my @items = split(/&/,$response);
 6795:             foreach my $item (@items) {
 6796:                 my ($key,$value) = split('=',$item);
 6797:                 $validations{&unescape($key)} = &thaw_unescape($value);
 6798:             }
 6799:         }
 6800:     }
 6801:     return %validations; 
 6802: }
 6803: 
 6804: sub auto_courserequest_validation {
 6805:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
 6806:     my ($homeserver,$response);
 6807:     if ($dom =~ /^$match_domain$/) {
 6808:         $homeserver = &domain($dom,'primary');
 6809:     }
 6810:     unless ($homeserver eq 'no_host') {  
 6811:           
 6812:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 6813:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 6814:                                     ':'.&escape($instcode).':'.&escape($instseclist),
 6815:                                     $homeserver));
 6816:     }
 6817:     return $response;
 6818: }
 6819: 
 6820: sub auto_validate_class_sec {
 6821:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 6822:     my $homeserver = &homeserver($cnum,$cdom);
 6823:     my $ownerlist;
 6824:     if (ref($owners) eq 'ARRAY') {
 6825:         $ownerlist = join(',',@{$owners});
 6826:     } else {
 6827:         $ownerlist = $owners;
 6828:     }
 6829:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 6830:                         &escape($ownerlist).':'.$cdom,$homeserver);
 6831:     return $response;
 6832: }
 6833: 
 6834: # ------------------------------------------------------- Course Group routines
 6835: 
 6836: sub get_coursegroups {
 6837:     my ($cdom,$cnum,$group,$namespace) = @_;
 6838:     return(&dump($namespace,$cdom,$cnum,$group));
 6839: }
 6840: 
 6841: sub modify_coursegroup {
 6842:     my ($cdom,$cnum,$groupsettings) = @_;
 6843:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 6844: }
 6845: 
 6846: sub toggle_coursegroup_status {
 6847:     my ($cdom,$cnum,$group,$action) = @_;
 6848:     my ($from_namespace,$to_namespace);
 6849:     if ($action eq 'delete') {
 6850:         $from_namespace = 'coursegroups';
 6851:         $to_namespace = 'deleted_groups';
 6852:     } else {
 6853:         $from_namespace = 'deleted_groups';
 6854:         $to_namespace = 'coursegroups';
 6855:     }
 6856:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 6857:     if (my $tmp = &error(%curr_group)) {
 6858:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 6859:         return ('read error',$tmp);
 6860:     } else {
 6861:         my %savedsettings = %curr_group; 
 6862:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 6863:         my $deloutcome;
 6864:         if ($result eq 'ok') {
 6865:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 6866:         } else {
 6867:             return ('write error',$result);
 6868:         }
 6869:         if ($deloutcome eq 'ok') {
 6870:             return 'ok';
 6871:         } else {
 6872:             return ('delete error',$deloutcome);
 6873:         }
 6874:     }
 6875: }
 6876: 
 6877: sub modify_group_roles {
 6878:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 6879:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 6880:     my $role = 'gr/'.&escape($userprivs);
 6881:     my ($uname,$udom) = split(/:/,$user);
 6882:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 6883:     if ($result eq 'ok') {
 6884:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 6885:     }
 6886:     return $result;
 6887: }
 6888: 
 6889: sub modify_coursegroup_membership {
 6890:     my ($cdom,$cnum,$membership) = @_;
 6891:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 6892:     return $result;
 6893: }
 6894: 
 6895: sub get_active_groups {
 6896:     my ($udom,$uname,$cdom,$cnum) = @_;
 6897:     my $now = time;
 6898:     my %groups = ();
 6899:     foreach my $key (keys(%env)) {
 6900:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 6901:             my ($start,$end) = split(/\./,$env{$key});
 6902:             if (($end!=0) && ($end<$now)) { next; }
 6903:             if (($start!=0) && ($start>$now)) { next; }
 6904:             if ($1 eq $cdom && $2 eq $cnum) {
 6905:                 $groups{$3} = $env{$key} ;
 6906:             }
 6907:         }
 6908:     }
 6909:     return %groups;
 6910: }
 6911: 
 6912: sub get_group_membership {
 6913:     my ($cdom,$cnum,$group) = @_;
 6914:     return(&dump('groupmembership',$cdom,$cnum,$group));
 6915: }
 6916: 
 6917: sub get_users_groups {
 6918:     my ($udom,$uname,$courseid) = @_;
 6919:     my @usersgroups;
 6920:     my $cachetime=1800;
 6921: 
 6922:     my $hashid="$udom:$uname:$courseid";
 6923:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 6924:     if (defined($cached)) {
 6925:         @usersgroups = split(/:/,$grouplist);
 6926:     } else {  
 6927:         $grouplist = '';
 6928:         my $courseurl = &courseid_to_courseurl($courseid);
 6929:         my $extra = &freeze_escape({'skipcheck' => 1});
 6930:         my %roleshash = &dump('roles',$udom,$uname,$courseurl,undef,$extra);
 6931:         my $access_end = $env{'course.'.$courseid.
 6932:                               '.default_enrollment_end_date'};
 6933:         my $now = time;
 6934:         foreach my $key (keys(%roleshash)) {
 6935:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 6936:                 my $group = $1;
 6937:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 6938:                     my $start = $2;
 6939:                     my $end = $1;
 6940:                     if ($start == -1) { next; } # deleted from group
 6941:                     if (($start!=0) && ($start>$now)) { next; }
 6942:                     if (($end!=0) && ($end<$now)) {
 6943:                         if ($access_end && $access_end < $now) {
 6944:                             if ($access_end - $end < 86400) {
 6945:                                 push(@usersgroups,$group);
 6946:                             }
 6947:                         }
 6948:                         next;
 6949:                     }
 6950:                     push(@usersgroups,$group);
 6951:                 }
 6952:             }
 6953:         }
 6954:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 6955:         $grouplist = join(':',@usersgroups);
 6956:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 6957:     }
 6958:     return @usersgroups;
 6959: }
 6960: 
 6961: sub devalidate_getgroups_cache {
 6962:     my ($udom,$uname,$cdom,$cnum)=@_;
 6963:     my $courseid = $cdom.'_'.$cnum;
 6964: 
 6965:     my $hashid="$udom:$uname:$courseid";
 6966:     &devalidate_cache_new('getgroups',$hashid);
 6967: }
 6968: 
 6969: # ------------------------------------------------------------------ Plain Text
 6970: 
 6971: sub plaintext {
 6972:     my ($short,$type,$cid,$forcedefault) = @_;
 6973:     if ($short =~ m{^cr/}) {
 6974: 	return (split('/',$short))[-1];
 6975:     }
 6976:     if (!defined($cid)) {
 6977:         $cid = $env{'request.course.id'};
 6978:     }
 6979:     my %rolenames = (
 6980:                       Course    => 'std',
 6981:                       Community => 'alt1',
 6982:                     );
 6983:     if ($cid ne '') {
 6984:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 6985:             unless ($forcedefault) {
 6986:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 6987:                 &Apache::lonlocal::mt_escape(\$roletext);
 6988:                 return &Apache::lonlocal::mt($roletext);
 6989:             }
 6990:         }
 6991:     }
 6992:     if ((defined($type)) && (defined($rolenames{$type})) &&
 6993:         (defined($rolenames{$type})) && 
 6994:         (defined($prp{$short}{$rolenames{$type}}))) {
 6995:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 6996:     } elsif ($cid ne '') {
 6997:         my $crstype = $env{'course.'.$cid.'.type'};
 6998:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 6999:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 7000:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 7001:         }
 7002:     }
 7003:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 7004: }
 7005: 
 7006: # ----------------------------------------------------------------- Assign Role
 7007: 
 7008: sub assignrole {
 7009:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 7010:         $context)=@_;
 7011:     my $mrole;
 7012:     if ($role =~ /^cr\//) {
 7013:         my $cwosec=$url;
 7014:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 7015: 	unless (&allowed('ccr',$cwosec)) {
 7016:            my $refused = 1;
 7017:            if ($context eq 'requestcourses') {
 7018:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 7019:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 7020:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 7021:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 7022:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7023:                            if ($crsenv{'internal.courseowner'} eq
 7024:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 7025:                                $refused = '';
 7026:                            }
 7027:                        }
 7028:                    }
 7029:                }
 7030:            }
 7031:            if ($refused) {
 7032:                &logthis('Refused custom assignrole: '.
 7033:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 7034:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 7035:                return 'refused';
 7036:            }
 7037:         }
 7038:         $mrole='cr';
 7039:     } elsif ($role =~ /^gr\//) {
 7040:         my $cwogrp=$url;
 7041:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 7042:         unless (&allowed('mdg',$cwogrp)) {
 7043:             &logthis('Refused group assignrole: '.
 7044:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 7045:                     $env{'user.name'}.' at '.$env{'user.domain'});
 7046:             return 'refused';
 7047:         }
 7048:         $mrole='gr';
 7049:     } else {
 7050:         my $cwosec=$url;
 7051:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 7052:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 7053:             my $refused;
 7054:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 7055:                 if (!(&allowed('c'.$role,$url))) {
 7056:                     $refused = 1;
 7057:                 }
 7058:             } else {
 7059:                 $refused = 1;
 7060:             }
 7061:             if ($refused) {
 7062:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 7063:                 if (!$selfenroll && $context eq 'course') {
 7064:                     my %crsenv;
 7065:                     if ($role eq 'cc' || $role eq 'co') {
 7066:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7067:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 7068:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 7069:                                 if ($crsenv{'internal.courseowner'} eq 
 7070:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 7071:                                     $refused = '';
 7072:                                 }
 7073:                             }
 7074:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 7075:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 7076:                                 if ($crsenv{'internal.courseowner'} eq 
 7077:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 7078:                                     $refused = '';
 7079:                                 }
 7080:                             }
 7081:                         }
 7082:                     }
 7083:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7084:                     $refused = '';
 7085:                 } elsif ($context eq 'requestcourses') {
 7086:                     my @possroles = ('st','ta','ep','in','cc','co');
 7087:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 7088:                         my $wrongcc;
 7089:                         if ($cnum =~ /^$match_community$/) {
 7090:                             $wrongcc = 1 if ($role eq 'cc');
 7091:                         } else {
 7092:                             $wrongcc = 1 if ($role eq 'co');
 7093:                         }
 7094:                         unless ($wrongcc) {
 7095:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7096:                             if ($crsenv{'internal.courseowner'} eq 
 7097:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 7098:                                 $refused = '';
 7099:                             }
 7100:                         }
 7101:                     }
 7102:                 }
 7103:                 if ($refused) {
 7104:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 7105:                              ' '.$role.' '.$end.' '.$start.' by '.
 7106: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 7107:                     return 'refused';
 7108:                 }
 7109:             }
 7110:         } elsif ($role eq 'au') {
 7111:             if ($url ne '/'.$udom.'/') {
 7112:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 7113:                          ' to assign author role for '.$uname.':'.$udom.
 7114:                          ' in domain: '.$url.' refused (wrong domain).');
 7115:                 return 'refused';
 7116:             }
 7117:         }
 7118:         $mrole=$role;
 7119:     }
 7120:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 7121:                 "$udom:$uname:$url".'_'."$mrole=$role";
 7122:     if ($end) { $command.='_'.$end; }
 7123:     if ($start) {
 7124: 	if ($end) { 
 7125:            $command.='_'.$start; 
 7126:         } else {
 7127:            $command.='_0_'.$start;
 7128:         }
 7129:     }
 7130:     my $origstart = $start;
 7131:     my $origend = $end;
 7132:     my $delflag;
 7133: # actually delete
 7134:     if ($deleteflag) {
 7135: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 7136: # modify command to delete the role
 7137:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 7138:                 "$udom:$uname:$url".'_'."$mrole";
 7139: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 7140: # set start and finish to negative values for userrolelog
 7141:            $start=-1;
 7142:            $end=-1;
 7143:            $delflag = 1;
 7144:         }
 7145:     }
 7146: # send command
 7147:     my $answer=&reply($command,&homeserver($uname,$udom));
 7148: # log new user role if status is ok
 7149:     if ($answer eq 'ok') {
 7150: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 7151: # for course roles, perform group memberships changes triggered by role change.
 7152:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
 7153:         unless ($role =~ /^gr/) {
 7154:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 7155:                                              $origstart,$selfenroll,$context);
 7156:         }
 7157:         if ($role eq 'cc') {
 7158:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 7159:         }
 7160:     }
 7161:     return $answer;
 7162: }
 7163: 
 7164: sub autoupdate_coowners {
 7165:     my ($url,$end,$start,$uname,$udom) = @_;
 7166:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 7167:     if (($cdom ne '') && ($cnum ne '')) {
 7168:         my $now = time;
 7169:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 7170:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 7171:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 7172:             my $instcode = $coursehash{'internal.coursecode'};
 7173:             if ($instcode ne '') {
 7174:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 7175:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 7176:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 7177:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 7178:                         if ($result eq 'valid') {
 7179:                             if ($coursehash{'internal.co-owners'}) {
 7180:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 7181:                                     push(@newcoowners,$coowner);
 7182:                                 }
 7183:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 7184:                                     push(@newcoowners,$uname.':'.$udom);
 7185:                                 }
 7186:                                 @newcoowners = sort(@newcoowners);
 7187:                             } else {
 7188:                                 push(@newcoowners,$uname.':'.$udom);
 7189:                             }
 7190:                         } else {
 7191:                             if ($coursehash{'internal.co-owners'}) {
 7192:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 7193:                                     unless ($coowner eq $uname.':'.$udom) {
 7194:                                         push(@newcoowners,$coowner);
 7195:                                     }
 7196:                                 }
 7197:                                 unless (@newcoowners > 0) {
 7198:                                     $delcoowners = 1;
 7199:                                     $coowners = '';
 7200:                                 }
 7201:                             }
 7202:                         }
 7203:                         if (@newcoowners || $delcoowners) {
 7204:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 7205:                                             $delcoowners,@newcoowners);
 7206:                         }
 7207:                     }
 7208:                 }
 7209:             }
 7210:         }
 7211:     }
 7212: }
 7213: 
 7214: sub store_coowners {
 7215:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 7216:     my $cid = $cdom.'_'.$cnum;
 7217:     my ($coowners,$delresult,$putresult);
 7218:     if (@newcoowners) {
 7219:         $coowners = join(',',@newcoowners);
 7220:         my %coownershash = (
 7221:                             'internal.co-owners' => $coowners,
 7222:                            );
 7223:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 7224:         if ($putresult eq 'ok') {
 7225:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 7226:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 7227:             }
 7228:         }
 7229:     }
 7230:     if ($delcoowners) {
 7231:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 7232:         if ($delresult eq 'ok') {
 7233:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 7234:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 7235:             }
 7236:         }
 7237:     }
 7238:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 7239:         my %crsinfo =
 7240:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 7241:         if (ref($crsinfo{$cid}) eq 'HASH') {
 7242:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 7243:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 7244:         }
 7245:     }
 7246: }
 7247: 
 7248: # -------------------------------------------------- Modify user authentication
 7249: # Overrides without validation
 7250: 
 7251: sub modifyuserauth {
 7252:     my ($udom,$uname,$umode,$upass)=@_;
 7253:     my $uhome=&homeserver($uname,$udom);
 7254:     unless (&allowed('mau',$udom)) { return 'refused'; }
 7255:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 7256:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 7257:              ' in domain '.$env{'request.role.domain'});  
 7258:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 7259: 		     &escape($upass),$uhome);
 7260:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 7261:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 7262:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 7263:     &log($udom,,$uname,$uhome,
 7264:         'Authentication changed by '.$env{'user.domain'}.', '.
 7265:                                      $env{'user.name'}.', '.$umode.
 7266:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 7267:     unless ($reply eq 'ok') {
 7268:         &logthis('Authentication mode error: '.$reply);
 7269: 	return 'error: '.$reply;
 7270:     }   
 7271:     return 'ok';
 7272: }
 7273: 
 7274: # --------------------------------------------------------------- Modify a user
 7275: 
 7276: sub modifyuser {
 7277:     my ($udom,    $uname, $uid,
 7278:         $umode,   $upass, $first,
 7279:         $middle,  $last,  $gene,
 7280:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 7281:     $udom= &LONCAPA::clean_domain($udom);
 7282:     $uname=&LONCAPA::clean_username($uname);
 7283:     my $showcandelete = 'none';
 7284:     if (ref($candelete) eq 'ARRAY') {
 7285:         if (@{$candelete} > 0) {
 7286:             $showcandelete = join(', ',@{$candelete});
 7287:         }
 7288:     }
 7289:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 7290:              $umode.', '.$first.', '.$middle.', '.
 7291: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 7292:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 7293:                                      ' desiredhome not specified'). 
 7294:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 7295:              ' in domain '.$env{'request.role.domain'});
 7296:     my $uhome=&homeserver($uname,$udom,'true');
 7297:     my $newuser;
 7298:     if ($uhome eq 'no_host') {
 7299:         $newuser = 1;
 7300:     }
 7301: # ----------------------------------------------------------------- Create User
 7302:     if (($uhome eq 'no_host') && 
 7303: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 7304:         my $unhome='';
 7305:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 7306:             $unhome = $desiredhome;
 7307: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 7308: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 7309:         } else { # load balancing routine for determining $unhome
 7310:             my $loadm=10000000;
 7311: 	    my %servers = &get_servers($udom,'library');
 7312: 	    foreach my $tryserver (keys(%servers)) {
 7313: 		my $answer=reply('load',$tryserver);
 7314: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 7315: 		    $loadm=$answer;
 7316: 		    $unhome=$tryserver;
 7317: 		}
 7318: 	    }
 7319:         }
 7320:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 7321: 	    return 'error: unable to find a home server for '.$uname.
 7322:                    ' in domain '.$udom;
 7323:         }
 7324:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 7325:                          &escape($upass),$unhome);
 7326: 	unless ($reply eq 'ok') {
 7327:             return 'error: '.$reply;
 7328:         }   
 7329:         $uhome=&homeserver($uname,$udom,'true');
 7330:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 7331: 	    return 'error: unable verify users home machine.';
 7332:         }
 7333:     }   # End of creation of new user
 7334: # ---------------------------------------------------------------------- Add ID
 7335:     if ($uid) {
 7336:        $uid=~tr/A-Z/a-z/;
 7337:        my %uidhash=&idrget($udom,$uname);
 7338:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 7339:          && (!$forceid)) {
 7340: 	  unless ($uid eq $uidhash{$uname}) {
 7341: 	      return 'error: user id "'.$uid.'" does not match '.
 7342:                   'current user id "'.$uidhash{$uname}.'".';
 7343:           }
 7344:        } else {
 7345: 	  &idput($udom,($uname => $uid));
 7346:        }
 7347:     }
 7348: # -------------------------------------------------------------- Add names, etc
 7349:     my @tmp=&get('environment',
 7350: 		   ['firstname','middlename','lastname','generation','id',
 7351:                     'permanentemail','inststatus'],
 7352: 		   $udom,$uname);
 7353:     my (%names,%oldnames);
 7354:     if ($tmp[0] =~ m/^error:.*/) { 
 7355:         %names=(); 
 7356:     } else {
 7357:         %names = @tmp;
 7358:         %oldnames = %names;
 7359:     }
 7360: #
 7361: # If name, email and/or uid are blank (e.g., because an uploaded file
 7362: # of users did not contain them), do not overwrite existing values
 7363: # unless field is in $candelete array ref.  
 7364: #
 7365: 
 7366:     my @fields = ('firstname','middlename','lastname','generation',
 7367:                   'permanentemail','id');
 7368:     my %newvalues;
 7369:     if (ref($candelete) eq 'ARRAY') {
 7370:         foreach my $field (@fields) {
 7371:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 7372:                 if ($field eq 'firstname') {
 7373:                     $names{$field} = $first;
 7374:                 } elsif ($field eq 'middlename') {
 7375:                     $names{$field} = $middle;
 7376:                 } elsif ($field eq 'lastname') {
 7377:                     $names{$field} = $last;
 7378:                 } elsif ($field eq 'generation') { 
 7379:                     $names{$field} = $gene;
 7380:                 } elsif ($field eq 'permanentemail') {
 7381:                     $names{$field} = $email;
 7382:                 } elsif ($field eq 'id') {
 7383:                     $names{$field}  = $uid;
 7384:                 }
 7385:             }
 7386:         }
 7387:     }
 7388:     if ($first)  { $names{'firstname'}  = $first; }
 7389:     if (defined($middle)) { $names{'middlename'} = $middle; }
 7390:     if ($last)   { $names{'lastname'}   = $last; }
 7391:     if (defined($gene))   { $names{'generation'} = $gene; }
 7392:     if ($email) {
 7393:        $email=~s/[^\w\@\.\-\,]//gs;
 7394:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 7395:     }
 7396:     if ($uid) { $names{'id'}  = $uid; }
 7397:     if (defined($inststatus)) {
 7398:         $names{'inststatus'} = '';
 7399:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 7400:         if (ref($usertypes) eq 'HASH') {
 7401:             my @okstatuses; 
 7402:             foreach my $item (split(/:/,$inststatus)) {
 7403:                 if (defined($usertypes->{$item})) {
 7404:                     push(@okstatuses,$item);  
 7405:                 }
 7406:             }
 7407:             if (@okstatuses) {
 7408:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 7409:             }
 7410:         }
 7411:     }
 7412:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 7413:                  $umode.', '.$first.', '.$middle.', '.
 7414:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 7415:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 7416:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 7417:     } else {
 7418:         $logmsg .= ' during self creation';
 7419:     }
 7420:     my $changed;
 7421:     if ($newuser) {
 7422:         $changed = 1;
 7423:     } else {
 7424:         foreach my $field (@fields) {
 7425:             if ($names{$field} ne $oldnames{$field}) {
 7426:                 $changed = 1;
 7427:                 last;
 7428:             }
 7429:         }
 7430:     }
 7431:     unless ($changed) {
 7432:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 7433:         &logthis($logmsg);
 7434:         return 'ok';
 7435:     }
 7436:     my $reply = &put('environment', \%names, $udom,$uname);
 7437:     if ($reply ne 'ok') { 
 7438:         return 'error: '.$reply;
 7439:     }
 7440:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
 7441:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
 7442:     }
 7443:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 7444:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 7445:     $logmsg = 'Success modifying user '.$logmsg;
 7446:     &logthis($logmsg);
 7447:     return 'ok';
 7448: }
 7449: 
 7450: # -------------------------------------------------------------- Modify student
 7451: 
 7452: sub modifystudent {
 7453:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 7454:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 7455:         $selfenroll,$context,$inststatus)=@_;
 7456:     if (!$cid) {
 7457: 	unless ($cid=$env{'request.course.id'}) {
 7458: 	    return 'not_in_class';
 7459: 	}
 7460:     }
 7461: # --------------------------------------------------------------- Make the user
 7462:     my $reply=&modifyuser
 7463: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 7464:          $desiredhome,$email,$inststatus);
 7465:     unless ($reply eq 'ok') { return $reply; }
 7466:     # This will cause &modify_student_enrollment to get the uid from the
 7467:     # students environment
 7468:     $uid = undef if (!$forceid);
 7469:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 7470: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
 7471:     return $reply;
 7472: }
 7473: 
 7474: sub modify_student_enrollment {
 7475:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
 7476:     my ($cdom,$cnum,$chome);
 7477:     if (!$cid) {
 7478: 	unless ($cid=$env{'request.course.id'}) {
 7479: 	    return 'not_in_class';
 7480: 	}
 7481: 	$cdom=$env{'course.'.$cid.'.domain'};
 7482: 	$cnum=$env{'course.'.$cid.'.num'};
 7483:     } else {
 7484: 	($cdom,$cnum)=split(/_/,$cid);
 7485:     }
 7486:     $chome=$env{'course.'.$cid.'.home'};
 7487:     if (!$chome) {
 7488: 	$chome=&homeserver($cnum,$cdom);
 7489:     }
 7490:     if (!$chome) { return 'unknown_course'; }
 7491:     # Make sure the user exists
 7492:     my $uhome=&homeserver($uname,$udom);
 7493:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 7494: 	return 'error: no such user';
 7495:     }
 7496:     # Get student data if we were not given enough information
 7497:     if (!defined($first)  || $first  eq '' || 
 7498:         !defined($last)   || $last   eq '' || 
 7499:         !defined($uid)    || $uid    eq '' || 
 7500:         !defined($middle) || $middle eq '' || 
 7501:         !defined($gene)   || $gene   eq '') {
 7502:         # They did not supply us with enough data to enroll the student, so
 7503:         # we need to pick up more information.
 7504:         my %tmp = &get('environment',
 7505:                        ['firstname','middlename','lastname', 'generation','id']
 7506:                        ,$udom,$uname);
 7507: 
 7508:         #foreach my $key (keys(%tmp)) {
 7509:         #    &logthis("key $key = ".$tmp{$key});
 7510:         #}
 7511:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 7512:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 7513:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 7514:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 7515:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 7516:     }
 7517:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 7518:     my $reply=cput('classlist',
 7519: 		   {"$uname:$udom" => 
 7520: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 7521: 		   $cdom,$cnum);
 7522:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 7523: 	return 'error: '.$reply;
 7524:     } else {
 7525: 	&devalidate_getsection_cache($udom,$uname,$cid);
 7526:     }
 7527:     # Add student role to user
 7528:     my $uurl='/'.$cid;
 7529:     $uurl=~s/\_/\//g;
 7530:     if ($usec) {
 7531: 	$uurl.='/'.$usec;
 7532:     }
 7533:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
 7534: }
 7535: 
 7536: sub format_name {
 7537:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 7538:     my $name;
 7539:     if ($first ne 'lastname') {
 7540: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 7541:     } else {
 7542: 	if ($lastname=~/\S/) {
 7543: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 7544: 	    $name=~s/\s+,/,/;
 7545: 	} else {
 7546: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 7547: 	}
 7548:     }
 7549:     $name=~s/^\s+//;
 7550:     $name=~s/\s+$//;
 7551:     $name=~s/\s+/ /g;
 7552:     return $name;
 7553: }
 7554: 
 7555: # ------------------------------------------------- Write to course preferences
 7556: 
 7557: sub writecoursepref {
 7558:     my ($courseid,%prefs)=@_;
 7559:     $courseid=~s/^\///;
 7560:     $courseid=~s/\_/\//g;
 7561:     my ($cdomain,$cnum)=split(/\//,$courseid);
 7562:     my $chome=homeserver($cnum,$cdomain);
 7563:     if (($chome eq '') || ($chome eq 'no_host')) { 
 7564: 	return 'error: no such course';
 7565:     }
 7566:     my $cstring='';
 7567:     foreach my $pref (keys(%prefs)) {
 7568: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 7569:     }
 7570:     $cstring=~s/\&$//;
 7571:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 7572: }
 7573: 
 7574: # ---------------------------------------------------------- Make/modify course
 7575: 
 7576: sub createcourse {
 7577:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 7578:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 7579:     $url=&declutter($url);
 7580:     my $cid='';
 7581:     if ($context eq 'requestcourses') {
 7582:         my $can_create = 0;
 7583:         my ($ownername,$ownerdom) = split(':',$course_owner);
 7584:         if ($udom eq $ownerdom) {
 7585:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 7586:                                   $context)) {
 7587:                 $can_create = 1;
 7588:             }
 7589:         } else {
 7590:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 7591:                                            $category);
 7592:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 7593:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 7594:                 if (@curr > 0) {
 7595:                     my @options = qw(approval validate autolimit);
 7596:                     my $optregex = join('|',@options);
 7597:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 7598:                         $can_create = 1;
 7599:                     }
 7600:                 }
 7601:             }
 7602:         }
 7603:         if ($can_create) {
 7604:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 7605:                 unless (&allowed('ccc',$udom)) {
 7606:                     return 'refused'; 
 7607:                 }
 7608:             }
 7609:         } else {
 7610:             return 'refused';
 7611:         }
 7612:     } elsif (!&allowed('ccc',$udom)) {
 7613:         return 'refused';
 7614:     }
 7615: # --------------------------------------------------------------- Get Unique ID
 7616:     my $uname;
 7617:     if ($cnum =~ /^$match_courseid$/) {
 7618:         my $chome=&homeserver($cnum,$udom,'true');
 7619:         if (($chome eq '') || ($chome eq 'no_host')) {
 7620:             $uname = $cnum;
 7621:         } else {
 7622:             $uname = &generate_coursenum($udom,$crstype);
 7623:         }
 7624:     } else {
 7625:         $uname = &generate_coursenum($udom,$crstype);
 7626:     }
 7627:     return $uname if ($uname =~ /^error/);
 7628: # -------------------------------------------------- Check supplied server name
 7629:     if (!defined($course_server)) {
 7630:         if (defined(&domain($udom,'primary'))) {
 7631:             $course_server = &domain($udom,'primary');
 7632:         } else {
 7633:             $course_server = $env{'user.home'}; 
 7634:         }
 7635:     }
 7636:     my %host_servers =
 7637:         &Apache::lonnet::get_servers($udom,'library');
 7638:     unless ($host_servers{$course_server}) {
 7639:         return 'error: invalid home server for course: '.$course_server;
 7640:     }
 7641: # ------------------------------------------------------------- Make the course
 7642:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 7643:                       $course_server);
 7644:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 7645:     my $uhome=&homeserver($uname,$udom,'true');
 7646:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 7647: 	return 'error: no such course';
 7648:     }
 7649: # ----------------------------------------------------------------- Course made
 7650: # log existence
 7651:     my $now = time;
 7652:     my $newcourse = {
 7653:                     $udom.'_'.$uname => {
 7654:                                      description => $description,
 7655:                                      inst_code   => $inst_code,
 7656:                                      owner       => $course_owner,
 7657:                                      type        => $crstype,
 7658:                                      creator     => $env{'user.name'}.':'.
 7659:                                                     $env{'user.domain'},
 7660:                                      created     => $now,
 7661:                                      context     => $context,
 7662:                                                 },
 7663:                     };
 7664:     &courseidput($udom,$newcourse,$uhome,'notime');
 7665: # set toplevel url
 7666:     my $topurl=$url;
 7667:     unless ($nonstandard) {
 7668: # ------------------------------------------ For standard courses, make top url
 7669:         my $mapurl=&clutter($url);
 7670:         if ($mapurl eq '/res/') { $mapurl=''; }
 7671:         $env{'form.initmap'}=(<<ENDINITMAP);
 7672: <map>
 7673: <resource id="1" type="start"></resource>
 7674: <resource id="2" src="$mapurl"></resource>
 7675: <resource id="3" type="finish"></resource>
 7676: <link index="1" from="1" to="2"></link>
 7677: <link index="2" from="2" to="3"></link>
 7678: </map>
 7679: ENDINITMAP
 7680:         $topurl=&declutter(
 7681:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 7682:                           );
 7683:     }
 7684: # ----------------------------------------------------------- Write preferences
 7685:     &writecoursepref($udom.'_'.$uname,
 7686:                      ('description'              => $description,
 7687:                       'url'                      => $topurl,
 7688:                       'internal.creator'         => $env{'user.name'}.':'.
 7689:                                                     $env{'user.domain'},
 7690:                       'internal.created'         => $now,
 7691:                       'internal.creationcontext' => $context)
 7692:                     );
 7693:     return '/'.$udom.'/'.$uname;
 7694: }
 7695: 
 7696: # ------------------------------------------------------------------- Create ID
 7697: sub generate_coursenum {
 7698:     my ($udom,$crstype) = @_;
 7699:     my $domdesc = &domain($udom);
 7700:     return 'error: invalid domain' if ($domdesc eq '');
 7701:     my $first;
 7702:     if ($crstype eq 'Community') {
 7703:         $first = '0';
 7704:     } else {
 7705:         $first = int(1+rand(9)); 
 7706:     } 
 7707:     my $uname=$first.
 7708:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 7709:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
 7710:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 7711: # ----------------------------------------------- Make sure that does not exist
 7712:     my $uhome=&homeserver($uname,$udom,'true');
 7713:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
 7714:         if ($crstype eq 'Community') {
 7715:             $first = '0';
 7716:         } else {
 7717:             $first = int(1+rand(9));
 7718:         }
 7719:         $uname=$first.
 7720:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 7721:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
 7722:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 7723:         $uhome=&homeserver($uname,$udom,'true');
 7724:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
 7725:             return 'error: unable to generate unique course-ID';
 7726:         }
 7727:     }
 7728:     return $uname;
 7729: }
 7730: 
 7731: sub is_course {
 7732:     my ($cdom,$cnum) = @_;
 7733:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
 7734: 				undef,'.');
 7735:     if (exists($courses{$cdom.'_'.$cnum})) {
 7736:         return 1;
 7737:     }
 7738:     return 0;
 7739: }
 7740: 
 7741: sub store_userdata {
 7742:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
 7743:     my $result;
 7744:     if ($datakey ne '') {
 7745:         if (ref($storehash) eq 'HASH') {
 7746:             if ($udom eq '' || $uname eq '') {
 7747:                 $udom = $env{'user.domain'};
 7748:                 $uname = $env{'user.name'};
 7749:             }
 7750:             my $uhome=&homeserver($uname,$udom);
 7751:             if (($uhome eq '') || ($uhome eq 'no_host')) {
 7752:                 $result = 'error: no_host';
 7753:             } else {
 7754:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
 7755:                 $storehash->{'host'} = $perlvar{'lonHostID'};
 7756: 
 7757:                 my $namevalue='';
 7758:                 foreach my $key (keys(%{$storehash})) {
 7759:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 7760:                 }
 7761:                 $namevalue=~s/\&$//;
 7762:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
 7763:                                   $namevalue,$uhome);
 7764:             }
 7765:         } else {
 7766:             $result = 'error: data to store was not a hash reference'; 
 7767:         }
 7768:     } else {
 7769:         $result= 'error: invalid requestkey'; 
 7770:     }
 7771:     return $result;
 7772: }
 7773: 
 7774: # ---------------------------------------------------------- Assign Custom Role
 7775: 
 7776: sub assigncustomrole {
 7777:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 7778:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 7779:                        $end,$start,$deleteflag,$selfenroll,$context);
 7780: }
 7781: 
 7782: # ----------------------------------------------------------------- Revoke Role
 7783: 
 7784: sub revokerole {
 7785:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 7786:     my $now=time;
 7787:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 7788: }
 7789: 
 7790: # ---------------------------------------------------------- Revoke Custom Role
 7791: 
 7792: sub revokecustomrole {
 7793:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 7794:     my $now=time;
 7795:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 7796:            $deleteflag,$selfenroll,$context);
 7797: }
 7798: 
 7799: # ------------------------------------------------------------ Disk usage
 7800: sub diskusage {
 7801:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 7802:     $directorypath =~ s/\/$//;
 7803:     my $listing=&reply('du2:'.&escape($directorypath).':'
 7804:                        .&escape($getpropath).':'.&escape($uname).':'
 7805:                        .&escape($udom),homeserver($uname,$udom));
 7806:     if ($listing eq 'unknown_cmd') {
 7807:         if ($getpropath) {
 7808:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 7809:         }
 7810:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 7811:     }
 7812:     return $listing;
 7813: }
 7814: 
 7815: sub is_locked {
 7816:     my ($file_name, $domain, $user, $which) = @_;
 7817:     my @check;
 7818:     my $is_locked;
 7819:     push (@check,$file_name);
 7820:     my %locked = &get('file_permissions',\@check,
 7821: 		      $env{'user.domain'},$env{'user.name'});
 7822:     my ($tmp)=keys(%locked);
 7823:     if ($tmp=~/^error:/) { undef(%locked); }
 7824:     
 7825:     if (ref($locked{$file_name}) eq 'ARRAY') {
 7826:         $is_locked = 'false';
 7827:         foreach my $entry (@{$locked{$file_name}}) {
 7828:            if (ref($entry) eq 'ARRAY') {
 7829:                $is_locked = 'true';
 7830:                if (ref($which) eq 'ARRAY') {
 7831:                    push(@{$which},$entry);
 7832:                } else {
 7833:                    last;
 7834:                }
 7835:            }
 7836:        }
 7837:     } else {
 7838:         $is_locked = 'false';
 7839:     }
 7840:     return $is_locked;
 7841: }
 7842: 
 7843: sub declutter_portfile {
 7844:     my ($file) = @_;
 7845:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 7846:     return $file;
 7847: }
 7848: 
 7849: # ------------------------------------------------------------- Mark as Read Only
 7850: 
 7851: sub mark_as_readonly {
 7852:     my ($domain,$user,$files,$what) = @_;
 7853:     my %current_permissions = &dump('file_permissions',$domain,$user);
 7854:     my ($tmp)=keys(%current_permissions);
 7855:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 7856:     foreach my $file (@{$files}) {
 7857: 	$file = &declutter_portfile($file);
 7858:         push(@{$current_permissions{$file}},$what);
 7859:     }
 7860:     &put('file_permissions',\%current_permissions,$domain,$user);
 7861:     return;
 7862: }
 7863: 
 7864: # ------------------------------------------------------------Save Selected Files
 7865: 
 7866: sub save_selected_files {
 7867:     my ($user, $path, @files) = @_;
 7868:     my $filename = $user."savedfiles";
 7869:     my @other_files = &files_not_in_path($user, $path);
 7870:     open (OUT, '>'.$tmpdir.$filename);
 7871:     foreach my $file (@files) {
 7872:         print (OUT $env{'form.currentpath'}.$file."\n");
 7873:     }
 7874:     foreach my $file (@other_files) {
 7875:         print (OUT $file."\n");
 7876:     }
 7877:     close (OUT);
 7878:     return 'ok';
 7879: }
 7880: 
 7881: sub clear_selected_files {
 7882:     my ($user) = @_;
 7883:     my $filename = $user."savedfiles";
 7884:     open (OUT, '>'.LONCAPA::tempdir().$filename);
 7885:     print (OUT undef);
 7886:     close (OUT);
 7887:     return ("ok");    
 7888: }
 7889: 
 7890: sub files_in_path {
 7891:     my ($user, $path) = @_;
 7892:     my $filename = $user."savedfiles";
 7893:     my %return_files;
 7894:     open (IN, '<'.LONCAPA::tempdir().$filename);
 7895:     while (my $line_in = <IN>) {
 7896:         chomp ($line_in);
 7897:         my @paths_and_file = split (m!/!, $line_in);
 7898:         my $file_part = pop (@paths_and_file);
 7899:         my $path_part = join ('/', @paths_and_file);
 7900:         $path_part.='/';
 7901:         my $path_and_file = $path_part.$file_part;
 7902:         if ($path_part eq $path) {
 7903:             $return_files{$file_part}= 'selected';
 7904:         }
 7905:     }
 7906:     close (IN);
 7907:     return (\%return_files);
 7908: }
 7909: 
 7910: # called in portfolio select mode, to show files selected NOT in current directory
 7911: sub files_not_in_path {
 7912:     my ($user, $path) = @_;
 7913:     my $filename = $user."savedfiles";
 7914:     my @return_files;
 7915:     my $path_part;
 7916:     open(IN, '<'.LONCAPA::.$filename);
 7917:     while (my $line = <IN>) {
 7918:         #ok, I know it's clunky, but I want it to work
 7919:         my @paths_and_file = split(m|/|, $line);
 7920:         my $file_part = pop(@paths_and_file);
 7921:         chomp($file_part);
 7922:         my $path_part = join('/', @paths_and_file);
 7923:         $path_part .= '/';
 7924:         my $path_and_file = $path_part.$file_part;
 7925:         if ($path_part ne $path) {
 7926:             push(@return_files, ($path_and_file));
 7927:         }
 7928:     }
 7929:     close(OUT);
 7930:     return (@return_files);
 7931: }
 7932: 
 7933: #----------------------------------------------Get portfolio file permissions
 7934: 
 7935: sub get_portfile_permissions {
 7936:     my ($domain,$user) = @_;
 7937:     my %current_permissions = &dump('file_permissions',$domain,$user);
 7938:     my ($tmp)=keys(%current_permissions);
 7939:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 7940:     return \%current_permissions;
 7941: }
 7942: 
 7943: #---------------------------------------------Get portfolio file access controls
 7944: 
 7945: sub get_access_controls {
 7946:     my ($current_permissions,$group,$file) = @_;
 7947:     my %access;
 7948:     my $real_file = $file;
 7949:     $file =~ s/\.meta$//;
 7950:     if (defined($file)) {
 7951:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 7952:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 7953:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 7954:             }
 7955:         }
 7956:     } else {
 7957:         foreach my $key (keys(%{$current_permissions})) {
 7958:             if ($key =~ /\0accesscontrol$/) {
 7959:                 if (defined($group)) {
 7960:                     if ($key !~ m-^\Q$group\E/-) {
 7961:                         next;
 7962:                     }
 7963:                 }
 7964:                 my ($fullpath) = split(/\0/,$key);
 7965:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 7966:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 7967:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 7968:                     }
 7969:                 }
 7970:             }
 7971:         }
 7972:     }
 7973:     return %access;
 7974: }
 7975: 
 7976: sub modify_access_controls {
 7977:     my ($file_name,$changes,$domain,$user)=@_;
 7978:     my ($outcome,$deloutcome);
 7979:     my %store_permissions;
 7980:     my %new_values;
 7981:     my %new_control;
 7982:     my %translation;
 7983:     my @deletions = ();
 7984:     my $now = time;
 7985:     if (exists($$changes{'activate'})) {
 7986:         if (ref($$changes{'activate'}) eq 'HASH') {
 7987:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 7988:             my $numnew = scalar(@newitems);
 7989:             for (my $i=0; $i<$numnew; $i++) {
 7990:                 my $newkey = $newitems[$i];
 7991:                 my $newid = &Apache::loncommon::get_cgi_id();
 7992:                 if ($newkey =~ /^\d+:/) { 
 7993:                     $newkey =~ s/^(\d+)/$newid/;
 7994:                     $translation{$1} = $newid;
 7995:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 7996:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 7997:                     $translation{$1} = $newid;
 7998:                 }
 7999:                 $new_values{$file_name."\0".$newkey} = 
 8000:                                           $$changes{'activate'}{$newitems[$i]};
 8001:                 $new_control{$newkey} = $now;
 8002:             }
 8003:         }
 8004:     }
 8005:     my %todelete;
 8006:     my %changed_items;
 8007:     foreach my $action ('delete','update') {
 8008:         if (exists($$changes{$action})) {
 8009:             if (ref($$changes{$action}) eq 'HASH') {
 8010:                 foreach my $key (keys(%{$$changes{$action}})) {
 8011:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 8012:                     if ($action eq 'delete') { 
 8013:                         $todelete{$itemnum} = 1;
 8014:                     } else {
 8015:                         $changed_items{$itemnum} = $key;
 8016:                     }
 8017:                 }
 8018:             }
 8019:         }
 8020:     }
 8021:     # get lock on access controls for file.
 8022:     my $lockhash = {
 8023:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 8024:                                                        ':'.$env{'user.domain'},
 8025:                    }; 
 8026:     my $tries = 0;
 8027:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 8028:    
 8029:     while (($gotlock ne 'ok') && $tries <3) {
 8030:         $tries ++;
 8031:         sleep 1;
 8032:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 8033:     }
 8034:     if ($gotlock eq 'ok') {
 8035:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 8036:         my ($tmp)=keys(%curr_permissions);
 8037:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 8038:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 8039:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 8040:             if (ref($curr_controls) eq 'HASH') {
 8041:                 foreach my $control_item (keys(%{$curr_controls})) {
 8042:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 8043:                     if (defined($todelete{$itemnum})) {
 8044:                         push(@deletions,$file_name."\0".$control_item);
 8045:                     } else {
 8046:                         if (defined($changed_items{$itemnum})) {
 8047:                             $new_control{$changed_items{$itemnum}} = $now;
 8048:                             push(@deletions,$file_name."\0".$control_item);
 8049:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 8050:                         } else {
 8051:                             $new_control{$control_item} = $$curr_controls{$control_item};
 8052:                         }
 8053:                     }
 8054:                 }
 8055:             }
 8056:         }
 8057:         my ($group);
 8058:         if (&is_course($domain,$user)) {
 8059:             ($group,my $file) = split(/\//,$file_name,2);
 8060:         }
 8061:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 8062:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 8063:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 8064:         #  remove lock
 8065:         my @del_lock = ($file_name."\0".'locked_access_records');
 8066:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 8067:         my $sqlresult =
 8068:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 8069:                                     $group);
 8070:     } else {
 8071:         $outcome = "error: could not obtain lockfile\n";  
 8072:     }
 8073:     return ($outcome,$deloutcome,\%new_values,\%translation);
 8074: }
 8075: 
 8076: sub make_public_indefinitely {
 8077:     my ($requrl) = @_;
 8078:     my $now = time;
 8079:     my $action = 'activate';
 8080:     my $aclnum = 0;
 8081:     if (&is_portfolio_url($requrl)) {
 8082:         my (undef,$udom,$unum,$file_name,$group) =
 8083:             &parse_portfolio_url($requrl);
 8084:         my $current_perms = &get_portfile_permissions($udom,$unum);
 8085:         my %access_controls = &get_access_controls($current_perms,
 8086:                                                    $group,$file_name);
 8087:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 8088:             my ($num,$scope,$end,$start) = 
 8089:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 8090:             if ($scope eq 'public') {
 8091:                 if ($start <= $now && $end == 0) {
 8092:                     $action = 'none';
 8093:                 } else {
 8094:                     $action = 'update';
 8095:                     $aclnum = $num;
 8096:                 }
 8097:                 last;
 8098:             }
 8099:         }
 8100:         if ($action eq 'none') {
 8101:              return 'ok';
 8102:         } else {
 8103:             my %changes;
 8104:             my $newend = 0;
 8105:             my $newstart = $now;
 8106:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 8107:             $changes{$action}{$newkey} = {
 8108:                 type => 'public',
 8109:                 time => {
 8110:                     start => $newstart,
 8111:                     end   => $newend,
 8112:                 },
 8113:             };
 8114:             my ($outcome,$deloutcome,$new_values,$translation) =
 8115:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 8116:             return $outcome;
 8117:         }
 8118:     } else {
 8119:         return 'invalid';
 8120:     }
 8121: }
 8122: 
 8123: #------------------------------------------------------Get Marked as Read Only
 8124: 
 8125: sub get_marked_as_readonly {
 8126:     my ($domain,$user,$what,$group) = @_;
 8127:     my $current_permissions = &get_portfile_permissions($domain,$user);
 8128:     my @readonly_files;
 8129:     my $cmp1=$what;
 8130:     if (ref($what)) { $cmp1=join('',@{$what}) };
 8131:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 8132:         if (defined($group)) {
 8133:             if ($file_name !~ m-^\Q$group\E/-) {
 8134:                 next;
 8135:             }
 8136:         }
 8137:         if (ref($value) eq "ARRAY"){
 8138:             foreach my $stored_what (@{$value}) {
 8139:                 my $cmp2=$stored_what;
 8140:                 if (ref($stored_what) eq 'ARRAY') {
 8141:                     $cmp2=join('',@{$stored_what});
 8142:                 }
 8143:                 if ($cmp1 eq $cmp2) {
 8144:                     push(@readonly_files, $file_name);
 8145:                     last;
 8146:                 } elsif (!defined($what)) {
 8147:                     push(@readonly_files, $file_name);
 8148:                     last;
 8149:                 }
 8150:             }
 8151:         }
 8152:     }
 8153:     return @readonly_files;
 8154: }
 8155: #-----------------------------------------------------------Get Marked as Read Only Hash
 8156: 
 8157: sub get_marked_as_readonly_hash {
 8158:     my ($current_permissions,$group,$what) = @_;
 8159:     my %readonly_files;
 8160:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 8161:         if (defined($group)) {
 8162:             if ($file_name !~ m-^\Q$group\E/-) {
 8163:                 next;
 8164:             }
 8165:         }
 8166:         if (ref($value) eq "ARRAY"){
 8167:             foreach my $stored_what (@{$value}) {
 8168:                 if (ref($stored_what) eq 'ARRAY') {
 8169:                     foreach my $lock_descriptor(@{$stored_what}) {
 8170:                         if ($lock_descriptor eq 'graded') {
 8171:                             $readonly_files{$file_name} = 'graded';
 8172:                         } elsif ($lock_descriptor eq 'handback') {
 8173:                             $readonly_files{$file_name} = 'handback';
 8174:                         } else {
 8175:                             if (!exists($readonly_files{$file_name})) {
 8176:                                 $readonly_files{$file_name} = 'locked';
 8177:                             }
 8178:                         }
 8179:                     }
 8180:                 } 
 8181:             }
 8182:         } 
 8183:     }
 8184:     return %readonly_files;
 8185: }
 8186: # ------------------------------------------------------------ Unmark as Read Only
 8187: 
 8188: sub unmark_as_readonly {
 8189:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 8190:     # for portfolio submissions, $what contains [$symb,$crsid] 
 8191:     my ($domain,$user,$what,$file_name,$group) = @_;
 8192:     $file_name = &declutter_portfile($file_name);
 8193:     my $symb_crs = $what;
 8194:     if (ref($what)) { $symb_crs=join('',@$what); }
 8195:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 8196:     my ($tmp)=keys(%current_permissions);
 8197:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8198:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 8199:     foreach my $file (@readonly_files) {
 8200: 	my $clean_file = &declutter_portfile($file);
 8201: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 8202: 	my $current_locks = $current_permissions{$file};
 8203:         my @new_locks;
 8204:         my @del_keys;
 8205:         if (ref($current_locks) eq "ARRAY"){
 8206:             foreach my $locker (@{$current_locks}) {
 8207:                 my $compare=$locker;
 8208:                 if (ref($locker) eq 'ARRAY') {
 8209:                     $compare=join('',@{$locker});
 8210:                     if ($compare ne $symb_crs) {
 8211:                         push(@new_locks, $locker);
 8212:                     }
 8213:                 }
 8214:             }
 8215:             if (scalar(@new_locks) > 0) {
 8216:                 $current_permissions{$file} = \@new_locks;
 8217:             } else {
 8218:                 push(@del_keys, $file);
 8219:                 &del('file_permissions',\@del_keys, $domain, $user);
 8220:                 delete($current_permissions{$file});
 8221:             }
 8222:         }
 8223:     }
 8224:     &put('file_permissions',\%current_permissions,$domain,$user);
 8225:     return;
 8226: }
 8227: 
 8228: # ------------------------------------------------------------ Directory lister
 8229: 
 8230: sub dirlist {
 8231:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 8232:     $uri=~s/^\///;
 8233:     $uri=~s/\/$//;
 8234:     my ($udom, $uname);
 8235:     if ($getuserdir) {
 8236:         $udom = $userdomain;
 8237:         $uname = $username;
 8238:     } else {
 8239:         (undef,$udom,$uname)=split(/\//,$uri);
 8240:         if(defined($userdomain)) {
 8241:             $udom = $userdomain;
 8242:         }
 8243:         if(defined($username)) {
 8244:             $uname = $username;
 8245:         }
 8246:     }
 8247:     my ($dirRoot,$listing,@listing_results);
 8248: 
 8249:     $dirRoot = $perlvar{'lonDocRoot'};
 8250:     if (defined($getpropath)) {
 8251:         $dirRoot = &propath($udom,$uname);
 8252:         $dirRoot =~ s/\/$//;
 8253:     } elsif (defined($getuserdir)) {
 8254:         my $subdir=$uname.'__';
 8255:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 8256:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 8257:                    ."/$udom/$subdir/$uname";
 8258:     } elsif (defined($alternateRoot)) {
 8259:         $dirRoot = $alternateRoot;
 8260:     }
 8261: 
 8262:     if($udom) {
 8263:         if($uname) {
 8264:             my $uhome = &homeserver($uname,$udom);
 8265:             if ($uhome eq 'no_host') {
 8266:                 return ([],'no_host');
 8267:             }
 8268:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 8269:                               .$getuserdir.':'.&escape($dirRoot)
 8270:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
 8271:             if ($listing eq 'unknown_cmd') {
 8272:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
 8273:             } else {
 8274:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 8275:             }
 8276:             if ($listing eq 'unknown_cmd') {
 8277:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
 8278:                 @listing_results = split(/:/,$listing);
 8279:             } else {
 8280:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 8281:             }
 8282:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
 8283:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
 8284:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 8285:                 return ([],$listing);
 8286:             } else {
 8287:                 return (\@listing_results);
 8288:             }
 8289:         } elsif(!$alternateRoot) {
 8290:             my (%allusers,%listerror);
 8291: 	    my %servers = &get_servers($udom,'library');
 8292:  	    foreach my $tryserver (keys(%servers)) {
 8293:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 8294:                                   &escape($udom),$tryserver);
 8295:                 if ($listing eq 'unknown_cmd') {
 8296: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 8297: 				      $udom, $tryserver);
 8298:                 } else {
 8299:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 8300:                 }
 8301: 		if ($listing eq 'unknown_cmd') {
 8302: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 8303: 				      $udom, $tryserver);
 8304: 		    @listing_results = split(/:/,$listing);
 8305: 		} else {
 8306: 		    @listing_results =
 8307: 			map { &unescape($_); } split(/:/,$listing);
 8308: 		}
 8309:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
 8310:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
 8311:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 8312:                     $listerror{$tryserver} = $listing;
 8313:                 } else {
 8314: 		    foreach my $line (@listing_results) {
 8315: 			my ($entry) = split(/&/,$line,2);
 8316: 			$allusers{$entry} = 1;
 8317: 		    }
 8318: 		}
 8319:             }
 8320:             my @alluserslist=();
 8321:             foreach my $user (sort(keys(%allusers))) {
 8322:                 push(@alluserslist,$user.'&user');
 8323:             }
 8324:             return (\@alluserslist);
 8325:         } else {
 8326:             return ([],'missing username');
 8327:         }
 8328:     } elsif(!defined($getpropath)) {
 8329:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
 8330:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
 8331:         return (\@all_domains);
 8332:     } else {
 8333:         return ([],'missing domain');
 8334:     }
 8335: }
 8336: 
 8337: # --------------------------------------------- GetFileTimestamp
 8338: # This function utilizes dirlist and returns the date stamp for
 8339: # when it was last modified.  It will also return an error of -1
 8340: # if an error occurs
 8341: 
 8342: sub GetFileTimestamp {
 8343:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 8344:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 8345:     $studentName   = &LONCAPA::clean_username($studentName);
 8346:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
 8347:                                     undef,$getuserdir);
 8348:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 8349:         return -1;
 8350:     }
 8351:     if (ref($fileref) eq 'ARRAY') {
 8352:         my @stats = split('&',$fileref->[0]);
 8353:         # @stats contains first the filename, then the stat output
 8354:         return $stats[10]; # so this is 10 instead of 9.
 8355:     } else {
 8356:         return -1;
 8357:     }
 8358: }
 8359: 
 8360: sub stat_file {
 8361:     my ($uri) = @_;
 8362:     $uri = &clutter_with_no_wrapper($uri);
 8363: 
 8364:     my ($udom,$uname,$file);
 8365:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 8366: 	($udom,$uname,$file) =
 8367: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 8368: 	$file = 'userfiles/'.$file;
 8369:     }
 8370:     if ($uri =~ m-^/res/-) {
 8371: 	($udom,$uname) = 
 8372: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 8373: 	$file = $uri;
 8374:     }
 8375: 
 8376:     if (!$udom || !$uname || !$file) {
 8377: 	# unable to handle the uri
 8378: 	return ();
 8379:     }
 8380:     my $getpropath;
 8381:     if ($file =~ /^userfiles\//) {
 8382:         $getpropath = 1;
 8383:     }
 8384:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
 8385:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 8386:         return ();
 8387:     } else {
 8388:         if (ref($listref) eq 'ARRAY') {
 8389:             my @stats = split('&',$listref->[0]);
 8390: 	    shift(@stats); #filename is first
 8391: 	    return @stats;
 8392:         }
 8393:     }
 8394:     return ();
 8395: }
 8396: 
 8397: # -------------------------------------------------------- Value of a Condition
 8398: 
 8399: # gets the value of a specific preevaluated condition
 8400: #    stored in the string  $env{user.state.<cid>}
 8401: # or looks up a condition reference in the bighash and if if hasn't
 8402: # already been evaluated recurses into docondval to get the value of
 8403: # the condition, then memoizing it to 
 8404: #   $env{user.state.<cid>.<condition>}
 8405: sub directcondval {
 8406:     my $number=shift;
 8407:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 8408: 	&Apache::lonuserstate::evalstate();
 8409:     }
 8410:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 8411: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 8412:     } elsif ($number =~ /^_/) {
 8413: 	my $sub_condition;
 8414: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8415: 		&GDBM_READER(),0640)) {
 8416: 	    $sub_condition=$bighash{'conditions'.$number};
 8417: 	    untie(%bighash);
 8418: 	}
 8419: 	my $value = &docondval($sub_condition);
 8420: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 8421: 	return $value;
 8422:     }
 8423:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 8424:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 8425:     } else {
 8426:        return 2;
 8427:     }
 8428: }
 8429: 
 8430: # get the collection of conditions for this resource
 8431: sub condval {
 8432:     my $condidx=shift;
 8433:     my $allpathcond='';
 8434:     foreach my $cond (split(/\|/,$condidx)) {
 8435: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 8436: 	    $allpathcond.=
 8437: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 8438: 	}
 8439:     }
 8440:     $allpathcond=~s/\|$//;
 8441:     return &docondval($allpathcond);
 8442: }
 8443: 
 8444: #evaluates an expression of conditions
 8445: sub docondval {
 8446:     my ($allpathcond) = @_;
 8447:     my $result=0;
 8448:     if ($env{'request.course.id'}
 8449: 	&& defined($allpathcond)) {
 8450: 	my $operand='|';
 8451: 	my @stack;
 8452: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 8453: 	    if ($chunk eq '(') {
 8454: 		push @stack,($operand,$result);
 8455: 	    } elsif ($chunk eq ')') {
 8456: 		my $before=pop @stack;
 8457: 		if (pop @stack eq '&') {
 8458: 		    $result=$result>$before?$before:$result;
 8459: 		} else {
 8460: 		    $result=$result>$before?$result:$before;
 8461: 		}
 8462: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 8463: 		$operand=$chunk;
 8464: 	    } else {
 8465: 		my $new=directcondval($chunk);
 8466: 		if ($operand eq '&') {
 8467: 		    $result=$result>$new?$new:$result;
 8468: 		} else {
 8469: 		    $result=$result>$new?$result:$new;
 8470: 		}
 8471: 	    }
 8472: 	}
 8473:     }
 8474:     return $result;
 8475: }
 8476: 
 8477: # ---------------------------------------------------- Devalidate courseresdata
 8478: 
 8479: sub devalidatecourseresdata {
 8480:     my ($coursenum,$coursedomain)=@_;
 8481:     my $hashid=$coursenum.':'.$coursedomain;
 8482:     &devalidate_cache_new('courseres',$hashid);
 8483: }
 8484: 
 8485: 
 8486: # --------------------------------------------------- Course Resourcedata Query
 8487: #
 8488: #  Parameters:
 8489: #      $coursenum    - Number of the course.
 8490: #      $coursedomain - Domain at which the course was created.
 8491: #  Returns:
 8492: #     A hash of the course parameters along (I think) with timestamps
 8493: #     and version info.
 8494: 
 8495: sub get_courseresdata {
 8496:     my ($coursenum,$coursedomain)=@_;
 8497:     my $coursehom=&homeserver($coursenum,$coursedomain);
 8498:     my $hashid=$coursenum.':'.$coursedomain;
 8499:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 8500:     my %dumpreply;
 8501:     unless (defined($cached)) {
 8502: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 8503: 	$result=\%dumpreply;
 8504: 	my ($tmp) = keys(%dumpreply);
 8505: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 8506: 	    &do_cache_new('courseres',$hashid,$result,600);
 8507: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 8508: 	    return $tmp;
 8509: 	} elsif ($tmp =~ /^(error)/) {
 8510: 	    $result=undef;
 8511: 	    &do_cache_new('courseres',$hashid,$result,600);
 8512: 	}
 8513:     }
 8514:     return $result;
 8515: }
 8516: 
 8517: sub devalidateuserresdata {
 8518:     my ($uname,$udom)=@_;
 8519:     my $hashid="$udom:$uname";
 8520:     &devalidate_cache_new('userres',$hashid);
 8521: }
 8522: 
 8523: sub get_userresdata {
 8524:     my ($uname,$udom)=@_;
 8525:     #most student don\'t have any data set, check if there is some data
 8526:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 8527: 
 8528:     my $hashid="$udom:$uname";
 8529:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 8530:     if (!defined($cached)) {
 8531: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 8532: 	$result=\%resourcedata;
 8533: 	&do_cache_new('userres',$hashid,$result,600);
 8534:     }
 8535:     my ($tmp)=keys(%$result);
 8536:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 8537: 	return $result;
 8538:     }
 8539:     #error 2 occurs when the .db doesn't exist
 8540:     if ($tmp!~/error: 2 /) {
 8541: 	&logthis("<font color=\"blue\">WARNING:".
 8542: 		 " Trying to get resource data for ".
 8543: 		 $uname." at ".$udom.": ".
 8544: 		 $tmp."</font>");
 8545:     } elsif ($tmp=~/error: 2 /) {
 8546: 	#&EXT_cache_set($udom,$uname);
 8547: 	&do_cache_new('userres',$hashid,undef,600);
 8548: 	undef($tmp); # not really an error so don't send it back
 8549:     }
 8550:     return $tmp;
 8551: }
 8552: #----------------------------------------------- resdata - return resource data
 8553: #  Purpose:
 8554: #    Return resource data for either users or for a course.
 8555: #  Parameters:
 8556: #     $name      - Course/user name.
 8557: #     $domain    - Name of the domain the user/course is registered on.
 8558: #     $type      - Type of thing $name is (must be 'course' or 'user'
 8559: #     @which     - Array of names of resources desired.
 8560: #  Returns:
 8561: #     The value of the first reasource in @which that is found in the
 8562: #     resource hash.
 8563: #  Exceptional Conditions:
 8564: #     If the $type passed in is not valid (not the string 'course' or 
 8565: #     'user', an undefined  reference is returned.
 8566: #     If none of the resources are found, an undef is returned
 8567: sub resdata {
 8568:     my ($name,$domain,$type,@which)=@_;
 8569:     my $result;
 8570:     if ($type eq 'course') {
 8571: 	$result=&get_courseresdata($name,$domain);
 8572:     } elsif ($type eq 'user') {
 8573: 	$result=&get_userresdata($name,$domain);
 8574:     }
 8575:     if (!ref($result)) { return $result; }    
 8576:     foreach my $item (@which) {
 8577: 	if (defined($result->{$item->[0]})) {
 8578: 	    return [$result->{$item->[0]},$item->[1]];
 8579: 	}
 8580:     }
 8581:     return undef;
 8582: }
 8583: 
 8584: #
 8585: # EXT resource caching routines
 8586: #
 8587: 
 8588: sub clear_EXT_cache_status {
 8589:     &delenv('cache.EXT.');
 8590: }
 8591: 
 8592: sub EXT_cache_status {
 8593:     my ($target_domain,$target_user) = @_;
 8594:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 8595:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 8596:         # We know already the user has no data
 8597:         return 1;
 8598:     } else {
 8599:         return 0;
 8600:     }
 8601: }
 8602: 
 8603: sub EXT_cache_set {
 8604:     my ($target_domain,$target_user) = @_;
 8605:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 8606:     #&appenv({$cachename => time});
 8607: }
 8608: 
 8609: # --------------------------------------------------------- Value of a Variable
 8610: sub EXT {
 8611: 
 8612:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 8613:     unless ($varname) { return ''; }
 8614:     #get real user name/domain, courseid and symb
 8615:     my $courseid;
 8616:     my $publicuser;
 8617:     if ($symbparm) {
 8618: 	$symbparm=&get_symb_from_alias($symbparm);
 8619:     }
 8620:     if (!($uname && $udom)) {
 8621:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 8622:       if (!$symbparm) {	$symbparm=$cursymb; }
 8623:     } else {
 8624: 	$courseid=$env{'request.course.id'};
 8625:     }
 8626:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 8627:     my $rest;
 8628:     if (defined($therest[0])) {
 8629:        $rest=join('.',@therest);
 8630:     } else {
 8631:        $rest='';
 8632:     }
 8633: 
 8634:     my $qualifierrest=$qualifier;
 8635:     if ($rest) { $qualifierrest.='.'.$rest; }
 8636:     my $spacequalifierrest=$space;
 8637:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 8638:     if ($realm eq 'user') {
 8639: # --------------------------------------------------------------- user.resource
 8640: 	if ($space eq 'resource') {
 8641: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 8642: 		  || defined($Apache::lonhomework::parsing_a_task))
 8643: 		 &&
 8644: 		 ($symbparm eq &symbread()) ) {	
 8645: 		# if we are in the middle of processing the resource the
 8646: 		# get the value we are planning on committing
 8647:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 8648:                     return $Apache::lonhomework::results{$qualifierrest};
 8649:                 } else {
 8650:                     return $Apache::lonhomework::history{$qualifierrest};
 8651:                 }
 8652: 	    } else {
 8653: 		my %restored;
 8654: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 8655: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 8656: 		} else {
 8657: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 8658: 		}
 8659: 		return $restored{$qualifierrest};
 8660: 	    }
 8661: # ----------------------------------------------------------------- user.access
 8662:         } elsif ($space eq 'access') {
 8663: 	    # FIXME - not supporting calls for a specific user
 8664:             return &allowed($qualifier,$rest);
 8665: # ------------------------------------------ user.preferences, user.environment
 8666:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 8667: 	    if (($uname eq $env{'user.name'}) &&
 8668: 		($udom eq $env{'user.domain'})) {
 8669: 		return $env{join('.',('environment',$qualifierrest))};
 8670: 	    } else {
 8671: 		my %returnhash;
 8672: 		if (!$publicuser) {
 8673: 		    %returnhash=&userenvironment($udom,$uname,
 8674: 						 $qualifierrest);
 8675: 		}
 8676: 		return $returnhash{$qualifierrest};
 8677: 	    }
 8678: # ----------------------------------------------------------------- user.course
 8679:         } elsif ($space eq 'course') {
 8680: 	    # FIXME - not supporting calls for a specific user
 8681:             return $env{join('.',('request.course',$qualifier))};
 8682: # ------------------------------------------------------------------- user.role
 8683:         } elsif ($space eq 'role') {
 8684: 	    # FIXME - not supporting calls for a specific user
 8685:             my ($role,$where)=split(/\./,$env{'request.role'});
 8686:             if ($qualifier eq 'value') {
 8687: 		return $role;
 8688:             } elsif ($qualifier eq 'extent') {
 8689:                 return $where;
 8690:             }
 8691: # ----------------------------------------------------------------- user.domain
 8692:         } elsif ($space eq 'domain') {
 8693:             return $udom;
 8694: # ------------------------------------------------------------------- user.name
 8695:         } elsif ($space eq 'name') {
 8696:             return $uname;
 8697: # ---------------------------------------------------- Any other user namespace
 8698:         } else {
 8699: 	    my %reply;
 8700: 	    if (!$publicuser) {
 8701: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 8702: 	    }
 8703: 	    return $reply{$qualifierrest};
 8704:         }
 8705:     } elsif ($realm eq 'query') {
 8706: # ---------------------------------------------- pull stuff out of query string
 8707:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 8708: 						[$spacequalifierrest]);
 8709: 	return $env{'form.'.$spacequalifierrest}; 
 8710:    } elsif ($realm eq 'request') {
 8711: # ------------------------------------------------------------- request.browser
 8712:         if ($space eq 'browser') {
 8713:             return $env{'browser.'.$qualifier};
 8714: # ------------------------------------------------------------ request.filename
 8715:         } else {
 8716:             return $env{'request.'.$spacequalifierrest};
 8717:         }
 8718:     } elsif ($realm eq 'course') {
 8719: # ---------------------------------------------------------- course.description
 8720:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 8721:     } elsif ($realm eq 'resource') {
 8722: 
 8723: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 8724: 	    if (!$symbparm) { $symbparm=&symbread(); }
 8725: 	}
 8726: 
 8727: 	if ($space eq 'title') {
 8728: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 8729: 	    return &gettitle($symbparm);
 8730: 	}
 8731: 	
 8732: 	if ($space eq 'map') {
 8733: 	    my ($map) = &decode_symb($symbparm);
 8734: 	    return &symbread($map);
 8735: 	}
 8736: 	if ($space eq 'filename') {
 8737: 	    if ($symbparm) {
 8738: 		return &clutter((&decode_symb($symbparm))[2]);
 8739: 	    }
 8740: 	    return &hreflocation('',$env{'request.filename'});
 8741: 	}
 8742: 
 8743: 	my ($section, $group, @groups);
 8744: 	my ($courselevelm,$courselevel);
 8745: 	if ($symbparm && defined($courseid) && 
 8746: 	    $courseid eq $env{'request.course.id'}) {
 8747: 
 8748: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 8749: 
 8750: # ----------------------------------------------------- Cascading lookup scheme
 8751: 	    my $symbp=$symbparm;
 8752: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 8753: 
 8754: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 8755: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 8756: 
 8757: 	    if (($env{'user.name'} eq $uname) &&
 8758: 		($env{'user.domain'} eq $udom)) {
 8759: 		$section=$env{'request.course.sec'};
 8760:                 @groups = split(/:/,$env{'request.course.groups'});  
 8761:                 @groups=&sort_course_groups($courseid,@groups); 
 8762: 	    } else {
 8763: 		if (! defined($usection)) {
 8764: 		    $section=&getsection($udom,$uname,$courseid);
 8765: 		} else {
 8766: 		    $section = $usection;
 8767: 		}
 8768:                 @groups = &get_users_groups($udom,$uname,$courseid);
 8769: 	    }
 8770: 
 8771: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 8772: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 8773: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 8774: 
 8775: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 8776: 	    my $courselevelr=$courseid.'.'.$symbparm;
 8777: 	    $courselevelm=$courseid.'.'.$mapparm;
 8778: 
 8779: # ----------------------------------------------------------- first, check user
 8780: 
 8781: 	    my $userreply=&resdata($uname,$udom,'user',
 8782: 				       ([$courselevelr,'resource'],
 8783: 					[$courselevelm,'map'     ],
 8784: 					[$courselevel, 'course'  ]));
 8785: 	    if (defined($userreply)) { return &get_reply($userreply); }
 8786: 
 8787: # ------------------------------------------------ second, check some of course
 8788:             my $coursereply;
 8789:             if (@groups > 0) {
 8790:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 8791:                                        $mapparm,$spacequalifierrest);
 8792:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 8793:             }
 8794: 
 8795: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 8796: 				  $env{'course.'.$courseid.'.domain'},
 8797: 				  'course',
 8798: 				  ([$seclevelr,   'resource'],
 8799: 				   [$seclevelm,   'map'     ],
 8800: 				   [$seclevel,    'course'  ],
 8801: 				   [$courselevelr,'resource']));
 8802: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 8803: 
 8804: # ------------------------------------------------------ third, check map parms
 8805: 	    my %parmhash=();
 8806: 	    my $thisparm='';
 8807: 	    if (tie(%parmhash,'GDBM_File',
 8808: 		    $env{'request.course.fn'}.'_parms.db',
 8809: 		    &GDBM_READER(),0640)) {
 8810: 		$thisparm=$parmhash{$symbparm};
 8811: 		untie(%parmhash);
 8812: 	    }
 8813: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 8814: 	}
 8815: # ------------------------------------------ fourth, look in resource metadata
 8816: 
 8817: 	$spacequalifierrest=~s/\./\_/;
 8818: 	my $filename;
 8819: 	if (!$symbparm) { $symbparm=&symbread(); }
 8820: 	if ($symbparm) {
 8821: 	    $filename=(&decode_symb($symbparm))[2];
 8822: 	} else {
 8823: 	    $filename=$env{'request.filename'};
 8824: 	}
 8825: 	my $metadata=&metadata($filename,$spacequalifierrest);
 8826: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 8827: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 8828: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 8829: 
 8830: # ---------------------------------------------- fourth, look in rest of course
 8831: 	if ($symbparm && defined($courseid) && 
 8832: 	    $courseid eq $env{'request.course.id'}) {
 8833: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 8834: 				     $env{'course.'.$courseid.'.domain'},
 8835: 				     'course',
 8836: 				     ([$courselevelm,'map'   ],
 8837: 				      [$courselevel, 'course']));
 8838: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 8839: 	}
 8840: # ------------------------------------------------------------------ Cascade up
 8841: 	unless ($space eq '0') {
 8842: 	    my @parts=split(/_/,$space);
 8843: 	    my $id=pop(@parts);
 8844: 	    my $part=join('_',@parts);
 8845: 	    if ($part eq '') { $part='0'; }
 8846: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 8847: 				 $symbparm,$udom,$uname,$section,1);
 8848: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 8849: 	}
 8850: 	if ($recurse) { return undef; }
 8851: 	my $pack_def=&packages_tab_default($filename,$varname);
 8852: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 8853: # ---------------------------------------------------- Any other user namespace
 8854:     } elsif ($realm eq 'environment') {
 8855: # ----------------------------------------------------------------- environment
 8856: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 8857: 	    return $env{'environment.'.$spacequalifierrest};
 8858: 	} else {
 8859: 	    if ($uname eq 'anonymous' && $udom eq '') {
 8860: 		return '';
 8861: 	    }
 8862: 	    my %returnhash=&userenvironment($udom,$uname,
 8863: 					    $spacequalifierrest);
 8864: 	    return $returnhash{$spacequalifierrest};
 8865: 	}
 8866:     } elsif ($realm eq 'system') {
 8867: # ----------------------------------------------------------------- system.time
 8868: 	if ($space eq 'time') {
 8869: 	    return time;
 8870:         }
 8871:     } elsif ($realm eq 'server') {
 8872: # ----------------------------------------------------------------- system.time
 8873: 	if ($space eq 'name') {
 8874: 	    return $ENV{'SERVER_NAME'};
 8875:         }
 8876:     }
 8877:     return '';
 8878: }
 8879: 
 8880: sub get_reply {
 8881:     my ($reply_value) = @_;
 8882:     if (ref($reply_value) eq 'ARRAY') {
 8883:         if (wantarray) {
 8884: 	    return @$reply_value;
 8885:         }
 8886:         return $reply_value->[0];
 8887:     } else {
 8888:         return $reply_value;
 8889:     }
 8890: }
 8891: 
 8892: sub check_group_parms {
 8893:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 8894:     my @groupitems = ();
 8895:     my $resultitem;
 8896:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 8897:     foreach my $group (@{$groups}) {
 8898:         foreach my $level (@levels) {
 8899:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 8900:              push(@groupitems,[$item,$level->[1]]);
 8901:         }
 8902:     }
 8903:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 8904:                             $env{'course.'.$courseid.'.domain'},
 8905:                                      'course',@groupitems);
 8906:     return $coursereply;
 8907: }
 8908: 
 8909: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 8910:     my ($courseid,@groups) = @_;
 8911:     @groups = sort(@groups);
 8912:     return @groups;
 8913: }
 8914: 
 8915: sub packages_tab_default {
 8916:     my ($uri,$varname)=@_;
 8917:     my (undef,$part,$name)=split(/\./,$varname);
 8918: 
 8919:     my (@extension,@specifics,$do_default);
 8920:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 8921: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 8922: 	if ($pack_type eq 'default') {
 8923: 	    $do_default=1;
 8924: 	} elsif ($pack_type eq 'extension') {
 8925: 	    push(@extension,[$package,$pack_type,$pack_part]);
 8926: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 8927: 	    # only look at packages defaults for packages that this id is
 8928: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 8929: 	}
 8930:     }
 8931:     # first look for a package that matches the requested part id
 8932:     foreach my $package (@specifics) {
 8933: 	my (undef,$pack_type,$pack_part)=@{$package};
 8934: 	next if ($pack_part ne $part);
 8935: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 8936: 	    return $packagetab{"$pack_type&$name&default"};
 8937: 	}
 8938:     }
 8939:     # look for any possible matching non extension_ package
 8940:     foreach my $package (@specifics) {
 8941: 	my (undef,$pack_type,$pack_part)=@{$package};
 8942: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 8943: 	    return $packagetab{"$pack_type&$name&default"};
 8944: 	}
 8945: 	if ($pack_type eq 'part') { $pack_part='0'; }
 8946: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 8947: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 8948: 	}
 8949:     }
 8950:     # look for any posible extension_ match
 8951:     foreach my $package (@extension) {
 8952: 	my ($package,$pack_type)=@{$package};
 8953: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 8954: 	    return $packagetab{"$pack_type&$name&default"};
 8955: 	}
 8956: 	if (defined($packagetab{$package."&$name&default"})) {
 8957: 	    return $packagetab{$package."&$name&default"};
 8958: 	}
 8959:     }
 8960:     # look for a global default setting
 8961:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 8962: 	return $packagetab{"default&$name&default"};
 8963:     }
 8964:     return undef;
 8965: }
 8966: 
 8967: sub add_prefix_and_part {
 8968:     my ($prefix,$part)=@_;
 8969:     my $keyroot;
 8970:     if (defined($prefix) && $prefix !~ /^__/) {
 8971: 	# prefix that has a part already
 8972: 	$keyroot=$prefix;
 8973:     } elsif (defined($prefix)) {
 8974: 	# prefix that is missing a part
 8975: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 8976:     } else {
 8977: 	# no prefix at all
 8978: 	if (defined($part)) { $keyroot='_'.$part; }
 8979:     }
 8980:     return $keyroot;
 8981: }
 8982: 
 8983: # ---------------------------------------------------------------- Get metadata
 8984: 
 8985: my %metaentry;
 8986: my %importedpartids;
 8987: sub metadata {
 8988:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 8989:     $uri=&declutter($uri);
 8990:     # if it is a non metadata possible uri return quickly
 8991:     if (($uri eq '') || 
 8992: 	(($uri =~ m|^/*adm/|) && 
 8993: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 8994:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
 8995: 	return undef;
 8996:     }
 8997:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
 8998: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
 8999: 	return undef;
 9000:     }
 9001:     my $filename=$uri;
 9002:     $uri=~s/\.meta$//;
 9003: #
 9004: # Is the metadata already cached?
 9005: # Look at timestamp of caching
 9006: # Everything is cached by the main uri, libraries are never directly cached
 9007: #
 9008:     if (!defined($liburi)) {
 9009: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 9010: 	if (defined($cached)) { return $result->{':'.$what}; }
 9011:     }
 9012:     {
 9013: # Imported parts would go here
 9014:         my %importedids=();
 9015:         my @origfileimportpartids=();
 9016:         my $importedparts=0;
 9017: #
 9018: # Is this a recursive call for a library?
 9019: #
 9020: #	if (! exists($metacache{$uri})) {
 9021: #	    $metacache{$uri}={};
 9022: #	}
 9023: 	my $cachetime = 60*60;
 9024:         if ($liburi) {
 9025: 	    $liburi=&declutter($liburi);
 9026:             $filename=$liburi;
 9027:         } else {
 9028: 	    &devalidate_cache_new('meta',$uri);
 9029: 	    undef(%metaentry);
 9030: 	}
 9031:         my %metathesekeys=();
 9032:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 9033: 	my $metastring;
 9034: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
 9035: 	    my $which = &hreflocation('','/'.($liburi || $uri));
 9036: 	    $metastring = 
 9037: 		&Apache::lonnet::ssi_body($which,
 9038: 					  ('grade_target' => 'meta'));
 9039: 	    $cachetime = 1; # only want this cached in the child not long term
 9040: 	} elsif (($uri !~ m -^(editupload)/-) && 
 9041:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
 9042: 	    my $file=&filelocation('',&clutter($filename));
 9043: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 9044: 	    $metastring=&getfile($file);
 9045: 	}
 9046:         my $parser=HTML::LCParser->new(\$metastring);
 9047:         my $token;
 9048:         undef %metathesekeys;
 9049:         while ($token=$parser->get_token) {
 9050: 	    if ($token->[0] eq 'S') {
 9051: 		if (defined($token->[2]->{'package'})) {
 9052: #
 9053: # This is a package - get package info
 9054: #
 9055: 		    my $package=$token->[2]->{'package'};
 9056: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9057: 		    if (defined($token->[2]->{'id'})) { 
 9058: 			$keyroot.='_'.$token->[2]->{'id'}; 
 9059: 		    }
 9060: 		    if ($metaentry{':packages'}) {
 9061: 			$metaentry{':packages'}.=','.$package.$keyroot;
 9062: 		    } else {
 9063: 			$metaentry{':packages'}=$package.$keyroot;
 9064: 		    }
 9065: 		    foreach my $pack_entry (keys(%packagetab)) {
 9066: 			my $part=$keyroot;
 9067: 			$part=~s/^\_//;
 9068: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 9069: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 9070: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 9071: 			    # ignore package.tab specified default values
 9072:                             # here &package_tab_default() will fetch those
 9073: 			    if ($subp eq 'default') { next; }
 9074: 			    my $value=$packagetab{$pack_entry};
 9075: 			    my $unikey;
 9076: 			    if ($pack =~ /_0$/) {
 9077: 				$unikey='parameter_0_'.$name;
 9078: 				$part=0;
 9079: 			    } else {
 9080: 				$unikey='parameter'.$keyroot.'_'.$name;
 9081: 			    }
 9082: 			    if ($subp eq 'display') {
 9083: 				$value.=' [Part: '.$part.']';
 9084: 			    }
 9085: 			    $metaentry{':'.$unikey.'.part'}=$part;
 9086: 			    $metathesekeys{$unikey}=1;
 9087: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 9088: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 9089: 			    }
 9090: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 9091: 				$metaentry{':'.$unikey}=
 9092: 				    $metaentry{':'.$unikey.'.default'};
 9093: 			    }
 9094: 			}
 9095: 		    }
 9096: 		} else {
 9097: #
 9098: # This is not a package - some other kind of start tag
 9099: #
 9100: 		    my $entry=$token->[1];
 9101: 		    my $unikey='';
 9102: 
 9103: 		    if ($entry eq 'import') {
 9104: #
 9105: # Importing a library here
 9106: #
 9107:                         my $location=$parser->get_text('/import');
 9108:                         my $dir=$filename;
 9109:                         $dir=~s|[^/]*$||;
 9110:                         $location=&filelocation($dir,$location);
 9111:                        
 9112:                         my $importmode=$token->[2]->{'importmode'};
 9113:                         if ($importmode eq 'problem') {
 9114: # Import as problem/response
 9115:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9116:                         } elsif ($importmode eq 'part') {
 9117: # Import as part(s)
 9118:                            $importedparts=1;
 9119: # We need to get the original file and the imported file to get the part order correct
 9120: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
 9121: # Load and inspect original file
 9122:                            if ($#origfileimportpartids<0) {
 9123:                               undef(%importedpartids);
 9124:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
 9125:                               my $origfile=&getfile($origfilelocation);
 9126:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
 9127:                            }
 9128: 
 9129: # Load and inspect imported file
 9130:                            my $impfile=&getfile($location);
 9131:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
 9132:                            if ($#impfilepartids>=0) {
 9133: # This problem had parts
 9134:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
 9135:                            } else {
 9136: # Importing by turning a single problem into a problem part
 9137: # It gets the import-tags ID as part-ID
 9138:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
 9139:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
 9140:                            }
 9141:                         } else {
 9142: # Normal import
 9143:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9144:                            if (defined($token->[2]->{'id'})) {
 9145:                               $unikey.='_'.$token->[2]->{'id'};
 9146:                            }
 9147:                         }
 9148: 
 9149: 			if ($depthcount<20) {
 9150: 			    my $metadata = 
 9151: 				&metadata($uri,'keys', $location,$unikey,
 9152: 					  $depthcount+1);
 9153: 			    foreach my $meta (split(',',$metadata)) {
 9154: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 9155: 				$metathesekeys{$meta}=1;
 9156: 			    }
 9157: 			
 9158:                         }
 9159: 		    } else {
 9160: #
 9161: # Not importing, some other kind of non-package, non-library start tag
 9162: # 
 9163:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9164:                         if (defined($token->[2]->{'id'})) {
 9165:                             $unikey.='_'.$token->[2]->{'id'};
 9166:                         }
 9167: 			if (defined($token->[2]->{'name'})) { 
 9168: 			    $unikey.='_'.$token->[2]->{'name'}; 
 9169: 			}
 9170: 			$metathesekeys{$unikey}=1;
 9171: 			foreach my $param (@{$token->[3]}) {
 9172: 			    $metaentry{':'.$unikey.'.'.$param} =
 9173: 				$token->[2]->{$param};
 9174: 			}
 9175: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 9176: 			my $default=$metaentry{':'.$unikey.'.default'};
 9177: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 9178: 		 # only ws inside the tag, and not in default, so use default
 9179: 		 # as value
 9180: 			    $metaentry{':'.$unikey}=$default;
 9181: 			} elsif ( $internaltext =~ /\S/ ) {
 9182: 		  # something interesting inside the tag
 9183: 			    $metaentry{':'.$unikey}=$internaltext;
 9184: 			} else {
 9185: 		  # no interesting values, don't set a default
 9186: 			}
 9187: # end of not-a-package not-a-library import
 9188: 		    }
 9189: # end of not-a-package start tag
 9190: 		}
 9191: # the next is the end of "start tag"
 9192: 	    }
 9193: 	}
 9194: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 9195: 	$extension = lc($extension);
 9196: 	if ($extension eq 'htm') { $extension='html'; }
 9197: 
 9198: 	foreach my $key (keys(%packagetab)) {
 9199: 	    #no specific packages #how's our extension
 9200: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 9201: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 9202: 					 \%metathesekeys);
 9203: 	}
 9204: 
 9205: 	if (!exists($metaentry{':packages'})
 9206: 	    || $packagetab{"import_defaults&extension_$extension"}) {
 9207: 	    foreach my $key (keys(%packagetab)) {
 9208: 		#no specific packages well let's get default then
 9209: 		if ($key!~/^default&/) { next; }
 9210: 		&metadata_create_package_def($uri,$key,'default',
 9211: 					     \%metathesekeys);
 9212: 	    }
 9213: 	}
 9214: # are there custom rights to evaluate
 9215: 	if ($metaentry{':copyright'} eq 'custom') {
 9216: 
 9217:     #
 9218:     # Importing a rights file here
 9219:     #
 9220: 	    unless ($depthcount) {
 9221: 		my $location=$metaentry{':customdistributionfile'};
 9222: 		my $dir=$filename;
 9223: 		$dir=~s|[^/]*$||;
 9224: 		$location=&filelocation($dir,$location);
 9225: 		my $rights_metadata =
 9226: 		    &metadata($uri,'keys',$location,'_rights',
 9227: 			      $depthcount+1);
 9228: 		foreach my $rights (split(',',$rights_metadata)) {
 9229: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 9230: 		    $metathesekeys{$rights}=1;
 9231: 		}
 9232: 	    }
 9233: 	}
 9234: 	# uniqifiy package listing
 9235: 	my %seen;
 9236: 	my @uniq_packages =
 9237: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 9238: 	$metaentry{':packages'} = join(',',@uniq_packages);
 9239: 
 9240:         if ($importedparts) {
 9241: # We had imported parts and need to rebuild partorder
 9242:            $metaentry{':partorder'}='';
 9243:            $metathesekeys{'partorder'}=1;
 9244:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
 9245:                if ($origfileimportpartids[$index] eq 'part') {
 9246: # original part, part of the problem
 9247:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
 9248:                } else {
 9249: # we have imported parts at this position
 9250:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
 9251:                }
 9252:            }
 9253:            $metaentry{':partorder'}=~s/^\,//;
 9254:         }
 9255: 
 9256: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 9257: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 9258: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 9259: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
 9260: # this is the end of "was not already recently cached
 9261:     }
 9262:     return $metaentry{':'.$what};
 9263: }
 9264: 
 9265: sub metadata_create_package_def {
 9266:     my ($uri,$key,$package,$metathesekeys)=@_;
 9267:     my ($pack,$name,$subp)=split(/\&/,$key);
 9268:     if ($subp eq 'default') { next; }
 9269:     
 9270:     if (defined($metaentry{':packages'})) {
 9271: 	$metaentry{':packages'}.=','.$package;
 9272:     } else {
 9273: 	$metaentry{':packages'}=$package;
 9274:     }
 9275:     my $value=$packagetab{$key};
 9276:     my $unikey;
 9277:     $unikey='parameter_0_'.$name;
 9278:     $metaentry{':'.$unikey.'.part'}=0;
 9279:     $$metathesekeys{$unikey}=1;
 9280:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 9281: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 9282:     }
 9283:     if (defined($metaentry{':'.$unikey.'.default'})) {
 9284: 	$metaentry{':'.$unikey}=
 9285: 	    $metaentry{':'.$unikey.'.default'};
 9286:     }
 9287: }
 9288: 
 9289: sub metadata_generate_part0 {
 9290:     my ($metadata,$metacache,$uri) = @_;
 9291:     my %allnames;
 9292:     foreach my $metakey (keys(%$metadata)) {
 9293: 	if ($metakey=~/^parameter\_(.*)/) {
 9294: 	  my $part=$$metacache{':'.$metakey.'.part'};
 9295: 	  my $name=$$metacache{':'.$metakey.'.name'};
 9296: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 9297: 	    $allnames{$name}=$part;
 9298: 	  }
 9299: 	}
 9300:     }
 9301:     foreach my $name (keys(%allnames)) {
 9302:       $$metadata{"parameter_0_$name"}=1;
 9303:       my $key=":parameter_0_$name";
 9304:       $$metacache{"$key.part"}='0';
 9305:       $$metacache{"$key.name"}=$name;
 9306:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 9307: 					   $allnames{$name}.'_'.$name.
 9308: 					   '.type'};
 9309:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 9310: 			     '.display'};
 9311:       my $expr='[Part: '.$allnames{$name}.']';
 9312:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 9313:       $$metacache{"$key.display"}=$olddis;
 9314:     }
 9315: }
 9316: 
 9317: # ------------------------------------------------------ Devalidate title cache
 9318: 
 9319: sub devalidate_title_cache {
 9320:     my ($url)=@_;
 9321:     if (!$env{'request.course.id'}) { return; }
 9322:     my $symb=&symbread($url);
 9323:     if (!$symb) { return; }
 9324:     my $key=$env{'request.course.id'}."\0".$symb;
 9325:     &devalidate_cache_new('title',$key);
 9326: }
 9327: 
 9328: # ------------------------------------------------- Get the title of a course
 9329: 
 9330: sub current_course_title {
 9331:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
 9332: }
 9333: # ------------------------------------------------- Get the title of a resource
 9334: 
 9335: sub gettitle {
 9336:     my $urlsymb=shift;
 9337:     my $symb=&symbread($urlsymb);
 9338:     if ($symb) {
 9339: 	my $key=$env{'request.course.id'}."\0".$symb;
 9340: 	my ($result,$cached)=&is_cached_new('title',$key);
 9341: 	if (defined($cached)) { 
 9342: 	    return $result;
 9343: 	}
 9344: 	my ($map,$resid,$url)=&decode_symb($symb);
 9345: 	my $title='';
 9346: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
 9347: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
 9348: 	} else {
 9349: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9350: 		    &GDBM_READER(),0640)) {
 9351: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
 9352: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
 9353: 		untie(%bighash);
 9354: 	    }
 9355: 	}
 9356: 	$title=~s/\&colon\;/\:/gs;
 9357: 	if ($title) {
 9358: 	    return &do_cache_new('title',$key,$title,600);
 9359: 	}
 9360: 	$urlsymb=$url;
 9361:     }
 9362:     my $title=&metadata($urlsymb,'title');
 9363:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 9364:     return $title;
 9365: }
 9366: 
 9367: sub get_slot {
 9368:     my ($which,$cnum,$cdom)=@_;
 9369:     if (!$cnum || !$cdom) {
 9370: 	(undef,my $courseid)=&whichuser();
 9371: 	$cdom=$env{'course.'.$courseid.'.domain'};
 9372: 	$cnum=$env{'course.'.$courseid.'.num'};
 9373:     }
 9374:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 9375:     my %slotinfo;
 9376:     if (exists($remembered{$key})) {
 9377: 	$slotinfo{$which} = $remembered{$key};
 9378:     } else {
 9379: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 9380: 	&Apache::lonhomework::showhash(%slotinfo);
 9381: 	my ($tmp)=keys(%slotinfo);
 9382: 	if ($tmp=~/^error:/) { return (); }
 9383: 	$remembered{$key} = $slotinfo{$which};
 9384:     }
 9385:     if (ref($slotinfo{$which}) eq 'HASH') {
 9386: 	return %{$slotinfo{$which}};
 9387:     }
 9388:     return $slotinfo{$which};
 9389: }
 9390: # ------------------------------------------------- Update symbolic store links
 9391: 
 9392: sub symblist {
 9393:     my ($mapname,%newhash)=@_;
 9394:     $mapname=&deversion(&declutter($mapname));
 9395:     my %hash;
 9396:     if (($env{'request.course.fn'}) && (%newhash)) {
 9397:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 9398:                       &GDBM_WRCREAT(),0640)) {
 9399: 	    foreach my $url (keys(%newhash)) {
 9400: 		next if ($url eq 'last_known'
 9401: 			 && $env{'form.no_update_last_known'});
 9402: 		$hash{declutter($url)}=&encode_symb($mapname,
 9403: 						    $newhash{$url}->[1],
 9404: 						    $newhash{$url}->[0]);
 9405:             }
 9406:             if (untie(%hash)) {
 9407: 		return 'ok';
 9408:             }
 9409:         }
 9410:     }
 9411:     return 'error';
 9412: }
 9413: 
 9414: # --------------------------------------------------------------- Verify a symb
 9415: 
 9416: sub symbverify {
 9417:     my ($symb,$thisurl)=@_;
 9418:     my $thisfn=$thisurl;
 9419:     $thisfn=&declutter($thisfn);
 9420: # direct jump to resource in page or to a sequence - will construct own symbs
 9421:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 9422: # check URL part
 9423:     my ($map,$resid,$url)=&decode_symb($symb);
 9424: 
 9425:     unless ($url eq $thisfn) { return 0; }
 9426: 
 9427:     $symb=&symbclean($symb);
 9428:     $thisurl=&deversion($thisurl);
 9429:     $thisfn=&deversion($thisfn);
 9430: 
 9431:     my %bighash;
 9432:     my $okay=0;
 9433: 
 9434:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9435:                             &GDBM_READER(),0640)) {
 9436:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
 9437:             $thisurl =~ s/\?.+$//;
 9438:         }
 9439:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 9440:         unless ($ids) {
 9441:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
 9442:             $ids=$bighash{$idkey};
 9443:         }
 9444:         if ($ids) {
 9445: # ------------------------------------------------------------------- Has ID(s)
 9446: 	    foreach my $id (split(/\,/,$ids)) {
 9447: 	       my ($mapid,$resid)=split(/\./,$id);
 9448:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
 9449:                    $symb =~ s/\?.+$//;
 9450:                }
 9451:                if (
 9452:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 9453:    eq $symb) { 
 9454: 		   if (($env{'request.role.adv'}) ||
 9455: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
 9456:                        ($thisurl eq '/adm/navmaps')) {
 9457: 		       $okay=1; 
 9458: 		   }
 9459: 	       }
 9460: 	   }
 9461:         }
 9462: 	untie(%bighash);
 9463:     }
 9464:     return $okay;
 9465: }
 9466: 
 9467: # --------------------------------------------------------------- Clean-up symb
 9468: 
 9469: sub symbclean {
 9470:     my $symb=shift;
 9471:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 9472: # remove version from map
 9473:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 9474: 
 9475: # remove version from URL
 9476:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 9477: 
 9478: # remove wrapper
 9479: 
 9480:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 9481:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 9482:     return $symb;
 9483: }
 9484: 
 9485: # ---------------------------------------------- Split symb to find map and url
 9486: 
 9487: sub encode_symb {
 9488:     my ($map,$resid,$url)=@_;
 9489:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 9490: }
 9491: 
 9492: sub decode_symb {
 9493:     my $symb=shift;
 9494:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 9495:     my ($map,$resid,$url)=split(/___/,$symb);
 9496:     return (&fixversion($map),$resid,&fixversion($url));
 9497: }
 9498: 
 9499: sub fixversion {
 9500:     my $fn=shift;
 9501:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 9502:     my %bighash;
 9503:     my $uri=&clutter($fn);
 9504:     my $key=$env{'request.course.id'}.'_'.$uri;
 9505: # is this cached?
 9506:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 9507:     if (defined($cached)) { return $result; }
 9508: # unfortunately not cached, or expired
 9509:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9510: 	    &GDBM_READER(),0640)) {
 9511:  	if ($bighash{'version_'.$uri}) {
 9512:  	    my $version=$bighash{'version_'.$uri};
 9513:  	    unless (($version eq 'mostrecent') || 
 9514: 		    ($version==&getversion($uri))) {
 9515:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 9516:  	    }
 9517:  	}
 9518:  	untie %bighash;
 9519:     }
 9520:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 9521: }
 9522: 
 9523: sub deversion {
 9524:     my $url=shift;
 9525:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 9526:     return $url;
 9527: }
 9528: 
 9529: # ------------------------------------------------------ Return symb list entry
 9530: 
 9531: sub symbread {
 9532:     my ($thisfn,$donotrecurse)=@_;
 9533:     my $cache_str='request.symbread.cached.'.$thisfn;
 9534:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 9535: # no filename provided? try from environment
 9536:     unless ($thisfn) {
 9537:         if ($env{'request.symb'}) {
 9538: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 9539: 	}
 9540: 	$thisfn=$env{'request.filename'};
 9541:     }
 9542:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 9543: # is that filename actually a symb? Verify, clean, and return
 9544:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 9545: 	if (&symbverify($thisfn,$1)) {
 9546: 	    return $env{$cache_str}=&symbclean($thisfn);
 9547: 	}
 9548:     }
 9549:     $thisfn=declutter($thisfn);
 9550:     my %hash;
 9551:     my %bighash;
 9552:     my $syval='';
 9553:     if (($env{'request.course.fn'}) && ($thisfn)) {
 9554:         my $targetfn = $thisfn;
 9555:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 9556:             $targetfn = 'adm/wrapper/'.$thisfn;
 9557:         }
 9558: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 9559: 	    $targetfn=$1;
 9560: 	}
 9561:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 9562:                       &GDBM_READER(),0640)) {
 9563: 	    $syval=$hash{$targetfn};
 9564:             untie(%hash);
 9565:         }
 9566: # ---------------------------------------------------------- There was an entry
 9567:         if ($syval) {
 9568: 	    #unless ($syval=~/\_\d+$/) {
 9569: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 9570: 		    #&appenv({'request.ambiguous' => $thisfn});
 9571: 		    #return $env{$cache_str}='';
 9572: 		#}    
 9573: 		#$syval.=$1;
 9574: 	    #}
 9575:         } else {
 9576: # ------------------------------------------------------- Was not in symb table
 9577:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9578:                             &GDBM_READER(),0640)) {
 9579: # ---------------------------------------------- Get ID(s) for current resource
 9580:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 9581:               unless ($ids) { 
 9582:                  $ids=$bighash{'ids_/'.$thisfn};
 9583:               }
 9584:               unless ($ids) {
 9585: # alias?
 9586: 		  $ids=$bighash{'mapalias_'.$thisfn};
 9587:               }
 9588:               if ($ids) {
 9589: # ------------------------------------------------------------------- Has ID(s)
 9590:                  my @possibilities=split(/\,/,$ids);
 9591:                  if ($#possibilities==0) {
 9592: # ----------------------------------------------- There is only one possibility
 9593: 		     my ($mapid,$resid)=split(/\./,$ids);
 9594: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 9595: 						    $resid,$thisfn);
 9596:                  } elsif (!$donotrecurse) {
 9597: # ------------------------------------------ There is more than one possibility
 9598:                      my $realpossible=0;
 9599:                      foreach my $id (@possibilities) {
 9600: 			 my $file=$bighash{'src_'.$id};
 9601:                          if (&allowed('bre',$file)) {
 9602:          		    my ($mapid,$resid)=split(/\./,$id);
 9603:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 9604: 				$realpossible++;
 9605:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 9606: 						    $resid,$thisfn);
 9607:                             }
 9608: 			 }
 9609:                      }
 9610: 		     if ($realpossible!=1) { $syval=''; }
 9611:                  } else {
 9612:                      $syval='';
 9613:                  }
 9614: 	      }
 9615:               untie(%bighash)
 9616:            }
 9617:         }
 9618:         if ($syval) {
 9619: 	    return $env{$cache_str}=$syval;
 9620:         }
 9621:     }
 9622:     &appenv({'request.ambiguous' => $thisfn});
 9623:     return $env{$cache_str}='';
 9624: }
 9625: 
 9626: # ---------------------------------------------------------- Return random seed
 9627: 
 9628: sub numval {
 9629:     my $txt=shift;
 9630:     $txt=~tr/A-J/0-9/;
 9631:     $txt=~tr/a-j/0-9/;
 9632:     $txt=~tr/K-T/0-9/;
 9633:     $txt=~tr/k-t/0-9/;
 9634:     $txt=~tr/U-Z/0-5/;
 9635:     $txt=~tr/u-z/0-5/;
 9636:     $txt=~s/\D//g;
 9637:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 9638:     return int($txt);
 9639: }
 9640: 
 9641: sub numval2 {
 9642:     my $txt=shift;
 9643:     $txt=~tr/A-J/0-9/;
 9644:     $txt=~tr/a-j/0-9/;
 9645:     $txt=~tr/K-T/0-9/;
 9646:     $txt=~tr/k-t/0-9/;
 9647:     $txt=~tr/U-Z/0-5/;
 9648:     $txt=~tr/u-z/0-5/;
 9649:     $txt=~s/\D//g;
 9650:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 9651:     my $total;
 9652:     foreach my $val (@txts) { $total+=$val; }
 9653:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 9654:     return int($total);
 9655: }
 9656: 
 9657: sub numval3 {
 9658:     use integer;
 9659:     my $txt=shift;
 9660:     $txt=~tr/A-J/0-9/;
 9661:     $txt=~tr/a-j/0-9/;
 9662:     $txt=~tr/K-T/0-9/;
 9663:     $txt=~tr/k-t/0-9/;
 9664:     $txt=~tr/U-Z/0-5/;
 9665:     $txt=~tr/u-z/0-5/;
 9666:     $txt=~s/\D//g;
 9667:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 9668:     my $total;
 9669:     foreach my $val (@txts) { $total+=$val; }
 9670:     if ($_64bit) { $total=(($total<<32)>>32); }
 9671:     return $total;
 9672: }
 9673: 
 9674: sub digest {
 9675:     my ($data)=@_;
 9676:     my $digest=&Digest::MD5::md5($data);
 9677:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 9678:     my ($e,$f);
 9679:     {
 9680:         use integer;
 9681:         $e=($a+$b);
 9682:         $f=($c+$d);
 9683:         if ($_64bit) {
 9684:             $e=(($e<<32)>>32);
 9685:             $f=(($f<<32)>>32);
 9686:         }
 9687:     }
 9688:     if (wantarray) {
 9689: 	return ($e,$f);
 9690:     } else {
 9691: 	my $g;
 9692: 	{
 9693: 	    use integer;
 9694: 	    $g=($e+$f);
 9695: 	    if ($_64bit) {
 9696: 		$g=(($g<<32)>>32);
 9697: 	    }
 9698: 	}
 9699: 	return $g;
 9700:     }
 9701: }
 9702: 
 9703: sub latest_rnd_algorithm_id {
 9704:     return '64bit5';
 9705: }
 9706: 
 9707: sub get_rand_alg {
 9708:     my ($courseid)=@_;
 9709:     if (!$courseid) { $courseid=(&whichuser())[1]; }
 9710:     if ($courseid) {
 9711: 	return $env{"course.$courseid.rndseed"};
 9712:     }
 9713:     return &latest_rnd_algorithm_id();
 9714: }
 9715: 
 9716: sub validCODE {
 9717:     my ($CODE)=@_;
 9718:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 9719:     return 0;
 9720: }
 9721: 
 9722: sub getCODE {
 9723:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 9724:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 9725: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 9726: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 9727: 	return $Apache::lonhomework::history{'resource.CODE'};
 9728:     }
 9729:     return undef;
 9730: }
 9731: #
 9732: #  Determines the random seed for a specific context:
 9733: #
 9734: # parameters:
 9735: #   symb      - in course context the symb for the seed.
 9736: #   course_id - The course id of the form domain_coursenum.
 9737: #   domain    - Domain for the user.
 9738: #   course    - Course for the user.
 9739: #   cenv      - environment of the course.
 9740: #
 9741: # NOTE:
 9742: #   All parameters are picked out of the environment if missing
 9743: #   or not defined.
 9744: #   If a symb cannot be determined the current time is used instead.
 9745: #
 9746: #  For a given well defined symb, courside, domain, username,
 9747: #  and course environment, the seed is reproducible.
 9748: #
 9749: sub rndseed {
 9750:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
 9751:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
 9752:     if (!defined($symb)) {
 9753: 	unless ($symb=$wsymb) { return time; }
 9754:     }
 9755:     if (!defined $courseid) { 
 9756: 	$courseid=$wcourseid; 
 9757:     }
 9758:     if (!defined $domain) { $domain=$wdomain; }
 9759:     if (!defined $username) { $username=$wusername }
 9760: 
 9761:     my $which;
 9762:     if (defined($cenv->{'rndseed'})) {
 9763: 	$which = $cenv->{'rndseed'};
 9764:     } else {
 9765: 	$which =&get_rand_alg($courseid);
 9766:     }
 9767:     if (defined(&getCODE())) {
 9768: 
 9769: 	if ($which eq '64bit5') {
 9770: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 9771: 	} elsif ($which eq '64bit4') {
 9772: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 9773: 	} else {
 9774: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 9775: 	}
 9776:     } elsif ($which eq '64bit5') {
 9777: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 9778:     } elsif ($which eq '64bit4') {
 9779: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 9780:     } elsif ($which eq '64bit3') {
 9781: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 9782:     } elsif ($which eq '64bit2') {
 9783: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 9784:     } elsif ($which eq '64bit') {
 9785: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 9786:     }
 9787:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 9788: }
 9789: 
 9790: sub rndseed_32bit {
 9791:     my ($symb,$courseid,$domain,$username)=@_;
 9792:     {
 9793: 	use integer;
 9794: 	my $symbchck=unpack("%32C*",$symb) << 27;
 9795: 	my $symbseed=numval($symb) << 22;
 9796: 	my $namechck=unpack("%32C*",$username) << 17;
 9797: 	my $nameseed=numval($username) << 12;
 9798: 	my $domainseed=unpack("%32C*",$domain) << 7;
 9799: 	my $courseseed=unpack("%32C*",$courseid);
 9800: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 9801: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 9802: 	#&logthis("rndseed :$num:$symb");
 9803: 	if ($_64bit) { $num=(($num<<32)>>32); }
 9804: 	return $num;
 9805:     }
 9806: }
 9807: 
 9808: sub rndseed_64bit {
 9809:     my ($symb,$courseid,$domain,$username)=@_;
 9810:     {
 9811: 	use integer;
 9812: 	my $symbchck=unpack("%32S*",$symb) << 21;
 9813: 	my $symbseed=numval($symb) << 10;
 9814: 	my $namechck=unpack("%32S*",$username);
 9815: 	
 9816: 	my $nameseed=numval($username) << 21;
 9817: 	my $domainseed=unpack("%32S*",$domain) << 10;
 9818: 	my $courseseed=unpack("%32S*",$courseid);
 9819: 	
 9820: 	my $num1=$symbchck+$symbseed+$namechck;
 9821: 	my $num2=$nameseed+$domainseed+$courseseed;
 9822: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 9823: 	#&logthis("rndseed :$num:$symb");
 9824: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 9825: 	return "$num1,$num2";
 9826:     }
 9827: }
 9828: 
 9829: sub rndseed_64bit2 {
 9830:     my ($symb,$courseid,$domain,$username)=@_;
 9831:     {
 9832: 	use integer;
 9833: 	# strings need to be an even # of cahracters long, it it is odd the
 9834:         # last characters gets thrown away
 9835: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 9836: 	my $symbseed=numval($symb) << 10;
 9837: 	my $namechck=unpack("%32S*",$username.' ');
 9838: 	
 9839: 	my $nameseed=numval($username) << 21;
 9840: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 9841: 	my $courseseed=unpack("%32S*",$courseid.' ');
 9842: 	
 9843: 	my $num1=$symbchck+$symbseed+$namechck;
 9844: 	my $num2=$nameseed+$domainseed+$courseseed;
 9845: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 9846: 	#&logthis("rndseed :$num:$symb");
 9847: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 9848: 	return "$num1,$num2";
 9849:     }
 9850: }
 9851: 
 9852: sub rndseed_64bit3 {
 9853:     my ($symb,$courseid,$domain,$username)=@_;
 9854:     {
 9855: 	use integer;
 9856: 	# strings need to be an even # of cahracters long, it it is odd the
 9857:         # last characters gets thrown away
 9858: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 9859: 	my $symbseed=numval2($symb) << 10;
 9860: 	my $namechck=unpack("%32S*",$username.' ');
 9861: 	
 9862: 	my $nameseed=numval2($username) << 21;
 9863: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 9864: 	my $courseseed=unpack("%32S*",$courseid.' ');
 9865: 	
 9866: 	my $num1=$symbchck+$symbseed+$namechck;
 9867: 	my $num2=$nameseed+$domainseed+$courseseed;
 9868: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 9869: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 9870: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 9871: 	
 9872: 	return "$num1:$num2";
 9873:     }
 9874: }
 9875: 
 9876: sub rndseed_64bit4 {
 9877:     my ($symb,$courseid,$domain,$username)=@_;
 9878:     {
 9879: 	use integer;
 9880: 	# strings need to be an even # of cahracters long, it it is odd the
 9881:         # last characters gets thrown away
 9882: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 9883: 	my $symbseed=numval3($symb) << 10;
 9884: 	my $namechck=unpack("%32S*",$username.' ');
 9885: 	
 9886: 	my $nameseed=numval3($username) << 21;
 9887: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 9888: 	my $courseseed=unpack("%32S*",$courseid.' ');
 9889: 	
 9890: 	my $num1=$symbchck+$symbseed+$namechck;
 9891: 	my $num2=$nameseed+$domainseed+$courseseed;
 9892: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 9893: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 9894: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 9895: 	
 9896: 	return "$num1:$num2";
 9897:     }
 9898: }
 9899: 
 9900: sub rndseed_64bit5 {
 9901:     my ($symb,$courseid,$domain,$username)=@_;
 9902:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 9903:     return "$num1:$num2";
 9904: }
 9905: 
 9906: sub rndseed_CODE_64bit {
 9907:     my ($symb,$courseid,$domain,$username)=@_;
 9908:     {
 9909: 	use integer;
 9910: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 9911: 	my $symbseed=numval2($symb);
 9912: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 9913: 	my $CODEseed=numval(&getCODE());
 9914: 	my $courseseed=unpack("%32S*",$courseid.' ');
 9915: 	my $num1=$symbseed+$CODEchck;
 9916: 	my $num2=$CODEseed+$courseseed+$symbchck;
 9917: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 9918: 	#&logthis("rndseed :$num1:$num2:$symb");
 9919: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 9920: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 9921: 	return "$num1:$num2";
 9922:     }
 9923: }
 9924: 
 9925: sub rndseed_CODE_64bit4 {
 9926:     my ($symb,$courseid,$domain,$username)=@_;
 9927:     {
 9928: 	use integer;
 9929: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 9930: 	my $symbseed=numval3($symb);
 9931: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 9932: 	my $CODEseed=numval3(&getCODE());
 9933: 	my $courseseed=unpack("%32S*",$courseid.' ');
 9934: 	my $num1=$symbseed+$CODEchck;
 9935: 	my $num2=$CODEseed+$courseseed+$symbchck;
 9936: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 9937: 	#&logthis("rndseed :$num1:$num2:$symb");
 9938: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 9939: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 9940: 	return "$num1:$num2";
 9941:     }
 9942: }
 9943: 
 9944: sub rndseed_CODE_64bit5 {
 9945:     my ($symb,$courseid,$domain,$username)=@_;
 9946:     my $code = &getCODE();
 9947:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 9948:     return "$num1:$num2";
 9949: }
 9950: 
 9951: sub setup_random_from_rndseed {
 9952:     my ($rndseed)=@_;
 9953:     if ($rndseed =~/([,:])/) {
 9954: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 9955: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 9956:     } else {
 9957: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 9958:     }
 9959: }
 9960: 
 9961: sub latest_receipt_algorithm_id {
 9962:     return 'receipt3';
 9963: }
 9964: 
 9965: sub recunique {
 9966:     my $fucourseid=shift;
 9967:     my $unique;
 9968:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 9969: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 9970: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 9971:     } else {
 9972: 	$unique=$perlvar{'lonReceipt'};
 9973:     }
 9974:     return unpack("%32C*",$unique);
 9975: }
 9976: 
 9977: sub recprefix {
 9978:     my $fucourseid=shift;
 9979:     my $prefix;
 9980:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
 9981: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 9982: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 9983:     } else {
 9984: 	$prefix=$perlvar{'lonHostID'};
 9985:     }
 9986:     return unpack("%32C*",$prefix);
 9987: }
 9988: 
 9989: sub ireceipt {
 9990:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 9991: 
 9992:     my $return =&recprefix($fucourseid).'-';
 9993: 
 9994:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
 9995: 	$env{'request.state'} eq 'construct') {
 9996: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
 9997: 	return $return;
 9998:     }
 9999: 
10000:     my $cuname=unpack("%32C*",$funame);
10001:     my $cudom=unpack("%32C*",$fudom);
10002:     my $cucourseid=unpack("%32C*",$fucourseid);
10003:     my $cusymb=unpack("%32C*",$fusymb);
10004:     my $cunique=&recunique($fucourseid);
10005:     my $cpart=unpack("%32S*",$part);
10006:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
10007: 
10008: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
10009: 			       
10010: 	$return.= ($cunique%$cuname+
10011: 		   $cunique%$cudom+
10012: 		   $cusymb%$cuname+
10013: 		   $cusymb%$cudom+
10014: 		   $cucourseid%$cuname+
10015: 		   $cucourseid%$cudom+
10016: 		   $cpart%$cuname+
10017: 		   $cpart%$cudom);
10018:     } else {
10019: 	$return.= ($cunique%$cuname+
10020: 		   $cunique%$cudom+
10021: 		   $cusymb%$cuname+
10022: 		   $cusymb%$cudom+
10023: 		   $cucourseid%$cuname+
10024: 		   $cucourseid%$cudom);
10025:     }
10026:     return $return;
10027: }
10028: 
10029: sub receipt {
10030:     my ($part)=@_;
10031:     my ($symb,$courseid,$domain,$name) = &whichuser();
10032:     return &ireceipt($name,$domain,$courseid,$symb,$part);
10033: }
10034: 
10035: sub whichuser {
10036:     my ($passedsymb)=@_;
10037:     my ($symb,$courseid,$domain,$name,$publicuser);
10038:     if (defined($env{'form.grade_symb'})) {
10039: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
10040: 	my $allowed=&allowed('vgr',$tmp_courseid);
10041: 	if (!$allowed &&
10042: 	    exists($env{'request.course.sec'}) &&
10043: 	    $env{'request.course.sec'} !~ /^\s*$/) {
10044: 	    $allowed=&allowed('vgr',$tmp_courseid.
10045: 			      '/'.$env{'request.course.sec'});
10046: 	}
10047: 	if ($allowed) {
10048: 	    ($symb)=&get_env_multiple('form.grade_symb');
10049: 	    $courseid=$tmp_courseid;
10050: 	    ($domain)=&get_env_multiple('form.grade_domain');
10051: 	    ($name)=&get_env_multiple('form.grade_username');
10052: 	    return ($symb,$courseid,$domain,$name,$publicuser);
10053: 	}
10054:     }
10055:     if (!$passedsymb) {
10056: 	$symb=&symbread();
10057:     } else {
10058: 	$symb=$passedsymb;
10059:     }
10060:     $courseid=$env{'request.course.id'};
10061:     $domain=$env{'user.domain'};
10062:     $name=$env{'user.name'};
10063:     if ($name eq 'public' && $domain eq 'public') {
10064: 	if (!defined($env{'form.username'})) {
10065: 	    $env{'form.username'}.=time.rand(10000000);
10066: 	}
10067: 	$name.=$env{'form.username'};
10068:     }
10069:     return ($symb,$courseid,$domain,$name,$publicuser);
10070: 
10071: }
10072: 
10073: # ------------------------------------------------------------ Serves up a file
10074: # returns either the contents of the file or 
10075: # -1 if the file doesn't exist
10076: #
10077: # if the target is a file that was uploaded via DOCS, 
10078: # a check will be made to see if a current copy exists on the local server,
10079: # if it does this will be served, otherwise a copy will be retrieved from
10080: # the home server for the course and stored in /home/httpd/html/userfiles on
10081: # the local server.   
10082: 
10083: sub getfile {
10084:     my ($file) = @_;
10085:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
10086:     &repcopy($file);
10087:     return &readfile($file);
10088: }
10089: 
10090: sub repcopy_userfile {
10091:     my ($file)=@_;
10092:     my $londocroot = $perlvar{'lonDocRoot'};
10093:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
10094:     if ($file =~ m{^\Q$londocroot/lonUsers/\E}) { return 'ok'; }
10095:     my ($cdom,$cnum,$filename) = 
10096: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
10097:     my $uri="/uploaded/$cdom/$cnum/$filename";
10098:     if (-e "$file") {
10099: # we already have a local copy, check it out
10100: 	my @fileinfo = stat($file);
10101: 	my $rtncode;
10102: 	my $info;
10103: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
10104: 	if ($lwpresp ne 'ok') {
10105: # there is no such file anymore, even though we had a local copy
10106: 	    if ($rtncode eq '404') {
10107: 		unlink($file);
10108: 	    }
10109: 	    return -1;
10110: 	}
10111: 	if ($info < $fileinfo[9]) {
10112: # nice, the file we have is up-to-date, just say okay
10113: 	    return 'ok';
10114: 	} else {
10115: # the file is outdated, get rid of it
10116: 	    unlink($file);
10117: 	}
10118:     }
10119: # one way or the other, at this point, we don't have the file
10120: # construct the correct path for the file
10121:     my @parts = ($cdom,$cnum); 
10122:     if ($filename =~ m|^(.+)/[^/]+$|) {
10123: 	push @parts, split(/\//,$1);
10124:     }
10125:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
10126:     foreach my $part (@parts) {
10127: 	$path .= '/'.$part;
10128: 	if (!-e $path) {
10129: 	    mkdir($path,0770);
10130: 	}
10131:     }
10132: # now the path exists for sure
10133: # get a user agent
10134:     my $ua=new LWP::UserAgent;
10135:     my $transferfile=$file.'.in.transfer';
10136: # FIXME: this should flock
10137:     if (-e $transferfile) { return 'ok'; }
10138:     my $request;
10139:     $uri=~s/^\///;
10140:     my $homeserver = &homeserver($cnum,$cdom);
10141:     my $protocol = $protocol{$homeserver};
10142:     $protocol = 'http' if ($protocol ne 'https');
10143:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
10144:     my $response=$ua->request($request,$transferfile);
10145: # did it work?
10146:     if ($response->is_error()) {
10147: 	unlink($transferfile);
10148: 	&logthis("Userfile repcopy failed for $uri");
10149: 	return -1;
10150:     }
10151: # worked, rename the transfer file
10152:     rename($transferfile,$file);
10153:     return 'ok';
10154: }
10155: 
10156: sub tokenwrapper {
10157:     my $uri=shift;
10158:     $uri=~s|^https?\://([^/]+)||;
10159:     $uri=~s|^/||;
10160:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
10161:     my $token=$1;
10162:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
10163:     if ($udom && $uname && $file) {
10164: 	$file=~s|(\?\.*)*$||;
10165:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
10166:         my $homeserver = &homeserver($uname,$udom);
10167:         my $protocol = $protocol{$homeserver};
10168:         $protocol = 'http' if ($protocol ne 'https');
10169:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
10170:                (($uri=~/\?/)?'&':'?').'token='.$token.
10171:                                '&tokenissued='.$perlvar{'lonHostID'};
10172:     } else {
10173:         return '/adm/notfound.html';
10174:     }
10175: }
10176: 
10177: # call with reqtype HEAD: get last modification time
10178: # call with reqtype GET: get the file contents
10179: # Do not call this with reqtype GET for large files! It loads everything into memory
10180: #
10181: sub getuploaded {
10182:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
10183:     $uri=~s/^\///;
10184:     my $homeserver = &homeserver($cnum,$cdom);
10185:     my $protocol = $protocol{$homeserver};
10186:     $protocol = 'http' if ($protocol ne 'https');
10187:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
10188:     my $ua=new LWP::UserAgent;
10189:     my $request=new HTTP::Request($reqtype,$uri);
10190:     my $response=$ua->request($request);
10191:     $$rtncode = $response->code;
10192:     if (! $response->is_success()) {
10193: 	return 'failed';
10194:     }      
10195:     if ($reqtype eq 'HEAD') {
10196: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
10197:     } elsif ($reqtype eq 'GET') {
10198: 	$$info = $response->content;
10199:     }
10200:     return 'ok';
10201: }
10202: 
10203: sub readfile {
10204:     my $file = shift;
10205:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
10206:     my $fh;
10207:     open($fh,"<$file");
10208:     my $a='';
10209:     while (my $line = <$fh>) { $a .= $line; }
10210:     return $a;
10211: }
10212: 
10213: sub filelocation {
10214:     my ($dir,$file) = @_;
10215:     my $location;
10216:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
10217: 
10218:     if ($file =~ m-^/adm/-) {
10219: 	$file=~s-^/adm/wrapper/-/-;
10220: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
10221:     }
10222: 
10223:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
10224:         $location = $file;
10225:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
10226:         my ($udom,$uname,$filename)=
10227:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
10228:         my $home=&homeserver($uname,$udom);
10229:         my $is_me=0;
10230:         my @ids=&current_machine_ids();
10231:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
10232:         if ($is_me) {
10233:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
10234:         } else {
10235:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
10236:   	      $udom.'/'.$uname.'/'.$filename;
10237:         }
10238:     } elsif ($file =~ m-^/adm/-) {
10239: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
10240:     } else {
10241:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
10242:         $file=~s:^/(res|priv)/:/:;
10243:         my $space=$1;
10244:         if ( !( $file =~ m:^/:) ) {
10245:             $location = $dir. '/'.$file;
10246:         } else {
10247:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
10248:         }
10249:     }
10250:     $location=~s://+:/:g; # remove duplicate /
10251:     while ($location=~m{/\.\./}) {
10252: 	if ($location =~ m{/[^/]+/\.\./}) {
10253: 	    $location=~ s{/[^/]+/\.\./}{/}g;
10254: 	} else {
10255: 	    $location=~ s{/\.\./}{/}g;
10256: 	}
10257:     } #remove dir/..
10258:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
10259:     return $location;
10260: }
10261: 
10262: sub hreflocation {
10263:     my ($dir,$file)=@_;
10264:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
10265: 	$file=filelocation($dir,$file);
10266:     } elsif ($file=~m-^/adm/-) {
10267: 	$file=~s-^/adm/wrapper/-/-;
10268: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
10269:     }
10270:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
10271: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
10272:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
10273: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
10274: 	        {/uploaded/$1/$2/}x;
10275:     }
10276:     if ($file=~ m{^/userfiles/}) {
10277: 	$file =~ s{^/userfiles/}{/uploaded/};
10278:     }
10279:     return $file;
10280: }
10281: 
10282: 
10283: 
10284: 
10285: 
10286: sub current_machine_domains {
10287:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
10288: }
10289: 
10290: sub machine_domains {
10291:     my ($hostname) = @_;
10292:     my @domains;
10293:     my %hostname = &all_hostnames();
10294:     while( my($id, $name) = each(%hostname)) {
10295: #	&logthis("-$id-$name-$hostname-");
10296: 	if ($hostname eq $name) {
10297: 	    push(@domains,&host_domain($id));
10298: 	}
10299:     }
10300:     return @domains;
10301: }
10302: 
10303: sub current_machine_ids {
10304:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
10305: }
10306: 
10307: sub machine_ids {
10308:     my ($hostname) = @_;
10309:     $hostname ||= &hostname($perlvar{'lonHostID'});
10310:     my @ids;
10311:     my %name_to_host = &all_names();
10312:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
10313: 	return @{ $name_to_host{$hostname} };
10314:     }
10315:     return;
10316: }
10317: 
10318: sub additional_machine_domains {
10319:     my @domains;
10320:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
10321:     while( my $line = <$fh>) {
10322:         $line =~ s/\s//g;
10323:         push(@domains,$line);
10324:     }
10325:     return @domains;
10326: }
10327: 
10328: sub default_login_domain {
10329:     my $domain = $perlvar{'lonDefDomain'};
10330:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
10331:     foreach my $posdom (&current_machine_domains(),
10332:                         &additional_machine_domains()) {
10333:         if (lc($posdom) eq lc($testdomain)) {
10334:             $domain=$posdom;
10335:             last;
10336:         }
10337:     }
10338:     return $domain;
10339: }
10340: 
10341: # ------------------------------------------------------------- Declutters URLs
10342: 
10343: sub declutter {
10344:     my $thisfn=shift;
10345:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
10346:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
10347:     $thisfn=~s/^\///;
10348:     $thisfn=~s|^adm/wrapper/||;
10349:     $thisfn=~s|^adm/coursedocs/showdoc/||;
10350:     $thisfn=~s/^res\///;
10351:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
10352:         $thisfn=~s/\?.+$//;
10353:     }
10354:     return $thisfn;
10355: }
10356: 
10357: # ------------------------------------------------------------- Clutter up URLs
10358: 
10359: sub clutter {
10360:     my $thisfn='/'.&declutter(shift);
10361:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
10362: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
10363:        $thisfn='/res'.$thisfn; 
10364:     }
10365:     if ($thisfn !~m|^/adm|) {
10366: 	if ($thisfn =~ m|^/ext/|) {
10367: 	    $thisfn='/adm/wrapper'.$thisfn;
10368: 	} else {
10369: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
10370: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
10371: 	    if ($embstyle eq 'ssi'
10372: 		|| ($embstyle eq 'hdn')
10373: 		|| ($embstyle eq 'rat')
10374: 		|| ($embstyle eq 'prv')
10375: 		|| ($embstyle eq 'ign')) {
10376: 		#do nothing with these
10377: 	    } elsif (($embstyle eq 'img') 
10378: 		|| ($embstyle eq 'emb')
10379: 		|| ($embstyle eq 'wrp')) {
10380: 		$thisfn='/adm/wrapper'.$thisfn;
10381: 	    } elsif ($embstyle eq 'unk'
10382: 		     && $thisfn!~/\.(sequence|page)$/) {
10383: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
10384: 	    } else {
10385: #		&logthis("Got a blank emb style");
10386: 	    }
10387: 	}
10388:     }
10389:     return $thisfn;
10390: }
10391: 
10392: sub clutter_with_no_wrapper {
10393:     my $uri = &clutter(shift);
10394:     if ($uri =~ m-^/adm/-) {
10395: 	$uri =~ s-^/adm/wrapper/-/-;
10396: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
10397:     }
10398:     return $uri;
10399: }
10400: 
10401: sub freeze_escape {
10402:     my ($value)=@_;
10403:     if (ref($value)) {
10404: 	$value=&nfreeze($value);
10405: 	return '__FROZEN__'.&escape($value);
10406:     }
10407:     return &escape($value);
10408: }
10409: 
10410: 
10411: sub thaw_unescape {
10412:     my ($value)=@_;
10413:     if ($value =~ /^__FROZEN__/) {
10414: 	substr($value,0,10,undef);
10415: 	$value=&unescape($value);
10416: 	return &thaw($value);
10417:     }
10418:     return &unescape($value);
10419: }
10420: 
10421: sub correct_line_ends {
10422:     my ($result)=@_;
10423:     $$result =~s/\r\n/\n/mg;
10424:     $$result =~s/\r/\n/mg;
10425: }
10426: # ================================================================ Main Program
10427: 
10428: sub goodbye {
10429:    &logthis("Starting Shut down");
10430: #not converted to using infrastruture and probably shouldn't be
10431:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
10432: #converted
10433: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
10434:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
10435: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
10436: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
10437: #1.1 only
10438: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
10439: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
10440: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
10441: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
10442:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
10443:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
10444:    &logthis(sprintf("%-20s is %s",'hits',$hits));
10445:    &flushcourselogs();
10446:    &logthis("Shutting down");
10447: }
10448: 
10449: sub get_dns {
10450:     my ($url,$func,$ignore_cache) = @_;
10451:     if (!$ignore_cache) {
10452: 	my ($content,$cached)=
10453: 	    &Apache::lonnet::is_cached_new('dns',$url);
10454: 	if ($cached) {
10455: 	    &$func($content);
10456: 	    return;
10457: 	}
10458:     }
10459: 
10460:     my %alldns;
10461:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10462:     foreach my $dns (<$config>) {
10463: 	next if ($dns !~ /^\^(\S*)/x);
10464:         my $line = $1;
10465:         my ($host,$protocol) = split(/:/,$line);
10466:         if ($protocol ne 'https') {
10467:             $protocol = 'http';
10468:         }
10469: 	$alldns{$host} = $protocol;
10470:     }
10471:     while (%alldns) {
10472: 	my ($dns) = keys(%alldns);
10473: 	my $ua=new LWP::UserAgent;
10474:         $ua->timeout(30);
10475: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
10476: 	my $response=$ua->request($request);
10477:         delete($alldns{$dns});
10478: 	next if ($response->is_error());
10479: 	my @content = split("\n",$response->content);
10480: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
10481: 	&$func(\@content);
10482: 	return;
10483:     }
10484:     close($config);
10485:     my $which = (split('/',$url))[3];
10486:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
10487:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
10488:     my @content = <$config>;
10489:     &$func(\@content);
10490:     return;
10491: }
10492: # ------------------------------------------------------------ Read domain file
10493: {
10494:     my $loaded;
10495:     my %domain;
10496: 
10497:     sub parse_domain_tab {
10498: 	my ($lines) = @_;
10499: 	foreach my $line (@$lines) {
10500: 	    next if ($line =~ /^(\#|\s*$ )/x);
10501: 
10502: 	    chomp($line);
10503: 	    my ($name,@elements) = split(/:/,$line,9);
10504: 	    my %this_domain;
10505: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
10506: 			       'lang_def', 'city', 'longi', 'lati',
10507: 			       'primary') {
10508: 		$this_domain{$field} = shift(@elements);
10509: 	    }
10510: 	    $domain{$name} = \%this_domain;
10511: 	}
10512:     }
10513: 
10514:     sub reset_domain_info {
10515: 	undef($loaded);
10516: 	undef(%domain);
10517:     }
10518: 
10519:     sub load_domain_tab {
10520: 	my ($ignore_cache) = @_;
10521: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
10522: 	my $fh;
10523: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
10524: 	    my @lines = <$fh>;
10525: 	    &parse_domain_tab(\@lines);
10526: 	}
10527: 	close($fh);
10528: 	$loaded = 1;
10529:     }
10530: 
10531:     sub domain {
10532: 	&load_domain_tab() if (!$loaded);
10533: 
10534: 	my ($name,$what) = @_;
10535: 	return if ( !exists($domain{$name}) );
10536: 
10537: 	if (!$what) {
10538: 	    return $domain{$name}{'description'};
10539: 	}
10540: 	return $domain{$name}{$what};
10541:     }
10542: 
10543:     sub domain_info {
10544:         &load_domain_tab() if (!$loaded);
10545:         return %domain;
10546:     }
10547: 
10548: }
10549: 
10550: 
10551: # ------------------------------------------------------------- Read hosts file
10552: {
10553:     my %hostname;
10554:     my %hostdom;
10555:     my %libserv;
10556:     my $loaded;
10557:     my %name_to_host;
10558:     my %internetdom;
10559:     my %LC_dns_serv;
10560: 
10561:     sub parse_hosts_tab {
10562: 	my ($file) = @_;
10563: 	foreach my $configline (@$file) {
10564: 	    next if ($configline =~ /^(\#|\s*$ )/x);
10565:             chomp($configline);
10566: 	    if ($configline =~ /^\^/) {
10567:                 if ($configline =~ /^\^([\w.\-]+)/) {
10568:                     $LC_dns_serv{$1} = 1;
10569:                 }
10570:                 next;
10571:             }
10572: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
10573: 	    $name=~s/\s//g;
10574: 	    if ($id && $domain && $role && $name) {
10575: 		$hostname{$id}=$name;
10576: 		push(@{$name_to_host{$name}}, $id);
10577: 		$hostdom{$id}=$domain;
10578: 		if ($role eq 'library') { $libserv{$id}=$name; }
10579:                 if (defined($protocol)) {
10580:                     if ($protocol eq 'https') {
10581:                         $protocol{$id} = $protocol;
10582:                     } else {
10583:                         $protocol{$id} = 'http'; 
10584:                     }
10585:                 } else {
10586:                     $protocol{$id} = 'http';
10587:                 }
10588:                 if (defined($intdom)) {
10589:                     $internetdom{$id} = $intdom;
10590:                 }
10591: 	    }
10592: 	}
10593:     }
10594:     
10595:     sub reset_hosts_info {
10596: 	&purge_remembered();
10597: 	&reset_domain_info();
10598: 	&reset_hosts_ip_info();
10599: 	undef(%name_to_host);
10600: 	undef(%hostname);
10601: 	undef(%hostdom);
10602: 	undef(%libserv);
10603: 	undef($loaded);
10604:     }
10605: 
10606:     sub load_hosts_tab {
10607: 	my ($ignore_cache) = @_;
10608: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
10609: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10610: 	my @config = <$config>;
10611: 	&parse_hosts_tab(\@config);
10612: 	close($config);
10613: 	$loaded=1;
10614:     }
10615: 
10616:     sub hostname {
10617: 	&load_hosts_tab() if (!$loaded);
10618: 
10619: 	my ($lonid) = @_;
10620: 	return $hostname{$lonid};
10621:     }
10622: 
10623:     sub all_hostnames {
10624: 	&load_hosts_tab() if (!$loaded);
10625: 
10626: 	return %hostname;
10627:     }
10628: 
10629:     sub all_names {
10630: 	&load_hosts_tab() if (!$loaded);
10631: 
10632: 	return %name_to_host;
10633:     }
10634: 
10635:     sub all_host_domain {
10636:         &load_hosts_tab() if (!$loaded);
10637:         return %hostdom;
10638:     }
10639: 
10640:     sub is_library {
10641: 	&load_hosts_tab() if (!$loaded);
10642: 
10643: 	return exists($libserv{$_[0]});
10644:     }
10645: 
10646:     sub all_library {
10647: 	&load_hosts_tab() if (!$loaded);
10648: 
10649: 	return %libserv;
10650:     }
10651: 
10652:     sub unique_library {
10653: 	#2x reverse removes all hostnames that appear more than once
10654:         my %unique = reverse &all_library();
10655:         return reverse %unique;
10656:     }
10657: 
10658:     sub get_servers {
10659: 	&load_hosts_tab() if (!$loaded);
10660: 
10661: 	my ($domain,$type) = @_;
10662: 	my %possible_hosts = ($type eq 'library') ? %libserv
10663: 	                                          : %hostname;
10664: 	my %result;
10665: 	if (ref($domain) eq 'ARRAY') {
10666: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
10667: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
10668: 		    $result{$host} = $hostname;
10669: 		}
10670: 	    }
10671: 	} else {
10672: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
10673: 		if ($hostdom{$host} eq $domain) {
10674: 		    $result{$host} = $hostname;
10675: 		}
10676: 	    }
10677: 	}
10678: 	return %result;
10679:     }
10680: 
10681:     sub get_unique_servers {
10682:         my %unique = reverse &get_servers(@_);
10683: 	return reverse %unique;
10684:     }
10685: 
10686:     sub host_domain {
10687: 	&load_hosts_tab() if (!$loaded);
10688: 
10689: 	my ($lonid) = @_;
10690: 	return $hostdom{$lonid};
10691:     }
10692: 
10693:     sub all_domains {
10694: 	&load_hosts_tab() if (!$loaded);
10695: 
10696: 	my %seen;
10697: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
10698: 	return @uniq;
10699:     }
10700: 
10701:     sub internet_dom {
10702:         &load_hosts_tab() if (!$loaded);
10703: 
10704:         my ($lonid) = @_;
10705:         return $internetdom{$lonid};
10706:     }
10707: 
10708:     sub is_LC_dns {
10709:         &load_hosts_tab() if (!$loaded);
10710: 
10711:         my ($hostname) = @_;
10712:         return exists($LC_dns_serv{$hostname});
10713:     }
10714: 
10715: }
10716: 
10717: { 
10718:     my %iphost;
10719:     my %name_to_ip;
10720:     my %lonid_to_ip;
10721: 
10722:     sub get_hosts_from_ip {
10723: 	my ($ip) = @_;
10724: 	my %iphosts = &get_iphost();
10725: 	if (ref($iphosts{$ip})) {
10726: 	    return @{$iphosts{$ip}};
10727: 	}
10728: 	return;
10729:     }
10730:     
10731:     sub reset_hosts_ip_info {
10732: 	undef(%iphost);
10733: 	undef(%name_to_ip);
10734: 	undef(%lonid_to_ip);
10735:     }
10736: 
10737:     sub get_host_ip {
10738: 	my ($lonid) = @_;
10739: 	if (exists($lonid_to_ip{$lonid})) {
10740: 	    return $lonid_to_ip{$lonid};
10741: 	}
10742: 	my $name=&hostname($lonid);
10743:    	my $ip = gethostbyname($name);
10744: 	return if (!$ip || length($ip) ne 4);
10745: 	$ip=inet_ntoa($ip);
10746: 	$name_to_ip{$name}   = $ip;
10747: 	$lonid_to_ip{$lonid} = $ip;
10748: 	return $ip;
10749:     }
10750:     
10751:     sub get_iphost {
10752: 	my ($ignore_cache) = @_;
10753: 
10754: 	if (!$ignore_cache) {
10755: 	    if (%iphost) {
10756: 		return %iphost;
10757: 	    }
10758: 	    my ($ip_info,$cached)=
10759: 		&Apache::lonnet::is_cached_new('iphost','iphost');
10760: 	    if ($cached) {
10761: 		%iphost      = %{$ip_info->[0]};
10762: 		%name_to_ip  = %{$ip_info->[1]};
10763: 		%lonid_to_ip = %{$ip_info->[2]};
10764: 		return %iphost;
10765: 	    }
10766: 	}
10767: 
10768: 	# get yesterday's info for fallback
10769: 	my %old_name_to_ip;
10770: 	my ($ip_info,$cached)=
10771: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
10772: 	if ($cached) {
10773: 	    %old_name_to_ip = %{$ip_info->[1]};
10774: 	}
10775: 
10776: 	my %name_to_host = &all_names();
10777: 	foreach my $name (keys(%name_to_host)) {
10778: 	    my $ip;
10779: 	    if (!exists($name_to_ip{$name})) {
10780: 		$ip = gethostbyname($name);
10781: 		if (!$ip || length($ip) ne 4) {
10782: 		    if (defined($old_name_to_ip{$name})) {
10783: 			$ip = $old_name_to_ip{$name};
10784: 			&logthis("Can't find $name defaulting to old $ip");
10785: 		    } else {
10786: 			&logthis("Name $name no IP found");
10787: 			next;
10788: 		    }
10789: 		} else {
10790: 		    $ip=inet_ntoa($ip);
10791: 		}
10792: 		$name_to_ip{$name} = $ip;
10793: 	    } else {
10794: 		$ip = $name_to_ip{$name};
10795: 	    }
10796: 	    foreach my $id (@{ $name_to_host{$name} }) {
10797: 		$lonid_to_ip{$id} = $ip;
10798: 	    }
10799: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
10800: 	}
10801: 	&Apache::lonnet::do_cache_new('iphost','iphost',
10802: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
10803: 				      48*60*60);
10804: 
10805: 	return %iphost;
10806:     }
10807: 
10808:     #
10809:     #  Given a DNS returns the loncapa host name for that DNS 
10810:     # 
10811:     sub host_from_dns {
10812:         my ($dns) = @_;
10813:         my @hosts;
10814:         my $ip;
10815: 
10816:         if (exists($name_to_ip{$dns})) {
10817:             $ip = $name_to_ip{$dns};
10818:         }
10819:         if (!$ip) {
10820:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
10821:             if (length($ip) == 4) { 
10822: 	        $ip   = &IO::Socket::inet_ntoa($ip);
10823:             }
10824:         }
10825:         if ($ip) {
10826: 	    @hosts = get_hosts_from_ip($ip);
10827: 	    return $hosts[0];
10828:         }
10829:         return undef;
10830:     }
10831: 
10832:     sub get_internet_names {
10833:         my ($lonid) = @_;
10834:         return if ($lonid eq '');
10835:         my ($idnref,$cached)=
10836:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
10837:         if ($cached) {
10838:             return $idnref;
10839:         }
10840:         my $ip = &get_host_ip($lonid);
10841:         my @hosts = &get_hosts_from_ip($ip);
10842:         my %iphost = &get_iphost();
10843:         my (@idns,%seen);
10844:         foreach my $id (@hosts) {
10845:             my $dom = &host_domain($id);
10846:             my $prim_id = &domain($dom,'primary');
10847:             my $prim_ip = &get_host_ip($prim_id);
10848:             next if ($seen{$prim_ip});
10849:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
10850:                 foreach my $id (@{$iphost{$prim_ip}}) {
10851:                     my $intdom = &internet_dom($id);
10852:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
10853:                         push(@idns,$intdom);
10854:                     }
10855:                 }
10856:             }
10857:             $seen{$prim_ip} = 1;
10858:         }
10859:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
10860:     }
10861: 
10862: }
10863: 
10864: sub all_loncaparevs {
10865:     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);
10866: }
10867: 
10868: BEGIN {
10869: 
10870: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
10871:     unless ($readit) {
10872: {
10873:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
10874:     %perlvar = (%perlvar,%{$configvars});
10875: }
10876: 
10877: 
10878: # ------------------------------------------------------ Read spare server file
10879: {
10880:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
10881: 
10882:     while (my $configline=<$config>) {
10883:        chomp($configline);
10884:        if ($configline) {
10885: 	   my ($host,$type) = split(':',$configline,2);
10886: 	   if (!defined($type) || $type eq '') { $type = 'default' };
10887: 	   push(@{ $spareid{$type} }, $host);
10888:        }
10889:     }
10890:     close($config);
10891: }
10892: # ------------------------------------------------------------ Read permissions
10893: {
10894:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
10895: 
10896:     while (my $configline=<$config>) {
10897: 	chomp($configline);
10898: 	if ($configline) {
10899: 	    my ($role,$perm)=split(/ /,$configline);
10900: 	    if ($perm ne '') { $pr{$role}=$perm; }
10901: 	}
10902:     }
10903:     close($config);
10904: }
10905: 
10906: # -------------------------------------------- Read plain texts for permissions
10907: {
10908:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
10909: 
10910:     while (my $configline=<$config>) {
10911: 	chomp($configline);
10912: 	if ($configline) {
10913: 	    my ($short,@plain)=split(/:/,$configline);
10914:             %{$prp{$short}} = ();
10915: 	    if (@plain > 0) {
10916:                 $prp{$short}{'std'} = $plain[0];
10917:                 for (my $i=1; $i<@plain; $i++) {
10918:                     $prp{$short}{'alt'.$i} = $plain[$i];  
10919:                 }
10920:             }
10921: 	}
10922:     }
10923:     close($config);
10924: }
10925: 
10926: # ---------------------------------------------------------- Read package table
10927: {
10928:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
10929: 
10930:     while (my $configline=<$config>) {
10931: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
10932: 	chomp($configline);
10933: 	my ($short,$plain)=split(/:/,$configline);
10934: 	my ($pack,$name)=split(/\&/,$short);
10935: 	if ($plain ne '') {
10936: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
10937: 	    $packagetab{$short}=$plain; 
10938: 	}
10939:     }
10940:     close($config);
10941: }
10942: 
10943: # ---------------------------------------------------------- Read loncaparev table
10944: {
10945:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
10946:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
10947:             while (my $configline=<$config>) {
10948:                 chomp($configline);
10949:                 my ($hostid,$loncaparev)=split(/:/,$configline);
10950:                 $loncaparevs{$hostid}=$loncaparev;
10951:             }
10952:             close($config);
10953:         }
10954:     }
10955: }
10956: 
10957: # ---------------------------------------------------------- Read serverhostID table
10958: {
10959:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
10960:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
10961:             while (my $configline=<$config>) {
10962:                 chomp($configline);
10963:                 my ($name,$id)=split(/:/,$configline);
10964:                 $serverhomeIDs{$name}=$id;
10965:             }
10966:             close($config);
10967:         }
10968:     }
10969: }
10970: 
10971: {
10972:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
10973:     if (-e $file) {
10974:         my $parser = HTML::LCParser->new($file);
10975:         while (my $token = $parser->get_token()) {
10976:             if ($token->[0] eq 'S') {
10977:                 my $item = $token->[1];
10978:                 my $name = $token->[2]{'name'};
10979:                 my $value = $token->[2]{'value'};
10980:                 if ($item ne '' && $name ne '' && $value ne '') {
10981:                     my $release = $parser->get_text();
10982:                     $release =~ s/(^\s*|\s*$ )//gx;
10983:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
10984:                 }
10985:             }
10986:         }
10987:     }
10988: }
10989: 
10990: # ---------------------------------------------------------- Read managers table
10991: {
10992:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
10993:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
10994:             while (my $configline=<$config>) {
10995:                 chomp($configline);
10996:                 next if ($configline =~ /^\#/);
10997:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
10998:                     $managerstab{$configline} = 1;
10999:                 }
11000:             }
11001:             close($config);
11002:         }
11003:     }
11004: }
11005: 
11006: # ------------- set up temporary directory
11007: {
11008:     $tmpdir = LONCAPA::tempdir();
11009: 
11010: }
11011: 
11012: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
11013: 				'compress_threshold'=> 20_000,
11014:  			        });
11015: 
11016: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
11017: $dumpcount=0;
11018: $locknum=0;
11019: 
11020: &logtouch();
11021: &logthis('<font color="yellow">INFO: Read configuration</font>');
11022: $readit=1;
11023:     {
11024: 	use integer;
11025: 	my $test=(2**32)+1;
11026: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
11027: 	&logthis(" Detected 64bit platform ($_64bit)");
11028:     }
11029: }
11030: }
11031: 
11032: 1;
11033: __END__
11034: 
11035: =pod
11036: 
11037: =head1 NAME
11038: 
11039: Apache::lonnet - Subroutines to ask questions about things in the network.
11040: 
11041: =head1 SYNOPSIS
11042: 
11043: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
11044: 
11045:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
11046: 
11047: Common parameters:
11048: 
11049: =over 4
11050: 
11051: =item *
11052: 
11053: $uname : an internal username (if $cname expecting a course Id specifically)
11054: 
11055: =item *
11056: 
11057: $udom : a domain (if $cdom expecting a course's domain specifically)
11058: 
11059: =item *
11060: 
11061: $symb : a resource instance identifier
11062: 
11063: =item *
11064: 
11065: $namespace : the name of a .db file that contains the data needed or
11066: being set.
11067: 
11068: =back
11069: 
11070: =head1 OVERVIEW
11071: 
11072: lonnet provides subroutines which interact with the
11073: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
11074: about classes, users, and resources.
11075: 
11076: For many of these objects you can also use this to store data about
11077: them or modify them in various ways.
11078: 
11079: =head2 Symbs
11080: 
11081: To identify a specific instance of a resource, LON-CAPA uses symbols
11082: or "symbs"X<symb>. These identifiers are built from the URL of the
11083: map, the resource number of the resource in the map, and the URL of
11084: the resource itself. The latter is somewhat redundant, but might help
11085: if maps change.
11086: 
11087: An example is
11088: 
11089:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
11090: 
11091: The respective map entry is
11092: 
11093:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
11094:   title="Problem 2">
11095:  </resource>
11096: 
11097: Symbs are used by the random number generator, as well as to store and
11098: restore data specific to a certain instance of for example a problem.
11099: 
11100: =head2 Storing And Retrieving Data
11101: 
11102: X<store()>X<cstore()>X<restore()>Three of the most important functions
11103: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
11104: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
11105: is is the non-critical message twin of cstore. These functions are for
11106: handlers to store a perl hash to a user's permanent data space in an
11107: easy manner, and to retrieve it again on another call. It is expected
11108: that a handler would use this once at the beginning to retrieve data,
11109: and then again once at the end to send only the new data back.
11110: 
11111: The data is stored in the user's data directory on the user's
11112: homeserver under the ID of the course.
11113: 
11114: The hash that is returned by restore will have all of the previous
11115: value for all of the elements of the hash.
11116: 
11117: Example:
11118: 
11119:  #creating a hash
11120:  my %hash;
11121:  $hash{'foo'}='bar';
11122: 
11123:  #storing it
11124:  &Apache::lonnet::cstore(\%hash);
11125: 
11126:  #changing a value
11127:  $hash{'foo'}='notbar';
11128: 
11129:  #adding a new value
11130:  $hash{'bar'}='foo';
11131:  &Apache::lonnet::cstore(\%hash);
11132: 
11133:  #retrieving the hash
11134:  my %history=&Apache::lonnet::restore();
11135: 
11136:  #print the hash
11137:  foreach my $key (sort(keys(%history))) {
11138:    print("\%history{$key} = $history{$key}");
11139:  }
11140: 
11141: Will print out:
11142: 
11143:  %history{1:foo} = bar
11144:  %history{1:keys} = foo:timestamp
11145:  %history{1:timestamp} = 990455579
11146:  %history{2:bar} = foo
11147:  %history{2:foo} = notbar
11148:  %history{2:keys} = foo:bar:timestamp
11149:  %history{2:timestamp} = 990455580
11150:  %history{bar} = foo
11151:  %history{foo} = notbar
11152:  %history{timestamp} = 990455580
11153:  %history{version} = 2
11154: 
11155: Note that the special hash entries C<keys>, C<version> and
11156: C<timestamp> were added to the hash. C<version> will be equal to the
11157: total number of versions of the data that have been stored. The
11158: C<timestamp> attribute will be the UNIX time the hash was
11159: stored. C<keys> is available in every historical section to list which
11160: keys were added or changed at a specific historical revision of a
11161: hash.
11162: 
11163: B<Warning>: do not store the hash that restore returns directly. This
11164: will cause a mess since it will restore the historical keys as if the
11165: were new keys. I.E. 1:foo will become 1:1:foo etc.
11166: 
11167: Calling convention:
11168: 
11169:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
11170:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
11171: 
11172: For more detailed information, see lonnet specific documentation.
11173: 
11174: =head1 RETURN MESSAGES
11175: 
11176: =over 4
11177: 
11178: =item * B<con_lost>: unable to contact remote host
11179: 
11180: =item * B<con_delayed>: unable to contact remote host, message will be delivered
11181: when the connection is brought back up
11182: 
11183: =item * B<con_failed>: unable to contact remote host and unable to save message
11184: for later delivery
11185: 
11186: =item * B<error:>: an error a occurred, a description of the error follows the :
11187: 
11188: =item * B<no_such_host>: unable to fund a host associated with the user/domain
11189: that was requested
11190: 
11191: =back
11192: 
11193: =head1 PUBLIC SUBROUTINES
11194: 
11195: =head2 Session Environment Functions
11196: 
11197: =over 4
11198: 
11199: =item * 
11200: X<appenv()>
11201: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
11202: the user envirnoment file, and will be restored for each access this
11203: user makes during this session, also modifies the %env for the current
11204: process. Optional rolesarrayref - if defined contains a reference to an array
11205: of roles which are exempt from the restriction on modifying user.role entries 
11206: in the user's environment.db and in %env.    
11207: 
11208: =item *
11209: X<delenv()>
11210: B<delenv($delthis,$regexp)>: removes all items from the session
11211: environment file that begin with $delthis. If the 
11212: optional second arg - $regexp - is true, $delthis is treated as a 
11213: regular expression, otherwise \Q$delthis\E is used. 
11214: The values are also deleted from the current processes %env.
11215: 
11216: =item * get_env_multiple($name) 
11217: 
11218: gets $name from the %env hash, it seemlessly handles the cases where multiple
11219: values may be defined and end up as an array ref.
11220: 
11221: returns an array of values
11222: 
11223: =back
11224: 
11225: =head2 User Information
11226: 
11227: =over 4
11228: 
11229: =item *
11230: X<queryauthenticate()>
11231: B<queryauthenticate($uname,$udom)>: try to determine user's current 
11232: authentication scheme
11233: 
11234: =item *
11235: X<authenticate()>
11236: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
11237: authenticate user from domain's lib servers (first use the current
11238: one). C<$upass> should be the users password.
11239: $checkdefauth is optional (value is 1 if a check should be made to
11240:    authenticate user using default authentication method, and allow
11241:    account creation if username does not have account in the domain).
11242: $clientcancheckhost is optional (value is 1 if checking whether the
11243:    server can host will occur on the client side in lonauth.pm).   
11244: 
11245: =item *
11246: X<homeserver()>
11247: B<homeserver($uname,$udom)>: find the server which has
11248: the user's directory and files (there must be only one), this caches
11249: the answer, and also caches if there is a borken connection.
11250: 
11251: =item *
11252: X<idget()>
11253: B<idget($udom,@ids)>: find the usernames behind a list of IDs
11254: (IDs are a unique resource in a domain, there must be only 1 ID per
11255: username, and only 1 username per ID in a specific domain) (returns
11256: hash: id=>name,id=>name)
11257: 
11258: =item *
11259: X<idrget()>
11260: B<idrget($udom,@unames)>: find the IDs behind a list of
11261: usernames (returns hash: name=>id,name=>id)
11262: 
11263: =item *
11264: X<idput()>
11265: B<idput($udom,%ids)>: store away a list of names and associated IDs
11266: 
11267: =item *
11268: X<rolesinit()>
11269: B<rolesinit($udom,$username,$authhost)>: get user privileges
11270: 
11271: =item *
11272: X<getsection()>
11273: B<getsection($udom,$uname,$cname)>: finds the section of student in the
11274: course $cname, return section name/number or '' for "not in course"
11275: and '-1' for "no section"
11276: 
11277: =item *
11278: X<userenvironment()>
11279: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
11280: passed in @what from the requested user's environment, returns a hash
11281: 
11282: =item * 
11283: X<userlog_query()>
11284: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
11285: activity.log file. %filters defines filters applied when parsing the
11286: log file. These can be start or end timestamps, or the type of action
11287: - log to look for Login or Logout events, check for Checkin or
11288: Checkout, role for role selection. The response is in the form
11289: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
11290: escaped strings of the action recorded in the activity.log file.
11291: 
11292: =back
11293: 
11294: =head2 User Roles
11295: 
11296: =over 4
11297: 
11298: =item *
11299: 
11300: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
11301:  F: full access
11302:  U,I,K: authentication modes (cxx only)
11303:  '': forbidden
11304:  1: user needs to choose course
11305:  2: browse allowed
11306:  A: passphrase authentication needed
11307: 
11308: =item *
11309: 
11310: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
11311: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
11312: and course level
11313: 
11314: =item *
11315: 
11316: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
11317: (rolesplain.tab); plain text explanation of a user role term.
11318: $type is Course (default) or Community.
11319: If $forcedefault evaluates to true, text returned will be default 
11320: text for $type. Otherwise, if this is a course, the text returned 
11321: will be a custom name for the role (if defined in the course's 
11322: environment).  If no custom name is defined the default is returned.
11323:    
11324: =item *
11325: 
11326: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
11327: All arguments are optional. Returns a hash of a roles, either for
11328: co-author/assistant author roles for a user's Construction Space
11329: (default), or if $context is 'userroles', roles for the user himself,
11330: In the hash, keys are set to colon-separated $uname,$udom,$role, and
11331: (optionally) if $withsec is true, a fourth colon-separated item - $section.
11332: For each key, value is set to colon-separated start and end times for
11333: the role.  If no username and domain are specified, will default to
11334: current user/domain. Types, roles, and roledoms are references to arrays
11335: of role statuses (active, future or previous), roles 
11336: (e.g., cc,in, st etc.) and domains of the roles which can be used
11337: to restrict the list of roles reported. If no array ref is 
11338: provided for types, will default to return only active roles.
11339: 
11340: =back
11341: 
11342: =head2 User Modification
11343: 
11344: =over 4
11345: 
11346: =item *
11347: 
11348: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
11349: user for the level given by URL.  Optional start and end dates (leave empty
11350: string or zero for "no date")
11351: 
11352: =item *
11353: 
11354: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
11355: change a users, password, possible return values are: ok,
11356: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
11357: refused
11358: 
11359: =item *
11360: 
11361: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
11362: 
11363: =item *
11364: 
11365: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
11366:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
11367: 
11368: will update user information (firstname,middlename,lastname,generation,
11369: permanentemail), and if forceid is true, student/employee ID also.
11370: A user's institutional affiliation(s) can also be updated.
11371: User information fields will not be overwritten with empty entries 
11372: unless the field is included in the $candelete array reference.
11373: This array is included when a single user is modified via "Manage Users",
11374: or when Autoupdate.pl is run by cron in a domain.
11375: 
11376: =item *
11377: 
11378: modifystudent
11379: 
11380: modify a student's enrollment and identification information.
11381: The course id is resolved based on the current users environment.  
11382: This means the envoking user must be a course coordinator or otherwise
11383: associated with a course.
11384: 
11385: This call is essentially a wrapper for lonnet::modifyuser and
11386: lonnet::modify_student_enrollment
11387: 
11388: Inputs: 
11389: 
11390: =over 4
11391: 
11392: =item B<$udom> Student's loncapa domain
11393: 
11394: =item B<$uname> Student's loncapa login name
11395: 
11396: =item B<$uid> Student/Employee ID
11397: 
11398: =item B<$umode> Student's authentication mode
11399: 
11400: =item B<$upass> Student's password
11401: 
11402: =item B<$first> Student's first name
11403: 
11404: =item B<$middle> Student's middle name
11405: 
11406: =item B<$last> Student's last name
11407: 
11408: =item B<$gene> Student's generation
11409: 
11410: =item B<$usec> Student's section in course
11411: 
11412: =item B<$end> Unix time of the roles expiration
11413: 
11414: =item B<$start> Unix time of the roles start date
11415: 
11416: =item B<$forceid> If defined, allow $uid to be changed
11417: 
11418: =item B<$desiredhome> server to use as home server for student
11419: 
11420: =item B<$email> Student's permanent e-mail address
11421: 
11422: =item B<$type> Type of enrollment (auto or manual)
11423: 
11424: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
11425: 
11426: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
11427: 
11428: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
11429: 
11430: =item B<$context> role change context (shown in User Management Logs display in a course)
11431: 
11432: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
11433: 
11434: =back
11435: 
11436: =item *
11437: 
11438: modify_student_enrollment
11439: 
11440: Change a students enrollment status in a class.  The environment variable
11441: 'role.request.course' must be defined for this function to proceed.
11442: 
11443: Inputs:
11444: 
11445: =over 4
11446: 
11447: =item $udom, students domain
11448: 
11449: =item $uname, students name
11450: 
11451: =item $uid, students user id
11452: 
11453: =item $first, students first name
11454: 
11455: =item $middle
11456: 
11457: =item $last
11458: 
11459: =item $gene
11460: 
11461: =item $usec
11462: 
11463: =item $end
11464: 
11465: =item $start
11466: 
11467: =item $type
11468: 
11469: =item $locktype
11470: 
11471: =item $cid
11472: 
11473: =item $selfenroll
11474: 
11475: =item $context
11476: 
11477: =back
11478: 
11479: 
11480: =item *
11481: 
11482: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
11483: custom role; give a custom role to a user for the level given by URL.  Specify
11484: name and domain of role author, and role name
11485: 
11486: =item *
11487: 
11488: revokerole($udom,$uname,$url,$role) : revoke a role for url
11489: 
11490: =item *
11491: 
11492: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
11493: 
11494: =back
11495: 
11496: =head2 Course Infomation
11497: 
11498: =over 4
11499: 
11500: =item *
11501: 
11502: coursedescription($courseid,$options) : returns a hash of information about the
11503: specified course id, including all environment settings for the
11504: course, the description of the course will be in the hash under the
11505: key 'description'
11506: 
11507: $options is an optional parameter that if supplied is a hash reference that controls
11508: what how this function works.  It has the following key/values:
11509: 
11510: =over 4
11511: 
11512: =item freshen_cache
11513: 
11514: If defined, and the environment cache for the course is valid, it is 
11515: returned in the returned hash.
11516: 
11517: =item one_time
11518: 
11519: If defined, the last cache time is set to _now_
11520: 
11521: =item user
11522: 
11523: If defined, the supplied username is used instead of the current user.
11524: 
11525: 
11526: =back
11527: 
11528: =item *
11529: 
11530: resdata($name,$domain,$type,@which) : request for current parameter
11531: setting for a specific $type, where $type is either 'course' or 'user',
11532: @what should be a list of parameters to ask about. This routine caches
11533: answers for 5 minutes.
11534: 
11535: =item *
11536: 
11537: get_courseresdata($courseid, $domain) : dump the entire course resource
11538: data base, returning a hash that is keyed by the resource name and has
11539: values that are the resource value.  I believe that the timestamps and
11540: versions are also returned.
11541: 
11542: 
11543: =back
11544: 
11545: =head2 Course Modification
11546: 
11547: =over 4
11548: 
11549: =item *
11550: 
11551: writecoursepref($courseid,%prefs) : write preferences (environment
11552: database) for a course
11553: 
11554: =item *
11555: 
11556: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
11557: 
11558: =item *
11559: 
11560: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
11561: 
11562: =back
11563: 
11564: =head2 Resource Subroutines
11565: 
11566: =over 4
11567: 
11568: =item *
11569: 
11570: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
11571: 
11572: =item *
11573: 
11574: repcopy($filename) : subscribes to the requested file, and attempts to
11575: replicate from the owning library server, Might return
11576: 'unavailable', 'not_found', 'forbidden', 'ok', or
11577: 'bad_request', also attempts to grab the metadata for the
11578: resource. Expects the local filesystem pathname
11579: (/home/httpd/html/res/....)
11580: 
11581: =back
11582: 
11583: =head2 Resource Information
11584: 
11585: =over 4
11586: 
11587: =item *
11588: 
11589: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
11590: a vairety of different possible values, $varname should be a request
11591: string, and the other parameters can be used to specify who and what
11592: one is asking about.
11593: 
11594: Possible values for $varname are environment.lastname (or other item
11595: from the envirnment hash), user.name (or someother aspect about the
11596: user), resource.0.maxtries (or some other part and parameter of a
11597: resource)
11598: 
11599: =item *
11600: 
11601: directcondval($number) : get current value of a condition; reads from a state
11602: string
11603: 
11604: =item *
11605: 
11606: condval($condidx) : value of condition index based on state
11607: 
11608: =item *
11609: 
11610: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
11611: resource's metadata, $what should be either a specific key, or either
11612: 'keys' (to get a list of possible keys) or 'packages' to get a list of
11613: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
11614: 
11615: this function automatically caches all requests
11616: 
11617: =item *
11618: 
11619: metadata_query($query,$custom,$customshow) : make a metadata query against the
11620: network of library servers; returns file handle of where SQL and regex results
11621: will be stored for query
11622: 
11623: =item *
11624: 
11625: symbread($filename) : return symbolic list entry (filename argument optional);
11626: returns the data handle
11627: 
11628: =item *
11629: 
11630: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
11631: a possible symb for the URL in $thisfn, and if is an encryypted
11632: resource that the user accessed using /enc/ returns a 1 on success, 0
11633: on failure, user must be in a course, as it assumes the existance of
11634: the course initial hash, and uses $env('request.course.id'}
11635: 
11636: 
11637: =item *
11638: 
11639: symbclean($symb) : removes versions numbers from a symb, returns the
11640: cleaned symb
11641: 
11642: =item *
11643: 
11644: is_on_map($uri) : checks if the $uri is somewhere on the current
11645: course map, user must be in a course for it to work.
11646: 
11647: =item *
11648: 
11649: numval($salt) : return random seed value (addend for rndseed)
11650: 
11651: =item *
11652: 
11653: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
11654: a random seed, all arguments are optional, if they aren't sent it uses the
11655: environment to derive them. Note: if symb isn't sent and it can't get one
11656: from &symbread it will use the current time as its return value
11657: 
11658: =item *
11659: 
11660: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
11661: unfakeable, receipt
11662: 
11663: =item *
11664: 
11665: receipt() : API to ireceipt working off of env values; given out to users
11666: 
11667: =item *
11668: 
11669: countacc($url) : count the number of accesses to a given URL
11670: 
11671: =item *
11672: 
11673: 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
11674: 
11675: =item *
11676: 
11677: 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)
11678: 
11679: =item *
11680: 
11681: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
11682: 
11683: =item *
11684: 
11685: devalidate($symb) : devalidate temporary spreadsheet calculations,
11686: forcing spreadsheet to reevaluate the resource scores next time.
11687: 
11688: =back
11689: 
11690: =head2 Storing/Retreiving Data
11691: 
11692: =over 4
11693: 
11694: =item *
11695: 
11696: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
11697: for this url; hashref needs to be given and should be a \%hashname; the
11698: remaining args aren't required and if they aren't passed or are '' they will
11699: be derived from the env
11700: 
11701: =item *
11702: 
11703: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
11704: uses critical subroutine
11705: 
11706: =item *
11707: 
11708: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
11709: all args are optional
11710: 
11711: =item *
11712: 
11713: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
11714: dumps the complete (or key matching regexp) namespace into a hash
11715: ($udom, $uname, $regexp, $range are optional) for a namespace that is
11716: normally &store()ed into
11717: 
11718: $range should be either an integer '100' (give me the first 100
11719:                                            matching records)
11720:               or be  two integers sperated by a - with no spaces
11721:                  '30-50' (give me the 30th through the 50th matching
11722:                           records)
11723: 
11724: 
11725: =item *
11726: 
11727: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
11728: replaces a &store() version of data with a replacement set of data
11729: for a particular resource in a namespace passed in the $storehash hash 
11730: reference
11731: 
11732: =item *
11733: 
11734: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
11735: works very similar to store/cstore, but all data is stored in a
11736: temporary location and can be reset using tmpreset, $storehash should
11737: be a hash reference, returns nothing on success
11738: 
11739: =item *
11740: 
11741: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
11742: similar to restore, but all data is stored in a temporary location and
11743: can be reset using tmpreset. Returns a hash of values on success,
11744: error string otherwise.
11745: 
11746: =item *
11747: 
11748: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
11749: deltes all keys for $symb form the temporary storage hash.
11750: 
11751: =item *
11752: 
11753: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11754: reference filled in from namesp ($udom and $uname are optional)
11755: 
11756: =item *
11757: 
11758: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
11759: namesp ($udom and $uname are optional)
11760: 
11761: =item *
11762: 
11763: dump($namespace,$udom,$uname,$regexp,$range) : 
11764: dumps the complete (or key matching regexp) namespace into a hash
11765: ($udom, $uname, $regexp, $range are optional)
11766: 
11767: $range should be either an integer '100' (give me the first 100
11768:                                            matching records)
11769:               or be  two integers sperated by a - with no spaces
11770:                  '30-50' (give me the 30th through the 50th matching
11771:                           records)
11772: =item *
11773: 
11774: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
11775: $store can be a scalar, an array reference, or if the amount to be 
11776: incremented is > 1, a hash reference.
11777: 
11778: ($udom and $uname are optional)
11779: 
11780: =item *
11781: 
11782: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
11783: ($udom and $uname are optional)
11784: 
11785: =item *
11786: 
11787: cput($namespace,$storehash,$udom,$uname) : critical put
11788: ($udom and $uname are optional)
11789: 
11790: =item *
11791: 
11792: newput($namespace,$storehash,$udom,$uname) :
11793: 
11794: Attempts to store the items in the $storehash, but only if they don't
11795: currently exist, if this succeeds you can be certain that you have 
11796: successfully created a new key value pair in the $namespace db.
11797: 
11798: 
11799: Args:
11800:  $namespace: name of database to store values to
11801:  $storehash: hashref to store to the db
11802:  $udom: (optional) domain of user containing the db
11803:  $uname: (optional) name of user caontaining the db
11804: 
11805: Returns:
11806:  'ok' -> succeeded in storing all keys of $storehash
11807:  'key_exists: <key>' -> failed to anything out of $storehash, as at
11808:                         least <key> already existed in the db (other
11809:                         requested keys may also already exist)
11810:  'error: <msg>' -> unable to tie the DB or other error occurred
11811:  'con_lost' -> unable to contact request server
11812:  'refused' -> action was not allowed by remote machine
11813: 
11814: 
11815: =item *
11816: 
11817: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11818: reference filled in from namesp (encrypts the return communication)
11819: ($udom and $uname are optional)
11820: 
11821: =item *
11822: 
11823: log($udom,$name,$home,$message) : write to permanent log for user; use
11824: critical subroutine
11825: 
11826: =item *
11827: 
11828: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
11829: array reference filled in from namespace found in domain level on either
11830: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
11831: 
11832: =item *
11833: 
11834: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
11835: domain level either on specified domain server ($uhome) or primary domain 
11836: server ($udom and $uhome are optional)
11837: 
11838: =item * 
11839: 
11840: get_domain_defaults($target_domain) : returns hash with defaults for
11841: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
11842: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
11843: or localauth), initial password or a kerberos realm, language (e.g., en-us).
11844: Values are retrieved from cache (if current), or from domain's configuration.db
11845: (if available), or lastly from values in lonTabs/dns_domain,tab, 
11846: or lonTabs/domain.tab. 
11847: 
11848: %domdefaults = &get_auth_defaults($target_domain);
11849: 
11850: =back
11851: 
11852: =head2 Network Status Functions
11853: 
11854: =over 4
11855: 
11856: =item *
11857: 
11858: dirlist() : return directory list based on URI (first arg).
11859: 
11860: Inputs: 1 required, 5 optional.
11861: 
11862: =over
11863: 
11864: =item 
11865: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
11866: 
11867: =item
11868: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
11869: 
11870: =item
11871: $username -  username of user/course to be listed. Extracted from $uri if absent. 
11872: 
11873: =item
11874: $getpropath - boolean: 1 if prepend path using &propath(). 
11875: 
11876: =item
11877: $getuserdir - boolean: 1 if prepend path for "userfiles".
11878: 
11879: =item 
11880: $alternateRoot - path to prepend in place of path from $uri.
11881: 
11882: =back
11883: 
11884: Returns: Array of up to two items.
11885: 
11886: =over
11887: 
11888: a reference to an array of files/subdirectories
11889: 
11890: =over
11891: 
11892: Each element in the array of files/subdirectories is a & separated list of
11893: item name and the result of running stat on the item.  If dirlist was requested
11894: for a file instead of a directory, the item name will be ''. For a directory 
11895: listing, if the item is a metadata file, the element will end &N&M 
11896: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
11897: default copyright set (1).  
11898: 
11899: =back
11900: 
11901: a scalar containing error condition (if encountered).
11902: 
11903: =over
11904: 
11905: =item 
11906: no_host (no homeserver identified for $username:$domain).
11907: 
11908: =item 
11909: no_such_host (server contacted for listing not identified as valid host).
11910: 
11911: =item 
11912: con_lost (connection to remote server failed).
11913: 
11914: =item 
11915: refused (invalid $username:$domain received on lond side).
11916: 
11917: =item 
11918: no_such_dir (directory at specified path on lond side does not exist). 
11919: 
11920: =item 
11921: empty (directory at specified path on lond side is empty).
11922: 
11923: =over
11924: 
11925: This is currently not encountered because the &ls3, &ls2, 
11926: &ls (_handler) routines on the lond side do not filter out
11927: . and .. from a directory listing. 
11928: 
11929: =back
11930: 
11931: =back
11932: 
11933: =back
11934: 
11935: =item *
11936: 
11937: spareserver() : find server with least workload from spare.tab
11938: 
11939: 
11940: =item *
11941: 
11942: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
11943: if there is no corresponding loncapa host.
11944: 
11945: =back
11946: 
11947: 
11948: =head2 Apache Request
11949: 
11950: =over 4
11951: 
11952: =item *
11953: 
11954: ssi($url,%hash) : server side include, does a complete request cycle on url to
11955: localhost, posts hash
11956: 
11957: =back
11958: 
11959: =head2 Data to String to Data
11960: 
11961: =over 4
11962: 
11963: =item *
11964: 
11965: hash2str(%hash) : convert a hash into a string complete with escaping and '='
11966: and '&' separators, supports elements that are arrayrefs and hashrefs
11967: 
11968: =item *
11969: 
11970: hashref2str($hashref) : convert a hashref into a string complete with
11971: escaping and '=' and '&' separators, supports elements that are
11972: arrayrefs and hashrefs
11973: 
11974: =item *
11975: 
11976: arrayref2str($arrayref) : convert an arrayref into a string complete
11977: with escaping and '&' separators, supports elements that are arrayrefs
11978: and hashrefs
11979: 
11980: =item *
11981: 
11982: str2hash($string) : convert string to hash using unescaping and
11983: splitting on '=' and '&', supports elements that are arrayrefs and
11984: hashrefs
11985: 
11986: =item *
11987: 
11988: str2array($string) : convert string to hash using unescaping and
11989: splitting on '&', supports elements that are arrayrefs and hashrefs
11990: 
11991: =back
11992: 
11993: =head2 Logging Routines
11994: 
11995: 
11996: These routines allow one to make log messages in the lonnet.log and
11997: lonnet.perm logfiles.
11998: 
11999: =over 4
12000: 
12001: =item *
12002: 
12003: logtouch() : make sure the logfile, lonnet.log, exists
12004: 
12005: =item *
12006: 
12007: logthis() : append message to the normal lonnet.log file, it gets
12008: preiodically rolled over and deleted.
12009: 
12010: =item *
12011: 
12012: logperm() : append a permanent message to lonnet.perm.log, this log
12013: file never gets deleted by any automated portion of the system, only
12014: messages of critical importance should go in here.
12015: 
12016: 
12017: =back
12018: 
12019: =head2 General File Helper Routines
12020: 
12021: =over 4
12022: 
12023: =item *
12024: 
12025: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
12026: (a) files in /uploaded
12027:   (i) If a local copy of the file exists - 
12028:       compares modification date of local copy with last-modified date for 
12029:       definitive version stored on home server for course. If local copy is 
12030:       stale, requests a new version from the home server and stores it. 
12031:       If the original has been removed from the home server, then local copy 
12032:       is unlinked.
12033:   (ii) If local copy does not exist -
12034:       requests the file from the home server and stores it. 
12035:   
12036:   If $caller is 'uploadrep':  
12037:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
12038:     for request for files originally uploaded via DOCS. 
12039:      - returns 'ok' if fresh local copy now available, -1 otherwise.
12040:   
12041:   Otherwise:
12042:      This indicates a call from the content generation phase of the request.
12043:      -  returns the entire contents of the file or -1.
12044:      
12045: (b) files in /res
12046:    - returns the entire contents of a file or -1; 
12047:    it properly subscribes to and replicates the file if neccessary.
12048: 
12049: 
12050: =item *
12051: 
12052: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
12053:                   reference
12054: 
12055: returns either a stat() list of data about the file or an empty list
12056: if the file doesn't exist or couldn't find out about it (connection
12057: problems or user unknown)
12058: 
12059: =item *
12060: 
12061: filelocation($dir,$file) : returns file system location of a file
12062: based on URI; meant to be "fairly clean" absolute reference, $dir is a
12063: directory that relative $file lookups are to looked in ($dir of /a/dir
12064: and a file of ../bob will become /a/bob)
12065: 
12066: =item *
12067: 
12068: hreflocation($dir,$file) : returns file system location or a URL; same as
12069: filelocation except for hrefs
12070: 
12071: =item *
12072: 
12073: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
12074: 
12075: =back
12076: 
12077: =head2 Usererfile file routines (/uploaded*)
12078: 
12079: =over 4
12080: 
12081: =item *
12082: 
12083: userfileupload(): main rotine for putting a file in a user or course's
12084:                   filespace, arguments are,
12085: 
12086:  formname - required - this is the name of the element in $env where the
12087:            filename, and the contents of the file to create/modifed exist
12088:            the filename is in $env{'form.'.$formname.'.filename'} and the
12089:            contents of the file is located in $env{'form.'.$formname}
12090:  context - if coursedoc, store the file in the course of the active role
12091:              of the current user; 
12092:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
12093:            if 'canceloverwrite': delete file in tmp/overwrites directory
12094:  subdir - required - subdirectory to put the file in under ../userfiles/
12095:          if undefined, it will be placed in "unknown"
12096: 
12097:  (This routine calls clean_filename() to remove any dangerous
12098:  characters from the filename, and then calls finuserfileupload() to
12099:  complete the transaction)
12100: 
12101:  returns either the url of the uploaded file (/uploaded/....) if successful
12102:  and /adm/notfound.html if unsuccessful
12103: 
12104: =item *
12105: 
12106: clean_filename(): routine for cleaing a filename up for storage in
12107:                  userfile space, argument is:
12108: 
12109:  filename - proposed filename
12110: 
12111: returns: the new clean filename
12112: 
12113: =item *
12114: 
12115: finishuserfileupload(): routine that creates and sends the file to
12116: userspace, probably shouldn't be called directly
12117: 
12118:   docuname: username or courseid of destination for the file
12119:   docudom: domain of user/course of destination for the file
12120:   formname: same as for userfileupload()
12121:   fname: filename (including subdirectories) for the file
12122:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
12123:   allfiles: reference to hash used to store objects found by parser
12124:   codebase: reference to hash used for codebases of java objects found by parser
12125:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
12126:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
12127:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
12128:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
12129:   context: if 'overwrite', will move the uploaded file from its temporary location to
12130:             userfiles to facilitate overwriting a previously uploaded file with same name.
12131:   mimetype: reference to scalar to accommodate mime type determined
12132:             from File::MMagic if $parser = parse.
12133: 
12134:  returns either the url of the uploaded file (/uploaded/....) if successful
12135:  and /adm/notfound.html if unsuccessful (or an error message if context 
12136:  was 'overwrite').
12137:  
12138: 
12139: =item *
12140: 
12141: renameuserfile(): renames an existing userfile to a new name
12142: 
12143:   Args:
12144:    docuname: username or courseid of destination for the file
12145:    docudom: domain of user/course of destination for the file
12146:    old: current file name (including any subdirs under userfiles)
12147:    new: desired file name (including any subdirs under userfiles)
12148: 
12149: =item *
12150: 
12151: mkdiruserfile(): creates a directory is a userfiles dir
12152: 
12153:   Args:
12154:    docuname: username or courseid of destination for the file
12155:    docudom: domain of user/course of destination for the file
12156:    dir: dir to create (including any subdirs under userfiles)
12157: 
12158: =item *
12159: 
12160: removeuserfile(): removes a file that exists in userfiles
12161: 
12162:   Args:
12163:    docuname: username or courseid of destination for the file
12164:    docudom: domain of user/course of destination for the file
12165:    fname: filname to delete (including any subdirs under userfiles)
12166: 
12167: =item *
12168: 
12169: removeuploadedurl(): convience function for removeuserfile()
12170: 
12171:   Args:
12172:    url:  a full /uploaded/... url to delete
12173: 
12174: =item * 
12175: 
12176: get_portfile_permissions():
12177:   Args:
12178:     domain: domain of user or course contain the portfolio files
12179:     user: name of user or num of course contain the portfolio files
12180:   Returns:
12181:     hashref of a dump of the proper file_permissions.db
12182:    
12183: 
12184: =item * 
12185: 
12186: get_access_controls():
12187: 
12188: Args:
12189:   current_permissions: the hash ref returned from get_portfile_permissions()
12190:   group: (optional) the group you want the files associated with
12191:   file: (optional) the file you want access info on
12192: 
12193: Returns:
12194:     a hash (keys are file names) of hashes containing
12195:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
12196:         values are XML containing access control settings (see below) 
12197: 
12198: Internal notes:
12199: 
12200:  access controls are stored in file_permissions.db as key=value pairs.
12201:     key -> path to file/file_name\0uniqueID:scope_end_start
12202:         where scope -> public,guest,course,group,domains or users.
12203:               end -> UNIX time for end of access (0 -> no end date)
12204:               start -> UNIX time for start of access
12205: 
12206:     value -> XML description of access control
12207:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
12208:             <start></start>
12209:             <end></end>
12210: 
12211:             <password></password>  for scope type = guest
12212: 
12213:             <domain></domain>     for scope type = course or group
12214:             <number></number>
12215:             <roles id="">
12216:              <role></role>
12217:              <access></access>
12218:              <section></section>
12219:              <group></group>
12220:             </roles>
12221: 
12222:             <dom></dom>         for scope type = domains
12223: 
12224:             <users>             for scope type = users
12225:              <user>
12226:               <uname></uname>
12227:               <udom></udom>
12228:              </user>
12229:             </users>
12230:            </scope> 
12231:               
12232:  Access data is also aggregated for each file in an additional key=value pair:
12233:  key -> path to file/file_name\0accesscontrol 
12234:  value -> reference to hash
12235:           hash contains key = value pairs
12236:           where key = uniqueID:scope_end_start
12237:                 value = UNIX time record was last updated
12238: 
12239:           Used to improve speed of look-ups of access controls for each file.  
12240:  
12241:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
12242: 
12243: modify_access_controls():
12244: 
12245: Modifies access controls for a portfolio file
12246: Args
12247: 1. file name
12248: 2. reference to hash of required changes,
12249: 3. domain
12250: 4. username
12251:   where domain,username are the domain of the portfolio owner 
12252:   (either a user or a course) 
12253: 
12254: Returns:
12255: 1. result of additions or updates ('ok' or 'error', with error message). 
12256: 2. result of deletions ('ok' or 'error', with error message).
12257: 3. reference to hash of any new or updated access controls.
12258: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
12259:    key = integer (inbound ID)
12260:    value = uniqueID  
12261: 
12262: =back
12263: 
12264: =head2 HTTP Helper Routines
12265: 
12266: =over 4
12267: 
12268: =item *
12269: 
12270: escape() : unpack non-word characters into CGI-compatible hex codes
12271: 
12272: =item *
12273: 
12274: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
12275: 
12276: =back
12277: 
12278: =head1 PRIVATE SUBROUTINES
12279: 
12280: =head2 Underlying communication routines (Shouldn't call)
12281: 
12282: =over 4
12283: 
12284: =item *
12285: 
12286: subreply() : tries to pass a message to lonc, returns con_lost if incapable
12287: 
12288: =item *
12289: 
12290: reply() : uses subreply to send a message to remote machine, logs all failures
12291: 
12292: =item *
12293: 
12294: critical() : passes a critical message to another server; if cannot
12295: get through then place message in connection buffer directory and
12296: returns con_delayed, if incapable of saving message, returns
12297: con_failed
12298: 
12299: =item *
12300: 
12301: reconlonc() : tries to reconnect lonc client processes.
12302: 
12303: =back
12304: 
12305: =head2 Resource Access Logging
12306: 
12307: =over 4
12308: 
12309: =item *
12310: 
12311: flushcourselogs() : flush (save) buffer logs and access logs
12312: 
12313: =item *
12314: 
12315: courselog($what) : save message for course in hash
12316: 
12317: =item *
12318: 
12319: courseacclog($what) : save message for course using &courselog().  Perform
12320: special processing for specific resource types (problems, exams, quizzes, etc).
12321: 
12322: =item *
12323: 
12324: goodbye() : flush course logs and log shutting down; it is called in srm.conf
12325: as a PerlChildExitHandler
12326: 
12327: =back
12328: 
12329: =head2 Other
12330: 
12331: =over 4
12332: 
12333: =item *
12334: 
12335: symblist($mapname,%newhash) : update symbolic storage links
12336: 
12337: =back
12338: 
12339: =cut
12340: 

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