File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1278: download - view: text, annotated - select for diffs
Mon Mar 30 21:13:24 2015 UTC (9 years, 3 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Arg passed to &get_server_homeID() needs to be hostname not hostID.
- Remove Apache::lonnet:: from some calls to routines within lonnet.pm

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1278 2015/03/30 21:13:24 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: =pod
   31: 
   32: =head1 NAME
   33: 
   34: Apache::lonnet.pm
   35: 
   36: =head1 SYNOPSIS
   37: 
   38: This file is an interface to the lonc processes of
   39: the LON-CAPA network as well as set of elaborated functions for handling information
   40: necessary for navigating through a given cluster of LON-CAPA machines within a
   41: domain. There are over 40 specialized functions in this module which handle the
   42: reading and transmission of metadata, user information (ids, names, environments, roles,
   43: logs), file information (storage, reading, directories, extensions, replication, embedded
   44: styles and descriptors), educational resources (course descriptions, section names and
   45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
   46: and from more descriptive phrases or explanations.
   47: 
   48: This is part of the LearningOnline Network with CAPA project
   49: described at http://www.lon-capa.org.
   50: 
   51: =head1 Package Variables
   52: 
   53: These are largely undocumented, so if you decipher one please note it here.
   54: 
   55: =over 4
   56: 
   57: =item $processmarker
   58: 
   59: Contains the time this process was started and this servers host id.
   60: 
   61: =item $dumpcount
   62: 
   63: Counts the number of times a message log flush has been attempted (regardless
   64: of success) by this process.  Used as part of the filename when messages are
   65: delayed.
   66: 
   67: =back
   68: 
   69: =cut
   70: 
   71: package Apache::lonnet;
   72: 
   73: use strict;
   74: use LWP::UserAgent();
   75: use HTTP::Date;
   76: use Image::Magick;
   77: 
   78: 
   79: use Encode;
   80: 
   81: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
   82:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
   83:             %managerstab);
   84: 
   85: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   86:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   87:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   88:     %courseownerbuf, %coursetypebuf,$locknum);
   89: 
   90: use IO::Socket;
   91: use GDBM_File;
   92: use HTML::LCParser;
   93: use Fcntl qw(:flock);
   94: use Storable qw(thaw nfreeze);
   95: use Time::HiRes qw( gettimeofday tv_interval );
   96: use Cache::Memcached;
   97: use Digest::MD5;
   98: use Math::Random;
   99: use File::MMagic;
  100: use LONCAPA qw(:DEFAULT :match);
  101: use LONCAPA::Configuration;
  102: use LONCAPA::lonmetadata;
  103: use LONCAPA::Lond;
  104: 
  105: use File::Copy;
  106: 
  107: my $readit;
  108: my $max_connection_retries = 10;     # Or some such value.
  109: 
  110: require Exporter;
  111: 
  112: our @ISA = qw (Exporter);
  113: our @EXPORT = qw(%env);
  114: 
  115: 
  116: # ------------------------------------ Logging (parameters, docs, slots, roles)
  117: {
  118:     my $logid;
  119:     sub write_log {
  120: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  121:         if ($context eq 'course') {
  122:             if (($cnum eq '') || ($cdom eq '')) {
  123:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  124:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  125:             }
  126:         }
  127: 	$logid ++;
  128:         my $now = time();
  129: 	my $id=$now.'00000'.$$.'00000'.$logid;
  130:         my $logentry = { 
  131:                           $id => {
  132:                                    'exe_uname' => $env{'user.name'},
  133:                                    'exe_udom'  => $env{'user.domain'},
  134:                                    'exe_time'  => $now,
  135:                                    'exe_ip'    => $ENV{'REMOTE_ADDR'},
  136:                                    'delflag'   => $delflag,
  137:                                    'logentry'  => $storehash,
  138:                                    'uname'     => $uname,
  139:                                    'udom'      => $udom,
  140:                                   }
  141:                        };
  142: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
  143:     }
  144: }
  145: 
  146: sub logtouch {
  147:     my $execdir=$perlvar{'lonDaemons'};
  148:     unless (-e "$execdir/logs/lonnet.log") {	
  149: 	open(my $fh,">>$execdir/logs/lonnet.log");
  150: 	close $fh;
  151:     }
  152:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  153:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  154: }
  155: 
  156: sub logthis {
  157:     my $message=shift;
  158:     my $execdir=$perlvar{'lonDaemons'};
  159:     my $now=time;
  160:     my $local=localtime($now);
  161:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  162: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  163: 	print $fh $logstring;
  164: 	close($fh);
  165:     }
  166:     return 1;
  167: }
  168: 
  169: sub logperm {
  170:     my $message=shift;
  171:     my $execdir=$perlvar{'lonDaemons'};
  172:     my $now=time;
  173:     my $local=localtime($now);
  174:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  175: 	print $fh "$now:$message:$local\n";
  176: 	close($fh);
  177:     }
  178:     return 1;
  179: }
  180: 
  181: sub create_connection {
  182:     my ($hostname,$lonid) = @_;
  183:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  184: 				     Type    => SOCK_STREAM,
  185: 				     Timeout => 10);
  186:     return 0 if (!$client);
  187:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  188:     my $result = <$client>;
  189:     chomp($result);
  190:     return 1 if ($result eq 'done');
  191:     return 0;
  192: }
  193: 
  194: sub get_server_timezone {
  195:     my ($cnum,$cdom) = @_;
  196:     my $home=&homeserver($cnum,$cdom);
  197:     if ($home ne 'no_host') {
  198:         my $cachetime = 24*3600;
  199:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  200:         if (defined($cached)) {
  201:             return $timezone;
  202:         } else {
  203:             my $timezone = &reply('servertimezone',$home);
  204:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  205:         }
  206:     }
  207: }
  208: 
  209: sub get_server_distarch {
  210:     my ($lonhost,$ignore_cache) = @_;
  211:     if (defined($lonhost)) {
  212:         if (!defined(&hostname($lonhost))) {
  213:             return;
  214:         }
  215:         my $cachetime = 12*3600;
  216:         if (!$ignore_cache) {
  217:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  218:             if (defined($cached)) {
  219:                 return $distarch;
  220:             }
  221:         }
  222:         my $rep = &reply('serverdistarch',$lonhost);
  223:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  224:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  225:                 $rep eq '') {
  226:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  227:         }
  228:     }
  229:     return;
  230: }
  231: 
  232: sub get_server_loncaparev {
  233:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  234:     if (defined($lonhost)) {
  235:         if (!defined(&hostname($lonhost))) {
  236:             undef($lonhost);
  237:         }
  238:     }
  239:     if (!defined($lonhost)) {
  240:         if (defined(&domain($dom,'primary'))) {
  241:             $lonhost=&domain($dom,'primary');
  242:             if ($lonhost eq 'no_host') {
  243:                 undef($lonhost);
  244:             }
  245:         }
  246:     }
  247:     if (defined($lonhost)) {
  248:         my $cachetime = 12*3600;
  249:         if (!$ignore_cache) {
  250:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  251:             if (defined($cached)) {
  252:                 return $loncaparev;
  253:             }
  254:         }
  255:         my ($answer,$loncaparev);
  256:         my @ids=&current_machine_ids();
  257:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  258:             $answer = $perlvar{'lonVersion'};
  259:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  260:                 $loncaparev = $1;
  261:             }
  262:         } else {
  263:             $answer = &reply('serverloncaparev',$lonhost);
  264:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  265:                 if ($caller eq 'loncron') {
  266:                     my $ua=new LWP::UserAgent;
  267:                     $ua->timeout(4);
  268:                     my $protocol = $protocol{$lonhost};
  269:                     $protocol = 'http' if ($protocol ne 'https');
  270:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
  271:                     my $request=new HTTP::Request('GET',$url);
  272:                     my $response=$ua->request($request);
  273:                     unless ($response->is_error()) {
  274:                         my $content = $response->content;
  275:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  276:                             $loncaparev = $1;
  277:                         }
  278:                     }
  279:                 } else {
  280:                     $loncaparev = $loncaparevs{$lonhost};
  281:                 }
  282:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  283:                 $loncaparev = $1;
  284:             }
  285:         }
  286:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  287:     }
  288: }
  289: 
  290: sub get_server_homeID {
  291:     my ($hostname,$ignore_cache,$caller) = @_;
  292:     unless ($ignore_cache) {
  293:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  294:         if (defined($cached)) {
  295:             return $serverhomeID;
  296:         }
  297:     }
  298:     my $cachetime = 12*3600;
  299:     my $serverhomeID;
  300:     if ($caller eq 'loncron') { 
  301:         my @machine_ids = &machine_ids($hostname);
  302:         foreach my $id (@machine_ids) {
  303:             my $response = &reply('serverhomeID',$id);
  304:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  305:                 $serverhomeID = $response;
  306:                 last;
  307:             }
  308:         }
  309:         if ($serverhomeID eq '') {
  310:             $serverhomeID = $machine_ids[-1];
  311:         }
  312:     } else {
  313:         $serverhomeID = $serverhomeIDs{$hostname};
  314:     }
  315:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  316: }
  317: 
  318: sub get_remote_globals {
  319:     my ($lonhost,$whathash,$ignore_cache) = @_;
  320:     my ($result,%returnhash,%whatneeded);
  321:     if (ref($whathash) eq 'HASH') {
  322:         foreach my $what (sort(keys(%{$whathash}))) {
  323:             my $hashid = $lonhost.'-'.$what;
  324:             my ($response,$cached);
  325:             unless ($ignore_cache) {
  326:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  327:             }
  328:             if (defined($cached)) {
  329:                 $returnhash{$what} = $response;
  330:             } else {
  331:                 $whatneeded{$what} = 1;
  332:             }
  333:         }
  334:         if (keys(%whatneeded) == 0) {
  335:             $result = 'ok';
  336:         } else {
  337:             my $requested = &freeze_escape(\%whatneeded);
  338:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  339:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  340:                 ($rep eq 'unknown_cmd')) {
  341:                 $result = $rep;
  342:             } else {
  343:                 $result = 'ok';
  344:                 my @pairs=split(/\&/,$rep);
  345:                 foreach my $item (@pairs) {
  346:                     my ($key,$value)=split(/=/,$item,2);
  347:                     my $what = &unescape($key);
  348:                     my $hashid = $lonhost.'-'.$what;
  349:                     $returnhash{$what}=&thaw_unescape($value);
  350:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  351:                 }
  352:             }
  353:         }
  354:     }
  355:     return ($result,\%returnhash);
  356: }
  357: 
  358: sub remote_devalidate_cache {
  359:     my ($lonhost,$cachekeys) = @_;
  360:     my $items;
  361:     return unless (ref($cachekeys) eq 'ARRAY');
  362:     my $cachestr = join('&',@{$cachekeys});
  363:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
  364:     return $response;
  365: }
  366: 
  367: # -------------------------------------------------- Non-critical communication
  368: sub subreply {
  369:     my ($cmd,$server)=@_;
  370:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  371:     #
  372:     #  With loncnew process trimming, there's a timing hole between lonc server
  373:     #  process exit and the master server picking up the listen on the AF_UNIX
  374:     #  socket.  In that time interval, a lock file will exist:
  375: 
  376:     my $lockfile=$peerfile.".lock";
  377:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  378: 	sleep(1);
  379:     }
  380:     # At this point, either a loncnew parent is listening or an old lonc
  381:     # or loncnew child is listening so we can connect or everything's dead.
  382:     #
  383:     #   We'll give the connection a few tries before abandoning it.  If
  384:     #   connection is not possible, we'll con_lost back to the client.
  385:     #   
  386:     my $client;
  387:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  388: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  389: 				      Type    => SOCK_STREAM,
  390: 				      Timeout => 10);
  391: 	if ($client) {
  392: 	    last;		# Connected!
  393: 	} else {
  394: 	    &create_connection(&hostname($server),$server);
  395: 	}
  396:         sleep(1);		# Try again later if failed connection.
  397:     }
  398:     my $answer;
  399:     if ($client) {
  400: 	print $client "sethost:$server:$cmd\n";
  401: 	$answer=<$client>;
  402: 	if (!$answer) { $answer="con_lost"; }
  403: 	chomp($answer);
  404:     } else {
  405: 	$answer = 'con_lost';	# Failed connection.
  406:     }
  407:     return $answer;
  408: }
  409: 
  410: sub reply {
  411:     my ($cmd,$server)=@_;
  412:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  413:     my $answer=subreply($cmd,$server);
  414:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  415:        &logthis("<font color=\"blue\">WARNING:".
  416:                 " $cmd to $server returned $answer</font>");
  417:     }
  418:     return $answer;
  419: }
  420: 
  421: # ----------------------------------------------------------- Send USR1 to lonc
  422: 
  423: sub reconlonc {
  424:     my ($lonid) = @_;
  425:     my $hostname = &hostname($lonid);
  426:     if ($lonid) {
  427: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  428: 	if ($hostname && -e $peerfile) {
  429: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  430: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  431: 					     Type    => SOCK_STREAM,
  432: 					     Timeout => 10);
  433: 	    if ($client) {
  434: 		print $client ("reset_retries\n");
  435: 		my $answer=<$client>;
  436: 		#reset just this one.
  437: 	    }
  438: 	}
  439: 	return;
  440:     }
  441: 
  442:     &logthis("Trying to reconnect lonc");
  443:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  444:     if (open(my $fh,"<$loncfile")) {
  445: 	my $loncpid=<$fh>;
  446:         chomp($loncpid);
  447:         if (kill 0 => $loncpid) {
  448: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  449:             kill USR1 => $loncpid;
  450:             sleep 1;
  451:          } else {
  452: 	    &logthis(
  453:                "<font color=\"blue\">WARNING:".
  454:                " lonc at pid $loncpid not responding, giving up</font>");
  455:         }
  456:     } else {
  457: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  458:     }
  459: }
  460: 
  461: # ------------------------------------------------------ Critical communication
  462: 
  463: sub critical {
  464:     my ($cmd,$server)=@_;
  465:     unless (&hostname($server)) {
  466:         &logthis("<font color=\"blue\">WARNING:".
  467:                " Critical message to unknown server ($server)</font>");
  468:         return 'no_such_host';
  469:     }
  470:     my $answer=reply($cmd,$server);
  471:     if ($answer eq 'con_lost') {
  472: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  473: 	my $answer=reply($cmd,$server);
  474:         if ($answer eq 'con_lost') {
  475:             my $now=time;
  476:             my $middlename=$cmd;
  477:             $middlename=substr($middlename,0,16);
  478:             $middlename=~s/\W//g;
  479:             my $dfilename=
  480:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  481:             $dumpcount++;
  482:             {
  483: 		my $dfh;
  484: 		if (open($dfh,">$dfilename")) {
  485: 		    print $dfh "$cmd\n"; 
  486: 		    close($dfh);
  487: 		}
  488:             }
  489:             sleep 2;
  490:             my $wcmd='';
  491:             {
  492: 		my $dfh;
  493: 		if (open($dfh,"<$dfilename")) {
  494: 		    $wcmd=<$dfh>; 
  495: 		    close($dfh);
  496: 		}
  497:             }
  498:             chomp($wcmd);
  499:             if ($wcmd eq $cmd) {
  500: 		&logthis("<font color=\"blue\">WARNING: ".
  501:                          "Connection buffer $dfilename: $cmd</font>");
  502:                 &logperm("D:$server:$cmd");
  503: 	        return 'con_delayed';
  504:             } else {
  505:                 &logthis("<font color=\"red\">CRITICAL:"
  506:                         ." Critical connection failed: $server $cmd</font>");
  507:                 &logperm("F:$server:$cmd");
  508:                 return 'con_failed';
  509:             }
  510:         }
  511:     }
  512:     return $answer;
  513: }
  514: 
  515: # ------------------------------------------- check if return value is an error
  516: 
  517: sub error {
  518:     my ($result) = @_;
  519:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  520: 	if ($2 == 2) { return undef; }
  521: 	return $1;
  522:     }
  523:     return undef;
  524: }
  525: 
  526: sub convert_and_load_session_env {
  527:     my ($lonidsdir,$handle)=@_;
  528:     my @profile;
  529:     {
  530: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  531: 	if (!$opened) {
  532: 	    return 0;
  533: 	}
  534: 	flock($idf,LOCK_SH);
  535: 	@profile=<$idf>;
  536: 	close($idf);
  537:     }
  538:     my %temp_env;
  539:     foreach my $line (@profile) {
  540: 	if ($line !~ m/=/) {
  541: 	    return 0;
  542: 	}
  543: 	chomp($line);
  544: 	my ($envname,$envvalue)=split(/=/,$line,2);
  545: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  546:     }
  547:     unlink("$lonidsdir/$handle.id");
  548:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  549: 	    0640)) {
  550: 	%disk_env = %temp_env;
  551: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  552: 	untie(%disk_env);
  553:     }
  554:     return 1;
  555: }
  556: 
  557: # ------------------------------------------- Transfer profile into environment
  558: my $env_loaded;
  559: sub transfer_profile_to_env {
  560:     my ($lonidsdir,$handle,$force_transfer) = @_;
  561:     if (!$force_transfer && $env_loaded) { return; } 
  562: 
  563:     if (!defined($lonidsdir)) {
  564: 	$lonidsdir = $perlvar{'lonIDsDir'};
  565:     }
  566:     if (!defined($handle)) {
  567:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  568:     }
  569: 
  570:     my $convert;
  571:     {
  572:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  573: 	if (!$opened) {
  574: 	    return;
  575: 	}
  576: 	flock($idf,LOCK_SH);
  577: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  578: 		&GDBM_READER(),0640)) {
  579: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  580: 	    untie(%disk_env);
  581: 	} else {
  582: 	    $convert = 1;
  583: 	}
  584:     }
  585:     if ($convert) {
  586: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  587: 	    &logthis("Failed to load session, or convert session.");
  588: 	}
  589:     }
  590: 
  591:     my %remove;
  592:     while ( my $envname = each(%env) ) {
  593:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  594:             if ($time < time-300) {
  595:                 $remove{$key}++;
  596:             }
  597:         }
  598:     }
  599: 
  600:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  601:     $env_loaded=1;
  602:     foreach my $expired_key (keys(%remove)) {
  603:         &delenv($expired_key);
  604:     }
  605: }
  606: 
  607: # ---------------------------------------------------- Check for valid session 
  608: sub check_for_valid_session {
  609:     my ($r,$name,$userhashref) = @_;
  610:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  611:     if ($name eq '') {
  612:         $name = 'lonID';
  613:     }
  614:     my $lonid=$cookies{$name};
  615:     return undef if (!$lonid);
  616: 
  617:     my $handle=&LONCAPA::clean_handle($lonid->value);
  618:     my $lonidsdir;
  619:     if ($name eq 'lonDAV') {
  620:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  621:     } else {
  622:         $lonidsdir=$r->dir_config('lonIDsDir');
  623:     }
  624:     return undef if (!-e "$lonidsdir/$handle.id");
  625: 
  626:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  627:     return undef if (!$opened);
  628: 
  629:     flock($idf,LOCK_SH);
  630:     my %disk_env;
  631:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  632: 	    &GDBM_READER(),0640)) {
  633: 	return undef;	
  634:     }
  635: 
  636:     if (!defined($disk_env{'user.name'})
  637: 	|| !defined($disk_env{'user.domain'})) {
  638: 	return undef;
  639:     }
  640: 
  641:     if (ref($userhashref) eq 'HASH') {
  642:         $userhashref->{'name'} = $disk_env{'user.name'};
  643:         $userhashref->{'domain'} = $disk_env{'user.domain'};
  644:     }
  645: 
  646:     return $handle;
  647: }
  648: 
  649: sub timed_flock {
  650:     my ($file,$lock_type) = @_;
  651:     my $failed=0;
  652:     eval {
  653: 	local $SIG{__DIE__}='DEFAULT';
  654: 	local $SIG{ALRM}=sub {
  655: 	    $failed=1;
  656: 	    die("failed lock");
  657: 	};
  658: 	alarm(13);
  659: 	flock($file,$lock_type);
  660: 	alarm(0);
  661:     };
  662:     if ($failed) {
  663: 	return undef;
  664:     } else {
  665: 	return 1;
  666:     }
  667: }
  668: 
  669: # ---------------------------------------------------------- Append Environment
  670: 
  671: sub appenv {
  672:     my ($newenv,$roles) = @_;
  673:     if (ref($newenv) eq 'HASH') {
  674:         foreach my $key (keys(%{$newenv})) {
  675:             my $refused = 0;
  676: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  677:                 $refused = 1;
  678:                 if (ref($roles) eq 'ARRAY') {
  679:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
  680:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  681:                         $refused = 0;
  682:                     }
  683:                 }
  684:             }
  685:             if ($refused) {
  686:                 &logthis("<font color=\"blue\">WARNING: ".
  687:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  688:                          .'</font>');
  689: 	        delete($newenv->{$key});
  690:             } else {
  691:                 $env{$key}=$newenv->{$key};
  692:             }
  693:         }
  694:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  695:         if ($opened
  696: 	    && &timed_flock($env_file,LOCK_EX)
  697: 	    &&
  698: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  699: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  700: 	    while (my ($key,$value) = each(%{$newenv})) {
  701: 	        $disk_env{$key} = $value;
  702: 	    }
  703: 	    untie(%disk_env);
  704:         }
  705:     }
  706:     return 'ok';
  707: }
  708: # ----------------------------------------------------- Delete from Environment
  709: 
  710: sub delenv {
  711:     my ($delthis,$regexp,$roles) = @_;
  712:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  713:         my $refused = 1;
  714:         if (ref($roles) eq 'ARRAY') {
  715:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  716:             if (grep(/^\Q$role\E$/,@{$roles})) {
  717:                 $refused = 0;
  718:             }
  719:         }
  720:         if ($refused) {
  721:             &logthis("<font color=\"blue\">WARNING: ".
  722:                      "Attempt to delete from environment ".$delthis);
  723:             return 'error';
  724:         }
  725:     }
  726:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  727:     if ($opened
  728: 	&& &timed_flock($env_file,LOCK_EX)
  729: 	&&
  730: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  731: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  732: 	foreach my $key (keys(%disk_env)) {
  733: 	    if ($regexp) {
  734:                 if ($key=~/^$delthis/) {
  735:                     delete($env{$key});
  736:                     delete($disk_env{$key});
  737:                 } 
  738:             } else {
  739:                 if ($key=~/^\Q$delthis\E/) {
  740: 		    delete($env{$key});
  741: 		    delete($disk_env{$key});
  742: 	        }
  743:             }
  744: 	}
  745: 	untie(%disk_env);
  746:     }
  747:     return 'ok';
  748: }
  749: 
  750: sub get_env_multiple {
  751:     my ($name) = @_;
  752:     my @values;
  753:     if (defined($env{$name})) {
  754:         # exists is it an array
  755:         if (ref($env{$name})) {
  756:             @values=@{ $env{$name} };
  757:         } else {
  758:             $values[0]=$env{$name};
  759:         }
  760:     }
  761:     return(@values);
  762: }
  763: 
  764: # ------------------------------------------------------------------- Locking
  765: 
  766: sub set_lock {
  767:     my ($text)=@_;
  768:     $locknum++;
  769:     my $id=$$.'-'.$locknum;
  770:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  771:              'session.lock.'.$id => $text});
  772:     return $id;
  773: }
  774: 
  775: sub get_locks {
  776:     my $num=0;
  777:     my %texts=();
  778:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  779:        if ($lock=~/\w/) {
  780:           $num++;
  781:           $texts{$lock}=$env{'session.lock.'.$lock};
  782:        }
  783:    }
  784:    return ($num,%texts);
  785: }
  786: 
  787: sub remove_lock {
  788:     my ($id)=@_;
  789:     my $newlocks='';
  790:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  791:        if (($lock=~/\w/) && ($lock ne $id)) {
  792:           $newlocks.=','.$lock;
  793:        }
  794:     }
  795:     &appenv({'session.locks' => $newlocks});
  796:     &delenv('session.lock.'.$id);
  797: }
  798: 
  799: sub remove_all_locks {
  800:     my $activelocks=$env{'session.locks'};
  801:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  802:        if ($lock=~/\w/) {
  803:           &remove_lock($lock);
  804:        }
  805:     }
  806: }
  807: 
  808: 
  809: # ------------------------------------------ Find out current server userload
  810: sub userload {
  811:     my $numusers=0;
  812:     {
  813: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  814: 	my $filename;
  815: 	my $curtime=time;
  816: 	while ($filename=readdir(LONIDS)) {
  817: 	    next if ($filename eq '.' || $filename eq '..');
  818: 	    next if ($filename =~ /publicuser_\d+\.id/);
  819: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  820: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  821: 	}
  822: 	closedir(LONIDS);
  823:     }
  824:     my $userloadpercent=0;
  825:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  826:     if ($maxuserload) {
  827: 	$userloadpercent=100*$numusers/$maxuserload;
  828:     }
  829:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  830:     return $userloadpercent;
  831: }
  832: 
  833: # ------------------------------ Find server with least workload from spare.tab
  834: 
  835: sub spareserver {
  836:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  837:     my $spare_server;
  838:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  839:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  840:                                                      :  $userloadpercent;
  841:     my ($uint_dom,$remotesessions);
  842:     if (($udom ne '') && (&domain($udom) ne '')) {
  843:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  844:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  845:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  846:         $remotesessions = $udomdefaults{'remotesessions'};
  847:     }
  848:     my $spareshash = &this_host_spares($udom);
  849:     if (ref($spareshash) eq 'HASH') {
  850:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  851:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  852:                 if ($uint_dom) {
  853:                     next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  854:                                                  $try_server));
  855:                 }
  856: 	        ($spare_server, $lowest_load) =
  857: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  858:             }
  859:         }
  860: 
  861:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
  862: 
  863:         if (!$found_server) {
  864:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
  865: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
  866:                     if ($uint_dom) {
  867:                         next unless (&spare_can_host($udom,$uint_dom,
  868:                                                      $remotesessions,$try_server));
  869:                     }
  870: 	            ($spare_server, $lowest_load) =
  871: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
  872:                 }
  873: 	    }
  874:         }
  875:     }
  876: 
  877:     if (!$want_server_name) {
  878:         my $protocol = 'http';
  879:         if ($protocol{$spare_server} eq 'https') {
  880:             $protocol = $protocol{$spare_server};
  881:         }
  882:         if (defined($spare_server)) {
  883:             my $hostname = &hostname($spare_server);
  884:             if (defined($hostname)) {
  885: 	        $spare_server = $protocol.'://'.$hostname;
  886:             }
  887:         }
  888:     }
  889:     return $spare_server;
  890: }
  891: 
  892: sub compare_server_load {
  893:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
  894: 
  895:     if ($required) {
  896:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
  897:         my $remoterev = &get_server_loncaparev(undef,$try_server);
  898:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
  899:         if (($major eq '' && $minor eq '') ||
  900:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
  901:             return ($spare_server,$lowest_load);
  902:         }
  903:     }
  904: 
  905:     my $loadans     = &reply('load',    $try_server);
  906:     my $userloadans = &reply('userload',$try_server);
  907: 
  908:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  909: 	return ($spare_server, $lowest_load); #didn't get a number from the server
  910:     }
  911: 
  912:     my $load;
  913:     if ($loadans =~ /\d/) {
  914: 	if ($userloadans =~ /\d/) {
  915: 	    #both are numbers, pick the bigger one
  916: 	    $load = ($loadans > $userloadans) ? $loadans 
  917: 		                              : $userloadans;
  918: 	} else {
  919: 	    $load = $loadans;
  920: 	}
  921:     } else {
  922: 	$load = $userloadans;
  923:     }
  924: 
  925:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  926: 	$spare_server = $try_server;
  927: 	$lowest_load  = $load;
  928:     }
  929:     return ($spare_server,$lowest_load);
  930: }
  931: 
  932: # --------------------------- ask offload servers if user already has a session
  933: sub find_existing_session {
  934:     my ($udom,$uname) = @_;
  935:     my $spareshash = &this_host_spares($udom);
  936:     if (ref($spareshash) eq 'HASH') {
  937:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  938:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  939:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  940:             }
  941:         }
  942:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
  943:             foreach my $try_server (@{ $spareshash->{'default'} }) {
  944:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  945:             }
  946:         }
  947:     }
  948:     return;
  949: }
  950: 
  951: # -------------------------------- ask if server already has a session for user
  952: sub has_user_session {
  953:     my ($lonid,$udom,$uname) = @_;
  954:     my $result = &reply(join(':','userhassession',
  955: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  956:     return 1 if ($result eq 'ok');
  957: 
  958:     return 0;
  959: }
  960: 
  961: # --------- determine least loaded server in a user's domain which allows login
  962: 
  963: sub choose_server {
  964:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
  965:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
  966:     my %servers = &get_servers($udom);
  967:     my $lowest_load = 30000;
  968:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
  969:     if ($skiploadbal) {
  970:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
  971:         unless (defined($cached)) {
  972:             my $cachetime = 60*60*24;
  973:             my %domconfig =
  974:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
  975:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
  976:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
  977:                                            $cachetime);
  978:             }
  979:         }
  980:     }
  981:     foreach my $lonhost (keys(%servers)) {
  982:         if ($skiploadbal) {
  983:             if (ref($balancers) eq 'HASH') {
  984:                 next if (exists($balancers->{$lonhost}));
  985:             }
  986:         }   
  987:         my $loginvia;
  988:         if ($checkloginvia) {
  989:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
  990:             if ($loginvia) {
  991:                 my ($server,$path) = split(/:/,$loginvia);
  992:                 ($login_host, $lowest_load) =
  993:                     &compare_server_load($server, $login_host, $lowest_load, $required);
  994:                 if ($login_host eq $server) {
  995:                     $portal_path = $path;
  996:                     $isredirect = 1;
  997:                 }
  998:             } else {
  999:                 ($login_host, $lowest_load) =
 1000:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1001:                 if ($login_host eq $lonhost) {
 1002:                     $portal_path = '';
 1003:                     $isredirect = ''; 
 1004:                 }
 1005:             }
 1006:         } else {
 1007:             ($login_host, $lowest_load) =
 1008:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1009:         }
 1010:     }
 1011:     if ($login_host ne '') {
 1012:         $hostname = &hostname($login_host);
 1013:     }
 1014:     return ($login_host,$hostname,$portal_path,$isredirect);
 1015: }
 1016: 
 1017: # --------------------------------------------- Try to change a user's password
 1018: 
 1019: sub changepass {
 1020:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
 1021:     $currentpass = &escape($currentpass);
 1022:     $newpass     = &escape($newpass);
 1023:     my $lonhost = $perlvar{'lonHostID'};
 1024:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
 1025: 		       $server);
 1026:     if (! $answer) {
 1027: 	&logthis("No reply on password change request to $server ".
 1028: 		 "by $uname in domain $udom.");
 1029:     } elsif ($answer =~ "^ok") {
 1030:         &logthis("$uname in $udom successfully changed their password ".
 1031: 		 "on $server.");
 1032:     } elsif ($answer =~ "^pwchange_failure") {
 1033: 	&logthis("$uname in $udom was unable to change their password ".
 1034: 		 "on $server.  The action was blocked by either lcpasswd ".
 1035: 		 "or pwchange");
 1036:     } elsif ($answer =~ "^non_authorized") {
 1037:         &logthis("$uname in $udom did not get their password correct when ".
 1038: 		 "attempting to change it on $server.");
 1039:     } elsif ($answer =~ "^auth_mode_error") {
 1040:         &logthis("$uname in $udom attempted to change their password despite ".
 1041: 		 "not being locally or internally authenticated on $server.");
 1042:     } elsif ($answer =~ "^unknown_user") {
 1043:         &logthis("$uname in $udom attempted to change their password ".
 1044: 		 "on $server but were unable to because $server is not ".
 1045: 		 "their home server.");
 1046:     } elsif ($answer =~ "^refused") {
 1047: 	&logthis("$server refused to change $uname in $udom password because ".
 1048: 		 "it was sent an unencrypted request to change the password.");
 1049:     } elsif ($answer =~ "invalid_client") {
 1050:         &logthis("$server refused to change $uname in $udom password because ".
 1051:                  "it was a reset by e-mail originating from an invalid server.");
 1052:     }
 1053:     return $answer;
 1054: }
 1055: 
 1056: # ----------------------- Try to determine user's current authentication scheme
 1057: 
 1058: sub queryauthenticate {
 1059:     my ($uname,$udom)=@_;
 1060:     my $uhome=&homeserver($uname,$udom);
 1061:     if (!$uhome) {
 1062: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1063: 	return 'no_host';
 1064:     }
 1065:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1066:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1067: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1068:     }
 1069:     return $answer;
 1070: }
 1071: 
 1072: # --------- Try to authenticate user from domain's lib servers (first this one)
 1073: 
 1074: sub authenticate {
 1075:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1076:     $upass=&escape($upass);
 1077:     $uname= &LONCAPA::clean_username($uname);
 1078:     my $uhome=&homeserver($uname,$udom,1);
 1079:     my $newhome;
 1080:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1081: # Maybe the machine was offline and only re-appeared again recently?
 1082:         &reconlonc();
 1083: # One more
 1084: 	$uhome=&homeserver($uname,$udom,1);
 1085:         if (($uhome eq 'no_host') && $checkdefauth) {
 1086:             if (defined(&domain($udom,'primary'))) {
 1087:                 $newhome=&domain($udom,'primary');
 1088:             }
 1089:             if ($newhome ne '') {
 1090:                 $uhome = $newhome;
 1091:             }
 1092:         }
 1093: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1094: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1095: 	    return 'no_host';
 1096:         }
 1097:     }
 1098:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1099:     if ($answer eq 'authorized') {
 1100:         if ($newhome) {
 1101:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1102:             return 'no_account_on_host'; 
 1103:         } else {
 1104:             &logthis("User $uname at $udom authorized by $uhome");
 1105:             return $uhome;
 1106:         }
 1107:     }
 1108:     if ($answer eq 'non_authorized') {
 1109: 	&logthis("User $uname at $udom rejected by $uhome");
 1110: 	return 'no_host'; 
 1111:     }
 1112:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1113:     return 'no_host';
 1114: }
 1115: 
 1116: sub can_host_session {
 1117:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1118:     my $canhost = 1;
 1119:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1120:     if (ref($remotesessions) eq 'HASH') {
 1121:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1122:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1123:                 $canhost = 0;
 1124:             } else {
 1125:                 $canhost = 1;
 1126:             }
 1127:         }
 1128:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1129:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1130:                 $canhost = 1;
 1131:             } else {
 1132:                 $canhost = 0;
 1133:             }
 1134:         }
 1135:         if ($canhost) {
 1136:             if ($remotesessions->{'version'} ne '') {
 1137:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1138:                 if ($reqmajor ne '' && $reqminor ne '') {
 1139:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1140:                         my $major = $1;
 1141:                         my $minor = $2;
 1142:                         if (($major < $reqmajor ) ||
 1143:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1144:                             $canhost = 0;
 1145:                         }
 1146:                     } else {
 1147:                         $canhost = 0;
 1148:                     }
 1149:                 }
 1150:             }
 1151:         }
 1152:     }
 1153:     if ($canhost) {
 1154:         if (ref($hostedsessions) eq 'HASH') {
 1155:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1156:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1157:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1158:                 if (($uint_dom ne '') && 
 1159:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1160:                     $canhost = 0;
 1161:                 } else {
 1162:                     $canhost = 1;
 1163:                 }
 1164:             }
 1165:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1166:                 if (($uint_dom ne '') && 
 1167:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1168:                     $canhost = 1;
 1169:                 } else {
 1170:                     $canhost = 0;
 1171:                 }
 1172:             }
 1173:         }
 1174:     }
 1175:     return $canhost;
 1176: }
 1177: 
 1178: sub spare_can_host {
 1179:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1180:     my $canhost=1;
 1181:     my @intdoms;
 1182:     my $internet_names = &get_internet_names($try_server);
 1183:     if (ref($internet_names) eq 'ARRAY') {
 1184:         @intdoms = @{$internet_names};
 1185:     }
 1186:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1187:         my $try_server_hostname = &hostname($try_server);
 1188:         my $serverhomeID = &get_server_homeID($try_server_hostname);
 1189:         my $serverhomedom = &host_domain($serverhomeID);
 1190:         my %defdomdefaults = &get_domain_defaults($serverhomedom);
 1191:         my $remoterev = &get_server_loncaparev(undef,$try_server);
 1192:         $canhost = &can_host_session($udom,$try_server,$remoterev,
 1193:                                      $remotesessions,
 1194:                                      $defdomdefaults{'hostedsessions'});
 1195:     }
 1196:     return $canhost;
 1197: }
 1198: 
 1199: sub this_host_spares {
 1200:     my ($dom) = @_;
 1201:     my ($dom_in_use,$lonhost_in_use,$result);
 1202:     my @hosts = &current_machine_ids();
 1203:     foreach my $lonhost (@hosts) {
 1204:         if (&host_domain($lonhost) eq $dom) {
 1205:             $dom_in_use = $dom;
 1206:             $lonhost_in_use = $lonhost;
 1207:             last;
 1208:         }
 1209:     }
 1210:     if ($dom_in_use ne '') {
 1211:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1212:     }
 1213:     if (ref($result) ne 'HASH') {
 1214:         $lonhost_in_use = $perlvar{'lonHostID'};
 1215:         $dom_in_use = &host_domain($lonhost_in_use);
 1216:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1217:         if (ref($result) ne 'HASH') {
 1218:             $result = \%spareid;
 1219:         }
 1220:     }
 1221:     return $result;
 1222: }
 1223: 
 1224: sub spares_for_offload  {
 1225:     my ($dom_in_use,$lonhost_in_use) = @_;
 1226:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1227:     if (defined($cached)) {
 1228:         return $result;
 1229:     } else {
 1230:         my $cachetime = 60*60*24;
 1231:         my %domconfig =
 1232:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1233:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1234:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1235:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1236:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1237:                 }
 1238:             }
 1239:         }
 1240:     }
 1241:     return;
 1242: }
 1243: 
 1244: sub get_lonbalancer_config {
 1245:     my ($servers) = @_;
 1246:     my ($currbalancer,$currtargets);
 1247:     if (ref($servers) eq 'HASH') {
 1248:         foreach my $server (keys(%{$servers})) {
 1249:             my %what = (
 1250:                          spareid => 1,
 1251:                          perlvar => 1,
 1252:                        );
 1253:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1254:             if ($result eq 'ok') {
 1255:                 if (ref($returnhash) eq 'HASH') {
 1256:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1257:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1258:                             $currbalancer = $server;
 1259:                             $currtargets = {};
 1260:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1261:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1262:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1263:                                 }
 1264:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1265:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1266:                                 }
 1267:                             }
 1268:                             last;
 1269:                         }
 1270:                     }
 1271:                 }
 1272:             }
 1273:         }
 1274:     }
 1275:     return ($currbalancer,$currtargets);
 1276: }
 1277: 
 1278: sub check_loadbalancing {
 1279:     my ($uname,$udom) = @_;
 1280:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1281:         $rule_in_effect,$offloadto,$otherserver);
 1282:     my $lonhost = $perlvar{'lonHostID'};
 1283:     my @hosts = &current_machine_ids();
 1284:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1285:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1286:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1287:     my $serverhomedom = &host_domain($lonhost);
 1288: 
 1289:     my $cachetime = 60*60*24;
 1290: 
 1291:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1292:         $dom_in_use = $udom;
 1293:         $homeintdom = 1;
 1294:     } else {
 1295:         $dom_in_use = $serverhomedom;
 1296:     }
 1297:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1298:     unless (defined($cached)) {
 1299:         my %domconfig =
 1300:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1301:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1302:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1303:         }
 1304:     }
 1305:     if (ref($result) eq 'HASH') {
 1306:         ($is_balancer,$currtargets,$currrules) = 
 1307:             &check_balancer_result($result,@hosts);
 1308:         if ($is_balancer) {
 1309:             if (ref($currrules) eq 'HASH') {
 1310:                 if ($homeintdom) {
 1311:                     if ($uname ne '') {
 1312:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1313:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1314:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1315:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1316:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1317:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1318:                             }
 1319:                         }
 1320:                         if ($rule_in_effect eq '') {
 1321:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1322:                             if ($userenv{'inststatus'} ne '') {
 1323:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1324:                                 my ($othertitle,$usertypes,$types) =
 1325:                                     &Apache::loncommon::sorted_inst_types($udom);
 1326:                                 if (ref($types) eq 'ARRAY') {
 1327:                                     foreach my $type (@{$types}) {
 1328:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1329:                                             if (exists($currrules->{$type})) {
 1330:                                                 $rule_in_effect = $currrules->{$type};
 1331:                                             }
 1332:                                         }
 1333:                                     }
 1334:                                 }
 1335:                             } else {
 1336:                                 if (exists($currrules->{'default'})) {
 1337:                                     $rule_in_effect = $currrules->{'default'};
 1338:                                 }
 1339:                             }
 1340:                         }
 1341:                     } else {
 1342:                         if (exists($currrules->{'default'})) {
 1343:                             $rule_in_effect = $currrules->{'default'};
 1344:                         }
 1345:                     }
 1346:                 } else {
 1347:                     if ($currrules->{'_LC_external'} ne '') {
 1348:                         $rule_in_effect = $currrules->{'_LC_external'};
 1349:                     }
 1350:                 }
 1351:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1352:                                                        $uname,$udom);
 1353:             }
 1354:         }
 1355:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1356:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1357:         unless (defined($cached)) {
 1358:             my %domconfig =
 1359:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1360:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1361:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1362:             }
 1363:         }
 1364:         if (ref($result) eq 'HASH') {
 1365:             ($is_balancer,$currtargets,$currrules) = 
 1366:                 &check_balancer_result($result,@hosts);
 1367:             if ($is_balancer) {
 1368:                 if (ref($currrules) eq 'HASH') {
 1369:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1370:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1371:                     }
 1372:                 }
 1373:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1374:                                                        $uname,$udom);
 1375:             }
 1376:         } else {
 1377:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1378:                 $is_balancer = 1;
 1379:                 $offloadto = &this_host_spares($dom_in_use);
 1380:             }
 1381:         }
 1382:     } else {
 1383:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1384:             $is_balancer = 1;
 1385:             $offloadto = &this_host_spares($dom_in_use);
 1386:         }
 1387:     }
 1388:     if ($is_balancer) {
 1389:         my $lowest_load = 30000;
 1390:         if (ref($offloadto) eq 'HASH') {
 1391:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1392:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1393:                     ($otherserver,$lowest_load) =
 1394:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1395:                 }
 1396:             }
 1397:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1398: 
 1399:             if (!$found_server) {
 1400:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1401:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1402:                         ($otherserver,$lowest_load) =
 1403:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1404:                     }
 1405:                 }
 1406:             }
 1407:         } elsif (ref($offloadto) eq 'ARRAY') {
 1408:             if (@{$offloadto} == 1) {
 1409:                 $otherserver = $offloadto->[0];
 1410:             } elsif (@{$offloadto} > 1) {
 1411:                 foreach my $try_server (@{$offloadto}) {
 1412:                     ($otherserver,$lowest_load) =
 1413:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1414:                 }
 1415:             }
 1416:         }
 1417:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1418:             $is_balancer = 0;
 1419:             if ($uname ne '' && $udom ne '') {
 1420:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1421:                     
 1422:                     &appenv({'user.loadbalexempt'     => $lonhost,  
 1423:                              'user.loadbalcheck.time' => time});
 1424:                 }
 1425:             }
 1426:         }
 1427:     }
 1428:     return ($is_balancer,$otherserver);
 1429: }
 1430: 
 1431: sub check_balancer_result {
 1432:     my ($result,@hosts) = @_;
 1433:     my ($is_balancer,$currtargets,$currrules);
 1434:     if (ref($result) eq 'HASH') {
 1435:         if ($result->{'lonhost'} ne '') {
 1436:             my $currbalancer = $result->{'lonhost'};
 1437:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1438:                 $is_balancer = 1;
 1439:                 $currtargets = $result->{'targets'};
 1440:                 $currrules = $result->{'rules'};
 1441:             }
 1442:         } else {
 1443:             foreach my $key (keys(%{$result})) {
 1444:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1445:                     (ref($result->{$key}) eq 'HASH')) {
 1446:                     $is_balancer = 1;
 1447:                     $currrules = $result->{$key}{'rules'};
 1448:                     $currtargets = $result->{$key}{'targets'};
 1449:                     last;
 1450:                 }
 1451:             }
 1452:         }
 1453:     }
 1454:     return ($is_balancer,$currtargets,$currrules);
 1455: }
 1456: 
 1457: sub get_loadbalancer_targets {
 1458:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1459:     my $offloadto;
 1460:     if ($rule_in_effect eq 'none') {
 1461:         return [$perlvar{'lonHostID'}];
 1462:     } elsif ($rule_in_effect eq '') {
 1463:         $offloadto = $currtargets;
 1464:     } else {
 1465:         if ($rule_in_effect eq 'homeserver') {
 1466:             my $homeserver = &homeserver($uname,$udom);
 1467:             if ($homeserver ne 'no_host') {
 1468:                 $offloadto = [$homeserver];
 1469:             }
 1470:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1471:             my %domconfig =
 1472:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1473:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1474:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1475:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1476:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1477:                     }
 1478:                 }
 1479:             } else {
 1480:                 my %servers = &internet_dom_servers($udom);
 1481:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1482:                 if (&hostname($remotebalancer) ne '') {
 1483:                     $offloadto = [$remotebalancer];
 1484:                 }
 1485:             }
 1486:         } elsif (&hostname($rule_in_effect) ne '') {
 1487:             $offloadto = [$rule_in_effect];
 1488:         }
 1489:     }
 1490:     return $offloadto;
 1491: }
 1492: 
 1493: sub internet_dom_servers {
 1494:     my ($dom) = @_;
 1495:     my (%uniqservers,%servers);
 1496:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1497:     my @machinedoms = &machine_domains($primaryserver);
 1498:     foreach my $mdom (@machinedoms) {
 1499:         my %currservers = %servers;
 1500:         my %server = &get_servers($mdom);
 1501:         %servers = (%currservers,%server);
 1502:     }
 1503:     my %by_hostname;
 1504:     foreach my $id (keys(%servers)) {
 1505:         push(@{$by_hostname{$servers{$id}}},$id);
 1506:     }
 1507:     foreach my $hostname (sort(keys(%by_hostname))) {
 1508:         if (@{$by_hostname{$hostname}} > 1) {
 1509:             my $match = 0;
 1510:             foreach my $id (@{$by_hostname{$hostname}}) {
 1511:                 if (&host_domain($id) eq $dom) {
 1512:                     $uniqservers{$id} = $hostname;
 1513:                     $match = 1;
 1514:                 }
 1515:             }
 1516:             unless ($match) {
 1517:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1518:             }
 1519:         } else {
 1520:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1521:         }
 1522:     }
 1523:     return %uniqservers;
 1524: }
 1525: 
 1526: # ---------------------- Find the homebase for a user from domain's lib servers
 1527: 
 1528: my %homecache;
 1529: sub homeserver {
 1530:     my ($uname,$udom,$ignoreBadCache)=@_;
 1531:     my $index="$uname:$udom";
 1532: 
 1533:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1534: 
 1535:     my %servers = &get_servers($udom,'library');
 1536:     foreach my $tryserver (keys(%servers)) {
 1537:         next if ($ignoreBadCache ne 'true' && 
 1538: 		 exists($badServerCache{$tryserver}));
 1539: 
 1540: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1541: 	if ($answer eq 'found') {
 1542: 	    delete($badServerCache{$tryserver}); 
 1543: 	    return $homecache{$index}=$tryserver;
 1544: 	} elsif ($answer eq 'no_host') {
 1545: 	    $badServerCache{$tryserver}=1;
 1546: 	}
 1547:     }    
 1548:     return 'no_host';
 1549: }
 1550: 
 1551: # ------------------------------------- Find the usernames behind a list of IDs
 1552: 
 1553: sub idget {
 1554:     my ($udom,@ids)=@_;
 1555:     my %returnhash=();
 1556:     
 1557:     my %servers = &get_servers($udom,'library');
 1558:     foreach my $tryserver (keys(%servers)) {
 1559: 	my $idlist=join('&',@ids);
 1560: 	$idlist=~tr/A-Z/a-z/; 
 1561: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1562: 	my @answer=();
 1563: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1564: 	    @answer=split(/\&/,$reply);
 1565: 	}                    ;
 1566: 	my $i;
 1567: 	for ($i=0;$i<=$#ids;$i++) {
 1568: 	    if ($answer[$i]) {
 1569: 		$returnhash{$ids[$i]}=$answer[$i];
 1570: 	    } 
 1571: 	}
 1572:     } 
 1573:     return %returnhash;
 1574: }
 1575: 
 1576: # ------------------------------------- Find the IDs behind a list of usernames
 1577: 
 1578: sub idrget {
 1579:     my ($udom,@unames)=@_;
 1580:     my %returnhash=();
 1581:     foreach my $uname (@unames) {
 1582:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1583:     }
 1584:     return %returnhash;
 1585: }
 1586: 
 1587: # ------------------------------- Store away a list of names and associated IDs
 1588: 
 1589: sub idput {
 1590:     my ($udom,%ids)=@_;
 1591:     my %servers=();
 1592:     foreach my $uname (keys(%ids)) {
 1593: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1594:         my $uhom=&homeserver($uname,$udom);
 1595:         if ($uhom ne 'no_host') {
 1596:             my $id=&escape($ids{$uname});
 1597:             $id=~tr/A-Z/a-z/;
 1598:             my $esc_unam=&escape($uname);
 1599: 	    if ($servers{$uhom}) {
 1600: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
 1601:             } else {
 1602:                 $servers{$uhom}=$id.'='.$esc_unam;
 1603:             }
 1604:         }
 1605:     }
 1606:     foreach my $server (keys(%servers)) {
 1607:         &critical('idput:'.$udom.':'.$servers{$server},$server);
 1608:     }
 1609: }
 1610: 
 1611: # ---------------------------------------- Delete unwanted IDs from ids.db file 
 1612: 
 1613: sub iddel {
 1614:     my ($udom,$idshashref,$uhome)=@_;
 1615:     my %result=();
 1616:     unless (ref($idshashref) eq 'HASH') {
 1617:         return %result;
 1618:     }
 1619:     my %servers=();
 1620:     while (my ($id,$uname) = each(%{$idshashref})) {
 1621:         my $uhom;
 1622:         if ($uhome) {
 1623:             $uhom = $uhome;
 1624:         } else {
 1625:             $uhom=&homeserver($uname,$udom);
 1626:         }
 1627:         if ($uhom ne 'no_host') {
 1628:             if ($servers{$uhom}) {
 1629:                 $servers{$uhom}.='&'.&escape($id);
 1630:             } else {
 1631:                 $servers{$uhom}=&escape($id);
 1632:             }
 1633:         }
 1634:     }
 1635:     foreach my $server (keys(%servers)) {
 1636:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
 1637:     }
 1638:     return %result;
 1639: }
 1640: 
 1641: # ------------------------------dump from db file owned by domainconfig user
 1642: sub dump_dom {
 1643:     my ($namespace, $udom, $regexp) = @_;
 1644: 
 1645:     $udom ||= $env{'user.domain'};
 1646: 
 1647:     return () unless $udom;
 1648: 
 1649:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 1650: }
 1651: 
 1652: # ------------------------------------------ get items from domain db files   
 1653: 
 1654: sub get_dom {
 1655:     my ($namespace,$storearr,$udom,$uhome)=@_;
 1656:     return if ($udom eq 'public');
 1657:     my $items='';
 1658:     foreach my $item (@$storearr) {
 1659:         $items.=&escape($item).'&';
 1660:     }
 1661:     $items=~s/\&$//;
 1662:     if (!$udom) {
 1663:         $udom=$env{'user.domain'};
 1664:         return if ($udom eq 'public');
 1665:         if (defined(&domain($udom,'primary'))) {
 1666:             $uhome=&domain($udom,'primary');
 1667:         } else {
 1668:             undef($uhome);
 1669:         }
 1670:     } else {
 1671:         if (!$uhome) {
 1672:             if (defined(&domain($udom,'primary'))) {
 1673:                 $uhome=&domain($udom,'primary');
 1674:             }
 1675:         }
 1676:     }
 1677:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1678:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 1679:         my %returnhash;
 1680:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 1681:             return %returnhash;
 1682:         }
 1683:         my @pairs=split(/\&/,$rep);
 1684:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1685:             return @pairs;
 1686:         }
 1687:         my $i=0;
 1688:         foreach my $item (@$storearr) {
 1689:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 1690:             $i++;
 1691:         }
 1692:         return %returnhash;
 1693:     } else {
 1694:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1695:     }
 1696: }
 1697: 
 1698: # -------------------------------------------- put items in domain db files 
 1699: 
 1700: sub put_dom {
 1701:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1702:     if (!$udom) {
 1703:         $udom=$env{'user.domain'};
 1704:         if (defined(&domain($udom,'primary'))) {
 1705:             $uhome=&domain($udom,'primary');
 1706:         } else {
 1707:             undef($uhome);
 1708:         }
 1709:     } else {
 1710:         if (!$uhome) {
 1711:             if (defined(&domain($udom,'primary'))) {
 1712:                 $uhome=&domain($udom,'primary');
 1713:             }
 1714:         }
 1715:     } 
 1716:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1717:         my $items='';
 1718:         foreach my $item (keys(%$storehash)) {
 1719:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 1720:         }
 1721:         $items=~s/\&$//;
 1722:         return &reply("putdom:$udom:$namespace:$items",$uhome);
 1723:     } else {
 1724:         &logthis("put_dom failed - no homeserver and/or domain");
 1725:     }
 1726: }
 1727: 
 1728: # --------------------- newput for items in db file owned by domainconfig user
 1729: sub newput_dom {
 1730:     my ($namespace,$storehash,$udom) = @_;
 1731:     my $result;
 1732:     if (!$udom) {
 1733:         $udom=$env{'user.domain'};
 1734:     }
 1735:     if ($udom) {
 1736:         my $uname = &get_domainconfiguser($udom);
 1737:         $result = &newput($namespace,$storehash,$udom,$uname);
 1738:     }
 1739:     return $result;
 1740: }
 1741: 
 1742: # --------------------- delete for items in db file owned by domainconfig user
 1743: sub del_dom {
 1744:     my ($namespace,$storearr,$udom)=@_;
 1745:     if (ref($storearr) eq 'ARRAY') {
 1746:         if (!$udom) {
 1747:             $udom=$env{'user.domain'};
 1748:         }
 1749:         if ($udom) {
 1750:             my $uname = &get_domainconfiguser($udom); 
 1751:             return &del($namespace,$storearr,$udom,$uname);
 1752:         }
 1753:     }
 1754: }
 1755: 
 1756: # ----------------------------------construct domainconfig user for a domain 
 1757: sub get_domainconfiguser {
 1758:     my ($udom) = @_;
 1759:     return $udom.'-domainconfig';
 1760: }
 1761: 
 1762: sub retrieve_inst_usertypes {
 1763:     my ($udom) = @_;
 1764:     my (%returnhash,@order);
 1765:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 1766:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 1767:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 1768:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
 1769:     } else {
 1770:         if (defined(&domain($udom,'primary'))) {
 1771:             my $uhome=&domain($udom,'primary');
 1772:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 1773:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 1774:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
 1775:                 return (\%returnhash,\@order);
 1776:             }
 1777:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 1778:             my @pairs=split(/\&/,$hashitems);
 1779:             foreach my $item (@pairs) {
 1780:                 my ($key,$value)=split(/=/,$item,2);
 1781:                 $key = &unescape($key);
 1782:                 next if ($key =~ /^error: 2 /);
 1783:                 $returnhash{$key}=&thaw_unescape($value);
 1784:             }
 1785:             my @esc_order = split(/\&/,$orderitems);
 1786:             foreach my $item (@esc_order) {
 1787:                 push(@order,&unescape($item));
 1788:             }
 1789:         } else {
 1790:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
 1791:         }
 1792:         return (\%returnhash,\@order);
 1793:     }
 1794: }
 1795: 
 1796: sub is_domainimage {
 1797:     my ($url) = @_;
 1798:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1799:         if (&domain($1) ne '') {
 1800:             return '1';
 1801:         }
 1802:     }
 1803:     return;
 1804: }
 1805: 
 1806: sub inst_directory_query {
 1807:     my ($srch) = @_;
 1808:     my $udom = $srch->{'srchdomain'};
 1809:     my %results;
 1810:     my $homeserver = &domain($udom,'primary');
 1811:     my $outcome;
 1812:     if ($homeserver ne '') {
 1813: 	my $queryid=&reply("querysend:instdirsearch:".
 1814: 			   &escape($srch->{'srchby'}).':'.
 1815: 			   &escape($srch->{'srchterm'}).':'.
 1816: 			   &escape($srch->{'srchtype'}),$homeserver);
 1817: 	my $host=&hostname($homeserver);
 1818: 	if ($queryid !~/^\Q$host\E\_/) {
 1819: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1820: 	    return;
 1821: 	}
 1822: 	my $response = &get_query_reply($queryid);
 1823: 	my $maxtries = 5;
 1824: 	my $tries = 1;
 1825: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1826: 	    $response = &get_query_reply($queryid);
 1827: 	    $tries ++;
 1828: 	}
 1829: 
 1830:         if (!&error($response) && $response ne 'refused') {
 1831:             if ($response eq 'unavailable') {
 1832:                 $outcome = $response;
 1833:             } else {
 1834:                 $outcome = 'ok';
 1835:                 my @matches = split(/\n/,$response);
 1836:                 foreach my $match (@matches) {
 1837:                     my ($key,$value) = split(/=/,$match);
 1838:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1839:                 }
 1840:             }
 1841:         }
 1842:     }
 1843:     return ($outcome,%results);
 1844: }
 1845: 
 1846: sub usersearch {
 1847:     my ($srch) = @_;
 1848:     my $dom = $srch->{'srchdomain'};
 1849:     my %results;
 1850:     my %libserv = &all_library();
 1851:     my $query = 'usersearch';
 1852:     foreach my $tryserver (keys(%libserv)) {
 1853:         if (&host_domain($tryserver) eq $dom) {
 1854:             my $host=&hostname($tryserver);
 1855:             my $queryid=
 1856:                 &reply("querysend:".&escape($query).':'.
 1857:                        &escape($srch->{'srchby'}).':'.
 1858:                        &escape($srch->{'srchtype'}).':'.
 1859:                        &escape($srch->{'srchterm'}),$tryserver);
 1860:             if ($queryid !~/^\Q$host\E\_/) {
 1861:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1862:                 next;
 1863:             }
 1864:             my $reply = &get_query_reply($queryid);
 1865:             my $maxtries = 1;
 1866:             my $tries = 1;
 1867:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1868:                 $reply = &get_query_reply($queryid);
 1869:                 $tries ++;
 1870:             }
 1871:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1872:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1873:             } else {
 1874:                 my @matches;
 1875:                 if ($reply =~ /\n/) {
 1876:                     @matches = split(/\n/,$reply);
 1877:                 } else {
 1878:                     @matches = split(/\&/,$reply);
 1879:                 }
 1880:                 foreach my $match (@matches) {
 1881:                     my ($uname,$udom,%userhash);
 1882:                     foreach my $entry (split(/:/,$match)) {
 1883:                         my ($key,$value) =
 1884:                             map {&unescape($_);} split(/=/,$entry);
 1885:                         $userhash{$key} = $value;
 1886:                         if ($key eq 'username') {
 1887:                             $uname = $value;
 1888:                         } elsif ($key eq 'domain') {
 1889:                             $udom = $value;
 1890:                         }
 1891:                     }
 1892:                     $results{$uname.':'.$udom} = \%userhash;
 1893:                 }
 1894:             }
 1895:         }
 1896:     }
 1897:     return %results;
 1898: }
 1899: 
 1900: sub get_instuser {
 1901:     my ($udom,$uname,$id) = @_;
 1902:     my $homeserver = &domain($udom,'primary');
 1903:     my ($outcome,%results);
 1904:     if ($homeserver ne '') {
 1905:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1906:                            &escape($id).':'.&escape($udom),$homeserver);
 1907:         my $host=&hostname($homeserver);
 1908:         if ($queryid !~/^\Q$host\E\_/) {
 1909:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1910:             return;
 1911:         }
 1912:         my $response = &get_query_reply($queryid);
 1913:         my $maxtries = 5;
 1914:         my $tries = 1;
 1915:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1916:             $response = &get_query_reply($queryid);
 1917:             $tries ++;
 1918:         }
 1919:         if (!&error($response) && $response ne 'refused') {
 1920:             if ($response eq 'unavailable') {
 1921:                 $outcome = $response;
 1922:             } else {
 1923:                 $outcome = 'ok';
 1924:                 my @matches = split(/\n/,$response);
 1925:                 foreach my $match (@matches) {
 1926:                     my ($key,$value) = split(/=/,$match);
 1927:                     $results{&unescape($key)} = &thaw_unescape($value);
 1928:                 }
 1929:             }
 1930:         }
 1931:     }
 1932:     my %userinfo;
 1933:     if (ref($results{$uname}) eq 'HASH') {
 1934:         %userinfo = %{$results{$uname}};
 1935:     } 
 1936:     return ($outcome,%userinfo);
 1937: }
 1938: 
 1939: sub inst_rulecheck {
 1940:     my ($udom,$uname,$id,$item,$rules) = @_;
 1941:     my %returnhash;
 1942:     if ($udom ne '') {
 1943:         if (ref($rules) eq 'ARRAY') {
 1944:             @{$rules} = map {&escape($_);} (@{$rules});
 1945:             my $rulestr = join(':',@{$rules});
 1946:             my $homeserver=&domain($udom,'primary');
 1947:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1948:                 my $response;
 1949:                 if ($item eq 'username') {                
 1950:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1951:                                               ':'.&escape($uname).':'.$rulestr,
 1952:                                               $homeserver));
 1953:                 } elsif ($item eq 'id') {
 1954:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1955:                                               ':'.&escape($id).':'.$rulestr,
 1956:                                               $homeserver));
 1957:                 } elsif ($item eq 'selfcreate') {
 1958:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1959:                                                &escape($udom).':'.&escape($uname).
 1960:                                               ':'.$rulestr,$homeserver));
 1961:                 }
 1962:                 if ($response ne 'refused') {
 1963:                     my @pairs=split(/\&/,$response);
 1964:                     foreach my $item (@pairs) {
 1965:                         my ($key,$value)=split(/=/,$item,2);
 1966:                         $key = &unescape($key);
 1967:                         next if ($key =~ /^error: 2 /);
 1968:                         $returnhash{$key}=&thaw_unescape($value);
 1969:                     }
 1970:                 }
 1971:             }
 1972:         }
 1973:     }
 1974:     return %returnhash;
 1975: }
 1976: 
 1977: sub inst_userrules {
 1978:     my ($udom,$check) = @_;
 1979:     my (%ruleshash,@ruleorder);
 1980:     if ($udom ne '') {
 1981:         my $homeserver=&domain($udom,'primary');
 1982:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1983:             my $response;
 1984:             if ($check eq 'id') {
 1985:                 $response=&reply('instidrules:'.&escape($udom),
 1986:                                  $homeserver);
 1987:             } elsif ($check eq 'email') {
 1988:                 $response=&reply('instemailrules:'.&escape($udom),
 1989:                                  $homeserver);
 1990:             } else {
 1991:                 $response=&reply('instuserrules:'.&escape($udom),
 1992:                                  $homeserver);
 1993:             }
 1994:             if (($response ne 'refused') && ($response ne 'error') && 
 1995:                 ($response ne 'unknown_cmd') && 
 1996:                 ($response ne 'no_such_host')) {
 1997:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1998:                 my @pairs=split(/\&/,$hashitems);
 1999:                 foreach my $item (@pairs) {
 2000:                     my ($key,$value)=split(/=/,$item,2);
 2001:                     $key = &unescape($key);
 2002:                     next if ($key =~ /^error: 2 /);
 2003:                     $ruleshash{$key}=&thaw_unescape($value);
 2004:                 }
 2005:                 my @esc_order = split(/\&/,$orderitems);
 2006:                 foreach my $item (@esc_order) {
 2007:                     push(@ruleorder,&unescape($item));
 2008:                 }
 2009:             }
 2010:         }
 2011:     }
 2012:     return (\%ruleshash,\@ruleorder);
 2013: }
 2014: 
 2015: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 2016: 
 2017: sub get_domain_defaults {
 2018:     my ($domain,$ignore_cache) = @_;
 2019:     return if (($domain eq '') || ($domain eq 'public'));
 2020:     my $cachetime = 60*60*24;
 2021:     unless ($ignore_cache) {
 2022:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 2023:         if (defined($cached)) {
 2024:             if (ref($result) eq 'HASH') {
 2025:                 return %{$result};
 2026:             }
 2027:         }
 2028:     }
 2029:     my %domdefaults;
 2030:     my %domconfig =
 2031:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 2032:                                   'requestcourses','inststatus',
 2033:                                   'coursedefaults','usersessions',
 2034:                                   'requestauthor','selfenrollment',
 2035:                                   'coursecategories'],$domain);
 2036:     my @coursetypes = ('official','unofficial','community','textbook');
 2037:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2038:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2039:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2040:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2041:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2042:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2043:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2044:     } else {
 2045:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2046:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2047:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2048:     }
 2049:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2050:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2051:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2052:         } else {
 2053:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2054:         }
 2055:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2056:         foreach my $item (@usertools) {
 2057:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2058:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2059:             }
 2060:         }
 2061:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2062:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2063:         }
 2064:     }
 2065:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2066:         foreach my $item ('official','unofficial','community','textbook') {
 2067:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2068:         }
 2069:     }
 2070:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2071:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2072:     }
 2073:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2074:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
 2075:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2076:         }
 2077:     }
 2078:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2079:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
 2080:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
 2081:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
 2082:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
 2083:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
 2084:         }
 2085:         foreach my $type (@coursetypes) {
 2086:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2087:                 unless ($type eq 'community') {
 2088:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
 2089:                 }
 2090:             }
 2091:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2092:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
 2093:             }
 2094:             if ($domdefaults{'postsubmit'} eq 'on') {
 2095:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
 2096:                     $domdefaults{$type.'postsubtimeout'} = 
 2097:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
 2098:                 }
 2099:             }
 2100:         }
 2101:     }
 2102:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2103:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2104:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2105:         }
 2106:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2107:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2108:         }
 2109:     }
 2110:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
 2111:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
 2112:             my @settings = ('types','registered','enroll_dates','access_dates','section',
 2113:                             'approval','limit');
 2114:             foreach my $type (@coursetypes) {
 2115:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
 2116:                     my @mgrdc = ();
 2117:                     foreach my $item (@settings) {
 2118:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
 2119:                             push(@mgrdc,$item);
 2120:                         }
 2121:                     }
 2122:                     if (@mgrdc) {
 2123:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
 2124:                     }
 2125:                 }
 2126:             }
 2127:         }
 2128:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
 2129:             foreach my $type (@coursetypes) {
 2130:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
 2131:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
 2132:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
 2133:                     }
 2134:                 }
 2135:             }
 2136:         }
 2137:     }
 2138:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2139:         $domdefaults{'catauth'} = 'std';
 2140:         $domdefaults{'catunauth'} = 'std';
 2141:         if ($domconfig{'coursecategories'}{'auth'}) { 
 2142:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
 2143:         }
 2144:         if ($domconfig{'coursecategories'}{'unauth'}) {
 2145:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
 2146:         }
 2147:     }
 2148:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2149:     return %domdefaults;
 2150: }
 2151: 
 2152: # --------------------------------------------------- Assign a key to a student
 2153: 
 2154: sub assign_access_key {
 2155: #
 2156: # a valid key looks like uname:udom#comments
 2157: # comments are being appended
 2158: #
 2159:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2160:     $kdom=
 2161:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2162:     $knum=
 2163:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2164:     $cdom=
 2165:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2166:     $cnum=
 2167:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2168:     $udom=$env{'user.name'} unless (defined($udom));
 2169:     $uname=$env{'user.domain'} unless (defined($uname));
 2170:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2171:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2172:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2173:                                                   # assigned to this person
 2174:                                                   # - this should not happen,
 2175:                                                   # unless something went wrong
 2176:                                                   # the first time around
 2177: # ready to assign
 2178:         $logentry=$1.'; '.$logentry;
 2179:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2180:                                                  $kdom,$knum) eq 'ok') {
 2181: # key now belongs to user
 2182: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2183:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2184:                 &appenv({'environment.'.$envkey => $ckey});
 2185:                 return 'ok';
 2186:             } else {
 2187:                 return 
 2188:   'error: Count not permanently assign key, will need to be re-entered later.';
 2189: 	    }
 2190:         } else {
 2191:             return 'error: Could not assign key, try again later.';
 2192:         }
 2193:     } elsif (!$existing{$ckey}) {
 2194: # the key does not exist
 2195: 	return 'error: The key does not exist';
 2196:     } else {
 2197: # the key is somebody else's
 2198: 	return 'error: The key is already in use';
 2199:     }
 2200: }
 2201: 
 2202: # ------------------------------------------ put an additional comment on a key
 2203: 
 2204: sub comment_access_key {
 2205: #
 2206: # a valid key looks like uname:udom#comments
 2207: # comments are being appended
 2208: #
 2209:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2210:     $cdom=
 2211:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2212:     $cnum=
 2213:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2214:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2215:     if ($existing{$ckey}) {
 2216:         $existing{$ckey}.='; '.$logentry;
 2217: # ready to assign
 2218:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2219:                                                  $cdom,$cnum) eq 'ok') {
 2220: 	    return 'ok';
 2221:         } else {
 2222: 	    return 'error: Count not store comment.';
 2223:         }
 2224:     } else {
 2225: # the key does not exist
 2226: 	return 'error: The key does not exist';
 2227:     }
 2228: }
 2229: 
 2230: # ------------------------------------------------------ Generate a set of keys
 2231: 
 2232: sub generate_access_keys {
 2233:     my ($number,$cdom,$cnum,$logentry)=@_;
 2234:     $cdom=
 2235:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2236:     $cnum=
 2237:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2238:     unless (&allowed('mky',$cdom)) { return 0; }
 2239:     unless (($cdom) && ($cnum)) { return 0; }
 2240:     if ($number>10000) { return 0; }
 2241:     sleep(2); # make sure don't get same seed twice
 2242:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2243:     my $total=0;
 2244:     for (my $i=1;$i<=$number;$i++) {
 2245:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2246:                   sprintf("%lx",int(100000*rand)).'-'.
 2247:                   sprintf("%lx",int(100000*rand));
 2248:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2249:        $newkey=~s/0/h/g; # and also 0 and O
 2250:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2251:        if ($existing{$newkey}) {
 2252:            $i--;
 2253:        } else {
 2254: 	  if (&put('accesskeys',
 2255:               { $newkey => '# generated '.localtime().
 2256:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2257:                            '; '.$logentry },
 2258: 		   $cdom,$cnum) eq 'ok') {
 2259:               $total++;
 2260: 	  }
 2261:        }
 2262:     }
 2263:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2264:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2265:     return $total;
 2266: }
 2267: 
 2268: # ------------------------------------------------------- Validate an accesskey
 2269: 
 2270: sub validate_access_key {
 2271:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2272:     $cdom=
 2273:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2274:     $cnum=
 2275:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2276:     $udom=$env{'user.domain'} unless (defined($udom));
 2277:     $uname=$env{'user.name'} unless (defined($uname));
 2278:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2279:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2280: }
 2281: 
 2282: # ------------------------------------- Find the section of student in a course
 2283: sub devalidate_getsection_cache {
 2284:     my ($udom,$unam,$courseid)=@_;
 2285:     my $hashid="$udom:$unam:$courseid";
 2286:     &devalidate_cache_new('getsection',$hashid);
 2287: }
 2288: 
 2289: sub courseid_to_courseurl {
 2290:     my ($courseid) = @_;
 2291:     #already url style courseid
 2292:     return $courseid if ($courseid =~ m{^/});
 2293: 
 2294:     if (exists($env{'course.'.$courseid.'.num'})) {
 2295: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2296: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2297: 	return "/$cdom/$cnum";
 2298:     }
 2299: 
 2300:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2301:     if (exists($courseinfo{'num'})) {
 2302: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2303:     }
 2304: 
 2305:     return undef;
 2306: }
 2307: 
 2308: sub getsection {
 2309:     my ($udom,$unam,$courseid)=@_;
 2310:     my $cachetime=1800;
 2311: 
 2312:     my $hashid="$udom:$unam:$courseid";
 2313:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2314:     if (defined($cached)) { return $result; }
 2315: 
 2316:     my %Pending; 
 2317:     my %Expired;
 2318:     #
 2319:     # Each role can either have not started yet (pending), be active, 
 2320:     #    or have expired.
 2321:     #
 2322:     # If there is an active role, we are done.
 2323:     #
 2324:     # If there is more than one role which has not started yet, 
 2325:     #     choose the one which will start sooner
 2326:     # If there is one role which has not started yet, return it.
 2327:     #
 2328:     # If there is more than one expired role, choose the one which ended last.
 2329:     # If there is a role which has expired, return it.
 2330:     #
 2331:     $courseid = &courseid_to_courseurl($courseid);
 2332:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 2333:     foreach my $key (keys(%roleshash)) {
 2334:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2335:         my $section=$1;
 2336:         if ($key eq $courseid.'_st') { $section=''; }
 2337:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2338:         my $now=time;
 2339:         if (defined($end) && $end && ($now > $end)) {
 2340:             $Expired{$end}=$section;
 2341:             next;
 2342:         }
 2343:         if (defined($start) && $start && ($now < $start)) {
 2344:             $Pending{$start}=$section;
 2345:             next;
 2346:         }
 2347:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2348:     }
 2349:     #
 2350:     # Presumedly there will be few matching roles from the above
 2351:     # loop and the sorting time will be negligible.
 2352:     if (scalar(keys(%Pending))) {
 2353:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2354:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2355:     } 
 2356:     if (scalar(keys(%Expired))) {
 2357:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2358:         my $time = pop(@sorted);
 2359:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2360:     }
 2361:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2362: }
 2363: 
 2364: sub save_cache {
 2365:     &purge_remembered();
 2366:     #&Apache::loncommon::validate_page();
 2367:     undef(%env);
 2368:     undef($env_loaded);
 2369: }
 2370: 
 2371: my $to_remember=-1;
 2372: my %remembered;
 2373: my %accessed;
 2374: my $kicks=0;
 2375: my $hits=0;
 2376: sub make_key {
 2377:     my ($name,$id) = @_;
 2378:     if (length($id) > 65 
 2379: 	&& length(&escape($id)) > 200) {
 2380: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2381:     }
 2382:     return &escape($name.':'.$id);
 2383: }
 2384: 
 2385: sub devalidate_cache_new {
 2386:     my ($name,$id,$debug) = @_;
 2387:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2388:     $id=&make_key($name,$id);
 2389:     $memcache->delete($id);
 2390:     delete($remembered{$id});
 2391:     delete($accessed{$id});
 2392: }
 2393: 
 2394: sub is_cached_new {
 2395:     my ($name,$id,$debug) = @_;
 2396:     $id=&make_key($name,$id);
 2397:     if (exists($remembered{$id})) {
 2398: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
 2399: 	$accessed{$id}=[&gettimeofday()];
 2400: 	$hits++;
 2401: 	return ($remembered{$id},1);
 2402:     }
 2403:     my $value = $memcache->get($id);
 2404:     if (!(defined($value))) {
 2405: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2406: 	return (undef,undef);
 2407:     }
 2408:     if ($value eq '__undef__') {
 2409: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2410: 	$value=undef;
 2411:     }
 2412:     &make_room($id,$value,$debug);
 2413:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2414:     return ($value,1);
 2415: }
 2416: 
 2417: sub do_cache_new {
 2418:     my ($name,$id,$value,$time,$debug) = @_;
 2419:     $id=&make_key($name,$id);
 2420:     my $setvalue=$value;
 2421:     if (!defined($setvalue)) {
 2422: 	$setvalue='__undef__';
 2423:     }
 2424:     if (!defined($time) ) {
 2425: 	$time=600;
 2426:     }
 2427:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 2428:     my $result = $memcache->set($id,$setvalue,$time);
 2429:     if (! $result) {
 2430: 	&logthis("caching of id -> $id  failed");
 2431: 	$memcache->disconnect_all();
 2432:     }
 2433:     # need to make a copy of $value
 2434:     &make_room($id,$value,$debug);
 2435:     return $value;
 2436: }
 2437: 
 2438: sub make_room {
 2439:     my ($id,$value,$debug)=@_;
 2440: 
 2441:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 2442:                                     : $value;
 2443:     if ($to_remember<0) { return; }
 2444:     $accessed{$id}=[&gettimeofday()];
 2445:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 2446:     my $to_kick;
 2447:     my $max_time=0;
 2448:     foreach my $other (keys(%accessed)) {
 2449: 	if (&tv_interval($accessed{$other}) > $max_time) {
 2450: 	    $to_kick=$other;
 2451: 	    $max_time=&tv_interval($accessed{$other});
 2452: 	}
 2453:     }
 2454:     delete($remembered{$to_kick});
 2455:     delete($accessed{$to_kick});
 2456:     $kicks++;
 2457:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 2458:     return;
 2459: }
 2460: 
 2461: sub purge_remembered {
 2462:     #&logthis("Tossing ".scalar(keys(%remembered)));
 2463:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 2464:     undef(%remembered);
 2465:     undef(%accessed);
 2466: }
 2467: # ------------------------------------- Read an entry from a user's environment
 2468: 
 2469: sub userenvironment {
 2470:     my ($udom,$unam,@what)=@_;
 2471:     my $items;
 2472:     foreach my $item (@what) {
 2473:         $items.=&escape($item).'&';
 2474:     }
 2475:     $items=~s/\&$//;
 2476:     my %returnhash=();
 2477:     my $uhome = &homeserver($unam,$udom);
 2478:     unless ($uhome eq 'no_host') {
 2479:         my @answer=split(/\&/, 
 2480:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 2481:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 2482:             return %returnhash;
 2483:         }
 2484:         my $i;
 2485:         for ($i=0;$i<=$#what;$i++) {
 2486: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 2487:         }
 2488:     }
 2489:     return %returnhash;
 2490: }
 2491: 
 2492: # ---------------------------------------------------------- Get a studentphoto
 2493: sub studentphoto {
 2494:     my ($udom,$unam,$ext) = @_;
 2495:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2496:     if (defined($env{'request.course.id'})) {
 2497:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 2498:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 2499:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 2500:             } else {
 2501:                 my ($result,$perm_reqd)=
 2502: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2503:                 if ($result eq 'ok') {
 2504:                     if (!($perm_reqd eq 'yes')) {
 2505:                         return(&retrievestudentphoto($udom,$unam,$ext));
 2506:                     }
 2507:                 }
 2508:             }
 2509:         }
 2510:     } else {
 2511:         my ($result,$perm_reqd) = 
 2512: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2513:         if ($result eq 'ok') {
 2514:             if (!($perm_reqd eq 'yes')) {
 2515:                 return(&retrievestudentphoto($udom,$unam,$ext));
 2516:             }
 2517:         }
 2518:     }
 2519:     return '/adm/lonKaputt/lonlogo_broken.gif';
 2520: }
 2521: 
 2522: sub retrievestudentphoto {
 2523:     my ($udom,$unam,$ext,$type) = @_;
 2524:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2525:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 2526:     if ($ret eq 'ok') {
 2527:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 2528:         if ($type eq 'thumbnail') {
 2529:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 2530:         }
 2531:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 2532:         return $tokenurl;
 2533:     } else {
 2534:         if ($type eq 'thumbnail') {
 2535:             return '/adm/lonKaputt/genericstudent_tn.gif';
 2536:         } else { 
 2537:             return '/adm/lonKaputt/lonlogo_broken.gif';
 2538:         }
 2539:     }
 2540: }
 2541: 
 2542: # -------------------------------------------------------------------- New chat
 2543: 
 2544: sub chatsend {
 2545:     my ($newentry,$anon,$group)=@_;
 2546:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 2547:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2548:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 2549:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 2550: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 2551: 		   &escape($newentry)).':'.$group,$chome);
 2552: }
 2553: 
 2554: # ------------------------------------------ Find current version of a resource
 2555: 
 2556: sub getversion {
 2557:     my $fname=&clutter(shift);
 2558:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 2559:     return &currentversion(&filelocation('',$fname));
 2560: }
 2561: 
 2562: sub currentversion {
 2563:     my $fname=shift;
 2564:     my $author=$fname;
 2565:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2566:     my ($udom,$uname)=split(/\//,$author);
 2567:     my $home=&homeserver($uname,$udom);
 2568:     if ($home eq 'no_host') { 
 2569:         return -1; 
 2570:     }
 2571:     my $answer=&reply("currentversion:$fname",$home);
 2572:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2573: 	return -1;
 2574:     }
 2575:     return $answer;
 2576: }
 2577: 
 2578: #
 2579: # Return special version number of resource if set by override, empty otherwise
 2580: #
 2581: sub usedversion {
 2582:     my $fname=shift;
 2583:     unless ($fname) { $fname=$env{'request.uri'}; }
 2584:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 2585:     if ($urlversion) { return $urlversion; }
 2586:     return '';
 2587: }
 2588: 
 2589: # ----------------------------- Subscribe to a resource, return URL if possible
 2590: 
 2591: sub subscribe {
 2592:     my $fname=shift;
 2593:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 2594:     $fname=~s/[\n\r]//g;
 2595:     my $author=$fname;
 2596:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2597:     my ($udom,$uname)=split(/\//,$author);
 2598:     my $home=homeserver($uname,$udom);
 2599:     if ($home eq 'no_host') {
 2600:         return 'not_found';
 2601:     }
 2602:     my $answer=reply("sub:$fname",$home);
 2603:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2604: 	$answer.=' by '.$home;
 2605:     }
 2606:     return $answer;
 2607: }
 2608:     
 2609: # -------------------------------------------------------------- Replicate file
 2610: 
 2611: sub repcopy {
 2612:     my $filename=shift;
 2613:     $filename=~s/\/+/\//g;
 2614:     my $londocroot = $perlvar{'lonDocRoot'};
 2615:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 2616:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 2617:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 2618: 	$filename=~m{^/*(uploaded|editupload)/}) {
 2619: 	return &repcopy_userfile($filename);
 2620:     }
 2621:     $filename=~s/[\n\r]//g;
 2622:     my $transname="$filename.in.transfer";
 2623: # FIXME: this should flock
 2624:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 2625:     my $remoteurl=subscribe($filename);
 2626:     if ($remoteurl =~ /^con_lost by/) {
 2627: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2628:            return 'unavailable';
 2629:     } elsif ($remoteurl eq 'not_found') {
 2630: 	   #&logthis("Subscribe returned not_found: $filename");
 2631: 	   return 'not_found';
 2632:     } elsif ($remoteurl =~ /^rejected by/) {
 2633: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2634:            return 'forbidden';
 2635:     } elsif ($remoteurl eq 'directory') {
 2636:            return 'ok';
 2637:     } else {
 2638:         my $author=$filename;
 2639:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2640:         my ($udom,$uname)=split(/\//,$author);
 2641:         my $home=homeserver($uname,$udom);
 2642:         unless ($home eq $perlvar{'lonHostID'}) {
 2643:            my @parts=split(/\//,$filename);
 2644:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 2645:            if ($path ne "$londocroot/res") {
 2646:                &logthis("Malconfiguration for replication: $filename");
 2647: 	       return 'bad_request';
 2648:            }
 2649:            my $count;
 2650:            for ($count=5;$count<$#parts;$count++) {
 2651:                $path.="/$parts[$count]";
 2652:                if ((-e $path)!=1) {
 2653: 		   mkdir($path,0777);
 2654:                }
 2655:            }
 2656:            my $ua=new LWP::UserAgent;
 2657:            my $request=new HTTP::Request('GET',"$remoteurl");
 2658:            my $response=$ua->request($request,$transname);
 2659:            if ($response->is_error()) {
 2660: 	       unlink($transname);
 2661:                my $message=$response->status_line;
 2662:                &logthis("<font color=\"blue\">WARNING:"
 2663:                        ." LWP get: $message: $filename</font>");
 2664:                return 'unavailable';
 2665:            } else {
 2666: 	       if ($remoteurl!~/\.meta$/) {
 2667:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 2668:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 2669:                   if ($mresponse->is_error()) {
 2670: 		      unlink($filename.'.meta');
 2671:                       &logthis(
 2672:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 2673:                   }
 2674: 	       }
 2675:                rename($transname,$filename);
 2676:                return 'ok';
 2677:            }
 2678:        }
 2679:     }
 2680: }
 2681: 
 2682: # ------------------------------------------------ Get server side include body
 2683: sub ssi_body {
 2684:     my ($filelink,%form)=@_;
 2685:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 2686:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 2687:     }
 2688:     my $output='';
 2689:     my $response;
 2690:     if ($filelink=~/^https?\:/) {
 2691:        ($output,$response)=&externalssi($filelink);
 2692:     } else {
 2693:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 2694:        $filelink .= 'inhibitmenu=yes';
 2695:        ($output,$response)=&ssi($filelink,%form);
 2696:     }
 2697:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 2698:     $output=~s/^.*?\<body[^\>]*\>//si;
 2699:     $output=~s/\<\/body\s*\>.*?$//si;
 2700:     if (wantarray) {
 2701:         return ($output, $response);
 2702:     } else {
 2703:         return $output;
 2704:     }
 2705: }
 2706: 
 2707: # --------------------------------------------------------- Server Side Include
 2708: 
 2709: sub absolute_url {
 2710:     my ($host_name) = @_;
 2711:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 2712:     if ($host_name eq '') {
 2713: 	$host_name = $ENV{'SERVER_NAME'};
 2714:     }
 2715:     return $protocol.$host_name;
 2716: }
 2717: 
 2718: #
 2719: #   Server side include.
 2720: # Parameters:
 2721: #  fn     Possibly encrypted resource name/id.
 2722: #  form   Hash that describes how the rendering should be done
 2723: #         and other things.
 2724: # Returns:
 2725: #   Scalar context: The content of the response.
 2726: #   Array context:  2 element list of the content and the full response object.
 2727: #     
 2728: sub ssi {
 2729: 
 2730:     my ($fn,%form)=@_;
 2731:     my $ua=new LWP::UserAgent;
 2732:     my $request;
 2733: 
 2734:     $form{'no_update_last_known'}=1;
 2735:     &Apache::lonenc::check_encrypt(\$fn);
 2736:     if (%form) {
 2737:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 2738:       $request->content(join('&',map { 
 2739:             my $name = escape($_);
 2740:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
 2741:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
 2742:             : &escape($form{$_}) );    
 2743:         } keys(%form)));
 2744:     } else {
 2745:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 2746:     }
 2747: 
 2748:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 2749:     my $response= $ua->request($request);
 2750:     my $content = $response->content;
 2751: 
 2752: 
 2753:     if (wantarray) {
 2754: 	return ($content, $response);
 2755:     } else {
 2756: 	return $content;
 2757:     }
 2758: }
 2759: 
 2760: sub externalssi {
 2761:     my ($url)=@_;
 2762:     my $ua=new LWP::UserAgent;
 2763:     my $request=new HTTP::Request('GET',$url);
 2764:     my $response=$ua->request($request);
 2765:     if (wantarray) {
 2766:         return ($response->content, $response);
 2767:     } else {
 2768:         return $response->content;
 2769:     }
 2770: }
 2771: 
 2772: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 2773: 
 2774: sub allowuploaded {
 2775:     my ($srcurl,$url)=@_;
 2776:     $url=&clutter(&declutter($url));
 2777:     my $dir=$url;
 2778:     $dir=~s/\/[^\/]+$//;
 2779:     my %httpref=();
 2780:     my $httpurl=&hreflocation('',$url);
 2781:     $httpref{'httpref.'.$httpurl}=$srcurl;
 2782:     &Apache::lonnet::appenv(\%httpref);
 2783: }
 2784: 
 2785: #
 2786: # Determine if the current user should be able to edit a particular resource,
 2787: # when viewing in course context.
 2788: # (a) When viewing resource used to determine if "Edit" item is included in 
 2789: #     Functions.
 2790: # (b) When displaying folder contents in course editor, used to determine if
 2791: #     "Edit" link will be displayed alongside resource.
 2792: #
 2793: #  input: six args -- filename (decluttered), course number, course domain,
 2794: #                   url, symb (if registered) and group (if this is a group
 2795: #                   item -- e.g., bulletin board, group page etc.).
 2796: #  output: array of five scalars -- 
 2797: #          $cfile -- url for file editing if editable on current server
 2798: #          $home -- homeserver of resource (i.e., for author if published,
 2799: #                                           or course if uploaded.).
 2800: #          $switchserver --  1 if server switch will be needed.
 2801: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 2802: #          $forceview -- 1 if icon/link should be to go to view mode
 2803: #
 2804: 
 2805: sub can_edit_resource {
 2806:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 2807:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 2808: #
 2809: # For aboutme pages user can only edit his/her own.
 2810: #
 2811:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 2812:         my ($sdom,$sname) = ($1,$2);
 2813:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 2814:             $home = $env{'user.home'};
 2815:             $cfile = $resurl;
 2816:             if ($env{'form.forceedit'}) {
 2817:                 $forceview = 1;
 2818:             } else {
 2819:                 $forceedit = 1;
 2820:             }
 2821:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 2822:         } else {
 2823:             return;
 2824:         }
 2825:     }
 2826: 
 2827:     if ($env{'request.course.id'}) {
 2828:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 2829:         if ($group ne '') {
 2830: # if this is a group homepage or group bulletin board, check group privs
 2831:             my $allowed = 0;
 2832:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 2833:                 if ((&allowed('mdg',$env{'request.course.id'}.
 2834:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 2835:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 2836:                     $allowed = 1;
 2837:                 }
 2838:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 2839:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 2840:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 2841:                     $allowed = 1;
 2842:                 }
 2843:             }
 2844:             if ($allowed) {
 2845:                 $home=&homeserver($cnum,$cdom);
 2846:                 if ($env{'form.forceedit'}) {
 2847:                     $forceview = 1;
 2848:                 } else {
 2849:                     $forceedit = 1;
 2850:                 }
 2851:                 $cfile = $resurl;
 2852:             } else {
 2853:                 return;
 2854:             }
 2855:         } else {
 2856:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 2857:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 2858:                     return;
 2859:                 }
 2860:             } elsif (!$crsedit) {
 2861: #
 2862: # No edit allowed where CC has switched to student role.
 2863: #
 2864:                 return;
 2865:             }
 2866:         }
 2867:     }
 2868: 
 2869:     if ($file ne '') {
 2870:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 2871:             if (&is_course_upload($file,$cnum,$cdom)) {
 2872:                 $uploaded = 1;
 2873:                 $incourse = 1;
 2874:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 2875:                     $cfile = &hreflocation('',$file);
 2876:                     if ($env{'form.forceedit'}) {
 2877:                         $forceview = 1;
 2878:                     } else {
 2879:                         $forceedit = 1;
 2880:                     }
 2881:                 }
 2882:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 2883:                 $incourse = 1;
 2884:                 if ($env{'form.forceedit'}) {
 2885:                     $forceview = 1;
 2886:                 } else {
 2887:                     $forceedit = 1;
 2888:                 }
 2889:                 $cfile = $resurl;
 2890:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 2891:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 2892:                     $incourse = 1;
 2893:                     if ($env{'form.forceedit'}) {
 2894:                         $forceview = 1;
 2895:                     } else {
 2896:                         $forceedit = 1;
 2897:                     }
 2898:                     $cfile = $resurl;
 2899:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 2900:                     $incourse = 1;
 2901:                     $cfile = $resurl.'/smpedit';
 2902:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 2903:                     $incourse = 1;
 2904:                     if ($env{'form.forceedit'}) {
 2905:                         $forceview = 1;
 2906:                     } else {
 2907:                         $forceedit = 1;
 2908:                     }
 2909:                     $cfile = $resurl;
 2910:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 2911:                     $incourse = 1;
 2912:                     if ($env{'form.forceedit'}) {
 2913:                         $forceview = 1;
 2914:                     } else {
 2915:                         $forceedit = 1;
 2916:                     }
 2917:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 2918:                 }
 2919:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 2920:                 my $template = '/res/lib/templates/simpleproblem.problem';
 2921:                 if (&is_on_map($template)) { 
 2922:                     $incourse = 1;
 2923:                     $forceview = 1;
 2924:                     $cfile = $template;
 2925:                 }
 2926:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 2927:                     $incourse = 1;
 2928:                     if ($env{'form.forceedit'}) {
 2929:                         $forceview = 1;
 2930:                     } else {
 2931:                         $forceedit = 1;
 2932:                     }
 2933:                     $cfile = $resurl;
 2934:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 2935:                 $incourse = 1;
 2936:                 $forceview = 1;
 2937:                 if ($symb) {
 2938:                     my ($map,$id,$res)=&decode_symb($symb);
 2939:                     $env{'request.symb'} = $symb;
 2940:                     $cfile = &clutter($res);
 2941:                 } else {
 2942:                     $cfile = $env{'form.suppurl'};
 2943:                     $cfile =~ s{^http://}{};
 2944:                     $cfile = '/adm/wrapper/ext/'.$cfile;
 2945:                 }
 2946:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 2947:                 if ($env{'form.forceedit'}) {
 2948:                     $forceview = 1;
 2949:                 } else {
 2950:                     $forceedit = 1;
 2951:                 }
 2952:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 2953:             }
 2954:         }
 2955:         if ($uploaded || $incourse) {
 2956:             $home=&homeserver($cnum,$cdom);
 2957:         } elsif ($file !~ m{/$}) {
 2958:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 2959:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 2960:             # Check that the user has permission to edit this resource
 2961:             my $setpriv = 1;
 2962:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 2963:             if (defined($cfudom)) {
 2964:                 $home=&homeserver($cfuname,$cfudom);
 2965:                 $cfile=$file;
 2966:             }
 2967:         }
 2968:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 2969:             (($home ne '') && ($home ne 'no_host'))) {
 2970:             my @ids=&current_machine_ids();
 2971:             unless (grep(/^\Q$home\E$/,@ids)) {
 2972:                 $switchserver=1;
 2973:             }
 2974:         }
 2975:     }
 2976:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 2977: }
 2978: 
 2979: sub is_course_upload {
 2980:     my ($file,$cnum,$cdom) = @_;
 2981:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 2982:     $uploadpath =~ s{^\/}{};
 2983:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 2984:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 2985:         return 1;
 2986:     }
 2987:     return;
 2988: }
 2989: 
 2990: sub in_course {
 2991:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 2992:     if ($hideprivileged) {
 2993:         my $skipuser;
 2994:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 2995:         my @possdoms = ($cdom);  
 2996:         if ($coursehash{'checkforpriv'}) { 
 2997:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 2998:         }
 2999:         if (&privileged($uname,$udom,\@possdoms)) {
 3000:             $skipuser = 1;
 3001:             if ($coursehash{'nothideprivileged'}) {
 3002:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3003:                     my $user;
 3004:                     if ($item =~ /:/) {
 3005:                         $user = $item;
 3006:                     } else {
 3007:                         $user = join(':',split(/[\@]/,$item));
 3008:                     }
 3009:                     if ($user eq $uname.':'.$udom) {
 3010:                         undef($skipuser);
 3011:                         last;
 3012:                     }
 3013:                 }
 3014:             }
 3015:             if ($skipuser) {
 3016:                 return 0;
 3017:             }
 3018:         }
 3019:     }
 3020:     $type ||= 'any';
 3021:     if (!defined($cdom) || !defined($cnum)) {
 3022:         my $cid  = $env{'request.course.id'};
 3023:         $cdom = $env{'course.'.$cid.'.domain'};
 3024:         $cnum = $env{'course.'.$cid.'.num'};
 3025:     }
 3026:     my $typesref;
 3027:     if (($type eq 'any') || ($type eq 'all')) {
 3028:         $typesref = ['active','previous','future'];
 3029:     } elsif ($type eq 'previous' || $type eq 'future') {
 3030:         $typesref = [$type];
 3031:     }
 3032:     my %roles = &get_my_roles($uname,$udom,'userroles',
 3033:                               $typesref,undef,[$cdom]);
 3034:     my ($tmp) = keys(%roles);
 3035:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 3036:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 3037:     if (@course_roles > 0) {
 3038:         return 1;
 3039:     }
 3040:     return 0;
 3041: }
 3042: 
 3043: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 3044: # input: action, courseID, current domain, intended
 3045: #        path to file, source of file, instruction to parse file for objects,
 3046: #        ref to hash for embedded objects,
 3047: #        ref to hash for codebase of java objects.
 3048: #        reference to scalar to accommodate mime type determined
 3049: #          from File::MMagic if $parser = parse.
 3050: #
 3051: # output: url to file (if action was uploaddoc), 
 3052: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 3053: #
 3054: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 3055: # course.
 3056: #
 3057: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3058: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 3059: #          course's home server.
 3060: #
 3061: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 3062: #          be copied from $source (current location) to 
 3063: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3064: #         and will then be copied to
 3065: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 3066: #         course's home server.
 3067: #
 3068: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3069: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 3070: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3071: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 3072: #         in course's home server.
 3073: #
 3074: 
 3075: sub process_coursefile {
 3076:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 3077:         $mimetype)=@_;
 3078:     my $fetchresult;
 3079:     my $home=&homeserver($docuname,$docudom);
 3080:     if ($action eq 'propagate') {
 3081:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3082: 			     $home);
 3083:     } else {
 3084:         my $fpath = '';
 3085:         my $fname = $file;
 3086:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3087:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3088:         my $filepath = &build_filepath($fpath);
 3089:         if ($action eq 'copy') {
 3090:             if ($source eq '') {
 3091:                 $fetchresult = 'no source file';
 3092:                 return $fetchresult;
 3093:             } else {
 3094:                 my $destination = $filepath.'/'.$fname;
 3095:                 rename($source,$destination);
 3096:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3097:                                  $home);
 3098:             }
 3099:         } elsif ($action eq 'uploaddoc') {
 3100:             open(my $fh,'>'.$filepath.'/'.$fname);
 3101:             print $fh $env{'form.'.$source};
 3102:             close($fh);
 3103:             if ($parser eq 'parse') {
 3104:                 my $mm = new File::MMagic;
 3105:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 3106:                 if ($type eq 'text/html') {
 3107:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 3108:                     unless ($parse_result eq 'ok') {
 3109:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 3110:                     }
 3111:                 }
 3112:                 if (ref($mimetype)) {
 3113:                     $$mimetype = $type;
 3114:                 } 
 3115:             }
 3116:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3117:                                  $home);
 3118:             if ($fetchresult eq 'ok') {
 3119:                 return '/uploaded/'.$fpath.'/'.$fname;
 3120:             } else {
 3121:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3122:                         ' to host '.$home.': '.$fetchresult);
 3123:                 return '/adm/notfound.html';
 3124:             }
 3125:         }
 3126:     }
 3127:     unless ( $fetchresult eq 'ok') {
 3128:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3129:              ' to host '.$home.': '.$fetchresult);
 3130:     }
 3131:     return $fetchresult;
 3132: }
 3133: 
 3134: sub build_filepath {
 3135:     my ($fpath) = @_;
 3136:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 3137:     unless ($fpath eq '') {
 3138:         my @parts=split('/',$fpath);
 3139:         foreach my $part (@parts) {
 3140:             $filepath.= '/'.$part;
 3141:             if ((-e $filepath)!=1) {
 3142:                 mkdir($filepath,0777);
 3143:             }
 3144:         }
 3145:     }
 3146:     return $filepath;
 3147: }
 3148: 
 3149: sub store_edited_file {
 3150:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 3151:     my $file = $primary_url;
 3152:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 3153:     my $fpath = '';
 3154:     my $fname = $file;
 3155:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3156:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3157:     my $filepath = &build_filepath($fpath);
 3158:     open(my $fh,'>'.$filepath.'/'.$fname);
 3159:     print $fh $content;
 3160:     close($fh);
 3161:     my $home=&homeserver($docuname,$docudom);
 3162:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3163: 			  $home);
 3164:     if ($$fetchresult eq 'ok') {
 3165:         return '/uploaded/'.$fpath.'/'.$fname;
 3166:     } else {
 3167:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3168: 		 ' to host '.$home.': '.$$fetchresult);
 3169:         return '/adm/notfound.html';
 3170:     }
 3171: }
 3172: 
 3173: sub clean_filename {
 3174:     my ($fname,$args)=@_;
 3175: # Replace Windows backslashes by forward slashes
 3176:     $fname=~s/\\/\//g;
 3177:     if (!$args->{'keep_path'}) {
 3178:         # Get rid of everything but the actual filename
 3179: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 3180:     }
 3181: # Replace spaces by underscores
 3182:     $fname=~s/\s+/\_/g;
 3183: # Replace all other weird characters by nothing
 3184:     $fname=~s{[^/\w\.\-]}{}g;
 3185: # Replace all .\d. sequences with _\d. so they no longer look like version
 3186: # numbers
 3187:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 3188:     return $fname;
 3189: }
 3190: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 3191: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 3192: # image with the same aspect ratio as the original, but with dimensions which do 
 3193: # not exceed $resizewidth and $resizeheight.
 3194:  
 3195: sub resizeImage {
 3196:     my ($img_path,$resizewidth,$resizeheight) = @_;
 3197:     my $ima = Image::Magick->new;
 3198:     my $resized;
 3199:     if (-e $img_path) {
 3200:         $ima->Read($img_path);
 3201:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 3202:             my $width = $ima->Get('width');
 3203:             my $height = $ima->Get('height');
 3204:             if ($width > $resizewidth) {
 3205: 	        my $factor = $width/$resizewidth;
 3206:                 my $newheight = $height/$factor;
 3207:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 3208:                 $resized = 1;
 3209:             }
 3210:         }
 3211:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 3212:             my $width = $ima->Get('width');
 3213:             my $height = $ima->Get('height');
 3214:             if ($height > $resizeheight) {
 3215:                 my $factor = $height/$resizeheight;
 3216:                 my $newwidth = $width/$factor;
 3217:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 3218:                 $resized = 1;
 3219:             }
 3220:         }
 3221:         if ($resized) {
 3222:             $ima->Write($img_path);
 3223:         }
 3224:     }
 3225:     return;
 3226: }
 3227: 
 3228: # --------------- Take an uploaded file and put it into the userfiles directory
 3229: # input: $formname - the contents of the file are in $env{"form.$formname"}
 3230: #                    the desired filename is in $env{"form.$formname.filename"}
 3231: #        $context - possible values: coursedoc, existingfile, overwrite, 
 3232: #                                    canceloverwrite, or ''. 
 3233: #                   if 'coursedoc': upload to the current course
 3234: #                   if 'existingfile': write file to tmp/overwrites directory 
 3235: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 3236: #                   $context is passed as argument to &finishuserfileupload
 3237: #        $subdir - directory in userfile to store the file into
 3238: #        $parser - instruction to parse file for objects ($parser = parse)    
 3239: #        $allfiles - reference to hash for embedded objects
 3240: #        $codebase - reference to hash for codebase of java objects
 3241: #        $desuname - username for permanent storage of uploaded file
 3242: #        $dsetudom - domain for permanaent storage of uploaded file
 3243: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 3244: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 3245: #        $resizewidth - width (pixels) to which to resize uploaded image
 3246: #        $resizeheight - height (pixels) to which to resize uploaded image
 3247: #        $mimetype - reference to scalar to accommodate mime type determined
 3248: #                    from File::MMagic.
 3249: # 
 3250: # output: url of file in userspace, or error: <message> 
 3251: #             or /adm/notfound.html if failure to upload occurse
 3252: 
 3253: sub userfileupload {
 3254:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 3255:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 3256:     if (!defined($subdir)) { $subdir='unknown'; }
 3257:     my $fname=$env{'form.'.$formname.'.filename'};
 3258:     $fname=&clean_filename($fname);
 3259:     # See if there is anything left
 3260:     unless ($fname) { return 'error: no uploaded file'; }
 3261:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 3262:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 3263:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 3264:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3265:         my $now = time;
 3266:         my $filepath;
 3267:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 3268:              $filepath = 'tmp/helprequests/'.$now;
 3269:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 3270:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 3271:                          '_'.$env{'user.domain'}.'/pending';
 3272:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3273:             my ($docuname,$docudom);
 3274:             if ($destudom) {
 3275:                 $docudom = $destudom;
 3276:             } else {
 3277:                 $docudom = $env{'user.domain'};
 3278:             }
 3279:             if ($destuname) {
 3280:                 $docuname = $destuname;
 3281:             } else {
 3282:                 $docuname = $env{'user.name'};
 3283:             }
 3284:             if (exists($env{'form.group'})) {
 3285:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3286:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3287:             }
 3288:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 3289:             if ($context eq 'canceloverwrite') {
 3290:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 3291:                 if (-e  $tempfile) {
 3292:                     my @info = stat($tempfile);
 3293:                     if ($info[9] eq $env{'form.timestamp'}) {
 3294:                         unlink($tempfile);
 3295:                     }
 3296:                 }
 3297:                 return;
 3298:             }
 3299:         }
 3300:         # Create the directory if not present
 3301:         my @parts=split(/\//,$filepath);
 3302:         my $fullpath = $perlvar{'lonDaemons'};
 3303:         for (my $i=0;$i<@parts;$i++) {
 3304:             $fullpath .= '/'.$parts[$i];
 3305:             if ((-e $fullpath)!=1) {
 3306:                 mkdir($fullpath,0777);
 3307:             }
 3308:         }
 3309:         open(my $fh,'>'.$fullpath.'/'.$fname);
 3310:         print $fh $env{'form.'.$formname};
 3311:         close($fh);
 3312:         if ($context eq 'existingfile') {
 3313:             my @info = stat($fullpath.'/'.$fname);
 3314:             return ($fullpath.'/'.$fname,$info[9]);
 3315:         } else {
 3316:             return $fullpath.'/'.$fname;
 3317:         }
 3318:     }
 3319:     if ($subdir eq 'scantron') {
 3320:         $fname = 'scantron_orig_'.$fname;
 3321:     } else {
 3322:         $fname="$subdir/$fname";
 3323:     }
 3324:     if ($context eq 'coursedoc') {
 3325: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3326: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3327:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 3328:             return &finishuserfileupload($docuname,$docudom,
 3329: 					 $formname,$fname,$parser,$allfiles,
 3330: 					 $codebase,$thumbwidth,$thumbheight,
 3331:                                          $resizewidth,$resizeheight,$context,$mimetype);
 3332:         } else {
 3333:             if ($env{'form.folder'}) {
 3334:                 $fname=$env{'form.folder'}.'/'.$fname;
 3335:             }
 3336:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 3337: 				       $fname,$formname,$parser,
 3338: 				       $allfiles,$codebase,$mimetype);
 3339:         }
 3340:     } elsif (defined($destuname)) {
 3341:         my $docuname=$destuname;
 3342:         my $docudom=$destudom;
 3343: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3344: 				     $parser,$allfiles,$codebase,
 3345:                                      $thumbwidth,$thumbheight,
 3346:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3347:     } else {
 3348:         my $docuname=$env{'user.name'};
 3349:         my $docudom=$env{'user.domain'};
 3350:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 3351:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3352:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3353:         }
 3354: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3355: 				     $parser,$allfiles,$codebase,
 3356:                                      $thumbwidth,$thumbheight,
 3357:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3358:     }
 3359: }
 3360: 
 3361: sub finishuserfileupload {
 3362:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 3363:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 3364:     my $path=$docudom.'/'.$docuname.'/';
 3365:     my $filepath=$perlvar{'lonDocRoot'};
 3366:   
 3367:     my ($fnamepath,$file,$fetchthumb);
 3368:     $file=$fname;
 3369:     if ($fname=~m|/|) {
 3370:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 3371: 	$path.=$fnamepath.'/';
 3372:     }
 3373:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 3374:     my $count;
 3375:     for ($count=4;$count<=$#parts;$count++) {
 3376:         $filepath.="/$parts[$count]";
 3377:         if ((-e $filepath)!=1) {
 3378: 	    mkdir($filepath,0777);
 3379:         }
 3380:     }
 3381: 
 3382: # Save the file
 3383:     {
 3384: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 3385: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 3386: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 3387: 	    return '/adm/notfound.html';
 3388: 	}
 3389:         if ($context eq 'overwrite') {
 3390:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 3391:             my $target = $filepath.'/'.$file;
 3392:             if (-e $source) {
 3393:                 my @info = stat($source);
 3394:                 if ($info[9] eq $env{'form.timestamp'}) {   
 3395:                     unless (&File::Copy::move($source,$target)) {
 3396:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 3397:                         return "Moving from $source failed";
 3398:                     }
 3399:                 } else {
 3400:                     return "Temporary file: $source had unexpected date/time for last modification";
 3401:                 }
 3402:             } else {
 3403:                 return "Temporary file: $source missing";
 3404:             }
 3405:         } elsif (!print FH ($env{'form.'.$formname})) {
 3406: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 3407: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 3408: 	    return '/adm/notfound.html';
 3409: 	}
 3410: 	close(FH);
 3411:         if ($resizewidth && $resizeheight) {
 3412:             my $mm = new File::MMagic;
 3413:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 3414:             if ($mime_type =~ m{^image/}) {
 3415: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 3416:             }  
 3417: 	}
 3418:     }
 3419:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 3420:         if (ref($mimetype)) {
 3421:             if ($$mimetype eq '') {
 3422:                 my $mm = new File::MMagic;
 3423:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 3424:                 $$mimetype = $type;
 3425:             }
 3426:         }
 3427:     }
 3428:     if ($parser eq 'parse') {
 3429:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 3430:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 3431:                                                        $allfiles,$codebase);
 3432:             unless ($parse_result eq 'ok') {
 3433:                 &logthis('Failed to parse '.$filepath.$file.
 3434: 	   	         ' for embedded media: '.$parse_result); 
 3435:             }
 3436:         }
 3437:     }
 3438:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 3439:         my $input = $filepath.'/'.$file;
 3440:         my $output = $filepath.'/'.'tn-'.$file;
 3441:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 3442:         system("convert -sample $thumbsize $input $output");
 3443:         if (-e $filepath.'/'.'tn-'.$file) {
 3444:             $fetchthumb  = 1; 
 3445:         }
 3446:     }
 3447:  
 3448: # Notify homeserver to grep it
 3449: #
 3450:     my $docuhome=&homeserver($docuname,$docudom);	
 3451:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 3452:     if ($fetchresult eq 'ok') {
 3453:         if ($fetchthumb) {
 3454:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 3455:             if ($thumbresult ne 'ok') {
 3456:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 3457:                          $docuhome.': '.$thumbresult);
 3458:             }
 3459:         }
 3460: #
 3461: # Return the URL to it
 3462:         return '/uploaded/'.$path.$file;
 3463:     } else {
 3464:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 3465: 		 ': '.$fetchresult);
 3466:         return '/adm/notfound.html';
 3467:     }
 3468: }
 3469: 
 3470: sub extract_embedded_items {
 3471:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 3472:     my @state = ();
 3473:     my (%lastids,%related,%shockwave,%flashvars);
 3474:     my %javafiles = (
 3475:                       codebase => '',
 3476:                       code => '',
 3477:                       archive => ''
 3478:                     );
 3479:     my %mediafiles = (
 3480:                       src => '',
 3481:                       movie => '',
 3482:                      );
 3483:     my $p;
 3484:     if ($content) {
 3485:         $p = HTML::LCParser->new($content);
 3486:     } else {
 3487:         $p = HTML::LCParser->new($fullpath);
 3488:     }
 3489:     while (my $t=$p->get_token()) {
 3490: 	if ($t->[0] eq 'S') {
 3491: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 3492: 	    push(@state, $tagname);
 3493:             if (lc($tagname) eq 'allow') {
 3494:                 &add_filetype($allfiles,$attr->{'src'},'src');
 3495:             }
 3496: 	    if (lc($tagname) eq 'img') {
 3497: 		&add_filetype($allfiles,$attr->{'src'},'src');
 3498: 	    }
 3499: 	    if (lc($tagname) eq 'a') {
 3500:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 3501:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3502:                 }
 3503: 	    }
 3504:             if (lc($tagname) eq 'script') {
 3505:                 my $src;
 3506:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 3507:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 3508:                 } else {
 3509:                     if ($attr->{'src'} ne '') {
 3510:                         $src = $attr->{'src'};
 3511:                         &add_filetype($allfiles,$src,'src');
 3512:                     }
 3513:                 }
 3514:                 my $text = $p->get_trimmed_text();
 3515:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 3516:                     my @swfargs = split(/,/,$1);
 3517:                     foreach my $item (@swfargs) {
 3518:                         $item =~ s/["']//g;
 3519:                         $item =~ s/^\s+//;
 3520:                         $item =~ s/\s+$//;
 3521:                     }
 3522:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 3523:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 3524:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 3525:                         } else {
 3526:                             $related{$swfargs[0]} = [$swfargs[2]];
 3527:                         }
 3528:                     }
 3529:                 }
 3530:             }
 3531:             if (lc($tagname) eq 'link') {
 3532:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 3533:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3534:                 }
 3535:             }
 3536: 	    if (lc($tagname) eq 'object' ||
 3537: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 3538: 		foreach my $item (keys(%javafiles)) {
 3539: 		    $javafiles{$item} = '';
 3540: 		}
 3541:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 3542:                     $lastids{lc($tagname)} = $attr->{'id'};
 3543:                 }
 3544: 	    }
 3545: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 3546: 		my $name = lc($attr->{'name'});
 3547: 		foreach my $item (keys(%javafiles)) {
 3548: 		    if ($name eq $item) {
 3549: 			$javafiles{$item} = $attr->{'value'};
 3550: 			last;
 3551: 		    }
 3552: 		}
 3553:                 my $pathfrom;
 3554: 		foreach my $item (keys(%mediafiles)) {
 3555: 		    if ($name eq $item) {
 3556:                         $pathfrom = $attr->{'value'};
 3557:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 3558: 			&add_filetype($allfiles,$pathfrom,$name);
 3559: 			last;
 3560: 		    }
 3561: 		}
 3562:                 if ($name eq 'flashvars') {
 3563:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 3564:                 }
 3565:                 if ($pathfrom ne '') {
 3566:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 3567:                                          $pathfrom);
 3568:                 }
 3569: 	    }
 3570: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 3571: 		foreach my $item (keys(%javafiles)) {
 3572: 		    if ($attr->{$item}) {
 3573: 			$javafiles{$item} = $attr->{$item};
 3574: 			last;
 3575: 		    }
 3576: 		}
 3577: 		foreach my $item (keys(%mediafiles)) {
 3578: 		    if ($attr->{$item}) {
 3579: 			&add_filetype($allfiles,$attr->{$item},$item);
 3580: 			last;
 3581: 		    }
 3582: 		}
 3583:                 if (lc($tagname) eq 'embed') {
 3584:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 3585:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 3586:                                              $attr->{'src'});
 3587:                     }
 3588:                 }
 3589: 	    }
 3590:             if (lc($tagname) eq 'iframe') {
 3591:                 my $src = $attr->{'src'} ;
 3592:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 3593:                     &add_filetype($allfiles,$src,'src');
 3594:                 } elsif ($src =~ m{^/}) {
 3595:                     if ($env{'request.course.id'}) {
 3596:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3597:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3598:                         my $url = &hreflocation('',$fullpath);
 3599:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 3600:                             my $relpath = $1;
 3601:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 3602:                                 &add_filetype($allfiles,$1,'src');
 3603:                             }
 3604:                         }
 3605:                     }
 3606:                 }
 3607:             }
 3608:             if ($t->[4] =~ m{/>$}) {
 3609:                 pop(@state);
 3610:             }
 3611: 	} elsif ($t->[0] eq 'E') {
 3612: 	    my ($tagname) = ($t->[1]);
 3613: 	    if ($javafiles{'codebase'} ne '') {
 3614: 		$javafiles{'codebase'} .= '/';
 3615: 	    }  
 3616: 	    if (lc($tagname) eq 'applet' ||
 3617: 		lc($tagname) eq 'object' ||
 3618: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 3619: 		) {
 3620: 		foreach my $item (keys(%javafiles)) {
 3621: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 3622: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 3623: 			&add_filetype($allfiles,$file,$item);
 3624: 		    }
 3625: 		}
 3626: 	    } 
 3627: 	    pop @state;
 3628: 	}
 3629:     }
 3630:     foreach my $id (sort(keys(%flashvars))) {
 3631:         if ($shockwave{$id} ne '') {
 3632:             my @pairs = split(/\&/,$flashvars{$id});
 3633:             foreach my $pair (@pairs) {
 3634:                 my ($key,$value) = split(/\=/,$pair);
 3635:                 if ($key eq 'thumb') {
 3636:                     &add_filetype($allfiles,$value,$key);
 3637:                 } elsif ($key eq 'content') {
 3638:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 3639:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 3640:                     if ($ext ne '') {
 3641:                         &add_filetype($allfiles,$path.$value,$ext);
 3642:                     }
 3643:                 }
 3644:             }
 3645:         }
 3646:     }
 3647:     return 'ok';
 3648: }
 3649: 
 3650: sub add_filetype {
 3651:     my ($allfiles,$file,$type)=@_;
 3652:     if (exists($allfiles->{$file})) {
 3653: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 3654: 	    push(@{$allfiles->{$file}}, &escape($type));
 3655: 	}
 3656:     } else {
 3657: 	@{$allfiles->{$file}} = (&escape($type));
 3658:     }
 3659: }
 3660: 
 3661: sub embedded_dependency {
 3662:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 3663:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 3664:         if (($identifier ne '') &&
 3665:             (ref($related->{$identifier}) eq 'ARRAY') &&
 3666:             ($pathfrom ne '')) {
 3667:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 3668:             foreach my $dep (@{$related->{$identifier}}) {
 3669:                 &add_filetype($allfiles,$path.$dep,'object');
 3670:             }
 3671:         }
 3672:     }
 3673:     return;
 3674: }
 3675: 
 3676: sub removeuploadedurl {
 3677:     my ($url)=@_;	
 3678:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 3679:     return &removeuserfile($uname,$udom,$fname);
 3680: }
 3681: 
 3682: sub removeuserfile {
 3683:     my ($docuname,$docudom,$fname)=@_;
 3684:     my $home=&homeserver($docuname,$docudom);    
 3685:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 3686:     if ($result eq 'ok') {	
 3687:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 3688:             my $metafile = $fname.'.meta';
 3689:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 3690: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 3691:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 3692:             my $sqlresult = 
 3693:                 &update_portfolio_table($docuname,$docudom,$file,
 3694:                                         'portfolio_metadata',$group,
 3695:                                         'delete');
 3696:         }
 3697:     }
 3698:     return $result;
 3699: }
 3700: 
 3701: sub mkdiruserfile {
 3702:     my ($docuname,$docudom,$dir)=@_;
 3703:     my $home=&homeserver($docuname,$docudom);
 3704:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 3705: }
 3706: 
 3707: sub renameuserfile {
 3708:     my ($docuname,$docudom,$old,$new)=@_;
 3709:     my $home=&homeserver($docuname,$docudom);
 3710:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 3711:                         &escape("$old").':'.&escape("$new"),$home);
 3712:     if ($result eq 'ok') {
 3713:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 3714:             my $oldmeta = $old.'.meta';
 3715:             my $newmeta = $new.'.meta';
 3716:             my $metaresult = 
 3717:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 3718: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 3719:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 3720:             my $sqlresult = 
 3721:                 &update_portfolio_table($docuname,$docudom,$file,
 3722:                                         'portfolio_metadata',$group,
 3723:                                         'delete');
 3724:         }
 3725:     }
 3726:     return $result;
 3727: }
 3728: 
 3729: # ------------------------------------------------------------------------- Log
 3730: 
 3731: sub log {
 3732:     my ($dom,$nam,$hom,$what)=@_;
 3733:     return critical("log:$dom:$nam:$what",$hom);
 3734: }
 3735: 
 3736: # ------------------------------------------------------------------ Course Log
 3737: #
 3738: # This routine flushes several buffers of non-mission-critical nature
 3739: #
 3740: 
 3741: sub flushcourselogs {
 3742:     &logthis('Flushing log buffers');
 3743: #
 3744: # course logs
 3745: # This is a log of all transactions in a course, which can be used
 3746: # for data mining purposes
 3747: #
 3748: # It also collects the courseid database, which lists last transaction
 3749: # times and course titles for all courseids
 3750: #
 3751:     my %courseidbuffer=();
 3752:     foreach my $crsid (keys(%courselogs)) {
 3753:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 3754: 		          &escape($courselogs{$crsid}),
 3755: 		          $coursehombuf{$crsid}) eq 'ok') {
 3756: 	    delete $courselogs{$crsid};
 3757:         } else {
 3758:             &logthis('Failed to flush log buffer for '.$crsid);
 3759:             if (length($courselogs{$crsid})>40000) {
 3760:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 3761:                         " exceeded maximum size, deleting.</font>");
 3762:                delete $courselogs{$crsid};
 3763:             }
 3764:         }
 3765:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 3766:             'description' => $coursedescrbuf{$crsid},
 3767:             'inst_code'    => $courseinstcodebuf{$crsid},
 3768:             'type'        => $coursetypebuf{$crsid},
 3769:             'owner'       => $courseownerbuf{$crsid},
 3770:         };
 3771:     }
 3772: #
 3773: # Write course id database (reverse lookup) to homeserver of courses 
 3774: # Is used in pickcourse
 3775: #
 3776:     foreach my $crs_home (keys(%courseidbuffer)) {
 3777:         my $response = &courseidput(&host_domain($crs_home),
 3778:                                     $courseidbuffer{$crs_home},
 3779:                                     $crs_home,'timeonly');
 3780:     }
 3781: #
 3782: # File accesses
 3783: # Writes to the dynamic metadata of resources to get hit counts, etc.
 3784: #
 3785:     foreach my $entry (keys(%accesshash)) {
 3786:         if ($entry =~ /___count$/) {
 3787:             my ($dom,$name);
 3788:             ($dom,$name,undef)=
 3789: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 3790:             if (! defined($dom) || $dom eq '' || 
 3791:                 ! defined($name) || $name eq '') {
 3792:                 my $cid = $env{'request.course.id'};
 3793:                 $dom  = $env{'request.'.$cid.'.domain'};
 3794:                 $name = $env{'request.'.$cid.'.num'};
 3795:             }
 3796:             my $value = $accesshash{$entry};
 3797:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 3798:             my %temphash=($url => $value);
 3799:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 3800:             if ($result eq 'ok') {
 3801:                 delete $accesshash{$entry};
 3802:             }
 3803:         } else {
 3804:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 3805:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 3806:             my %temphash=($entry => $accesshash{$entry});
 3807:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 3808:                 delete $accesshash{$entry};
 3809:             }
 3810:         }
 3811:     }
 3812: #
 3813: # Roles
 3814: # Reverse lookup of user roles for course faculty/staff and co-authorship
 3815: #
 3816:     foreach my $entry (keys(%userrolehash)) {
 3817:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 3818: 	    split(/\:/,$entry);
 3819:         if (&Apache::lonnet::put('nohist_userroles',
 3820:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 3821:                 $rudom,$runame) eq 'ok') {
 3822: 	    delete $userrolehash{$entry};
 3823:         }
 3824:     }
 3825: #
 3826: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 3827: #
 3828:     my %domrolebuffer = ();
 3829:     foreach my $entry (keys(%domainrolehash)) {
 3830:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 3831:         if ($domrolebuffer{$rudom}) {
 3832:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 3833:                       '='.&escape($domainrolehash{$entry});
 3834:         } else {
 3835:             $domrolebuffer{$rudom}.=&escape($entry).
 3836:                       '='.&escape($domainrolehash{$entry});
 3837:         }
 3838:         delete $domainrolehash{$entry};
 3839:     }
 3840:     foreach my $dom (keys(%domrolebuffer)) {
 3841: 	my %servers = &get_servers($dom,'library');
 3842: 	foreach my $tryserver (keys(%servers)) {
 3843: 	    unless (&reply('domroleput:'.$dom.':'.
 3844: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 3845: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 3846: 	    }
 3847:         }
 3848:     }
 3849:     $dumpcount++;
 3850: }
 3851: 
 3852: sub courselog {
 3853:     my $what=shift;
 3854:     $what=time.':'.$what;
 3855:     unless ($env{'request.course.id'}) { return ''; }
 3856:     $coursedombuf{$env{'request.course.id'}}=
 3857:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 3858:     $coursenumbuf{$env{'request.course.id'}}=
 3859:        $env{'course.'.$env{'request.course.id'}.'.num'};
 3860:     $coursehombuf{$env{'request.course.id'}}=
 3861:        $env{'course.'.$env{'request.course.id'}.'.home'};
 3862:     $coursedescrbuf{$env{'request.course.id'}}=
 3863:        $env{'course.'.$env{'request.course.id'}.'.description'};
 3864:     $courseinstcodebuf{$env{'request.course.id'}}=
 3865:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 3866:     $courseownerbuf{$env{'request.course.id'}}=
 3867:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 3868:     $coursetypebuf{$env{'request.course.id'}}=
 3869:        $env{'course.'.$env{'request.course.id'}.'.type'};
 3870:     if (defined $courselogs{$env{'request.course.id'}}) {
 3871: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 3872:     } else {
 3873: 	$courselogs{$env{'request.course.id'}}.=$what;
 3874:     }
 3875:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 3876: 	&flushcourselogs();
 3877:     }
 3878: }
 3879: 
 3880: sub courseacclog {
 3881:     my $fnsymb=shift;
 3882:     unless ($env{'request.course.id'}) { return ''; }
 3883:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 3884:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 3885:         $what.=':POST';
 3886:         # FIXME: Probably ought to escape things....
 3887: 	foreach my $key (keys(%env)) {
 3888:             if ($key=~/^form\.(.*)/) {
 3889:                 my $formitem = $1;
 3890:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 3891:                     $what.=':'.$formitem.'='.$env{$key};
 3892:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 3893:                     $what.=':'.$formitem.'='.$env{$key};
 3894:                 }
 3895:             }
 3896:         }
 3897:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 3898:         # FIXME: We should not be depending on a form parameter that someone
 3899:         # editing lonsearchcat.pm might change in the future.
 3900:         if ($env{'form.phase'} eq 'course_search') {
 3901:             $what.= ':POST';
 3902:             # FIXME: Probably ought to escape things....
 3903:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 3904:                                  'crsdiscuss') {
 3905:                 $what.=':'.$element.'='.$env{'form.'.$element};
 3906:             }
 3907:         }
 3908:     }
 3909:     &courselog($what);
 3910: }
 3911: 
 3912: sub countacc {
 3913:     my $url=&declutter(shift);
 3914:     return if (! defined($url) || $url eq '');
 3915:     unless ($env{'request.course.id'}) { return ''; }
 3916: #
 3917: # Mark that this url was used in this course
 3918: #
 3919:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 3920: #
 3921: # Increase the access count for this resource in this child process
 3922: #
 3923:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 3924:     $accesshash{$key}++;
 3925: }
 3926: 
 3927: sub linklog {
 3928:     my ($from,$to)=@_;
 3929:     $from=&declutter($from);
 3930:     $to=&declutter($to);
 3931:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 3932:     $accesshash{$to.'___'.$from.'___goto'}=1;
 3933: }
 3934: 
 3935: sub statslog {
 3936:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 3937:     if ($users<2) { return; }
 3938:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 3939:             'course'       => $env{'request.course.id'},
 3940:             'sections'     => '"all"',
 3941:             'num_students' => $users,
 3942:             'part'         => $part,
 3943:             'symb'         => $symb,
 3944:             'mean_tries'   => $av_attempts,
 3945:             'deg_of_diff'  => $degdiff});
 3946:     foreach my $key (keys(%dynstore)) {
 3947:         $accesshash{$key}=$dynstore{$key};
 3948:     }
 3949: }
 3950:   
 3951: sub userrolelog {
 3952:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 3953:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 3954:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3955:        $userrolehash
 3956:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3957:                     =$tend.':'.$tstart;
 3958:     }
 3959:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 3960:        $userrolehash
 3961:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 3962:                     =$tend.':'.$tstart;
 3963:     }
 3964:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
 3965:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3966:        $domainrolehash
 3967:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3968:                     = $tend.':'.$tstart;
 3969:     }
 3970: }
 3971: 
 3972: sub courserolelog {
 3973:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 3974:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 3975:         my $cdom = $1;
 3976:         my $cnum = $2;
 3977:         my $sec = $3;
 3978:         my $namespace = 'rolelog';
 3979:         my %storehash = (
 3980:                            role    => $trole,
 3981:                            start   => $tstart,
 3982:                            end     => $tend,
 3983:                            selfenroll => $selfenroll,
 3984:                            context    => $context,
 3985:                         );
 3986:         if ($trole eq 'gr') {
 3987:             $namespace = 'groupslog';
 3988:             $storehash{'group'} = $sec;
 3989:         } else {
 3990:             $storehash{'section'} = $sec;
 3991:         }
 3992:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 3993:                    $domain,$cnum,$cdom);
 3994:         if (($trole ne 'st') || ($sec ne '')) {
 3995:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 3996:         }
 3997:     }
 3998:     return;
 3999: }
 4000: 
 4001: sub domainrolelog {
 4002:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4003:     if ($area =~ m{^/($match_domain)/$}) {
 4004:         my $cdom = $1;
 4005:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 4006:         my $namespace = 'rolelog';
 4007:         my %storehash = (
 4008:                            role    => $trole,
 4009:                            start   => $tstart,
 4010:                            end     => $tend,
 4011:                            context => $context,
 4012:                         );
 4013:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 4014:                    $domain,$domconfiguser,$cdom);
 4015:     }
 4016:     return;
 4017: 
 4018: }
 4019: 
 4020: sub coauthorrolelog {
 4021:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4022:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 4023:         my $audom = $1;
 4024:         my $auname = $2;
 4025:         my $namespace = 'rolelog';
 4026:         my %storehash = (
 4027:                            role    => $trole,
 4028:                            start   => $tstart,
 4029:                            end     => $tend,
 4030:                            context => $context,
 4031:                         );
 4032:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 4033:                    $domain,$auname,$audom);
 4034:     }
 4035:     return;
 4036: }
 4037: 
 4038: sub get_course_adv_roles {
 4039:     my ($cid,$codes) = @_;
 4040:     $cid=$env{'request.course.id'} unless (defined($cid));
 4041:     my %coursehash=&coursedescription($cid);
 4042:     my $crstype = &Apache::loncommon::course_type($cid);
 4043:     my %nothide=();
 4044:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4045:         if ($user !~ /:/) {
 4046: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 4047:         } else {
 4048:             $nothide{$user}=1;
 4049:         }
 4050:     }
 4051:     my @possdoms = ($coursehash{'domain'});
 4052:     if ($coursehash{'checkforpriv'}) {
 4053:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 4054:     }
 4055:     my %returnhash=();
 4056:     my %dumphash=
 4057:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 4058:     my $now=time;
 4059:     my %privileged;
 4060:     foreach my $entry (keys(%dumphash)) {
 4061: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4062:         if (($tstart) && ($tstart<0)) { next; }
 4063:         if (($tend) && ($tend<$now)) { next; }
 4064:         if (($tstart) && ($now<$tstart)) { next; }
 4065:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 4066: 	if ($username eq '' || $domain eq '') { next; }
 4067:         if ((&privileged($username,$domain,\@possdoms)) &&
 4068:             (!$nothide{$username.':'.$domain})) { next; }
 4069: 	if ($role eq 'cr') { next; }
 4070:         if ($codes) {
 4071:             if ($section) { $role .= ':'.$section; }
 4072:             if ($returnhash{$role}) {
 4073:                 $returnhash{$role}.=','.$username.':'.$domain;
 4074:             } else {
 4075:                 $returnhash{$role}=$username.':'.$domain;
 4076:             }
 4077:         } else {
 4078:             my $key=&plaintext($role,$crstype);
 4079:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 4080:             if ($returnhash{$key}) {
 4081: 	        $returnhash{$key}.=','.$username.':'.$domain;
 4082:             } else {
 4083:                 $returnhash{$key}=$username.':'.$domain;
 4084:             }
 4085:         }
 4086:     }
 4087:     return %returnhash;
 4088: }
 4089: 
 4090: sub get_my_roles {
 4091:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 4092:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 4093:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 4094:     my (%dumphash,%nothide);
 4095:     if ($context eq 'userroles') {
 4096:         %dumphash = &dump('roles',$udom,$uname);
 4097:     } else {
 4098:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 4099:         if ($hidepriv) {
 4100:             my %coursehash=&coursedescription($udom.'_'.$uname);
 4101:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4102:                 if ($user !~ /:/) {
 4103:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 4104:                 } else {
 4105:                     $nothide{$user} = 1;
 4106:                 }
 4107:             }
 4108:         }
 4109:     }
 4110:     my %returnhash=();
 4111:     my $now=time;
 4112:     my %privileged;
 4113:     foreach my $entry (keys(%dumphash)) {
 4114:         my ($role,$tend,$tstart);
 4115:         if ($context eq 'userroles') {
 4116:             next if ($entry =~ /^rolesdef/);
 4117: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 4118:         } else {
 4119:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4120:         }
 4121:         if (($tstart) && ($tstart<0)) { next; }
 4122:         my $status = 'active';
 4123:         if (($tend) && ($tend<=$now)) {
 4124:             $status = 'previous';
 4125:         } 
 4126:         if (($tstart) && ($now<$tstart)) {
 4127:             $status = 'future';
 4128:         }
 4129:         if (ref($types) eq 'ARRAY') {
 4130:             if (!grep(/^\Q$status\E$/,@{$types})) {
 4131:                 next;
 4132:             } 
 4133:         } else {
 4134:             if ($status ne 'active') {
 4135:                 next;
 4136:             }
 4137:         }
 4138:         my ($rolecode,$username,$domain,$section,$area);
 4139:         if ($context eq 'userroles') {
 4140:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 4141:             (undef,$domain,$username,$section) = split(/\//,$area);
 4142:         } else {
 4143:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 4144:         }
 4145:         if (ref($roledoms) eq 'ARRAY') {
 4146:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 4147:                 next;
 4148:             }
 4149:         }
 4150:         if (ref($roles) eq 'ARRAY') {
 4151:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 4152:                 if ($role =~ /^cr\//) {
 4153:                     if (!grep(/^cr$/,@{$roles})) {
 4154:                         next;
 4155:                     }
 4156:                 } elsif ($role =~ /^gr\//) {
 4157:                     if (!grep(/^gr$/,@{$roles})) {
 4158:                         next;
 4159:                     }
 4160:                 } else {
 4161:                     next;
 4162:                 }
 4163:             }
 4164:         }
 4165:         if ($hidepriv) {
 4166:             my @privroles = ('dc','su');
 4167:             if ($context eq 'userroles') {
 4168:                 next if (grep(/^\Q$role\E$/,@privroles));
 4169:             } else {
 4170:                 my $possdoms = [$domain];
 4171:                 if (ref($roledoms) eq 'ARRAY') {
 4172:                    push(@{$possdoms},@{$roledoms}); 
 4173:                 }
 4174:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 4175:                     if (!$nothide{$username.':'.$domain}) {
 4176:                         next;
 4177:                     }
 4178:                 }
 4179:             }
 4180:         }
 4181:         if ($withsec) {
 4182:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 4183:                 $tstart.':'.$tend;
 4184:         } else {
 4185:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 4186:         }
 4187:     }
 4188:     return %returnhash;
 4189: }
 4190: 
 4191: # ----------------------------------------------------- Frontpage Announcements
 4192: #
 4193: #
 4194: 
 4195: sub postannounce {
 4196:     my ($server,$text)=@_;
 4197:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 4198:     unless ($text=~/\w/) { $text=''; }
 4199:     return &reply('setannounce:'.&escape($text),$server);
 4200: }
 4201: 
 4202: sub getannounce {
 4203: 
 4204:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 4205: 	my $announcement='';
 4206: 	while (my $line = <$fh>) { $announcement .= $line; }
 4207: 	close($fh);
 4208: 	if ($announcement=~/\w/) { 
 4209: 	    return 
 4210:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 4211:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 4212: 	} else {
 4213: 	    return '';
 4214: 	}
 4215:     } else {
 4216: 	return '';
 4217:     }
 4218: }
 4219: 
 4220: # ---------------------------------------------------------- Course ID routines
 4221: # Deal with domain's nohist_courseid.db files
 4222: #
 4223: 
 4224: sub courseidput {
 4225:     my ($domain,$storehash,$coursehome,$caller) = @_;
 4226:     return unless (ref($storehash) eq 'HASH');
 4227:     my $outcome;
 4228:     if ($caller eq 'timeonly') {
 4229:         my $cids = '';
 4230:         foreach my $item (keys(%$storehash)) {
 4231:             $cids.=&escape($item).'&';
 4232:         }
 4233:         $cids=~s/\&$//;
 4234:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 4235:                           $coursehome);       
 4236:     } else {
 4237:         my $items = '';
 4238:         foreach my $item (keys(%$storehash)) {
 4239:             $items.= &escape($item).'='.
 4240:                      &freeze_escape($$storehash{$item}).'&';
 4241:         }
 4242:         $items=~s/\&$//;
 4243:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 4244:                           $coursehome);
 4245:     }
 4246:     if ($outcome eq 'unknown_cmd') {
 4247:         my $what;
 4248:         foreach my $cid (keys(%$storehash)) {
 4249:             $what .= &escape($cid).'=';
 4250:             foreach my $item ('description','inst_code','owner','type') {
 4251:                 $what .= &escape($storehash->{$cid}{$item}).':';
 4252:             }
 4253:             $what =~ s/\:$/&/;
 4254:         }
 4255:         $what =~ s/\&$//;  
 4256:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 4257:     } else {
 4258:         return $outcome;
 4259:     }
 4260: }
 4261: 
 4262: sub courseiddump {
 4263:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 4264:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 4265:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 4266:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 4267:         $hasuniquecode)=@_;
 4268:     my $as_hash = 1;
 4269:     my %returnhash;
 4270:     if (!$domfilter) { $domfilter=''; }
 4271:     my %libserv = &all_library();
 4272:     foreach my $tryserver (keys(%libserv)) {
 4273:         if ( (  $hostidflag == 1 
 4274: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 4275: 	     || (!defined($hostidflag)) ) {
 4276: 
 4277: 	    if (($domfilter eq '') ||
 4278: 		(&host_domain($tryserver) eq $domfilter)) {
 4279:                 my $rep;
 4280:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 4281:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 4282:                         join(":", (&host_domain($tryserver), $sincefilter, 
 4283:                                 &escape($descfilter), &escape($instcodefilter), 
 4284:                                 &escape($ownerfilter), &escape($coursefilter),
 4285:                                 &escape($typefilter), &escape($regexp_ok), 
 4286:                                 $as_hash, &escape($selfenrollonly), 
 4287:                                 &escape($catfilter), $showhidden, $caller, 
 4288:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 4289:                                 &escape($createdbefore), &escape($createdafter), 
 4290:                                 &escape($creationcontext), $domcloner, $hasuniquecode)));
 4291:                 } else {
 4292:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 4293:                              $sincefilter.':'.&escape($descfilter).':'.
 4294:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 4295:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 4296:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 4297:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 4298:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 4299:                              &escape($cc_clone).':'.$cloneonly.':'.
 4300:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 4301:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode,
 4302:                              $tryserver);
 4303:                 }
 4304:                      
 4305:                 my @pairs=split(/\&/,$rep);
 4306:                 foreach my $item (@pairs) {
 4307:                     my ($key,$value)=split(/\=/,$item,2);
 4308:                     $key = &unescape($key);
 4309:                     next if ($key =~ /^error: 2 /);
 4310:                     my $result = &thaw_unescape($value);
 4311:                     if (ref($result) eq 'HASH') {
 4312:                         $returnhash{$key}=$result;
 4313:                     } else {
 4314:                         my @responses = split(/:/,$value);
 4315:                         my @items = ('description','inst_code','owner','type');
 4316:                         for (my $i=0; $i<@responses; $i++) {
 4317:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 4318:                         }
 4319:                     }
 4320:                 }
 4321:             }
 4322:         }
 4323:     }
 4324:     return %returnhash;
 4325: }
 4326: 
 4327: sub courselastaccess {
 4328:     my ($cdom,$cnum,$hostidref) = @_;
 4329:     my %returnhash;
 4330:     if ($cdom && $cnum) {
 4331:         my $chome = &homeserver($cnum,$cdom);
 4332:         if ($chome ne 'no_host') {
 4333:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 4334:             &extract_lastaccess(\%returnhash,$rep);
 4335:         }
 4336:     } else {
 4337:         if (!$cdom) { $cdom=''; }
 4338:         my %libserv = &all_library();
 4339:         foreach my $tryserver (keys(%libserv)) {
 4340:             if (ref($hostidref) eq 'ARRAY') {
 4341:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 4342:             } 
 4343:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 4344:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 4345:                 &extract_lastaccess(\%returnhash,$rep);
 4346:             }
 4347:         }
 4348:     }
 4349:     return %returnhash;
 4350: }
 4351: 
 4352: sub extract_lastaccess {
 4353:     my ($returnhash,$rep) = @_;
 4354:     if (ref($returnhash) eq 'HASH') {
 4355:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 4356:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 4357:                  $rep eq '') {
 4358:             my @pairs=split(/\&/,$rep);
 4359:             foreach my $item (@pairs) {
 4360:                 my ($key,$value)=split(/\=/,$item,2);
 4361:                 $key = &unescape($key);
 4362:                 next if ($key =~ /^error: 2 /);
 4363:                 $returnhash->{$key} = &thaw_unescape($value);
 4364:             }
 4365:         }
 4366:     }
 4367:     return;
 4368: }
 4369: 
 4370: # ---------------------------------------------------------- DC e-mail
 4371: 
 4372: sub dcmailput {
 4373:     my ($domain,$msgid,$message,$server)=@_;
 4374:     my $status = &Apache::lonnet::critical(
 4375:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 4376:        &escape($message),$server);
 4377:     return $status;
 4378: }
 4379: 
 4380: sub dcmaildump {
 4381:     my ($dom,$startdate,$enddate,$senders) = @_;
 4382:     my %returnhash=();
 4383: 
 4384:     if (defined(&domain($dom,'primary'))) {
 4385:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 4386:                                                          &escape($enddate).':';
 4387: 	my @esc_senders=map { &escape($_)} @$senders;
 4388: 	$cmd.=&escape(join('&',@esc_senders));
 4389: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 4390:             my ($key,$value) = split(/\=/,$line,2);
 4391:             if (($key) && ($value)) {
 4392:                 $returnhash{&unescape($key)} = &unescape($value);
 4393:             }
 4394:         }
 4395:     }
 4396:     return %returnhash;
 4397: }
 4398: # ---------------------------------------------------------- Domain roles
 4399: 
 4400: sub get_domain_roles {
 4401:     my ($dom,$roles,$startdate,$enddate)=@_;
 4402:     if ((!defined($startdate)) || ($startdate eq '')) {
 4403:         $startdate = '.';
 4404:     }
 4405:     if ((!defined($enddate)) || ($enddate eq '')) {
 4406:         $enddate = '.';
 4407:     }
 4408:     my $rolelist;
 4409:     if (ref($roles) eq 'ARRAY') {
 4410:         $rolelist = join('&',@{$roles});
 4411:     }
 4412:     my %personnel = ();
 4413: 
 4414:     my %servers = &get_servers($dom,'library');
 4415:     foreach my $tryserver (keys(%servers)) {
 4416: 	%{$personnel{$tryserver}}=();
 4417: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 4418: 					    &escape($startdate).':'.
 4419: 					    &escape($enddate).':'.
 4420: 					    &escape($rolelist), $tryserver))) {
 4421: 	    my ($key,$value) = split(/\=/,$line,2);
 4422: 	    if (($key) && ($value)) {
 4423: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 4424: 	    }
 4425: 	}
 4426:     }
 4427:     return %personnel;
 4428: }
 4429: 
 4430: # ----------------------------------------------------------- Interval timing 
 4431: 
 4432: {
 4433: # Caches needed for speedup of navmaps
 4434: # We don't want to cache this for very long at all (5 seconds at most)
 4435: # 
 4436: # The user for whom we cache
 4437: my $cachedkey='';
 4438: # The cached times for this user
 4439: my %cachedtimes=();
 4440: # When this was last done
 4441: my $cachedtime=();
 4442: 
 4443: sub load_all_first_access {
 4444:     my ($uname,$udom)=@_;
 4445:     if (($cachedkey eq $uname.':'.$udom) &&
 4446:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
 4447:         return;
 4448:     }
 4449:     $cachedtime=time;
 4450:     $cachedkey=$uname.':'.$udom;
 4451:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 4452: }
 4453: 
 4454: sub get_first_access {
 4455:     my ($type,$argsymb,$argmap)=@_;
 4456:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4457:     if ($argsymb) { $symb=$argsymb; }
 4458:     my ($map,$id,$res)=&decode_symb($symb);
 4459:     if ($argmap) { $map = $argmap; }
 4460:     if ($type eq 'course') {
 4461: 	$res='course';
 4462:     } elsif ($type eq 'map') {
 4463: 	$res=&symbread($map);
 4464:     } else {
 4465: 	$res=$symb;
 4466:     }
 4467:     &load_all_first_access($uname,$udom);
 4468:     return $cachedtimes{"$courseid\0$res"};
 4469: }
 4470: 
 4471: sub set_first_access {
 4472:     my ($type,$interval)=@_;
 4473:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4474:     my ($map,$id,$res)=&decode_symb($symb);
 4475:     if ($type eq 'course') {
 4476: 	$res='course';
 4477:     } elsif ($type eq 'map') {
 4478: 	$res=&symbread($map);
 4479:     } else {
 4480: 	$res=$symb;
 4481:     }
 4482:     $cachedkey='';
 4483:     my $firstaccess=&get_first_access($type,$symb,$map);
 4484:     if (!$firstaccess) {
 4485:         my $start = time;
 4486: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 4487:                           $udom,$uname);
 4488:         if ($putres eq 'ok') {
 4489:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 4490:                  $udom,$uname); 
 4491:             &appenv(
 4492:                      {
 4493:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 4494:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 4495:                      }
 4496:                   );
 4497:         }
 4498:         return $putres;
 4499:     }
 4500:     return 'already_set';
 4501: }
 4502: }
 4503: # --------------------------------------------- Set Expire Date for Spreadsheet
 4504: 
 4505: sub expirespread {
 4506:     my ($uname,$udom,$stype,$usymb)=@_;
 4507:     my $cid=$env{'request.course.id'}; 
 4508:     if ($cid) {
 4509:        my $now=time;
 4510:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 4511:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 4512:                             $env{'course.'.$cid.'.num'}.
 4513: 	        	    ':nohist_expirationdates:'.
 4514:                             &escape($key).'='.$now,
 4515:                             $env{'course.'.$cid.'.home'})
 4516:     }
 4517:     return 'ok';
 4518: }
 4519: 
 4520: # ----------------------------------------------------- Devalidate Spreadsheets
 4521: 
 4522: sub devalidate {
 4523:     my ($symb,$uname,$udom)=@_;
 4524:     my $cid=$env{'request.course.id'}; 
 4525:     if ($cid) {
 4526:         # delete the stored spreadsheets for
 4527:         # - the student level sheet of this user in course's homespace
 4528:         # - the assessment level sheet for this resource 
 4529:         #   for this user in user's homespace
 4530: 	# - current conditional state info
 4531: 	my $key=$uname.':'.$udom.':';
 4532:         my $status=
 4533: 	    &del('nohist_calculatedsheets',
 4534: 		 [$key.'studentcalc:'],
 4535: 		 $env{'course.'.$cid.'.domain'},
 4536: 		 $env{'course.'.$cid.'.num'})
 4537: 		.' '.
 4538: 	    &del('nohist_calculatedsheets_'.$cid,
 4539: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 4540:         unless ($status eq 'ok ok') {
 4541:            &logthis('Could not devalidate spreadsheet '.
 4542:                     $uname.' at '.$udom.' for '.
 4543: 		    $symb.': '.$status);
 4544:         }
 4545: 	&delenv('user.state.'.$cid);
 4546:     }
 4547: }
 4548: 
 4549: sub get_scalar {
 4550:     my ($string,$end) = @_;
 4551:     my $value;
 4552:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 4553: 	$value = $1;
 4554:     } elsif ($$string =~ s/^([^&]*?)&//) {
 4555: 	$value = $1;
 4556:     }
 4557:     return &unescape($value);
 4558: }
 4559: 
 4560: sub array2str {
 4561:   my (@array) = @_;
 4562:   my $result=&arrayref2str(\@array);
 4563:   $result=~s/^__ARRAY_REF__//;
 4564:   $result=~s/__END_ARRAY_REF__$//;
 4565:   return $result;
 4566: }
 4567: 
 4568: sub arrayref2str {
 4569:   my ($arrayref) = @_;
 4570:   my $result='__ARRAY_REF__';
 4571:   foreach my $elem (@$arrayref) {
 4572:     if(ref($elem) eq 'ARRAY') {
 4573:       $result.=&arrayref2str($elem).'&';
 4574:     } elsif(ref($elem) eq 'HASH') {
 4575:       $result.=&hashref2str($elem).'&';
 4576:     } elsif(ref($elem)) {
 4577:       #print("Got a ref of ".(ref($elem))." skipping.");
 4578:     } else {
 4579:       $result.=&escape($elem).'&';
 4580:     }
 4581:   }
 4582:   $result=~s/\&$//;
 4583:   $result .= '__END_ARRAY_REF__';
 4584:   return $result;
 4585: }
 4586: 
 4587: sub hash2str {
 4588:   my (%hash) = @_;
 4589:   my $result=&hashref2str(\%hash);
 4590:   $result=~s/^__HASH_REF__//;
 4591:   $result=~s/__END_HASH_REF__$//;
 4592:   return $result;
 4593: }
 4594: 
 4595: sub hashref2str {
 4596:   my ($hashref)=@_;
 4597:   my $result='__HASH_REF__';
 4598:   foreach my $key (sort(keys(%$hashref))) {
 4599:     if (ref($key) eq 'ARRAY') {
 4600:       $result.=&arrayref2str($key).'=';
 4601:     } elsif (ref($key) eq 'HASH') {
 4602:       $result.=&hashref2str($key).'=';
 4603:     } elsif (ref($key)) {
 4604:       $result.='=';
 4605:       #print("Got a ref of ".(ref($key))." skipping.");
 4606:     } else {
 4607: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 4608:     }
 4609: 
 4610:     if(ref($hashref->{$key}) eq 'ARRAY') {
 4611:       $result.=&arrayref2str($hashref->{$key}).'&';
 4612:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 4613:       $result.=&hashref2str($hashref->{$key}).'&';
 4614:     } elsif(ref($hashref->{$key})) {
 4615:        $result.='&';
 4616:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 4617:     } else {
 4618:       $result.=&escape($hashref->{$key}).'&';
 4619:     }
 4620:   }
 4621:   $result=~s/\&$//;
 4622:   $result .= '__END_HASH_REF__';
 4623:   return $result;
 4624: }
 4625: 
 4626: sub str2hash {
 4627:     my ($string)=@_;
 4628:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 4629:     return %$hash;
 4630: }
 4631: 
 4632: sub str2hashref {
 4633:   my ($string) = @_;
 4634: 
 4635:   my %hash;
 4636: 
 4637:   if($string !~ /^__HASH_REF__/) {
 4638:       if (! ($string eq '' || !defined($string))) {
 4639: 	  $hash{'error'}='Not hash reference';
 4640:       }
 4641:       return (\%hash, $string);
 4642:   }
 4643: 
 4644:   $string =~ s/^__HASH_REF__//;
 4645: 
 4646:   while($string !~ /^__END_HASH_REF__/) {
 4647:       #key
 4648:       my $key='';
 4649:       if($string =~ /^__HASH_REF__/) {
 4650:           ($key, $string)=&str2hashref($string);
 4651:           if(defined($key->{'error'})) {
 4652:               $hash{'error'}='Bad data';
 4653:               return (\%hash, $string);
 4654:           }
 4655:       } elsif($string =~ /^__ARRAY_REF__/) {
 4656:           ($key, $string)=&str2arrayref($string);
 4657:           if($key->[0] eq 'Array reference error') {
 4658:               $hash{'error'}='Bad data';
 4659:               return (\%hash, $string);
 4660:           }
 4661:       } else {
 4662:           $string =~ s/^(.*?)=//;
 4663: 	  $key=&unescape($1);
 4664:       }
 4665:       $string =~ s/^=//;
 4666: 
 4667:       #value
 4668:       my $value='';
 4669:       if($string =~ /^__HASH_REF__/) {
 4670:           ($value, $string)=&str2hashref($string);
 4671:           if(defined($value->{'error'})) {
 4672:               $hash{'error'}='Bad data';
 4673:               return (\%hash, $string);
 4674:           }
 4675:       } elsif($string =~ /^__ARRAY_REF__/) {
 4676:           ($value, $string)=&str2arrayref($string);
 4677:           if($value->[0] eq 'Array reference error') {
 4678:               $hash{'error'}='Bad data';
 4679:               return (\%hash, $string);
 4680:           }
 4681:       } else {
 4682: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 4683:       }
 4684:       $string =~ s/^&//;
 4685: 
 4686:       $hash{$key}=$value;
 4687:   }
 4688: 
 4689:   $string =~ s/^__END_HASH_REF__//;
 4690: 
 4691:   return (\%hash, $string);
 4692: }
 4693: 
 4694: sub str2array {
 4695:     my ($string)=@_;
 4696:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 4697:     return @$array;
 4698: }
 4699: 
 4700: sub str2arrayref {
 4701:   my ($string) = @_;
 4702:   my @array;
 4703: 
 4704:   if($string !~ /^__ARRAY_REF__/) {
 4705:       if (! ($string eq '' || !defined($string))) {
 4706: 	  $array[0]='Array reference error';
 4707:       }
 4708:       return (\@array, $string);
 4709:   }
 4710: 
 4711:   $string =~ s/^__ARRAY_REF__//;
 4712: 
 4713:   while($string !~ /^__END_ARRAY_REF__/) {
 4714:       my $value='';
 4715:       if($string =~ /^__HASH_REF__/) {
 4716:           ($value, $string)=&str2hashref($string);
 4717:           if(defined($value->{'error'})) {
 4718:               $array[0] ='Array reference error';
 4719:               return (\@array, $string);
 4720:           }
 4721:       } elsif($string =~ /^__ARRAY_REF__/) {
 4722:           ($value, $string)=&str2arrayref($string);
 4723:           if($value->[0] eq 'Array reference error') {
 4724:               $array[0] ='Array reference error';
 4725:               return (\@array, $string);
 4726:           }
 4727:       } else {
 4728: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 4729:       }
 4730:       $string =~ s/^&//;
 4731: 
 4732:       push(@array, $value);
 4733:   }
 4734: 
 4735:   $string =~ s/^__END_ARRAY_REF__//;
 4736: 
 4737:   return (\@array, $string);
 4738: }
 4739: 
 4740: # -------------------------------------------------------------------Temp Store
 4741: 
 4742: sub tmpreset {
 4743:   my ($symb,$namespace,$domain,$stuname) = @_;
 4744:   if (!$symb) {
 4745:     $symb=&symbread();
 4746:     if (!$symb) { $symb= $env{'request.url'}; }
 4747:   }
 4748:   $symb=escape($symb);
 4749: 
 4750:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4751:   $namespace=~s/\//\_/g;
 4752:   $namespace=~s/\W//g;
 4753: 
 4754:   if (!$domain) { $domain=$env{'user.domain'}; }
 4755:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4756:   if ($domain eq 'public' && $stuname eq 'public') {
 4757:       $stuname=$ENV{'REMOTE_ADDR'};
 4758:   }
 4759:   my $path=LONCAPA::tempdir();
 4760:   my %hash;
 4761:   if (tie(%hash,'GDBM_File',
 4762: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4763: 	  &GDBM_WRCREAT(),0640)) {
 4764:     foreach my $key (keys(%hash)) {
 4765:       if ($key=~ /:$symb/) {
 4766: 	delete($hash{$key});
 4767:       }
 4768:     }
 4769:   }
 4770: }
 4771: 
 4772: sub tmpstore {
 4773:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4774: 
 4775:   if (!$symb) {
 4776:     $symb=&symbread();
 4777:     if (!$symb) { $symb= $env{'request.url'}; }
 4778:   }
 4779:   $symb=escape($symb);
 4780: 
 4781:   if (!$namespace) {
 4782:     # I don't think we would ever want to store this for a course.
 4783:     # it seems this will only be used if we don't have a course.
 4784:     #$namespace=$env{'request.course.id'};
 4785:     #if (!$namespace) {
 4786:       $namespace=$env{'request.state'};
 4787:     #}
 4788:   }
 4789:   $namespace=~s/\//\_/g;
 4790:   $namespace=~s/\W//g;
 4791:   if (!$domain) { $domain=$env{'user.domain'}; }
 4792:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4793:   if ($domain eq 'public' && $stuname eq 'public') {
 4794:       $stuname=$ENV{'REMOTE_ADDR'};
 4795:   }
 4796:   my $now=time;
 4797:   my %hash;
 4798:   my $path=LONCAPA::tempdir();
 4799:   if (tie(%hash,'GDBM_File',
 4800: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4801: 	  &GDBM_WRCREAT(),0640)) {
 4802:     $hash{"version:$symb"}++;
 4803:     my $version=$hash{"version:$symb"};
 4804:     my $allkeys=''; 
 4805:     foreach my $key (keys(%$storehash)) {
 4806:       $allkeys.=$key.':';
 4807:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 4808:     }
 4809:     $hash{"$version:$symb:timestamp"}=$now;
 4810:     $allkeys.='timestamp';
 4811:     $hash{"$version:keys:$symb"}=$allkeys;
 4812:     if (untie(%hash)) {
 4813:       return 'ok';
 4814:     } else {
 4815:       return "error:$!";
 4816:     }
 4817:   } else {
 4818:     return "error:$!";
 4819:   }
 4820: }
 4821: 
 4822: # -----------------------------------------------------------------Temp Restore
 4823: 
 4824: sub tmprestore {
 4825:   my ($symb,$namespace,$domain,$stuname) = @_;
 4826: 
 4827:   if (!$symb) {
 4828:     $symb=&symbread();
 4829:     if (!$symb) { $symb= $env{'request.url'}; }
 4830:   }
 4831:   $symb=escape($symb);
 4832: 
 4833:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4834: 
 4835:   if (!$domain) { $domain=$env{'user.domain'}; }
 4836:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4837:   if ($domain eq 'public' && $stuname eq 'public') {
 4838:       $stuname=$ENV{'REMOTE_ADDR'};
 4839:   }
 4840:   my %returnhash;
 4841:   $namespace=~s/\//\_/g;
 4842:   $namespace=~s/\W//g;
 4843:   my %hash;
 4844:   my $path=LONCAPA::tempdir();
 4845:   if (tie(%hash,'GDBM_File',
 4846: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4847: 	  &GDBM_READER(),0640)) {
 4848:     my $version=$hash{"version:$symb"};
 4849:     $returnhash{'version'}=$version;
 4850:     my $scope;
 4851:     for ($scope=1;$scope<=$version;$scope++) {
 4852:       my $vkeys=$hash{"$scope:keys:$symb"};
 4853:       my @keys=split(/:/,$vkeys);
 4854:       my $key;
 4855:       $returnhash{"$scope:keys"}=$vkeys;
 4856:       foreach $key (@keys) {
 4857: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4858: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4859:       }
 4860:     }
 4861:     if (!(untie(%hash))) {
 4862:       return "error:$!";
 4863:     }
 4864:   } else {
 4865:     return "error:$!";
 4866:   }
 4867:   return %returnhash;
 4868: }
 4869: 
 4870: # ----------------------------------------------------------------------- Store
 4871: 
 4872: sub store {
 4873:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 4874:     my $home='';
 4875: 
 4876:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4877: 
 4878:     $symb=&symbclean($symb);
 4879:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4880: 
 4881:     if (!$domain) { $domain=$env{'user.domain'}; }
 4882:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4883: 
 4884:     &devalidate($symb,$stuname,$domain);
 4885: 
 4886:     $symb=escape($symb);
 4887:     if (!$namespace) { 
 4888:        unless ($namespace=$env{'request.course.id'}) { 
 4889:           return ''; 
 4890:        } 
 4891:     }
 4892:     if (!$home) { $home=$env{'user.home'}; }
 4893: 
 4894:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4895:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4896: 
 4897:     my $namevalue='';
 4898:     foreach my $key (keys(%$storehash)) {
 4899:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4900:     }
 4901:     $namevalue=~s/\&$//;
 4902:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 4903:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 4904: }
 4905: 
 4906: # -------------------------------------------------------------- Critical Store
 4907: 
 4908: sub cstore {
 4909:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 4910:     my $home='';
 4911: 
 4912:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4913: 
 4914:     $symb=&symbclean($symb);
 4915:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4916: 
 4917:     if (!$domain) { $domain=$env{'user.domain'}; }
 4918:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4919: 
 4920:     &devalidate($symb,$stuname,$domain);
 4921: 
 4922:     $symb=escape($symb);
 4923:     if (!$namespace) { 
 4924:        unless ($namespace=$env{'request.course.id'}) { 
 4925:           return ''; 
 4926:        } 
 4927:     }
 4928:     if (!$home) { $home=$env{'user.home'}; }
 4929: 
 4930:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4931:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4932: 
 4933:     my $namevalue='';
 4934:     foreach my $key (keys(%$storehash)) {
 4935:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4936:     }
 4937:     $namevalue=~s/\&$//;
 4938:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 4939:     return critical
 4940:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 4941: }
 4942: 
 4943: # --------------------------------------------------------------------- Restore
 4944: 
 4945: sub restore {
 4946:     my ($symb,$namespace,$domain,$stuname) = @_;
 4947:     my $home='';
 4948: 
 4949:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4950: 
 4951:     if (!$symb) {
 4952:         return if ($namespace eq 'courserequests');
 4953:         unless ($symb=escape(&symbread())) { return ''; }
 4954:     } else {
 4955:         unless ($namespace eq 'courserequests') {
 4956:             $symb=&escape(&symbclean($symb));
 4957:         }
 4958:     }
 4959:     if (!$namespace) { 
 4960:        unless ($namespace=$env{'request.course.id'}) { 
 4961:           return ''; 
 4962:        } 
 4963:     }
 4964:     if (!$domain) { $domain=$env{'user.domain'}; }
 4965:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4966:     if (!$home) { $home=$env{'user.home'}; }
 4967:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 4968: 
 4969:     my %returnhash=();
 4970:     foreach my $line (split(/\&/,$answer)) {
 4971: 	my ($name,$value)=split(/\=/,$line);
 4972:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 4973:     }
 4974:     my $version;
 4975:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 4976:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 4977:           $returnhash{$item}=$returnhash{$version.':'.$item};
 4978:        }
 4979:     }
 4980:     return %returnhash;
 4981: }
 4982: 
 4983: # ---------------------------------------------------------- Course Description
 4984: #
 4985: #  
 4986: 
 4987: sub coursedescription {
 4988:     my ($courseid,$args)=@_;
 4989:     $courseid=~s/^\///;
 4990:     $courseid=~s/\_/\//g;
 4991:     my ($cdomain,$cnum)=split(/\//,$courseid);
 4992:     my $chome=&homeserver($cnum,$cdomain);
 4993:     my $normalid=$cdomain.'_'.$cnum;
 4994:     # need to always cache even if we get errors otherwise we keep 
 4995:     # trying and trying and trying to get the course description.
 4996:     my %envhash=();
 4997:     my %returnhash=();
 4998:     
 4999:     my $expiretime=600;
 5000:     if ($env{'request.course.id'} eq $normalid) {
 5001: 	$expiretime=120;
 5002:     }
 5003: 
 5004:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 5005:     if (!$args->{'freshen_cache'}
 5006: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 5007: 	foreach my $key (keys(%env)) {
 5008: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 5009: 	    my ($setting) = $1;
 5010: 	    $returnhash{$setting} = $env{$key};
 5011: 	}
 5012: 	return %returnhash;
 5013:     }
 5014: 
 5015:     # get the data again
 5016: 
 5017:     if (!$args->{'one_time'}) {
 5018: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 5019:     }
 5020: 
 5021:     if ($chome ne 'no_host') {
 5022:        %returnhash=&dump('environment',$cdomain,$cnum);
 5023:        if (!exists($returnhash{'con_lost'})) {
 5024: 	   my $username = $env{'user.name'}; # Defult username
 5025: 	   if(defined $args->{'user'}) {
 5026: 	       $username = $args->{'user'};
 5027: 	   }
 5028:            $returnhash{'home'}= $chome;
 5029: 	   $returnhash{'domain'} = $cdomain;
 5030: 	   $returnhash{'num'} = $cnum;
 5031:            if (!defined($returnhash{'type'})) {
 5032:                $returnhash{'type'} = 'Course';
 5033:            }
 5034:            while (my ($name,$value) = each %returnhash) {
 5035:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 5036:            }
 5037:            $returnhash{'url'}=&clutter($returnhash{'url'});
 5038:            $returnhash{'fn'}=LONCAPA::tempdir() .
 5039: 	       $username.'_'.$cdomain.'_'.$cnum;
 5040:            $envhash{'course.'.$normalid.'.home'}=$chome;
 5041:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 5042:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 5043:        }
 5044:     }
 5045:     if (!$args->{'one_time'}) {
 5046: 	&appenv(\%envhash);
 5047:     }
 5048:     return %returnhash;
 5049: }
 5050: 
 5051: sub update_released_required {
 5052:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 5053:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 5054:         $cid = $env{'request.course.id'};
 5055:         $cdom = $env{'course.'.$cid.'.domain'};
 5056:         $cnum = $env{'course.'.$cid.'.num'};
 5057:         $chome = $env{'course.'.$cid.'.home'};
 5058:     }
 5059:     if ($needsrelease) {
 5060:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 5061:         my $needsupdate;
 5062:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 5063:             $needsupdate = 1;
 5064:         } else {
 5065:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 5066:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 5067:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 5068:                 $needsupdate = 1;
 5069:             }
 5070:         }
 5071:         if ($needsupdate) {
 5072:             my %needshash = (
 5073:                              'internal.releaserequired' => $needsrelease,
 5074:                             );
 5075:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 5076:             if ($putresult eq 'ok') {
 5077:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 5078:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 5079:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 5080:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 5081:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 5082:                 }
 5083:             }
 5084:         }
 5085:     }
 5086:     return;
 5087: }
 5088: 
 5089: # -------------------------------------------------See if a user is privileged
 5090: 
 5091: sub privileged {
 5092:     my ($username,$domain,$possdomains,$possroles)=@_;
 5093:     my $now = time;
 5094:     my $roles;
 5095:     if (ref($possroles) eq 'ARRAY') {
 5096:         $roles = $possroles; 
 5097:     } else {
 5098:         $roles = ['dc','su'];
 5099:     }
 5100:     if (ref($possdomains) eq 'ARRAY') {
 5101:         my %privileged = &privileged_by_domain($possdomains,$roles);
 5102:         foreach my $dom (@{$possdomains}) {
 5103:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 5104:                 (ref($privileged{$dom}) eq 'HASH')) {
 5105:                 foreach my $role (@{$roles}) {
 5106:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5107:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 5108:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 5109:                             return 1 unless (($end && $end < $now) ||
 5110:                                              ($start && $start > $now));
 5111:                         }
 5112:                     }
 5113:                 }
 5114:             }
 5115:         }
 5116:     } else {
 5117:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 5118:         my $now = time;
 5119: 
 5120:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
 5121:             my ($trole, $tend, $tstart) = split(/_/, $role);
 5122:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 5123:                 return 1 unless ($tend && $tend < $now) 
 5124:                         or ($tstart && $tstart > $now);
 5125:             }
 5126:         }
 5127:     }
 5128:     return 0;
 5129: }
 5130: 
 5131: sub privileged_by_domain {
 5132:     my ($domains,$roles) = @_;
 5133:     my %privileged = ();
 5134:     my $cachetime = 60*60*24;
 5135:     my $now = time;
 5136:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 5137:         return %privileged;
 5138:     }
 5139:     foreach my $dom (@{$domains}) {
 5140:         next if (ref($privileged{$dom}) eq 'HASH');
 5141:         my $needroles;
 5142:         foreach my $role (@{$roles}) {
 5143:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 5144:             if (defined($cached)) {
 5145:                 if (ref($result) eq 'HASH') {
 5146:                     $privileged{$dom}{$role} = $result;
 5147:                 }
 5148:             } else {
 5149:                 $needroles = 1;
 5150:             }
 5151:         }
 5152:         if ($needroles) {
 5153:             my %dompersonnel = &get_domain_roles($dom,$roles);
 5154:             $privileged{$dom} = {};
 5155:             foreach my $server (keys(%dompersonnel)) {
 5156:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 5157:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 5158:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 5159:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 5160:                         next if ($end && $end < $now);
 5161:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 5162:                             $dompersonnel{$server}{$item};
 5163:                     }
 5164:                 }
 5165:             }
 5166:             if (ref($privileged{$dom}) eq 'HASH') {
 5167:                 foreach my $role (@{$roles}) {
 5168:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5169:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 5170:                     } else {
 5171:                         my %hash = ();
 5172:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 5173:                     }
 5174:                 }
 5175:             }
 5176:         }
 5177:     }
 5178:     return %privileged;
 5179: }
 5180: 
 5181: # -------------------------------------------------------- Get user privileges
 5182: 
 5183: sub rolesinit {
 5184:     my ($domain, $username) = @_;
 5185:     my %userroles = ('user.login.time' => time);
 5186:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 5187: 
 5188:     # firstaccess and timerinterval are related to timed maps/resources. 
 5189:     # also, blocking can be triggered by an activating timer
 5190:     # it's saved in the user's %env.
 5191:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 5192:     my %timerinterval = &dump('timerinterval', $domain, $username);
 5193:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 5194:         %timerintchk, %timerintenv);
 5195: 
 5196:     foreach my $key (keys(%firstaccess)) {
 5197:         my ($cid, $rest) = split(/\0/, $key);
 5198:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 5199:     }
 5200: 
 5201:     foreach my $key (keys(%timerinterval)) {
 5202:         my ($cid,$rest) = split(/\0/,$key);
 5203:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 5204:     }
 5205: 
 5206:     my %allroles=();
 5207:     my %allgroups=();
 5208: 
 5209:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
 5210:         my $role = $rolesdump{$area};
 5211:         $area =~ s/\_\w\w$//;
 5212: 
 5213:         my ($trole, $tend, $tstart, $group_privs);
 5214: 
 5215:         if ($role =~ /^cr/) {
 5216:         # Custom role, defined by a user 
 5217:         # e.g., user.role.cr/msu/smith/mynewrole
 5218:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 5219:                 $trole = $1;
 5220:                 ($tend, $tstart) = split('_', $2);
 5221:             } else {
 5222:                 $trole = $role;
 5223:             }
 5224:         } elsif ($role =~ m|^gr/|) {
 5225:         # Role of member in a group, defined within a course/community
 5226:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 5227:             ($trole, $tend, $tstart) = split(/_/, $role);
 5228:             next if $tstart eq '-1';
 5229:             ($trole, $group_privs) = split(/\//, $trole);
 5230:             $group_privs = &unescape($group_privs);
 5231:         } else {
 5232:         # Just a normal role, defined in roles.tab
 5233:             ($trole, $tend, $tstart) = split(/_/,$role);
 5234:         }
 5235: 
 5236:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 5237:                  $username);
 5238:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 5239: 
 5240:         # role expired or not available yet?
 5241:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 5242:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 5243: 
 5244:         next if $area eq '' or $trole eq '';
 5245: 
 5246:         my $spec = "$trole.$area";
 5247:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 5248: 
 5249:         if ($trole =~ /^cr\//) {
 5250:         # Custom role, defined by a user
 5251:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 5252:         } elsif ($trole eq 'gr') {
 5253:         # Role of a member in a group, defined within a course/community
 5254:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 5255:             next;
 5256:         } else {
 5257:         # Normal role, defined in roles.tab
 5258:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 5259:         }
 5260: 
 5261:         my $cid = $tdomain.'_'.$trest;
 5262:         unless ($firstaccchk{$cid}) {
 5263:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 5264:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 5265:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 5266:                         $coursetimerstarts{$cid}{$item}; 
 5267:                 }
 5268:             }
 5269:             $firstaccchk{$cid} = 1;
 5270:         }
 5271:         unless ($timerintchk{$cid}) {
 5272:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 5273:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 5274:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 5275:                        $coursetimerintervals{$cid}{$item};
 5276:                 }
 5277:             }
 5278:             $timerintchk{$cid} = 1;
 5279:         }
 5280:     }
 5281: 
 5282:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
 5283:         \%allroles, \%allgroups);
 5284:     $env{'user.adv'} = $userroles{'user.adv'};
 5285: 
 5286:     return (\%userroles,\%firstaccenv,\%timerintenv);
 5287: }
 5288: 
 5289: sub set_arearole {
 5290:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 5291:     unless ($nolog) {
 5292: # log the associated role with the area
 5293:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 5294:     }
 5295:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 5296: }
 5297: 
 5298: sub custom_roleprivs {
 5299:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 5300:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 5301:     my $homsvr = &homeserver($rauthor,$rdomain);
 5302:     if (&hostname($homsvr) ne '') {
 5303:         my ($rdummy,$roledef)=
 5304:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 5305:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 5306:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 5307:             if (defined($syspriv)) {
 5308:                 if ($trest =~ /^$match_community$/) {
 5309:                     $syspriv =~ s/bre\&S//; 
 5310:                 }
 5311:                 $$allroles{'cm./'}.=':'.$syspriv;
 5312:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 5313:             }
 5314:             if ($tdomain ne '') {
 5315:                 if (defined($dompriv)) {
 5316:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 5317:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 5318:                 }
 5319:                 if (($trest ne '') && (defined($coursepriv))) {
 5320:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 5321:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 5322:                 }
 5323:             }
 5324:         }
 5325:     }
 5326: }
 5327: 
 5328: sub group_roleprivs {
 5329:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 5330:     my $access = 1;
 5331:     my $now = time;
 5332:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 5333:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 5334:     if ($access) {
 5335:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 5336:         $$allgroups{$course}{$group} .=':'.$group_privs;
 5337:     }
 5338: }
 5339: 
 5340: sub standard_roleprivs {
 5341:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 5342:     if (defined($pr{$trole.':s'})) {
 5343:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 5344:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 5345:     }
 5346:     if ($tdomain ne '') {
 5347:         if (defined($pr{$trole.':d'})) {
 5348:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 5349:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 5350:         }
 5351:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 5352:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 5353:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 5354:         }
 5355:     }
 5356: }
 5357: 
 5358: sub set_userprivs {
 5359:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 5360:     my $author=0;
 5361:     my $adv=0;
 5362:     my %grouproles = ();
 5363:     if (keys(%{$allgroups}) > 0) {
 5364:         my @groupkeys; 
 5365:         foreach my $role (keys(%{$allroles})) {
 5366:             push(@groupkeys,$role);
 5367:         }
 5368:         if (ref($groups_roles) eq 'HASH') {
 5369:             foreach my $key (keys(%{$groups_roles})) {
 5370:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 5371:                     push(@groupkeys,$key);
 5372:                 }
 5373:             }
 5374:         }
 5375:         if (@groupkeys > 0) {
 5376:             foreach my $role (@groupkeys) {
 5377:                 my ($trole,$area,$sec,$extendedarea);
 5378:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 5379:                     $trole = $1;
 5380:                     $area = $2;
 5381:                     $sec = $3;
 5382:                     $extendedarea = $area.$sec;
 5383:                     if (exists($$allgroups{$area})) {
 5384:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 5385:                             my $spec = $trole.'.'.$extendedarea;
 5386:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 5387:                                                 $$allgroups{$area}{$group};
 5388:                         }
 5389:                     }
 5390:                 }
 5391:             }
 5392:         }
 5393:     }
 5394:     foreach my $group (keys(%grouproles)) {
 5395:         $$allroles{$group} = $grouproles{$group};
 5396:     }
 5397:     foreach my $role (keys(%{$allroles})) {
 5398:         my %thesepriv;
 5399:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 5400:         foreach my $item (split(/:/,$$allroles{$role})) {
 5401:             if ($item ne '') {
 5402:                 my ($privilege,$restrictions)=split(/&/,$item);
 5403:                 if ($restrictions eq '') {
 5404:                     $thesepriv{$privilege}='F';
 5405:                 } elsif ($thesepriv{$privilege} ne 'F') {
 5406:                     $thesepriv{$privilege}.=$restrictions;
 5407:                 }
 5408:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 5409:             }
 5410:         }
 5411:         my $thesestr='';
 5412:         foreach my $priv (sort(keys(%thesepriv))) {
 5413: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 5414: 	}
 5415:         $userroles->{'user.priv.'.$role} = $thesestr;
 5416:     }
 5417:     return ($author,$adv);
 5418: }
 5419: 
 5420: sub role_status {
 5421:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 5422:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 5423:         my ($one,$two) = split(m{\./},$rolekey,2);
 5424:         (undef,undef,$$role) = split(/\./,$one,3);
 5425:         unless (!defined($$role) || $$role eq '') {
 5426:             $$where = '/'.$two;
 5427:             $$trolecode=$$role.'.'.$$where;
 5428:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 5429:             $$tstatus='is';
 5430:             if ($$tstart && $$tstart>$update) {
 5431:                 $$tstatus='future';
 5432:                 if ($$tstart<$now) {
 5433:                     if ($$tstart && $$tstart>$refresh) {
 5434:                         if (($$where ne '') && ($$role ne '')) {
 5435:                             my (%allroles,%allgroups,$group_privs,
 5436:                                 %groups_roles,@rolecodes);
 5437:                             my %userroles = (
 5438:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 5439:                             );
 5440:                             @rolecodes = ('cm'); 
 5441:                             my $spec=$$role.'.'.$$where;
 5442:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 5443:                             if ($$role =~ /^cr\//) {
 5444:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 5445:                                 push(@rolecodes,'cr');
 5446:                             } elsif ($$role eq 'gr') {
 5447:                                 push(@rolecodes,$$role);
 5448:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 5449:                                                     $env{'user.name'});
 5450:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 5451:                                 (undef,my $group_privs) = split(/\//,$trole);
 5452:                                 $group_privs = &unescape($group_privs);
 5453:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 5454:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 5455:                                 &get_groups_roles($tdomain,$trest,
 5456:                                                   \%course_roles,\@rolecodes,
 5457:                                                   \%groups_roles);
 5458:                             } else {
 5459:                                 push(@rolecodes,$$role);
 5460:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 5461:                             }
 5462:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
 5463:                             &appenv(\%userroles,\@rolecodes);
 5464:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5465:                         }
 5466:                     }
 5467:                     $$tstatus = 'is';
 5468:                 }
 5469:             }
 5470:             if ($$tend) {
 5471:                 if ($$tend<$update) {
 5472:                     $$tstatus='expired';
 5473:                 } elsif ($$tend<$now) {
 5474:                     $$tstatus='will_not';
 5475:                 }
 5476:             }
 5477:         }
 5478:     }
 5479: }
 5480: 
 5481: sub get_groups_roles {
 5482:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 5483:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 5484:                   (ref($rolecodes) eq 'ARRAY') && 
 5485:                   (ref($groups_roles) eq 'HASH')); 
 5486:     if (keys(%{$cdom_courseroles}) > 0) {
 5487:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 5488:         if ($cdom ne '' && $cnum ne '') {
 5489:             foreach my $key (keys(%{$cdom_courseroles})) {
 5490:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 5491:                     my $crsrole = $1;
 5492:                     my $crssec = $2;
 5493:                     if ($crsrole =~ /^cr/) {
 5494:                         unless (grep(/^cr$/,@{$rolecodes})) {
 5495:                             push(@{$rolecodes},'cr');
 5496:                         }
 5497:                     } else {
 5498:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 5499:                             push(@{$rolecodes},$crsrole);
 5500:                         }
 5501:                     }
 5502:                     my $rolekey = "$crsrole./$cdom/$cnum";
 5503:                     if ($crssec ne '') {
 5504:                         $rolekey .= "/$crssec";
 5505:                     }
 5506:                     $rolekey .= './';
 5507:                     $groups_roles->{$rolekey} = $rolecodes;
 5508:                 }
 5509:             }
 5510:         }
 5511:     }
 5512:     return;
 5513: }
 5514: 
 5515: sub delete_env_groupprivs {
 5516:     my ($where,$courseroles,$possroles) = @_;
 5517:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 5518:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 5519:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 5520:         %{$courseroles->{$udom}} =
 5521:             &get_my_roles('','','userroles',['active'],
 5522:                           $possroles,[$udom],1);
 5523:     }
 5524:     if (ref($courseroles->{$udom}) eq 'HASH') {
 5525:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 5526:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 5527:             my $area = '/'.$cdom.'/'.$cnum;
 5528:             my $privkey = "user.priv.$crsrole.$area";
 5529:             if ($crssec ne '') {
 5530:                 $privkey .= '/'.$crssec;
 5531:             }
 5532:             $privkey .= ".$area/$group";
 5533:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 5534:         }
 5535:     }
 5536:     return;
 5537: }
 5538: 
 5539: sub check_adhoc_privs {
 5540:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
 5541:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 5542:     my $setprivs;
 5543:     if ($env{$cckey}) {
 5544:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 5545:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 5546:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 5547:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5548:             $setprivs = 1;
 5549:         }
 5550:     } else {
 5551:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5552:         $setprivs = 1;
 5553:     }
 5554:     return $setprivs;
 5555: }
 5556: 
 5557: sub set_adhoc_privileges {
 5558: # role can be cc or ca
 5559:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
 5560:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 5561:     my $spec = $role.'.'.$area;
 5562:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 5563:                                   $env{'user.name'},1);
 5564:     my %ccrole = ();
 5565:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
 5566:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
 5567:     &appenv(\%userroles,[$role,'cm']);
 5568:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5569:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 5570:         &appenv( {'request.role'        => $spec,
 5571:                   'request.role.domain' => $dcdom,
 5572:                   'request.course.sec'  => ''
 5573:                  }
 5574:                );
 5575:         my $tadv=0;
 5576:         if (&allowed('adv') eq 'F') { $tadv=1; }
 5577:         &appenv({'request.role.adv'    => $tadv});
 5578:     }
 5579: }
 5580: 
 5581: # --------------------------------------------------------------- get interface
 5582: 
 5583: sub get {
 5584:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5585:    my $items='';
 5586:    foreach my $item (@$storearr) {
 5587:        $items.=&escape($item).'&';
 5588:    }
 5589:    $items=~s/\&$//;
 5590:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5591:    if (!$uname) { $uname=$env{'user.name'}; }
 5592:    my $uhome=&homeserver($uname,$udomain);
 5593: 
 5594:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 5595:    my @pairs=split(/\&/,$rep);
 5596:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 5597:      return @pairs;
 5598:    }
 5599:    my %returnhash=();
 5600:    my $i=0;
 5601:    foreach my $item (@$storearr) {
 5602:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5603:       $i++;
 5604:    }
 5605:    return %returnhash;
 5606: }
 5607: 
 5608: # --------------------------------------------------------------- del interface
 5609: 
 5610: sub del {
 5611:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5612:    my $items='';
 5613:    foreach my $item (@$storearr) {
 5614:        $items.=&escape($item).'&';
 5615:    }
 5616: 
 5617:    $items=~s/\&$//;
 5618:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5619:    if (!$uname) { $uname=$env{'user.name'}; }
 5620:    my $uhome=&homeserver($uname,$udomain);
 5621:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 5622: }
 5623: 
 5624: # -------------------------------------------------------------- dump interface
 5625: 
 5626: sub unserialize {
 5627:     my ($rep, $escapedkeys) = @_;
 5628: 
 5629:     return {} if $rep =~ /^error/;
 5630: 
 5631:     my %returnhash=();
 5632: 	foreach my $item (split(/\&/,$rep)) {
 5633: 	    my ($key, $value) = split(/=/, $item, 2);
 5634: 	    $key = unescape($key) unless $escapedkeys;
 5635: 	    next if $key =~ /^error: 2 /;
 5636: 	    $returnhash{$key} = &thaw_unescape($value);
 5637: 	}
 5638:     #return %returnhash;
 5639:     return \%returnhash;
 5640: }        
 5641: 
 5642: # see Lond::dump_with_regexp
 5643: # if $escapedkeys hash keys won't get unescaped.
 5644: sub dump {
 5645:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 5646:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5647:     if (!$uname) { $uname=$env{'user.name'}; }
 5648:     my $uhome=&homeserver($uname,$udomain);
 5649: 
 5650:     if ($regexp) {
 5651:         $regexp=&escape($regexp);
 5652:     } else {
 5653:         $regexp='.';
 5654:     }
 5655:     if (grep { $_ eq $uhome } current_machine_ids()) {
 5656:         # user is hosted on this machine
 5657:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 5658:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 5659:         return %{unserialize($reply, $escapedkeys)};
 5660:     }
 5661:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 5662:     my @pairs=split(/\&/,$rep);
 5663:     my %returnhash=();
 5664:     if (!($rep =~ /^error/ )) {
 5665: 	foreach my $item (@pairs) {
 5666: 	    my ($key,$value)=split(/=/,$item,2);
 5667:         $key = unescape($key) unless $escapedkeys;
 5668:         #$key = &unescape($key);
 5669: 	    next if ($key =~ /^error: 2 /);
 5670: 	    $returnhash{$key}=&thaw_unescape($value);
 5671: 	}
 5672:     }
 5673:     return %returnhash;
 5674: }
 5675: 
 5676: 
 5677: # --------------------------------------------------------- dumpstore interface
 5678: 
 5679: sub dumpstore {
 5680:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 5681:    # same as dump but keys must be escaped. They may contain colon separated
 5682:    # lists of values that may themself contain colons (e.g. symbs).
 5683:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 5684: }
 5685: 
 5686: # -------------------------------------------------------------- keys interface
 5687: 
 5688: sub getkeys {
 5689:    my ($namespace,$udomain,$uname)=@_;
 5690:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5691:    if (!$uname) { $uname=$env{'user.name'}; }
 5692:    my $uhome=&homeserver($uname,$udomain);
 5693:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 5694:    my @keyarray=();
 5695:    foreach my $key (split(/\&/,$rep)) {
 5696:       next if ($key =~ /^error: 2 /);
 5697:       push(@keyarray,&unescape($key));
 5698:    }
 5699:    return @keyarray;
 5700: }
 5701: 
 5702: # --------------------------------------------------------------- currentdump
 5703: sub currentdump {
 5704:    my ($courseid,$sdom,$sname)=@_;
 5705:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 5706:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 5707:    $sname    = $env{'user.name'}         if (! defined($sname));
 5708:    my $uhome = &homeserver($sname,$sdom);
 5709:    my $rep;
 5710: 
 5711:    if (grep { $_ eq $uhome } current_machine_ids()) {
 5712:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 5713:                    $courseid)));
 5714:    } else {
 5715:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 5716:    }
 5717: 
 5718:    return if ($rep =~ /^(error:|no_such_host)/);
 5719:    #
 5720:    my %returnhash=();
 5721:    #
 5722:    if ($rep eq "unknown_cmd") { 
 5723:        # an old lond will not know currentdump
 5724:        # Do a dump and make it look like a currentdump
 5725:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 5726:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 5727:        my %hash = @tmp;
 5728:        @tmp=();
 5729:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 5730:    } else {
 5731:        my @pairs=split(/\&/,$rep);
 5732:        foreach my $pair (@pairs) {
 5733:            my ($key,$value)=split(/=/,$pair,2);
 5734:            my ($symb,$param) = split(/:/,$key);
 5735:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 5736:                                                         &thaw_unescape($value);
 5737:        }
 5738:    }
 5739:    return %returnhash;
 5740: }
 5741: 
 5742: sub convert_dump_to_currentdump{
 5743:     my %hash = %{shift()};
 5744:     my %returnhash;
 5745:     # Code ripped from lond, essentially.  The only difference
 5746:     # here is the unescaping done by lonnet::dump().  Conceivably
 5747:     # we might run in to problems with parameter names =~ /^v\./
 5748:     while (my ($key,$value) = each(%hash)) {
 5749:         my ($v,$symb,$param) = split(/:/,$key);
 5750: 	$symb  = &unescape($symb);
 5751: 	$param = &unescape($param);
 5752:         next if ($v eq 'version' || $symb eq 'keys');
 5753:         next if (exists($returnhash{$symb}) &&
 5754:                  exists($returnhash{$symb}->{$param}) &&
 5755:                  $returnhash{$symb}->{'v.'.$param} > $v);
 5756:         $returnhash{$symb}->{$param}=$value;
 5757:         $returnhash{$symb}->{'v.'.$param}=$v;
 5758:     }
 5759:     #
 5760:     # Remove all of the keys in the hashes which keep track of
 5761:     # the version of the parameter.
 5762:     while (my ($symb,$param_hash) = each(%returnhash)) {
 5763:         # use a foreach because we are going to delete from the hash.
 5764:         foreach my $key (keys(%$param_hash)) {
 5765:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 5766:         }
 5767:     }
 5768:     return \%returnhash;
 5769: }
 5770: 
 5771: # ------------------------------------------------------ critical inc interface
 5772: 
 5773: sub cinc {
 5774:     return &inc(@_,'critical');
 5775: }
 5776: 
 5777: # --------------------------------------------------------------- inc interface
 5778: 
 5779: sub inc {
 5780:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 5781:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5782:     if (!$uname) { $uname=$env{'user.name'}; }
 5783:     my $uhome=&homeserver($uname,$udomain);
 5784:     my $items='';
 5785:     if (! ref($store)) {
 5786:         # got a single value, so use that instead
 5787:         $items = &escape($store).'=&';
 5788:     } elsif (ref($store) eq 'SCALAR') {
 5789:         $items = &escape($$store).'=&';        
 5790:     } elsif (ref($store) eq 'ARRAY') {
 5791:         $items = join('=&',map {&escape($_);} @{$store});
 5792:     } elsif (ref($store) eq 'HASH') {
 5793:         while (my($key,$value) = each(%{$store})) {
 5794:             $items.= &escape($key).'='.&escape($value).'&';
 5795:         }
 5796:     }
 5797:     $items=~s/\&$//;
 5798:     if ($critical) {
 5799: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 5800:     } else {
 5801: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 5802:     }
 5803: }
 5804: 
 5805: # --------------------------------------------------------------- put interface
 5806: 
 5807: sub put {
 5808:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5809:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5810:    if (!$uname) { $uname=$env{'user.name'}; }
 5811:    my $uhome=&homeserver($uname,$udomain);
 5812:    my $items='';
 5813:    foreach my $item (keys(%$storehash)) {
 5814:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5815:    }
 5816:    $items=~s/\&$//;
 5817:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5818: }
 5819: 
 5820: # ------------------------------------------------------------ newput interface
 5821: 
 5822: sub newput {
 5823:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5824:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5825:    if (!$uname) { $uname=$env{'user.name'}; }
 5826:    my $uhome=&homeserver($uname,$udomain);
 5827:    my $items='';
 5828:    foreach my $key (keys(%$storehash)) {
 5829:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5830:    }
 5831:    $items=~s/\&$//;
 5832:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 5833: }
 5834: 
 5835: # ---------------------------------------------------------  putstore interface
 5836: 
 5837: sub putstore {
 5838:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
 5839:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5840:    if (!$uname) { $uname=$env{'user.name'}; }
 5841:    my $uhome=&homeserver($uname,$udomain);
 5842:    my $items='';
 5843:    foreach my $key (keys(%$storehash)) {
 5844:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 5845:    }
 5846:    $items=~s/\&$//;
 5847:    my $esc_symb=&escape($symb);
 5848:    my $esc_v=&escape($version);
 5849:    my $reply =
 5850:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 5851: 	      $uhome);
 5852:    if (($tolog) && ($reply eq 'ok')) {
 5853:        my $namevalue='';
 5854:        foreach my $key (keys(%{$storehash})) {
 5855:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 5856:        }
 5857:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
 5858:                      '&host='.&escape($perlvar{'lonHostID'}).
 5859:                      '&version='.$esc_v.
 5860:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
 5861:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
 5862:    }
 5863:    if ($reply eq 'unknown_cmd') {
 5864:        # gfall back to way things use to be done
 5865:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 5866: 			    $uname);
 5867:    }
 5868:    return $reply;
 5869: }
 5870: 
 5871: sub old_putstore {
 5872:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5873:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5874:     if (!$uname) { $uname=$env{'user.name'}; }
 5875:     my $uhome=&homeserver($uname,$udomain);
 5876:     my %newstorehash;
 5877:     foreach my $item (keys(%$storehash)) {
 5878: 	my $key = $version.':'.&escape($symb).':'.$item;
 5879: 	$newstorehash{$key} = $storehash->{$item};
 5880:     }
 5881:     my $items='';
 5882:     my %allitems = ();
 5883:     foreach my $item (keys(%newstorehash)) {
 5884: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 5885: 	    my $key = $1.':keys:'.$2;
 5886: 	    $allitems{$key} .= $3.':';
 5887: 	}
 5888: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 5889:     }
 5890:     foreach my $item (keys(%allitems)) {
 5891: 	$allitems{$item} =~ s/\:$//;
 5892: 	$items.= $item.'='.$allitems{$item}.'&';
 5893:     }
 5894:     $items=~s/\&$//;
 5895:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5896: }
 5897: 
 5898: # ------------------------------------------------------ critical put interface
 5899: 
 5900: sub cput {
 5901:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5902:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5903:    if (!$uname) { $uname=$env{'user.name'}; }
 5904:    my $uhome=&homeserver($uname,$udomain);
 5905:    my $items='';
 5906:    foreach my $item (keys(%$storehash)) {
 5907:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5908:    }
 5909:    $items=~s/\&$//;
 5910:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 5911: }
 5912: 
 5913: # -------------------------------------------------------------- eget interface
 5914: 
 5915: sub eget {
 5916:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5917:    my $items='';
 5918:    foreach my $item (@$storearr) {
 5919:        $items.=&escape($item).'&';
 5920:    }
 5921:    $items=~s/\&$//;
 5922:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5923:    if (!$uname) { $uname=$env{'user.name'}; }
 5924:    my $uhome=&homeserver($uname,$udomain);
 5925:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 5926:    my @pairs=split(/\&/,$rep);
 5927:    my %returnhash=();
 5928:    my $i=0;
 5929:    foreach my $item (@$storearr) {
 5930:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5931:       $i++;
 5932:    }
 5933:    return %returnhash;
 5934: }
 5935: 
 5936: # ------------------------------------------------------------ tmpput interface
 5937: sub tmpput {
 5938:     my ($storehash,$server,$context)=@_;
 5939:     my $items='';
 5940:     foreach my $item (keys(%$storehash)) {
 5941: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5942:     }
 5943:     $items=~s/\&$//;
 5944:     if (defined($context)) {
 5945:         $items .= ':'.&escape($context);
 5946:     }
 5947:     return &reply("tmpput:$items",$server);
 5948: }
 5949: 
 5950: # ------------------------------------------------------------ tmpget interface
 5951: sub tmpget {
 5952:     my ($token,$server)=@_;
 5953:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5954:     my $rep=&reply("tmpget:$token",$server);
 5955:     my %returnhash;
 5956:     foreach my $item (split(/\&/,$rep)) {
 5957: 	my ($key,$value)=split(/=/,$item);
 5958:         next if ($key =~ /^error: 2 /);
 5959: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 5960:     }
 5961:     return %returnhash;
 5962: }
 5963: 
 5964: # ------------------------------------------------------------ tmpdel interface
 5965: sub tmpdel {
 5966:     my ($token,$server)=@_;
 5967:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5968:     return &reply("tmpdel:$token",$server);
 5969: }
 5970: 
 5971: # ------------------------------------------------------------ get_timebased_id 
 5972: 
 5973: sub get_timebased_id {
 5974:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 5975:         $maxtries) = @_;
 5976:     my ($newid,$error,$dellock);
 5977:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 5978:         return ('','ok','invalid call to get suffix');
 5979:     }
 5980: 
 5981: # set defaults for any optional args for which values were not supplied
 5982:     if ($who eq '') {
 5983:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 5984:     }
 5985:     if (!$locktries) {
 5986:         $locktries = 3;
 5987:     }
 5988:     if (!$maxtries) {
 5989:         $maxtries = 10;
 5990:     }
 5991:     
 5992:     if (($cdom eq '') || ($cnum eq '')) {
 5993:         if ($env{'request.course.id'}) {
 5994:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5995:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5996:         }
 5997:         if (($cdom eq '') || ($cnum eq '')) {
 5998:             return ('','ok','call to get suffix not in course context');
 5999:         }
 6000:     }
 6001: 
 6002: # construct locking item
 6003:     my $lockhash = {
 6004:                       $prefix."\0".'locked_'.$keyid => $who,
 6005:                    };
 6006:     my $tries = 0;
 6007: 
 6008: # attempt to get lock on nohist_$namespace file
 6009:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 6010:     while (($gotlock ne 'ok') && $tries <$locktries) {
 6011:         $tries ++;
 6012:         sleep 1;
 6013:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 6014:     }
 6015: 
 6016: # attempt to get unique identifier, based on current timestamp
 6017:     if ($gotlock eq 'ok') {
 6018:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 6019:         my $id = time;
 6020:         $newid = $id;
 6021:         if ($idtype eq 'addcode') {
 6022:             $newid .= &sixnum_code();
 6023:         }
 6024:         my $idtries = 0;
 6025:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 6026:             if ($idtype eq 'concat') {
 6027:                 $newid = $id.$idtries;
 6028:             } elsif ($idtype eq 'addcode') {
 6029:                 $newid = $newid.&sixnum_code();
 6030:             } else {
 6031:                 $newid ++;
 6032:             }
 6033:             $idtries ++;
 6034:         }
 6035:         if (!exists($inuse{$prefix."\0".$newid})) {
 6036:             my %new_item =  (
 6037:                               $prefix."\0".$newid => $who,
 6038:                             );
 6039:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 6040:                                                  $cdom,$cnum);
 6041:             if ($putresult ne 'ok') {
 6042:                 undef($newid);
 6043:                 $error = 'error saving new item: '.$putresult;
 6044:             }
 6045:         } else {
 6046:              undef($newid);
 6047:              $error = ('error: no unique suffix available for the new item ');
 6048:         }
 6049: #  remove lock
 6050:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 6051:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 6052:     } else {
 6053:         $error = "error: could not obtain lockfile\n";
 6054:         $dellock = 'ok';
 6055:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
 6056:             $dellock = 'nolock';
 6057:         }
 6058:     }
 6059:     return ($newid,$dellock,$error);
 6060: }
 6061: 
 6062: sub sixnum_code {
 6063:     my $code;
 6064:     for (0..6) {
 6065:         $code .= int( rand(9) );
 6066:     }
 6067:     return $code;
 6068: }
 6069: 
 6070: # -------------------------------------------------- portfolio access checking
 6071: 
 6072: sub portfolio_access {
 6073:     my ($requrl,$clientip) = @_;
 6074:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 6075:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
 6076:     if ($result) {
 6077:         my %setters;
 6078:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 6079:             my ($startblock,$endblock) =
 6080:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 6081:             if ($startblock && $endblock) {
 6082:                 return 'B';
 6083:             }
 6084:         } else {
 6085:             my ($startblock,$endblock) =
 6086:                 &Apache::loncommon::blockcheck(\%setters,'port');
 6087:             if ($startblock && $endblock) {
 6088:                 return 'B';
 6089:             }
 6090:         }
 6091:     }
 6092:     if ($result eq 'ok') {
 6093:        return 'F';
 6094:     } elsif ($result =~ /^[^:]+:guest_/) {
 6095:        return 'A';
 6096:     }
 6097:     return '';
 6098: }
 6099: 
 6100: sub get_portfolio_access {
 6101:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
 6102: 
 6103:     if (!ref($access_hash)) {
 6104: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 6105: 	my %access_controls = &get_access_controls($current_perms,$group,
 6106: 						   $file_name);
 6107: 	$access_hash = $access_controls{$file_name};
 6108:     }
 6109: 
 6110:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
 6111:     my $now = time;
 6112:     if (ref($access_hash) eq 'HASH') {
 6113:         foreach my $key (keys(%{$access_hash})) {
 6114:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 6115:             if ($start > $now) {
 6116:                 next;
 6117:             }
 6118:             if ($end && $end<$now) {
 6119:                 next;
 6120:             }
 6121:             if ($scope eq 'public') {
 6122:                 $public = $key;
 6123:                 last;
 6124:             } elsif ($scope eq 'guest') {
 6125:                 $guest = $key;
 6126:             } elsif ($scope eq 'domains') {
 6127:                 push(@domains,$key);
 6128:             } elsif ($scope eq 'users') {
 6129:                 push(@users,$key);
 6130:             } elsif ($scope eq 'course') {
 6131:                 push(@courses,$key);
 6132:             } elsif ($scope eq 'group') {
 6133:                 push(@groups,$key);
 6134:             } elsif ($scope eq 'ip') {
 6135:                 push(@ips,$key);
 6136:             }
 6137:         }
 6138:         if ($public) {
 6139:             return 'ok';
 6140:         } elsif (@ips > 0) {
 6141:             my $allowed;
 6142:             foreach my $ipkey (@ips) {
 6143:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
 6144:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
 6145:                         $allowed = 1;
 6146:                         last; 
 6147:                     }
 6148:                 }
 6149:             }
 6150:             if ($allowed) {
 6151:                 return 'ok';
 6152:             }
 6153:         }
 6154:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 6155:             if ($guest) {
 6156:                 return $guest;
 6157:             }
 6158:         } else {
 6159:             if (@domains > 0) {
 6160:                 foreach my $domkey (@domains) {
 6161:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 6162:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 6163:                             return 'ok';
 6164:                         }
 6165:                     }
 6166:                 }
 6167:             }
 6168:             if (@users > 0) {
 6169:                 foreach my $userkey (@users) {
 6170:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 6171:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 6172:                             if (ref($item) eq 'HASH') {
 6173:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 6174:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 6175:                                     return 'ok';
 6176:                                 }
 6177:                             }
 6178:                         }
 6179:                     } 
 6180:                 }
 6181:             }
 6182:             my %roleshash;
 6183:             my @courses_and_groups = @courses;
 6184:             push(@courses_and_groups,@groups); 
 6185:             if (@courses_and_groups > 0) {
 6186:                 my (%allgroups,%allroles); 
 6187:                 my ($start,$end,$role,$sec,$group);
 6188:                 foreach my $envkey (%env) {
 6189:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 6190:                         my $cid = $2.'_'.$3; 
 6191:                         if ($1 eq 'gr') {
 6192:                             $group = $4;
 6193:                             $allgroups{$cid}{$group} = $env{$envkey};
 6194:                         } else {
 6195:                             if ($4 eq '') {
 6196:                                 $sec = 'none';
 6197:                             } else {
 6198:                                 $sec = $4;
 6199:                             }
 6200:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 6201:                         }
 6202:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 6203:                         my $cid = $2.'_'.$3;
 6204:                         if ($4 eq '') {
 6205:                             $sec = 'none';
 6206:                         } else {
 6207:                             $sec = $4;
 6208:                         }
 6209:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 6210:                     }
 6211:                 }
 6212:                 if (keys(%allroles) == 0) {
 6213:                     return;
 6214:                 }
 6215:                 foreach my $key (@courses_and_groups) {
 6216:                     my %content = %{$$access_hash{$key}};
 6217:                     my $cnum = $content{'number'};
 6218:                     my $cdom = $content{'domain'};
 6219:                     my $cid = $cdom.'_'.$cnum;
 6220:                     if (!exists($allroles{$cid})) {
 6221:                         next;
 6222:                     }    
 6223:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 6224:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 6225:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 6226:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 6227:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 6228:                         foreach my $role (keys(%{$allroles{$cid}})) {
 6229:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 6230:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 6231:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 6232:                                         if (grep/^all$/,@sections) {
 6233:                                             return 'ok';
 6234:                                         } else {
 6235:                                             if (grep/^$sec$/,@sections) {
 6236:                                                 return 'ok';
 6237:                                             }
 6238:                                         }
 6239:                                     }
 6240:                                 }
 6241:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 6242:                                     if (grep/^none$/,@groups) {
 6243:                                         return 'ok';
 6244:                                     }
 6245:                                 } else {
 6246:                                     if (grep/^all$/,@groups) {
 6247:                                         return 'ok';
 6248:                                     } 
 6249:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 6250:                                         if (grep/^$group$/,@groups) {
 6251:                                             return 'ok';
 6252:                                         }
 6253:                                     }
 6254:                                 } 
 6255:                             }
 6256:                         }
 6257:                     }
 6258:                 }
 6259:             }
 6260:             if ($guest) {
 6261:                 return $guest;
 6262:             }
 6263:         }
 6264:     }
 6265:     return;
 6266: }
 6267: 
 6268: sub course_group_datechecker {
 6269:     my ($dates,$now,$status) = @_;
 6270:     my ($start,$end) = split(/\./,$dates);
 6271:     if (!$start && !$end) {
 6272:         return 'ok';
 6273:     }
 6274:     if (grep/^active$/,@{$status}) {
 6275:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 6276:             return 'ok';
 6277:         }
 6278:     }
 6279:     if (grep/^previous$/,@{$status}) {
 6280:         if ($end > $now ) {
 6281:             return 'ok';
 6282:         }
 6283:     }
 6284:     if (grep/^future$/,@{$status}) {
 6285:         if ($start > $now) {
 6286:             return 'ok';
 6287:         }
 6288:     }
 6289:     return; 
 6290: }
 6291: 
 6292: sub parse_portfolio_url {
 6293:     my ($url) = @_;
 6294: 
 6295:     my ($type,$udom,$unum,$group,$file_name);
 6296:     
 6297:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 6298: 	$type = 1;
 6299:         $udom = $1;
 6300:         $unum = $2;
 6301:         $file_name = $3;
 6302:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 6303: 	$type = 2;
 6304:         $udom = $1;
 6305:         $unum = $2;
 6306:         $group = $3;
 6307:         $file_name = $3.'/'.$4;
 6308:     }
 6309:     if (wantarray) {
 6310: 	return ($type,$udom,$unum,$file_name,$group);
 6311:     }
 6312:     return $type;
 6313: }
 6314: 
 6315: sub is_portfolio_url {
 6316:     my ($url) = @_;
 6317:     return scalar(&parse_portfolio_url($url));
 6318: }
 6319: 
 6320: sub is_portfolio_file {
 6321:     my ($file) = @_;
 6322:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 6323:         return 1;
 6324:     }
 6325:     return;
 6326: }
 6327: 
 6328: sub usertools_access {
 6329:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 6330:     my ($access,%tools);
 6331:     if ($context eq '') {
 6332:         $context = 'tools';
 6333:     }
 6334:     if ($context eq 'requestcourses') {
 6335:         %tools = (
 6336:                       official   => 1,
 6337:                       unofficial => 1,
 6338:                       community  => 1,
 6339:                       textbook   => 1,
 6340:                  );
 6341:     } elsif ($context eq 'requestauthor') {
 6342:         %tools = (
 6343:                       requestauthor => 1,
 6344:                  );
 6345:     } else {
 6346:         %tools = (
 6347:                       aboutme   => 1,
 6348:                       blog      => 1,
 6349:                       webdav    => 1,
 6350:                       portfolio => 1,
 6351:                  );
 6352:     }
 6353:     return if (!defined($tools{$tool}));
 6354: 
 6355:     if (($udom eq '') || ($uname eq '')) {
 6356:         $udom = $env{'user.domain'};
 6357:         $uname = $env{'user.name'};
 6358:     }
 6359: 
 6360:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6361:         if ($action ne 'reload') {
 6362:             if ($context eq 'requestcourses') {
 6363:                 return $env{'environment.canrequest.'.$tool};
 6364:             } elsif ($context eq 'requestauthor') {
 6365:                 return $env{'environment.canrequest.author'};
 6366:             } else {
 6367:                 return $env{'environment.availabletools.'.$tool};
 6368:             }
 6369:         }
 6370:     }
 6371: 
 6372:     my ($toolstatus,$inststatus,$envkey);
 6373:     if ($context eq 'requestauthor') {
 6374:         $envkey = $context; 
 6375:     } else {
 6376:         $envkey = $context.'.'.$tool;
 6377:     }
 6378: 
 6379:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 6380:          ($action ne 'reload')) {
 6381:         $toolstatus = $env{'environment.'.$envkey};
 6382:         $inststatus = $env{'environment.inststatus'};
 6383:     } else {
 6384:         if (ref($userenvref) eq 'HASH') {
 6385:             $toolstatus = $userenvref->{$envkey};
 6386:             $inststatus = $userenvref->{'inststatus'};
 6387:         } else {
 6388:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 6389:             $toolstatus = $userenv{$envkey};
 6390:             $inststatus = $userenv{'inststatus'};
 6391:         }
 6392:     }
 6393: 
 6394:     if ($toolstatus ne '') {
 6395:         if ($toolstatus) {
 6396:             $access = 1;
 6397:         } else {
 6398:             $access = 0;
 6399:         }
 6400:         return $access;
 6401:     }
 6402: 
 6403:     my ($is_adv,%domdef);
 6404:     if (ref($is_advref) eq 'HASH') {
 6405:         $is_adv = $is_advref->{'is_adv'};
 6406:     } else {
 6407:         $is_adv = &is_advanced_user($udom,$uname);
 6408:     }
 6409:     if (ref($domdefref) eq 'HASH') {
 6410:         %domdef = %{$domdefref};
 6411:     } else {
 6412:         %domdef = &get_domain_defaults($udom);
 6413:     }
 6414:     if (ref($domdef{$tool}) eq 'HASH') {
 6415:         if ($is_adv) {
 6416:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 6417:                 if ($domdef{$tool}{'_LC_adv'}) { 
 6418:                     $access = 1;
 6419:                 } else {
 6420:                     $access = 0;
 6421:                 }
 6422:                 return $access;
 6423:             }
 6424:         }
 6425:         if ($inststatus ne '') {
 6426:             my ($hasaccess,$hasnoaccess);
 6427:             foreach my $affiliation (split(/:/,$inststatus)) {
 6428:                 if ($domdef{$tool}{$affiliation} ne '') { 
 6429:                     if ($domdef{$tool}{$affiliation}) {
 6430:                         $hasaccess = 1;
 6431:                     } else {
 6432:                         $hasnoaccess = 1;
 6433:                     }
 6434:                 }
 6435:             }
 6436:             if ($hasaccess || $hasnoaccess) {
 6437:                 if ($hasaccess) {
 6438:                     $access = 1;
 6439:                 } elsif ($hasnoaccess) {
 6440:                     $access = 0; 
 6441:                 }
 6442:                 return $access;
 6443:             }
 6444:         } else {
 6445:             if ($domdef{$tool}{'default'} ne '') {
 6446:                 if ($domdef{$tool}{'default'}) {
 6447:                     $access = 1;
 6448:                 } elsif ($domdef{$tool}{'default'} == 0) {
 6449:                     $access = 0;
 6450:                 }
 6451:                 return $access;
 6452:             }
 6453:         }
 6454:     } else {
 6455:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 6456:             $access = 1;
 6457:         } else {
 6458:             $access = 0;
 6459:         }
 6460:         return $access;
 6461:     }
 6462: }
 6463: 
 6464: sub is_course_owner {
 6465:     my ($cdom,$cnum,$udom,$uname) = @_;
 6466:     if (($udom eq '') || ($uname eq '')) {
 6467:         $udom = $env{'user.domain'};
 6468:         $uname = $env{'user.name'};
 6469:     }
 6470:     unless (($udom eq '') || ($uname eq '')) {
 6471:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 6472:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 6473:                 return 1;
 6474:             } else {
 6475:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 6476:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 6477:                     return 1;
 6478:                 }
 6479:             }
 6480:         }
 6481:     }
 6482:     return;
 6483: }
 6484: 
 6485: sub is_advanced_user {
 6486:     my ($udom,$uname) = @_;
 6487:     if ($udom ne '' && $uname ne '') {
 6488:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6489:             if (wantarray) {
 6490:                 return ($env{'user.adv'},$env{'user.author'});
 6491:             } else {
 6492:                 return $env{'user.adv'};
 6493:             }
 6494:         }
 6495:     }
 6496:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 6497:     my %allroles;
 6498:     my ($is_adv,$is_author);
 6499:     foreach my $role (keys(%roleshash)) {
 6500:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 6501:         my $area = '/'.$tdomain.'/'.$trest;
 6502:         if ($sec ne '') {
 6503:             $area .= '/'.$sec;
 6504:         }
 6505:         if (($area ne '') && ($trole ne '')) {
 6506:             my $spec=$trole.'.'.$area;
 6507:             if ($trole =~ /^cr\//) {
 6508:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6509:             } elsif ($trole ne 'gr') {
 6510:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6511:             }
 6512:             if ($trole eq 'au') {
 6513:                 $is_author = 1;
 6514:             }
 6515:         }
 6516:     }
 6517:     foreach my $role (keys(%allroles)) {
 6518:         last if ($is_adv);
 6519:         foreach my $item (split(/:/,$allroles{$role})) {
 6520:             if ($item ne '') {
 6521:                 my ($privilege,$restrictions)=split(/&/,$item);
 6522:                 if ($privilege eq 'adv') {
 6523:                     $is_adv = 1;
 6524:                     last;
 6525:                 }
 6526:             }
 6527:         }
 6528:     }
 6529:     if (wantarray) {
 6530:         return ($is_adv,$is_author);
 6531:     }
 6532:     return $is_adv;
 6533: }
 6534: 
 6535: sub check_can_request {
 6536:     my ($dom,$can_request,$request_domains) = @_;
 6537:     my $canreq = 0;
 6538:     my ($types,$typename) = &Apache::loncommon::course_types();
 6539:     my @options = ('approval','validate','autolimit');
 6540:     my $optregex = join('|',@options);
 6541:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 6542:         foreach my $type (@{$types}) {
 6543:             if (&usertools_access($env{'user.name'},
 6544:                                   $env{'user.domain'},
 6545:                                   $type,undef,'requestcourses')) {
 6546:                 $canreq ++;
 6547:                 if (ref($request_domains) eq 'HASH') {
 6548:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 6549:                 }
 6550:                 if ($dom eq $env{'user.domain'}) {
 6551:                     $can_request->{$type} = 1;
 6552:                 }
 6553:             }
 6554:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 6555:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 6556:                 if (@curr > 0) {
 6557:                     foreach my $item (@curr) {
 6558:                         if (ref($request_domains) eq 'HASH') {
 6559:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 6560:                             if ($otherdom ne '') {
 6561:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 6562:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 6563:                                         push(@{$request_domains->{$type}},$otherdom);
 6564:                                     }
 6565:                                 } else {
 6566:                                     push(@{$request_domains->{$type}},$otherdom);
 6567:                                 }
 6568:                             }
 6569:                         }
 6570:                     }
 6571:                     unless($dom eq $env{'user.domain'}) {
 6572:                         $canreq ++;
 6573:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 6574:                             $can_request->{$type} = 1;
 6575:                         }
 6576:                     }
 6577:                 }
 6578:             }
 6579:         }
 6580:     }
 6581:     return $canreq;
 6582: }
 6583: 
 6584: # ---------------------------------------------- Custom access rule evaluation
 6585: 
 6586: sub customaccess {
 6587:     my ($priv,$uri)=@_;
 6588:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 6589:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 6590:     $udom = &LONCAPA::clean_domain($udom);
 6591:     $ucrs = &LONCAPA::clean_username($ucrs);
 6592:     my $access=0;
 6593:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 6594: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 6595: 	if ($type eq 'user') {
 6596: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 6597: 		my ($tdom,$tuname)=split(m{/},$scope);
 6598: 		if ($tdom) {
 6599: 		    if ($tdom ne $env{'user.domain'}) { next; }
 6600: 		}
 6601: 		if ($tuname) {
 6602: 		    if ($tuname ne $env{'user.name'}) { next; }
 6603: 		}
 6604: 		$access=($effect eq 'allow');
 6605: 		last;
 6606: 	    }
 6607: 	} else {
 6608: 	    if ($role) {
 6609: 		if ($role ne $urole) { next; }
 6610: 	    }
 6611: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 6612: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 6613: 		if ($tdom) {
 6614: 		    if ($tdom ne $udom) { next; }
 6615: 		}
 6616: 		if ($tcrs) {
 6617: 		    if ($tcrs ne $ucrs) { next; }
 6618: 		}
 6619: 		if ($tsec) {
 6620: 		    if ($tsec ne $usec) { next; }
 6621: 		}
 6622: 		$access=($effect eq 'allow');
 6623: 		last;
 6624: 	    }
 6625: 	    if ($realm eq '' && $role eq '') {
 6626: 		$access=($effect eq 'allow');
 6627: 	    }
 6628: 	}
 6629:     }
 6630:     return $access;
 6631: }
 6632: 
 6633: # ------------------------------------------------- Check for a user privilege
 6634: 
 6635: sub allowed {
 6636:     my ($priv,$uri,$symb,$role,$clientip)=@_;
 6637:     my $ver_orguri=$uri;
 6638:     $uri=&deversion($uri);
 6639:     my $orguri=$uri;
 6640:     $uri=&declutter($uri);
 6641: 
 6642:     if ($priv eq 'evb') {
 6643: # Evade communication block restrictions for specified role in a course
 6644:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 6645:             return $1;
 6646:         } else {
 6647:             return;
 6648:         }
 6649:     }
 6650: 
 6651:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 6652: # Free bre access to adm and meta resources
 6653:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 6654: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 6655: 	&& ($priv eq 'bre')) {
 6656: 	return 'F';
 6657:     }
 6658: 
 6659: # Free bre access to user's own portfolio contents
 6660:     my ($space,$domain,$name,@dir)=split('/',$uri);
 6661:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 6662: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 6663:         my %setters;
 6664:         my ($startblock,$endblock) = 
 6665:             &Apache::loncommon::blockcheck(\%setters,'port');
 6666:         if ($startblock && $endblock) {
 6667:             return 'B';
 6668:         } else {
 6669:             return 'F';
 6670:         }
 6671:     }
 6672: 
 6673: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 6674:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 6675:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 6676:         if (exists($env{'request.course.id'})) {
 6677:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6678:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6679:             if (($domain eq $cdom) && ($name eq $cnum)) {
 6680:                 my $courseprivid=$env{'request.course.id'};
 6681:                 $courseprivid=~s/\_/\//;
 6682:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 6683:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 6684:                     return $1; 
 6685:                 } else {
 6686:                     if ($env{'request.course.sec'}) {
 6687:                         $courseprivid.='/'.$env{'request.course.sec'};
 6688:                     }
 6689:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 6690:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 6691:                         return $2;
 6692:                     }
 6693:                 }
 6694:             }
 6695:         }
 6696:     }
 6697: 
 6698: # Free bre to public access
 6699: 
 6700:     if ($priv eq 'bre') {
 6701:         my $copyright=&metadata($uri,'copyright');
 6702: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 6703:            return 'F'; 
 6704:         }
 6705:         if ($copyright eq 'priv') {
 6706:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6707: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 6708: 		return '';
 6709:             }
 6710:         }
 6711:         if ($copyright eq 'domain') {
 6712:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6713: 	    unless (($env{'user.domain'} eq $1) ||
 6714:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 6715: 		return '';
 6716:             }
 6717:         }
 6718:         if ($env{'request.role'}=~ /li\.\//) {
 6719:             # Library role, so allow browsing of resources in this domain.
 6720:             return 'F';
 6721:         }
 6722:         if ($copyright eq 'custom') {
 6723: 	    unless (&customaccess($priv,$uri)) { return ''; }
 6724:         }
 6725:     }
 6726:     # Domain coordinator is trying to create a course
 6727:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 6728:         # uri is the requested domain in this case.
 6729:         # comparison to 'request.role.domain' shows if the user has selected
 6730:         # a role of dc for the domain in question.
 6731:         return 'F' if ($uri eq $env{'request.role.domain'});
 6732:     }
 6733: 
 6734:     my $thisallowed='';
 6735:     my $statecond=0;
 6736:     my $courseprivid='';
 6737: 
 6738:     my $ownaccess;
 6739:     # Community Coordinator or Assistant Co-author browsing resource space.
 6740:     if (($priv eq 'bro') && ($env{'user.author'})) {
 6741:         if ($uri eq '') {
 6742:             $ownaccess = 1;
 6743:         } else {
 6744:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 6745:                 my $udom = $env{'user.domain'};
 6746:                 my $uname = $env{'user.name'};
 6747:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 6748:                     $ownaccess = 1;
 6749:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 6750:                     unless ($uri =~ m{\.\./}) {
 6751:                         $ownaccess = 1;
 6752:                     }
 6753:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 6754:                     my $now = time;
 6755:                     if ($uri =~ m{^([^/]+)/?$}) {
 6756:                         my $adom = $1;
 6757:                         foreach my $key (keys(%env)) {
 6758:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 6759:                                 my ($start,$end) = split('.',$env{$key});
 6760:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6761:                                     $ownaccess = 1;
 6762:                                     last;
 6763:                                 }
 6764:                             }
 6765:                         }
 6766:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 6767:                         my $adom = $1;
 6768:                         my $aname = $2;
 6769:                         foreach my $role ('ca','aa') { 
 6770:                             if ($env{"user.role.$role./$adom/$aname"}) {
 6771:                                 my ($start,$end) =
 6772:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 6773:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6774:                                     $ownaccess = 1;
 6775:                                     last;
 6776:                                 }
 6777:                             }
 6778:                         }
 6779:                     }
 6780:                 }
 6781:             }
 6782:         }
 6783:     }
 6784: 
 6785: # Course
 6786: 
 6787:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 6788:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6789:             $thisallowed.=$1;
 6790:         }
 6791:     }
 6792: 
 6793: # Domain
 6794: 
 6795:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 6796:        =~/\Q$priv\E\&([^\:]*)/) {
 6797:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6798:             $thisallowed.=$1;
 6799:         }
 6800:     }
 6801: 
 6802: # User who is not author or co-author might still be able to edit
 6803: # resource of an author in the domain (e.g., if Domain Coordinator).
 6804:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 6805:         (&allowed('mdc',$env{'request.course.id'}))) {
 6806:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 6807:             $thisallowed.=$1;
 6808:         }
 6809:     }
 6810: 
 6811: # Course: uri itself is a course
 6812:     my $courseuri=$uri;
 6813:     $courseuri=~s/\_(\d)/\/$1/;
 6814:     $courseuri=~s/^([^\/])/\/$1/;
 6815: 
 6816:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 6817:        =~/\Q$priv\E\&([^\:]*)/) {
 6818:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6819:             $thisallowed.=$1;
 6820:         }
 6821:     }
 6822: 
 6823: # URI is an uploaded document for this course, default permissions don't matter
 6824: # not allowing 'edit' access (editupload) to uploaded course docs
 6825:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 6826: 	$thisallowed='';
 6827:         my ($match)=&is_on_map($uri);
 6828:         if ($match) {
 6829:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 6830:                   =~/\Q$priv\E\&([^\:]*)/) {
 6831:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6832:                 if (@blockers > 0) {
 6833:                     $thisallowed = 'B';
 6834:                 } else {
 6835:                     $thisallowed.=$1;
 6836:                 }
 6837:             }
 6838:         } else {
 6839:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 6840:             if ($refuri) {
 6841:                 if ($refuri =~ m|^/adm/|) {
 6842:                     $thisallowed='F';
 6843:                 } else {
 6844:                     $refuri=&declutter($refuri);
 6845:                     my ($match) = &is_on_map($refuri);
 6846:                     if ($match) {
 6847:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6848:                         if (@blockers > 0) {
 6849:                             $thisallowed = 'B';
 6850:                         } else {
 6851:                             $thisallowed='F';
 6852:                         }
 6853:                     }
 6854:                 }
 6855:             }
 6856:         }
 6857:     }
 6858: 
 6859:     if ($priv eq 'bre'
 6860: 	&& $thisallowed ne 'F' 
 6861: 	&& $thisallowed ne '2'
 6862: 	&& &is_portfolio_url($uri)) {
 6863: 	$thisallowed = &portfolio_access($uri,$clientip);
 6864:     }
 6865: 
 6866: # Full access at system, domain or course-wide level? Exit.
 6867:     if ($thisallowed=~/F/) {
 6868: 	return 'F';
 6869:     }
 6870: 
 6871: # If this is generating or modifying users, exit with special codes
 6872: 
 6873:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 6874: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 6875: 	    my ($audom,$auname)=split('/',$uri);
 6876: # no author name given, so this just checks on the general right to make a co-author in this domain
 6877: 	    unless ($auname) { return $thisallowed; }
 6878: # an author name is given, so we are about to actually make a co-author for a certain account
 6879: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 6880: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 6881: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 6882: 	}
 6883: 	return $thisallowed;
 6884:     }
 6885: #
 6886: # Gathered so far: system, domain and course wide privileges
 6887: #
 6888: # Course: See if uri or referer is an individual resource that is part of 
 6889: # the course
 6890: 
 6891:     if ($env{'request.course.id'}) {
 6892: 
 6893:        $courseprivid=$env{'request.course.id'};
 6894:        if ($env{'request.course.sec'}) {
 6895:           $courseprivid.='/'.$env{'request.course.sec'};
 6896:        }
 6897:        $courseprivid=~s/\_/\//;
 6898:        my $checkreferer=1;
 6899:        my ($match,$cond)=&is_on_map($uri);
 6900:        if ($match) {
 6901:            $statecond=$cond;
 6902:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6903:                =~/\Q$priv\E\&([^\:]*)/) {
 6904:                my $value = $1;
 6905:                if ($priv eq 'bre') {
 6906:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6907:                    if (@blockers > 0) {
 6908:                        $thisallowed = 'B';
 6909:                    } else {
 6910:                        $thisallowed.=$value;
 6911:                    }
 6912:                } else {
 6913:                    $thisallowed.=$value;
 6914:                }
 6915:                $checkreferer=0;
 6916:            }
 6917:        }
 6918:        
 6919:        if ($checkreferer) {
 6920: 	  my $refuri=$env{'httpref.'.$orguri};
 6921:             unless ($refuri) {
 6922:                 foreach my $key (keys(%env)) {
 6923: 		    if ($key=~/^httpref\..*\*/) {
 6924: 			my $pattern=$key;
 6925:                         $pattern=~s/^httpref\.\/res\///;
 6926:                         $pattern=~s/\*/\[\^\/\]\+/g;
 6927:                         $pattern=~s/\//\\\//g;
 6928:                         if ($orguri=~/$pattern/) {
 6929: 			    $refuri=$env{$key};
 6930:                         }
 6931:                     }
 6932:                 }
 6933:             }
 6934: 
 6935:          if ($refuri) { 
 6936: 	  $refuri=&declutter($refuri);
 6937:           my ($match,$cond)=&is_on_map($refuri);
 6938:             if ($match) {
 6939:               my $refstatecond=$cond;
 6940:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6941:                   =~/\Q$priv\E\&([^\:]*)/) {
 6942:                   my $value = $1;
 6943:                   if ($priv eq 'bre') {
 6944:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6945:                       if (@blockers > 0) {
 6946:                           $thisallowed = 'B';
 6947:                       } else {
 6948:                           $thisallowed.=$value;
 6949:                       }
 6950:                   } else {
 6951:                       $thisallowed.=$value;
 6952:                   }
 6953:                   $uri=$refuri;
 6954:                   $statecond=$refstatecond;
 6955:               }
 6956:           }
 6957:         }
 6958:        }
 6959:    }
 6960: 
 6961: #
 6962: # Gathered now: all privileges that could apply, and condition number
 6963: # 
 6964: #
 6965: # Full or no access?
 6966: #
 6967: 
 6968:     if ($thisallowed=~/F/) {
 6969: 	return 'F';
 6970:     }
 6971: 
 6972:     unless ($thisallowed) {
 6973:         return '';
 6974:     }
 6975: 
 6976: # Restrictions exist, deal with them
 6977: #
 6978: #   C:according to course preferences
 6979: #   R:according to resource settings
 6980: #   L:unless locked
 6981: #   X:according to user session state
 6982: #
 6983: 
 6984: # Possibly locked functionality, check all courses
 6985: # Locks might take effect only after 10 minutes cache expiration for other
 6986: # courses, and 2 minutes for current course
 6987: 
 6988:     my $envkey;
 6989:     if ($thisallowed=~/L/) {
 6990:         foreach $envkey (keys(%env)) {
 6991:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 6992:                my $courseid=$2;
 6993:                my $roleid=$1.'.'.$2;
 6994:                $courseid=~s/^\///;
 6995:                my $expiretime=600;
 6996:                if ($env{'request.role'} eq $roleid) {
 6997: 		  $expiretime=120;
 6998:                }
 6999: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 7000:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 7001:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 7002: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 7003:                }
 7004:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 7005:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 7006: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 7007:                        &log($env{'user.domain'},$env{'user.name'},
 7008:                             $env{'user.home'},
 7009:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 7010:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 7011:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 7012: 		       return '';
 7013:                    }
 7014:                }
 7015:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 7016:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 7017: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 7018:                        &log($env{'user.domain'},$env{'user.name'},
 7019:                             $env{'user.home'},
 7020:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 7021:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 7022:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 7023: 		       return '';
 7024:                    }
 7025:                }
 7026: 	   }
 7027:        }
 7028:     }
 7029:    
 7030: #
 7031: # Rest of the restrictions depend on selected course
 7032: #
 7033: 
 7034:     unless ($env{'request.course.id'}) {
 7035: 	if ($thisallowed eq 'A') {
 7036: 	    return 'A';
 7037:         } elsif ($thisallowed eq 'B') {
 7038:             return 'B';
 7039: 	} else {
 7040: 	    return '1';
 7041: 	}
 7042:     }
 7043: 
 7044: #
 7045: # Now user is definitely in a course
 7046: #
 7047: 
 7048: 
 7049: # Course preferences
 7050: 
 7051:    if ($thisallowed=~/C/) {
 7052:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 7053:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 7054:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 7055: 	   =~/\Q$rolecode\E/) {
 7056: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 7057: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 7058: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 7059: 			$env{'request.course.id'});
 7060: 	   }
 7061:            return '';
 7062:        }
 7063: 
 7064:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 7065: 	   =~/\Q$unamedom\E/) {
 7066: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 7067: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 7068: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 7069: 			$env{'request.course.id'});
 7070: 	   }
 7071:            return '';
 7072:        }
 7073:    }
 7074: 
 7075: # Resource preferences
 7076: 
 7077:    if ($thisallowed=~/R/) {
 7078:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 7079:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 7080: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 7081: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 7082: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 7083: 	   }
 7084: 	   return '';
 7085:        }
 7086:    }
 7087: 
 7088: # Restricted by state or randomout?
 7089: 
 7090:    if ($thisallowed=~/X/) {
 7091:       if ($env{'acc.randomout'}) {
 7092: 	 if (!$symb) { $symb=&symbread($uri,1); }
 7093:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 7094:             return ''; 
 7095:          }
 7096:       }
 7097:       if (&condval($statecond)) {
 7098: 	 return '2';
 7099:       } else {
 7100:          return '';
 7101:       }
 7102:    }
 7103: 
 7104:     if ($thisallowed eq 'A') {
 7105: 	return 'A';
 7106:     } elsif ($thisallowed eq 'B') {
 7107:         return 'B';
 7108:     }
 7109:    return 'F';
 7110: }
 7111: 
 7112: # ------------------------------------------- Check construction space access
 7113: 
 7114: sub constructaccess {
 7115:     my ($url,$setpriv)=@_;
 7116: 
 7117: # We do not allow editing of previous versions of files
 7118:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 7119: 
 7120: # Get username and domain from URL
 7121:     my ($ownername,$ownerdomain,$ownerhome);
 7122: 
 7123:     ($ownerdomain,$ownername) =
 7124:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
 7125: 
 7126: # The URL does not really point to any authorspace, forget it
 7127:     unless (($ownername) && ($ownerdomain)) { return ''; }
 7128: 
 7129: # Now we need to see if the user has access to the authorspace of
 7130: # $ownername at $ownerdomain
 7131: 
 7132:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 7133: # Real author for this?
 7134:        $ownerhome = $env{'user.home'};
 7135:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 7136:           return ($ownername,$ownerdomain,$ownerhome);
 7137:        }
 7138:     } else {
 7139: # Co-author for this?
 7140:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 7141:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 7142:             $ownerhome = &homeserver($ownername,$ownerdomain);
 7143:             return ($ownername,$ownerdomain,$ownerhome);
 7144:         }
 7145:     }
 7146: 
 7147: # We don't have any access right now. If we are not possibly going to do anything about this,
 7148: # we might as well leave
 7149:    unless ($setpriv) { return ''; }
 7150: 
 7151: # Backdoor access?
 7152:     my $allowed=&allowed('eco',$ownerdomain);
 7153: # Nope
 7154:     unless ($allowed) { return ''; }
 7155: # Looks like we may have access, but could be locked by the owner of the construction space
 7156:     if ($allowed eq 'U') {
 7157:         my %blocked=&get('environment',['domcoord.author'],
 7158:                          $ownerdomain,$ownername);
 7159: # Is blocked by owner
 7160:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 7161:     }
 7162:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 7163: # Grant temporary access
 7164:         my $then=$env{'user.login.time'};
 7165:         my $update=$env{'user.update.time'};
 7166:         if (!$update) { $update = $then; }
 7167:         my $refresh=$env{'user.refresh.time'};
 7168:         if (!$refresh) { $refresh = $update; }
 7169:         my $now = time;
 7170:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 7171:                            $now,'ca','constructaccess');
 7172:         $ownerhome = &homeserver($ownername,$ownerdomain);
 7173:         return($ownername,$ownerdomain,$ownerhome);
 7174:     }
 7175: # No business here
 7176:     return '';
 7177: }
 7178: 
 7179: sub get_comm_blocks {
 7180:     my ($cdom,$cnum) = @_;
 7181:     if ($cdom eq '' || $cnum eq '') {
 7182:         return unless ($env{'request.course.id'});
 7183:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7184:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7185:     }
 7186:     my %commblocks;
 7187:     my $hashid=$cdom.'_'.$cnum;
 7188:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 7189:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 7190:         %commblocks = %{$blocksref};
 7191:     } else {
 7192:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 7193:         my $cachetime = 600;
 7194:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 7195:     }
 7196:     return %commblocks;
 7197: }
 7198: 
 7199: sub has_comm_blocking {
 7200:     my ($priv,$symb,$uri,$blocks) = @_;
 7201:     return unless ($env{'request.course.id'});
 7202:     return unless ($priv eq 'bre');
 7203:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 7204:     my %commblocks;
 7205:     if (ref($blocks) eq 'HASH') {
 7206:         %commblocks = %{$blocks};
 7207:     } else {
 7208:         %commblocks = &get_comm_blocks();
 7209:     }
 7210:     return unless (keys(%commblocks) > 0);
 7211:     if (!$symb) { $symb=&symbread($uri,1); }
 7212:     my ($map,$resid,undef)=&decode_symb($symb);
 7213:     my %tocheck = (
 7214:                     maps      => $map,
 7215:                     resources => $symb,
 7216:                   );
 7217:     my @blockers;
 7218:     my $now = time;
 7219:     my $navmap = Apache::lonnavmaps::navmap->new();
 7220:     foreach my $block (keys(%commblocks)) {
 7221:         if ($block =~ /^(\d+)____(\d+)$/) {
 7222:             my ($start,$end) = ($1,$2);
 7223:             if ($start <= $now && $end >= $now) {
 7224:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 7225:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 7226:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 7227:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
 7228:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 7229:                                     push(@blockers,$block);
 7230:                                 }
 7231:                             }
 7232:                         }
 7233:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 7234:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
 7235:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
 7236:                                     push(@blockers,$block);
 7237:                                 }
 7238:                             }
 7239:                         }
 7240:                     }
 7241:                 }
 7242:             }
 7243:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 7244:             my $item = $1;
 7245:             my @to_test;
 7246:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 7247:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 7248:                     my $check_interval;
 7249:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
 7250:                         my @interval;
 7251:                         my $type = 'map';
 7252:                         if ($item eq 'course') {
 7253:                             $type = 'course';
 7254:                             @interval=&EXT("resource.0.interval");
 7255:                         } else {
 7256:                             if ($item =~ /___\d+___/) {
 7257:                                 $type = 'resource';
 7258:                                 @interval=&EXT("resource.0.interval",$item);
 7259:                                 if (ref($navmap)) {                        
 7260:                                     my $res = $navmap->getBySymb($item); 
 7261:                                     push(@to_test,$res);
 7262:                                 }
 7263:                             } else {
 7264:                                 my $mapsymb = &symbread($item,1);
 7265:                                 if ($mapsymb) {
 7266:                                     if (ref($navmap)) {
 7267:                                         my $mapres = $navmap->getBySymb($mapsymb);
 7268:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
 7269:                                         foreach my $res (@to_test) {
 7270:                                             my $symb = $res->symb();
 7271:                                             next if ($symb eq $mapsymb);
 7272:                                             if ($symb ne '') {
 7273:                                                 @interval=&EXT("resource.0.interval",$symb);
 7274:                                                 last;
 7275:                                             }
 7276:                                         }
 7277:                                     }
 7278:                                 }
 7279:                             }
 7280:                         }
 7281:                         if ($interval[0] =~ /\d+/) {
 7282:                             my $first_access;
 7283:                             if ($type eq 'resource') {
 7284:                                 $first_access=&get_first_access($interval[1],$item);
 7285:                             } elsif ($type eq 'map') {
 7286:                                 $first_access=&get_first_access($interval[1],undef,$item);
 7287:                             } else {
 7288:                                 $first_access=&get_first_access($interval[1]);
 7289:                             }
 7290:                             if ($first_access) {
 7291:                                 my $timesup = $first_access+$interval[0];
 7292:                                 if ($timesup > $now) {
 7293:                                     foreach my $res (@to_test) {
 7294:                                         if ($res->is_problem()) {
 7295:                                             if ($res->completable()) {
 7296:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 7297:                                                     push(@blockers,$block);
 7298:                                                 }
 7299:                                                 last;
 7300:                                             }
 7301:                                         }
 7302:                                     }
 7303:                                 }
 7304:                             }
 7305:                         }
 7306:                     }
 7307:                 }
 7308:             }
 7309:         }
 7310:     }
 7311:     return @blockers;
 7312: }
 7313: 
 7314: sub check_docs_block {
 7315:     my ($docsblock,$tocheck) =@_;
 7316:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
 7317:         return;
 7318:     }
 7319:     if (ref($docsblock->{'maps'}) eq 'HASH') {
 7320:         if ($tocheck->{'maps'}) {
 7321:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
 7322:                 return 1;
 7323:             }
 7324:         }
 7325:     }
 7326:     if (ref($docsblock->{'resources'}) eq 'HASH') {
 7327:         if ($tocheck->{'resources'}) {
 7328:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
 7329:                 return 1;
 7330:             }
 7331:         }
 7332:     }
 7333:     return;
 7334: }
 7335: 
 7336: #
 7337: #   Removes the versino from a URI and
 7338: #   splits it in to its filename and path to the filename.
 7339: #   Seems like File::Basename could have done this more clearly.
 7340: #   Parameters:
 7341: #      $uri   - input URI
 7342: #   Returns:
 7343: #     Two element list consisting of 
 7344: #     $pathname  - the URI up to and excluding the trailing /
 7345: #     $filename  - The part of the URI following the last /
 7346: #  NOTE:
 7347: #    Another realization of this is simply:
 7348: #    use File::Basename;
 7349: #    ...
 7350: #    $uri = shift;
 7351: #    $filename = basename($uri);
 7352: #    $path     = dirname($uri);
 7353: #    return ($filename, $path);
 7354: #
 7355: #     The implementation below is probably faster however.
 7356: #
 7357: sub split_uri_for_cond {
 7358:     my $uri=&deversion(&declutter(shift));
 7359:     my @uriparts=split(/\//,$uri);
 7360:     my $filename=pop(@uriparts);
 7361:     my $pathname=join('/',@uriparts);
 7362:     return ($pathname,$filename);
 7363: }
 7364: # --------------------------------------------------- Is a resource on the map?
 7365: 
 7366: sub is_on_map {
 7367:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 7368:     #Trying to find the conditional for the file
 7369:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 7370: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 7371:     if ($match) {
 7372: 	return (1,$1);
 7373:     } else {
 7374: 	return (0,0);
 7375:     }
 7376: }
 7377: 
 7378: # --------------------------------------------------------- Get symb from alias
 7379: 
 7380: sub get_symb_from_alias {
 7381:     my $symb=shift;
 7382:     my ($map,$resid,$url)=&decode_symb($symb);
 7383: # Already is a symb
 7384:     if ($url) { return $symb; }
 7385: # Must be an alias
 7386:     my $aliassymb='';
 7387:     my %bighash;
 7388:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7389:                             &GDBM_READER(),0640)) {
 7390:         my $rid=$bighash{'mapalias_'.$symb};
 7391: 	if ($rid) {
 7392: 	    my ($mapid,$resid)=split(/\./,$rid);
 7393: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 7394: 				    $resid,$bighash{'src_'.$rid});
 7395: 	}
 7396:         untie %bighash;
 7397:     }
 7398:     return $aliassymb;
 7399: }
 7400: 
 7401: # ----------------------------------------------------------------- Define Role
 7402: 
 7403: sub definerole {
 7404:   if (allowed('mcr','/')) {
 7405:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 7406:     foreach my $role (split(':',$sysrole)) {
 7407: 	my ($crole,$cqual)=split(/\&/,$role);
 7408:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 7409:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 7410: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 7411:                return "refused:s:$crole&$cqual"; 
 7412:             }
 7413:         }
 7414:     }
 7415:     foreach my $role (split(':',$domrole)) {
 7416: 	my ($crole,$cqual)=split(/\&/,$role);
 7417:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 7418:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 7419: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 7420:                return "refused:d:$crole&$cqual"; 
 7421:             }
 7422:         }
 7423:     }
 7424:     foreach my $role (split(':',$courole)) {
 7425: 	my ($crole,$cqual)=split(/\&/,$role);
 7426:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 7427:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 7428: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 7429:                return "refused:c:$crole&$cqual"; 
 7430:             }
 7431:         }
 7432:     }
 7433:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 7434:                 "$env{'user.domain'}:$env{'user.name'}:".
 7435: 	        "rolesdef_$rolename=".
 7436:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 7437:     return reply($command,$env{'user.home'});
 7438:   } else {
 7439:     return 'refused';
 7440:   }
 7441: }
 7442: 
 7443: # ---------------- Make a metadata query against the network of library servers
 7444: 
 7445: sub metadata_query {
 7446:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 7447:     my %rhash;
 7448:     my %libserv = &all_library();
 7449:     my @server_list = (defined($server_array) ? @$server_array
 7450:                                               : keys(%libserv) );
 7451:     for my $server (@server_list) {
 7452:         my $domains = ''; 
 7453:         if (ref($domains_hash) eq 'HASH') {
 7454:             $domains = $domains_hash->{$server}; 
 7455:         }
 7456: 	unless ($custom or $customshow) {
 7457: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 7458: 	    $rhash{$server}=$reply;
 7459: 	}
 7460: 	else {
 7461: 	    my $reply=&reply("querysend:".&escape($query).':'.
 7462: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 7463: 			     $server);
 7464: 	    $rhash{$server}=$reply;
 7465: 	}
 7466:     }
 7467:     return \%rhash;
 7468: }
 7469: 
 7470: # ----------------------------------------- Send log queries and wait for reply
 7471: 
 7472: sub log_query {
 7473:     my ($uname,$udom,$query,%filters)=@_;
 7474:     my $uhome=&homeserver($uname,$udom);
 7475:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 7476:     my $uhost=&hostname($uhome);
 7477:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 7478:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 7479:                        $uhome);
 7480:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 7481:     return get_query_reply($queryid);
 7482: }
 7483: 
 7484: # -------------------------- Update MySQL table for portfolio file
 7485: 
 7486: sub update_portfolio_table {
 7487:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 7488:     if ($group ne '') {
 7489:         $file_name =~s /^\Q$group\E//;
 7490:     }
 7491:     my $homeserver = &homeserver($uname,$udom);
 7492:     my $queryid=
 7493:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 7494:                ':'.&escape($file_name).':'.$action,$homeserver);
 7495:     my $reply = &get_query_reply($queryid);
 7496:     return $reply;
 7497: }
 7498: 
 7499: # -------------------------- Update MySQL allusers table
 7500: 
 7501: sub update_allusers_table {
 7502:     my ($uname,$udom,$names) = @_;
 7503:     my $homeserver = &homeserver($uname,$udom);
 7504:     my $queryid=
 7505:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 7506:                'lastname='.&escape($names->{'lastname'}).'%%'.
 7507:                'firstname='.&escape($names->{'firstname'}).'%%'.
 7508:                'middlename='.&escape($names->{'middlename'}).'%%'.
 7509:                'generation='.&escape($names->{'generation'}).'%%'.
 7510:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 7511:                'id='.&escape($names->{'id'}),$homeserver);
 7512:     return;
 7513: }
 7514: 
 7515: # ------- Request retrieval of institutional classlists for course(s)
 7516: 
 7517: sub fetch_enrollment_query {
 7518:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 7519:     my $homeserver;
 7520:     my $maxtries = 1;
 7521:     if ($context eq 'automated') {
 7522:         $homeserver = $perlvar{'lonHostID'};
 7523:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 7524:     } else {
 7525:         $homeserver = &homeserver($cnum,$dom);
 7526:     }
 7527:     my $host=&hostname($homeserver);
 7528:     my $cmd = '';
 7529:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7530:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7531:     }
 7532:     $cmd =~ s/%%$//;
 7533:     $cmd = &escape($cmd);
 7534:     my $query = 'fetchenrollment';
 7535:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 7536:     unless ($queryid=~/^\Q$host\E\_/) { 
 7537:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 7538:         return 'error: '.$queryid;
 7539:     }
 7540:     my $reply = &get_query_reply($queryid);
 7541:     my $tries = 1;
 7542:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7543:         $reply = &get_query_reply($queryid);
 7544:         $tries ++;
 7545:     }
 7546:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7547:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7548:     } else {
 7549:         my @responses = split(/:/,$reply);
 7550:         if ($homeserver eq $perlvar{'lonHostID'}) {
 7551:             foreach my $line (@responses) {
 7552:                 my ($key,$value) = split(/=/,$line,2);
 7553:                 $$replyref{$key} = $value;
 7554:             }
 7555:         } else {
 7556:             my $pathname = LONCAPA::tempdir();
 7557:             foreach my $line (@responses) {
 7558:                 my ($key,$value) = split(/=/,$line);
 7559:                 $$replyref{$key} = $value;
 7560:                 if ($value > 0) {
 7561:                     foreach my $item (@{$$affiliatesref{$key}}) {
 7562:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 7563:                         my $destname = $pathname.'/'.$filename;
 7564:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 7565:                         if ($xml_classlist =~ /^error/) {
 7566:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 7567:                         } else {
 7568:                             if ( open(FILE,">$destname") ) {
 7569:                                 print FILE &unescape($xml_classlist);
 7570:                                 close(FILE);
 7571:                             } else {
 7572:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 7573:                             }
 7574:                         }
 7575:                     }
 7576:                 }
 7577:             }
 7578:         }
 7579:         return 'ok';
 7580:     }
 7581:     return 'error';
 7582: }
 7583: 
 7584: sub get_query_reply {
 7585:     my $queryid=shift;
 7586:     my $replyfile=LONCAPA::tempdir().$queryid;
 7587:     my $reply='';
 7588:     for (1..100) {
 7589: 	sleep 2;
 7590:         if (-e $replyfile.'.end') {
 7591: 	    if (open(my $fh,$replyfile)) {
 7592: 		$reply = join('',<$fh>);
 7593: 		close($fh);
 7594: 	   } else { return 'error: reply_file_error'; }
 7595:            return &unescape($reply);
 7596: 	}
 7597:     }
 7598:     return 'timeout:'.$queryid;
 7599: }
 7600: 
 7601: sub courselog_query {
 7602: #
 7603: # possible filters:
 7604: # url: url or symb
 7605: # username
 7606: # domain
 7607: # action: view, submit, grade
 7608: # start: timestamp
 7609: # end: timestamp
 7610: #
 7611:     my (%filters)=@_;
 7612:     unless ($env{'request.course.id'}) { return 'no_course'; }
 7613:     if ($filters{'url'}) {
 7614: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 7615:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 7616:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 7617:     }
 7618:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7619:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7620:     return &log_query($cname,$cdom,'courselog',%filters);
 7621: }
 7622: 
 7623: sub userlog_query {
 7624: #
 7625: # possible filters:
 7626: # action: log check role
 7627: # start: timestamp
 7628: # end: timestamp
 7629: #
 7630:     my ($uname,$udom,%filters)=@_;
 7631:     return &log_query($uname,$udom,'userlog',%filters);
 7632: }
 7633: 
 7634: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 7635: 
 7636: sub auto_run {
 7637:     my ($cnum,$cdom) = @_;
 7638:     my $response = 0;
 7639:     my $settings;
 7640:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 7641:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 7642:         $settings = $domconfig{'autoenroll'};
 7643:         if ($settings->{'run'} eq '1') {
 7644:             $response = 1;
 7645:         }
 7646:     } else {
 7647:         my $homeserver;
 7648:         if (&is_course($cdom,$cnum)) {
 7649:             $homeserver = &homeserver($cnum,$cdom);
 7650:         } else {
 7651:             $homeserver = &domain($cdom,'primary');
 7652:         }
 7653:         if ($homeserver ne 'no_host') {
 7654:             $response = &reply('autorun:'.$cdom,$homeserver);
 7655:         }
 7656:     }
 7657:     return $response;
 7658: }
 7659: 
 7660: sub auto_get_sections {
 7661:     my ($cnum,$cdom,$inst_coursecode) = @_;
 7662:     my $homeserver;
 7663:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 7664:         $homeserver = &homeserver($cnum,$cdom);
 7665:     }
 7666:     if (!defined($homeserver)) { 
 7667:         if ($cdom =~ /^$match_domain$/) {
 7668:             $homeserver = &domain($cdom,'primary');
 7669:         }
 7670:     }
 7671:     my @secs;
 7672:     if (defined($homeserver)) {
 7673:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 7674:         unless ($response eq 'refused') {
 7675:             @secs = split(/:/,$response);
 7676:         }
 7677:     }
 7678:     return @secs;
 7679: }
 7680: 
 7681: sub auto_new_course {
 7682:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 7683:     my $homeserver = &homeserver($cnum,$cdom);
 7684:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 7685:     return $response;
 7686: }
 7687: 
 7688: sub auto_validate_courseID {
 7689:     my ($cnum,$cdom,$inst_course_id) = @_;
 7690:     my $homeserver = &homeserver($cnum,$cdom);
 7691:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 7692:     return $response;
 7693: }
 7694: 
 7695: sub auto_validate_instcode {
 7696:     my ($cnum,$cdom,$instcode,$owner) = @_;
 7697:     my ($homeserver,$response);
 7698:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7699:         $homeserver = &homeserver($cnum,$cdom);
 7700:     }
 7701:     if (!defined($homeserver)) {
 7702:         if ($cdom =~ /^$match_domain$/) {
 7703:             $homeserver = &domain($cdom,'primary');
 7704:         }
 7705:     }
 7706:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 7707:                         &escape($instcode).':'.&escape($owner),$homeserver));
 7708:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 7709:     return ($outcome,$description,$defaultcredits);
 7710: }
 7711: 
 7712: sub auto_create_password {
 7713:     my ($cnum,$cdom,$authparam,$udom) = @_;
 7714:     my ($homeserver,$response);
 7715:     my $create_passwd = 0;
 7716:     my $authchk = '';
 7717:     if ($udom =~ /^$match_domain$/) {
 7718:         $homeserver = &domain($udom,'primary');
 7719:     }
 7720:     if ($homeserver eq '') {
 7721:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7722:             $homeserver = &homeserver($cnum,$cdom);
 7723:         }
 7724:     }
 7725:     if ($homeserver eq '') {
 7726:         $authchk = 'nodomain';
 7727:     } else {
 7728:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 7729:         if ($response eq 'refused') {
 7730:             $authchk = 'refused';
 7731:         } else {
 7732:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 7733:         }
 7734:     }
 7735:     return ($authparam,$create_passwd,$authchk);
 7736: }
 7737: 
 7738: sub auto_photo_permission {
 7739:     my ($cnum,$cdom,$students) = @_;
 7740:     my $homeserver = &homeserver($cnum,$cdom);
 7741:     my ($outcome,$perm_reqd,$conditions) = 
 7742: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 7743:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7744: 	return (undef,undef);
 7745:     }
 7746:     return ($outcome,$perm_reqd,$conditions);
 7747: }
 7748: 
 7749: sub auto_checkphotos {
 7750:     my ($uname,$udom,$pid) = @_;
 7751:     my $homeserver = &homeserver($uname,$udom);
 7752:     my ($result,$resulttype);
 7753:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 7754: 				   &escape($uname).':'.&escape($pid),
 7755: 				   $homeserver));
 7756:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7757: 	return (undef,undef);
 7758:     }
 7759:     if ($outcome) {
 7760:         ($result,$resulttype) = split(/:/,$outcome);
 7761:     } 
 7762:     return ($result,$resulttype);
 7763: }
 7764: 
 7765: sub auto_photochoice {
 7766:     my ($cnum,$cdom) = @_;
 7767:     my $homeserver = &homeserver($cnum,$cdom);
 7768:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 7769: 						       &escape($cdom),
 7770: 						       $homeserver)));
 7771:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7772: 	return (undef,undef);
 7773:     }
 7774:     return ($update,$comment);
 7775: }
 7776: 
 7777: sub auto_photoupdate {
 7778:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 7779:     my $homeserver = &homeserver($cnum,$dom);
 7780:     my $host=&hostname($homeserver);
 7781:     my $cmd = '';
 7782:     my $maxtries = 1;
 7783:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7784:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7785:     }
 7786:     $cmd =~ s/%%$//;
 7787:     $cmd = &escape($cmd);
 7788:     my $query = 'institutionalphotos';
 7789:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 7790:     unless ($queryid=~/^\Q$host\E\_/) {
 7791:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 7792:         return 'error: '.$queryid;
 7793:     }
 7794:     my $reply = &get_query_reply($queryid);
 7795:     my $tries = 1;
 7796:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7797:         $reply = &get_query_reply($queryid);
 7798:         $tries ++;
 7799:     }
 7800:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7801:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7802:     } else {
 7803:         my @responses = split(/:/,$reply);
 7804:         my $outcome = shift(@responses); 
 7805:         foreach my $item (@responses) {
 7806:             my ($key,$value) = split(/=/,$item);
 7807:             $$photo{$key} = $value;
 7808:         }
 7809:         return $outcome;
 7810:     }
 7811:     return 'error';
 7812: }
 7813: 
 7814: sub auto_instcode_format {
 7815:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 7816: 	$cat_order) = @_;
 7817:     my $courses = '';
 7818:     my @homeservers;
 7819:     if ($caller eq 'global') {
 7820: 	my %servers = &get_servers($codedom,'library');
 7821: 	foreach my $tryserver (keys(%servers)) {
 7822: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7823: 		push(@homeservers,$tryserver);
 7824: 	    }
 7825:         }
 7826:     } elsif ($caller eq 'requests') {
 7827:         if ($codedom =~ /^$match_domain$/) {
 7828:             my $chome = &domain($codedom,'primary');
 7829:             unless ($chome eq 'no_host') {
 7830:                 push(@homeservers,$chome);
 7831:             }
 7832:         }
 7833:     } else {
 7834:         push(@homeservers,&homeserver($caller,$codedom));
 7835:     }
 7836:     foreach my $code (keys(%{$instcodes})) {
 7837:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 7838:     }
 7839:     chop($courses);
 7840:     my $ok_response = 0;
 7841:     my $response;
 7842:     while (@homeservers > 0 && $ok_response == 0) {
 7843:         my $server = shift(@homeservers); 
 7844:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 7845:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 7846:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 7847: 		split(/:/,$response);
 7848:             %{$codes} = (%{$codes},&str2hash($codes_str));
 7849:             push(@{$codetitles},&str2array($codetitles_str));
 7850:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 7851:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 7852:             $ok_response = 1;
 7853:         }
 7854:     }
 7855:     if ($ok_response) {
 7856:         return 'ok';
 7857:     } else {
 7858:         return $response;
 7859:     }
 7860: }
 7861: 
 7862: sub auto_instcode_defaults {
 7863:     my ($domain,$returnhash,$code_order) = @_;
 7864:     my @homeservers;
 7865: 
 7866:     my %servers = &get_servers($domain,'library');
 7867:     foreach my $tryserver (keys(%servers)) {
 7868: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7869: 	    push(@homeservers,$tryserver);
 7870: 	}
 7871:     }
 7872: 
 7873:     my $response;
 7874:     foreach my $server (@homeservers) {
 7875:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 7876:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7877: 	
 7878: 	foreach my $pair (split(/\&/,$response)) {
 7879: 	    my ($name,$value)=split(/\=/,$pair);
 7880: 	    if ($name eq 'code_order') {
 7881: 		@{$code_order} = split(/\&/,&unescape($value));
 7882: 	    } else {
 7883: 		$returnhash->{&unescape($name)}=&unescape($value);
 7884: 	    }
 7885: 	}
 7886: 	return 'ok';
 7887:     }
 7888: 
 7889:     return $response;
 7890: }
 7891: 
 7892: sub auto_possible_instcodes {
 7893:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 7894:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 7895:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 7896:         return;
 7897:     }
 7898:     my (@homeservers,$uhome);
 7899:     if (defined(&domain($domain,'primary'))) {
 7900:         $uhome=&domain($domain,'primary');
 7901:         push(@homeservers,&domain($domain,'primary'));
 7902:     } else {
 7903:         my %servers = &get_servers($domain,'library');
 7904:         foreach my $tryserver (keys(%servers)) {
 7905:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7906:                 push(@homeservers,$tryserver);
 7907:             }
 7908:         }
 7909:     }
 7910:     my $response;
 7911:     foreach my $server (@homeservers) {
 7912:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 7913:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7914:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 7915:             split(':',$response);
 7916:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 7917:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 7918:         foreach my $item (split('&',$cat_title)) {   
 7919:             my ($name,$value)=split('=',$item);
 7920:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 7921:         }
 7922:         foreach my $item (split('&',$cat_order)) {
 7923:             my ($name,$value)=split('=',$item);
 7924:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 7925:         }
 7926:         return 'ok';
 7927:     }
 7928:     return $response;
 7929: }
 7930: 
 7931: sub auto_courserequest_checks {
 7932:     my ($dom) = @_;
 7933:     my ($homeserver,%validations);
 7934:     if ($dom =~ /^$match_domain$/) {
 7935:         $homeserver = &domain($dom,'primary');
 7936:     }
 7937:     unless ($homeserver eq 'no_host') {
 7938:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 7939:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 7940:             my @items = split(/&/,$response);
 7941:             foreach my $item (@items) {
 7942:                 my ($key,$value) = split('=',$item);
 7943:                 $validations{&unescape($key)} = &thaw_unescape($value);
 7944:             }
 7945:         }
 7946:     }
 7947:     return %validations; 
 7948: }
 7949: 
 7950: sub auto_courserequest_validation {
 7951:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
 7952:     my ($homeserver,$response);
 7953:     if ($dom =~ /^$match_domain$/) {
 7954:         $homeserver = &domain($dom,'primary');
 7955:     }
 7956:     unless ($homeserver eq 'no_host') {
 7957:         my $customdata;
 7958:         if (ref($custominfo) eq 'HASH') {
 7959:             $customdata = &freeze_escape($custominfo);
 7960:         }
 7961:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 7962:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 7963:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
 7964:                                     $customdata,$homeserver));
 7965:     }
 7966:     return $response;
 7967: }
 7968: 
 7969: sub auto_validate_class_sec {
 7970:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 7971:     my $homeserver = &homeserver($cnum,$cdom);
 7972:     my $ownerlist;
 7973:     if (ref($owners) eq 'ARRAY') {
 7974:         $ownerlist = join(',',@{$owners});
 7975:     } else {
 7976:         $ownerlist = $owners;
 7977:     }
 7978:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 7979:                         &escape($ownerlist).':'.$cdom,$homeserver);
 7980:     return $response;
 7981: }
 7982: 
 7983: sub auto_crsreq_update {
 7984:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
 7985:         $code,$accessstart,$accessend,$inbound) = @_;
 7986:     my ($homeserver,%crsreqresponse);
 7987:     if ($cdom =~ /^$match_domain$/) {
 7988:         $homeserver = &domain($cdom,'primary');
 7989:     }
 7990:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 7991:         my $info;
 7992:         if (ref($inbound) eq 'HASH') {
 7993:             $info = &freeze_escape($inbound);
 7994:         }
 7995:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
 7996:                             ':'.&escape($action).':'.&escape($ownername).':'.
 7997:                             &escape($ownerdomain).':'.&escape($fullname).':'.
 7998:                             &escape($title).':'.&escape($code).':'.
 7999:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
 8000:                             $homeserver);
 8001:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 8002:             my @items = split(/&/,$response);
 8003:             foreach my $item (@items) {
 8004:                 my ($key,$value) = split('=',$item);
 8005:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
 8006:             }
 8007:         }
 8008:     }
 8009:     return \%crsreqresponse;
 8010: }
 8011: 
 8012: # ------------------------------------------------------- Course Group routines
 8013: 
 8014: sub get_coursegroups {
 8015:     my ($cdom,$cnum,$group,$namespace) = @_;
 8016:     return(&dump($namespace,$cdom,$cnum,$group));
 8017: }
 8018: 
 8019: sub modify_coursegroup {
 8020:     my ($cdom,$cnum,$groupsettings) = @_;
 8021:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 8022: }
 8023: 
 8024: sub toggle_coursegroup_status {
 8025:     my ($cdom,$cnum,$group,$action) = @_;
 8026:     my ($from_namespace,$to_namespace);
 8027:     if ($action eq 'delete') {
 8028:         $from_namespace = 'coursegroups';
 8029:         $to_namespace = 'deleted_groups';
 8030:     } else {
 8031:         $from_namespace = 'deleted_groups';
 8032:         $to_namespace = 'coursegroups';
 8033:     }
 8034:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 8035:     if (my $tmp = &error(%curr_group)) {
 8036:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 8037:         return ('read error',$tmp);
 8038:     } else {
 8039:         my %savedsettings = %curr_group; 
 8040:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 8041:         my $deloutcome;
 8042:         if ($result eq 'ok') {
 8043:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 8044:         } else {
 8045:             return ('write error',$result);
 8046:         }
 8047:         if ($deloutcome eq 'ok') {
 8048:             return 'ok';
 8049:         } else {
 8050:             return ('delete error',$deloutcome);
 8051:         }
 8052:     }
 8053: }
 8054: 
 8055: sub modify_group_roles {
 8056:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 8057:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 8058:     my $role = 'gr/'.&escape($userprivs);
 8059:     my ($uname,$udom) = split(/:/,$user);
 8060:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 8061:     if ($result eq 'ok') {
 8062:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 8063:     }
 8064:     return $result;
 8065: }
 8066: 
 8067: sub modify_coursegroup_membership {
 8068:     my ($cdom,$cnum,$membership) = @_;
 8069:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 8070:     return $result;
 8071: }
 8072: 
 8073: sub get_active_groups {
 8074:     my ($udom,$uname,$cdom,$cnum) = @_;
 8075:     my $now = time;
 8076:     my %groups = ();
 8077:     foreach my $key (keys(%env)) {
 8078:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 8079:             my ($start,$end) = split(/\./,$env{$key});
 8080:             if (($end!=0) && ($end<$now)) { next; }
 8081:             if (($start!=0) && ($start>$now)) { next; }
 8082:             if ($1 eq $cdom && $2 eq $cnum) {
 8083:                 $groups{$3} = $env{$key} ;
 8084:             }
 8085:         }
 8086:     }
 8087:     return %groups;
 8088: }
 8089: 
 8090: sub get_group_membership {
 8091:     my ($cdom,$cnum,$group) = @_;
 8092:     return(&dump('groupmembership',$cdom,$cnum,$group));
 8093: }
 8094: 
 8095: sub get_users_groups {
 8096:     my ($udom,$uname,$courseid) = @_;
 8097:     my @usersgroups;
 8098:     my $cachetime=1800;
 8099: 
 8100:     my $hashid="$udom:$uname:$courseid";
 8101:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 8102:     if (defined($cached)) {
 8103:         @usersgroups = split(/:/,$grouplist);
 8104:     } else {  
 8105:         $grouplist = '';
 8106:         my $courseurl = &courseid_to_courseurl($courseid);
 8107:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 8108:         my $access_end = $env{'course.'.$courseid.
 8109:                               '.default_enrollment_end_date'};
 8110:         my $now = time;
 8111:         foreach my $key (keys(%roleshash)) {
 8112:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 8113:                 my $group = $1;
 8114:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 8115:                     my $start = $2;
 8116:                     my $end = $1;
 8117:                     if ($start == -1) { next; } # deleted from group
 8118:                     if (($start!=0) && ($start>$now)) { next; }
 8119:                     if (($end!=0) && ($end<$now)) {
 8120:                         if ($access_end && $access_end < $now) {
 8121:                             if ($access_end - $end < 86400) {
 8122:                                 push(@usersgroups,$group);
 8123:                             }
 8124:                         }
 8125:                         next;
 8126:                     }
 8127:                     push(@usersgroups,$group);
 8128:                 }
 8129:             }
 8130:         }
 8131:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 8132:         $grouplist = join(':',@usersgroups);
 8133:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 8134:     }
 8135:     return @usersgroups;
 8136: }
 8137: 
 8138: sub devalidate_getgroups_cache {
 8139:     my ($udom,$uname,$cdom,$cnum)=@_;
 8140:     my $courseid = $cdom.'_'.$cnum;
 8141: 
 8142:     my $hashid="$udom:$uname:$courseid";
 8143:     &devalidate_cache_new('getgroups',$hashid);
 8144: }
 8145: 
 8146: # ------------------------------------------------------------------ Plain Text
 8147: 
 8148: sub plaintext {
 8149:     my ($short,$type,$cid,$forcedefault) = @_;
 8150:     if ($short =~ m{^cr/}) {
 8151: 	return (split('/',$short))[-1];
 8152:     }
 8153:     if (!defined($cid)) {
 8154:         $cid = $env{'request.course.id'};
 8155:     }
 8156:     my %rolenames = (
 8157:                       Course    => 'std',
 8158:                       Community => 'alt1',
 8159:                     );
 8160:     if ($cid ne '') {
 8161:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 8162:             unless ($forcedefault) {
 8163:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 8164:                 &Apache::lonlocal::mt_escape(\$roletext);
 8165:                 return &Apache::lonlocal::mt($roletext);
 8166:             }
 8167:         }
 8168:     }
 8169:     if ((defined($type)) && (defined($rolenames{$type})) &&
 8170:         (defined($rolenames{$type})) && 
 8171:         (defined($prp{$short}{$rolenames{$type}}))) {
 8172:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 8173:     } elsif ($cid ne '') {
 8174:         my $crstype = $env{'course.'.$cid.'.type'};
 8175:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 8176:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 8177:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 8178:         }
 8179:     }
 8180:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 8181: }
 8182: 
 8183: # ----------------------------------------------------------------- Assign Role
 8184: 
 8185: sub assignrole {
 8186:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 8187:         $context)=@_;
 8188:     my $mrole;
 8189:     if ($role =~ /^cr\//) {
 8190:         my $cwosec=$url;
 8191:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 8192: 	unless (&allowed('ccr',$cwosec)) {
 8193:            my $refused = 1;
 8194:            if ($context eq 'requestcourses') {
 8195:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 8196:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 8197:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 8198:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 8199:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8200:                            if ($crsenv{'internal.courseowner'} eq
 8201:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 8202:                                $refused = '';
 8203:                            }
 8204:                        }
 8205:                    }
 8206:                }
 8207:            }
 8208:            if ($refused) {
 8209:                &logthis('Refused custom assignrole: '.
 8210:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 8211:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 8212:                return 'refused';
 8213:            }
 8214:         }
 8215:         $mrole='cr';
 8216:     } elsif ($role =~ /^gr\//) {
 8217:         my $cwogrp=$url;
 8218:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 8219:         unless (&allowed('mdg',$cwogrp)) {
 8220:             &logthis('Refused group assignrole: '.
 8221:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 8222:                     $env{'user.name'}.' at '.$env{'user.domain'});
 8223:             return 'refused';
 8224:         }
 8225:         $mrole='gr';
 8226:     } else {
 8227:         my $cwosec=$url;
 8228:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 8229:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 8230:             my $refused;
 8231:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 8232:                 if (!(&allowed('c'.$role,$url))) {
 8233:                     $refused = 1;
 8234:                 }
 8235:             } else {
 8236:                 $refused = 1;
 8237:             }
 8238:             if ($refused) {
 8239:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 8240:                 if (!$selfenroll && $context eq 'course') {
 8241:                     my %crsenv;
 8242:                     if ($role eq 'cc' || $role eq 'co') {
 8243:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8244:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 8245:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 8246:                                 if ($crsenv{'internal.courseowner'} eq 
 8247:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 8248:                                     $refused = '';
 8249:                                 }
 8250:                             }
 8251:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 8252:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 8253:                                 if ($crsenv{'internal.courseowner'} eq 
 8254:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 8255:                                     $refused = '';
 8256:                                 }
 8257:                             }
 8258:                         }
 8259:                     }
 8260:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 8261:                     $refused = '';
 8262:                 } elsif ($context eq 'requestcourses') {
 8263:                     my @possroles = ('st','ta','ep','in','cc','co');
 8264:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 8265:                         my $wrongcc;
 8266:                         if ($cnum =~ /^$match_community$/) {
 8267:                             $wrongcc = 1 if ($role eq 'cc');
 8268:                         } else {
 8269:                             $wrongcc = 1 if ($role eq 'co');
 8270:                         }
 8271:                         unless ($wrongcc) {
 8272:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8273:                             if ($crsenv{'internal.courseowner'} eq 
 8274:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 8275:                                 $refused = '';
 8276:                             }
 8277:                         }
 8278:                     }
 8279:                 } elsif ($context eq 'requestauthor') {
 8280:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
 8281:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 8282:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 8283:                             $refused = '';
 8284:                         } else {
 8285:                             my %domdefaults = &get_domain_defaults($udom);
 8286:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 8287:                                 my $checkbystatus;
 8288:                                 if ($env{'user.adv'}) { 
 8289:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 8290:                                     if ($disposition eq 'automatic') {
 8291:                                         $refused = '';
 8292:                                     } elsif ($disposition eq '') {
 8293:                                         $checkbystatus = 1;
 8294:                                     } 
 8295:                                 } else {
 8296:                                     $checkbystatus = 1;
 8297:                                 }
 8298:                                 if ($checkbystatus) {
 8299:                                     if ($env{'environment.inststatus'}) {
 8300:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 8301:                                         foreach my $type (@inststatuses) {
 8302:                                             if (($type ne '') &&
 8303:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 8304:                                                 $refused = '';
 8305:                                             }
 8306:                                         }
 8307:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 8308:                                         $refused = '';
 8309:                                     }
 8310:                                 }
 8311:                             }
 8312:                         }
 8313:                     }
 8314:                 }
 8315:                 if ($refused) {
 8316:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 8317:                              ' '.$role.' '.$end.' '.$start.' by '.
 8318: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 8319:                     return 'refused';
 8320:                 }
 8321:             }
 8322:         } elsif ($role eq 'au') {
 8323:             if ($url ne '/'.$udom.'/') {
 8324:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 8325:                          ' to assign author role for '.$uname.':'.$udom.
 8326:                          ' in domain: '.$url.' refused (wrong domain).');
 8327:                 return 'refused';
 8328:             }
 8329:         }
 8330:         $mrole=$role;
 8331:     }
 8332:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 8333:                 "$udom:$uname:$url".'_'."$mrole=$role";
 8334:     if ($end) { $command.='_'.$end; }
 8335:     if ($start) {
 8336: 	if ($end) { 
 8337:            $command.='_'.$start; 
 8338:         } else {
 8339:            $command.='_0_'.$start;
 8340:         }
 8341:     }
 8342:     my $origstart = $start;
 8343:     my $origend = $end;
 8344:     my $delflag;
 8345: # actually delete
 8346:     if ($deleteflag) {
 8347: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 8348: # modify command to delete the role
 8349:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 8350:                 "$udom:$uname:$url".'_'."$mrole";
 8351: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 8352: # set start and finish to negative values for userrolelog
 8353:            $start=-1;
 8354:            $end=-1;
 8355:            $delflag = 1;
 8356:         }
 8357:     }
 8358: # send command
 8359:     my $answer=&reply($command,&homeserver($uname,$udom));
 8360: # log new user role if status is ok
 8361:     if ($answer eq 'ok') {
 8362: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 8363:         if (($role eq 'cc') || ($role eq 'in') ||
 8364:             ($role eq 'ep') || ($role eq 'ad') ||
 8365:             ($role eq 'ta') || ($role eq 'st') ||
 8366:             ($role=~/^cr/) || ($role eq 'gr') ||
 8367:             ($role eq 'co')) {
 8368: # for course roles, perform group memberships changes triggered by role change.
 8369:             unless ($role =~ /^gr/) {
 8370:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 8371:                                                  $origstart,$selfenroll,$context);
 8372:             }
 8373:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8374:                            $selfenroll,$context);
 8375:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
 8376:                  ($role eq 'au') || ($role eq 'dc')) {
 8377:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8378:                            $context);
 8379:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
 8380:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8381:                              $context); 
 8382:         }
 8383:         if ($role eq 'cc') {
 8384:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 8385:         }
 8386:     }
 8387:     return $answer;
 8388: }
 8389: 
 8390: sub autoupdate_coowners {
 8391:     my ($url,$end,$start,$uname,$udom) = @_;
 8392:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 8393:     if (($cdom ne '') && ($cnum ne '')) {
 8394:         my $now = time;
 8395:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 8396:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 8397:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 8398:             my $instcode = $coursehash{'internal.coursecode'};
 8399:             if ($instcode ne '') {
 8400:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 8401:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 8402:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 8403:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 8404:                         if ($result eq 'valid') {
 8405:                             if ($coursehash{'internal.co-owners'}) {
 8406:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 8407:                                     push(@newcoowners,$coowner);
 8408:                                 }
 8409:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 8410:                                     push(@newcoowners,$uname.':'.$udom);
 8411:                                 }
 8412:                                 @newcoowners = sort(@newcoowners);
 8413:                             } else {
 8414:                                 push(@newcoowners,$uname.':'.$udom);
 8415:                             }
 8416:                         } else {
 8417:                             if ($coursehash{'internal.co-owners'}) {
 8418:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 8419:                                     unless ($coowner eq $uname.':'.$udom) {
 8420:                                         push(@newcoowners,$coowner);
 8421:                                     }
 8422:                                 }
 8423:                                 unless (@newcoowners > 0) {
 8424:                                     $delcoowners = 1;
 8425:                                     $coowners = '';
 8426:                                 }
 8427:                             }
 8428:                         }
 8429:                         if (@newcoowners || $delcoowners) {
 8430:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 8431:                                             $delcoowners,@newcoowners);
 8432:                         }
 8433:                     }
 8434:                 }
 8435:             }
 8436:         }
 8437:     }
 8438: }
 8439: 
 8440: sub store_coowners {
 8441:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 8442:     my $cid = $cdom.'_'.$cnum;
 8443:     my ($coowners,$delresult,$putresult);
 8444:     if (@newcoowners) {
 8445:         $coowners = join(',',@newcoowners);
 8446:         my %coownershash = (
 8447:                             'internal.co-owners' => $coowners,
 8448:                            );
 8449:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 8450:         if ($putresult eq 'ok') {
 8451:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 8452:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 8453:             }
 8454:         }
 8455:     }
 8456:     if ($delcoowners) {
 8457:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 8458:         if ($delresult eq 'ok') {
 8459:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 8460:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 8461:             }
 8462:         }
 8463:     }
 8464:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 8465:         my %crsinfo =
 8466:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 8467:         if (ref($crsinfo{$cid}) eq 'HASH') {
 8468:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 8469:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 8470:         }
 8471:     }
 8472: }
 8473: 
 8474: # -------------------------------------------------- Modify user authentication
 8475: # Overrides without validation
 8476: 
 8477: sub modifyuserauth {
 8478:     my ($udom,$uname,$umode,$upass)=@_;
 8479:     my $uhome=&homeserver($uname,$udom);
 8480:     unless (&allowed('mau',$udom)) { return 'refused'; }
 8481:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 8482:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 8483:              ' in domain '.$env{'request.role.domain'});  
 8484:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 8485: 		     &escape($upass),$uhome);
 8486:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 8487:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 8488:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 8489:     &log($udom,,$uname,$uhome,
 8490:         'Authentication changed by '.$env{'user.domain'}.', '.
 8491:                                      $env{'user.name'}.', '.$umode.
 8492:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 8493:     unless ($reply eq 'ok') {
 8494:         &logthis('Authentication mode error: '.$reply);
 8495: 	return 'error: '.$reply;
 8496:     }   
 8497:     return 'ok';
 8498: }
 8499: 
 8500: # --------------------------------------------------------------- Modify a user
 8501: 
 8502: sub modifyuser {
 8503:     my ($udom,    $uname, $uid,
 8504:         $umode,   $upass, $first,
 8505:         $middle,  $last,  $gene,
 8506:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 8507:     $udom= &LONCAPA::clean_domain($udom);
 8508:     $uname=&LONCAPA::clean_username($uname);
 8509:     my $showcandelete = 'none';
 8510:     if (ref($candelete) eq 'ARRAY') {
 8511:         if (@{$candelete} > 0) {
 8512:             $showcandelete = join(', ',@{$candelete});
 8513:         }
 8514:     }
 8515:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 8516:              $umode.', '.$first.', '.$middle.', '.
 8517: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 8518:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 8519:                                      ' desiredhome not specified'). 
 8520:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 8521:              ' in domain '.$env{'request.role.domain'});
 8522:     my $uhome=&homeserver($uname,$udom,'true');
 8523:     my $newuser;
 8524:     if ($uhome eq 'no_host') {
 8525:         $newuser = 1;
 8526:     }
 8527: # ----------------------------------------------------------------- Create User
 8528:     if (($uhome eq 'no_host') && 
 8529: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 8530:         my $unhome='';
 8531:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 8532:             $unhome = $desiredhome;
 8533: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 8534: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 8535:         } else { # load balancing routine for determining $unhome
 8536:             my $loadm=10000000;
 8537: 	    my %servers = &get_servers($udom,'library');
 8538: 	    foreach my $tryserver (keys(%servers)) {
 8539: 		my $answer=reply('load',$tryserver);
 8540: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 8541: 		    $loadm=$answer;
 8542: 		    $unhome=$tryserver;
 8543: 		}
 8544: 	    }
 8545:         }
 8546:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 8547: 	    return 'error: unable to find a home server for '.$uname.
 8548:                    ' in domain '.$udom;
 8549:         }
 8550:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 8551:                          &escape($upass),$unhome);
 8552: 	unless ($reply eq 'ok') {
 8553:             return 'error: '.$reply;
 8554:         }   
 8555:         $uhome=&homeserver($uname,$udom,'true');
 8556:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 8557: 	    return 'error: unable verify users home machine.';
 8558:         }
 8559:     }   # End of creation of new user
 8560: # ---------------------------------------------------------------------- Add ID
 8561:     if ($uid) {
 8562:        $uid=~tr/A-Z/a-z/;
 8563:        my %uidhash=&idrget($udom,$uname);
 8564:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 8565:          && (!$forceid)) {
 8566: 	  unless ($uid eq $uidhash{$uname}) {
 8567: 	      return 'error: user id "'.$uid.'" does not match '.
 8568:                   'current user id "'.$uidhash{$uname}.'".';
 8569:           }
 8570:        } else {
 8571: 	  &idput($udom,($uname => $uid));
 8572:        }
 8573:     }
 8574: # -------------------------------------------------------------- Add names, etc
 8575:     my @tmp=&get('environment',
 8576: 		   ['firstname','middlename','lastname','generation','id',
 8577:                     'permanentemail','inststatus'],
 8578: 		   $udom,$uname);
 8579:     my (%names,%oldnames);
 8580:     if ($tmp[0] =~ m/^error:.*/) { 
 8581:         %names=(); 
 8582:     } else {
 8583:         %names = @tmp;
 8584:         %oldnames = %names;
 8585:     }
 8586: #
 8587: # If name, email and/or uid are blank (e.g., because an uploaded file
 8588: # of users did not contain them), do not overwrite existing values
 8589: # unless field is in $candelete array ref.  
 8590: #
 8591: 
 8592:     my @fields = ('firstname','middlename','lastname','generation',
 8593:                   'permanentemail','id');
 8594:     my %newvalues;
 8595:     if (ref($candelete) eq 'ARRAY') {
 8596:         foreach my $field (@fields) {
 8597:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 8598:                 if ($field eq 'firstname') {
 8599:                     $names{$field} = $first;
 8600:                 } elsif ($field eq 'middlename') {
 8601:                     $names{$field} = $middle;
 8602:                 } elsif ($field eq 'lastname') {
 8603:                     $names{$field} = $last;
 8604:                 } elsif ($field eq 'generation') { 
 8605:                     $names{$field} = $gene;
 8606:                 } elsif ($field eq 'permanentemail') {
 8607:                     $names{$field} = $email;
 8608:                 } elsif ($field eq 'id') {
 8609:                     $names{$field}  = $uid;
 8610:                 }
 8611:             }
 8612:         }
 8613:     }
 8614:     if ($first)  { $names{'firstname'}  = $first; }
 8615:     if (defined($middle)) { $names{'middlename'} = $middle; }
 8616:     if ($last)   { $names{'lastname'}   = $last; }
 8617:     if (defined($gene))   { $names{'generation'} = $gene; }
 8618:     if ($email) {
 8619:        $email=~s/[^\w\@\.\-\,]//gs;
 8620:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 8621:     }
 8622:     if ($uid) { $names{'id'}  = $uid; }
 8623:     if (defined($inststatus)) {
 8624:         $names{'inststatus'} = '';
 8625:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 8626:         if (ref($usertypes) eq 'HASH') {
 8627:             my @okstatuses; 
 8628:             foreach my $item (split(/:/,$inststatus)) {
 8629:                 if (defined($usertypes->{$item})) {
 8630:                     push(@okstatuses,$item);  
 8631:                 }
 8632:             }
 8633:             if (@okstatuses) {
 8634:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 8635:             }
 8636:         }
 8637:     }
 8638:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 8639:                  $umode.', '.$first.', '.$middle.', '.
 8640:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 8641:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 8642:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 8643:     } else {
 8644:         $logmsg .= ' during self creation';
 8645:     }
 8646:     my $changed;
 8647:     if ($newuser) {
 8648:         $changed = 1;
 8649:     } else {
 8650:         foreach my $field (@fields) {
 8651:             if ($names{$field} ne $oldnames{$field}) {
 8652:                 $changed = 1;
 8653:                 last;
 8654:             }
 8655:         }
 8656:     }
 8657:     unless ($changed) {
 8658:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 8659:         &logthis($logmsg);
 8660:         return 'ok';
 8661:     }
 8662:     my $reply = &put('environment', \%names, $udom,$uname);
 8663:     if ($reply ne 'ok') { 
 8664:         return 'error: '.$reply;
 8665:     }
 8666:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
 8667:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
 8668:     }
 8669:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 8670:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 8671:     $logmsg = 'Success modifying user '.$logmsg;
 8672:     &logthis($logmsg);
 8673:     return 'ok';
 8674: }
 8675: 
 8676: # -------------------------------------------------------------- Modify student
 8677: 
 8678: sub modifystudent {
 8679:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 8680:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 8681:         $selfenroll,$context,$inststatus,$credits)=@_;
 8682:     if (!$cid) {
 8683: 	unless ($cid=$env{'request.course.id'}) {
 8684: 	    return 'not_in_class';
 8685: 	}
 8686:     }
 8687: # --------------------------------------------------------------- Make the user
 8688:     my $reply=&modifyuser
 8689: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 8690:          $desiredhome,$email,$inststatus);
 8691:     unless ($reply eq 'ok') { return $reply; }
 8692:     # This will cause &modify_student_enrollment to get the uid from the
 8693:     # student's environment
 8694:     $uid = undef if (!$forceid);
 8695:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 8696:                                         $gene,$usec,$end,$start,$type,$locktype,
 8697:                                         $cid,$selfenroll,$context,$credits);
 8698:     return $reply;
 8699: }
 8700: 
 8701: sub modify_student_enrollment {
 8702:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
 8703:         $locktype,$cid,$selfenroll,$context,$credits) = @_;
 8704:     my ($cdom,$cnum,$chome);
 8705:     if (!$cid) {
 8706: 	unless ($cid=$env{'request.course.id'}) {
 8707: 	    return 'not_in_class';
 8708: 	}
 8709: 	$cdom=$env{'course.'.$cid.'.domain'};
 8710: 	$cnum=$env{'course.'.$cid.'.num'};
 8711:     } else {
 8712: 	($cdom,$cnum)=split(/_/,$cid);
 8713:     }
 8714:     $chome=$env{'course.'.$cid.'.home'};
 8715:     if (!$chome) {
 8716: 	$chome=&homeserver($cnum,$cdom);
 8717:     }
 8718:     if (!$chome) { return 'unknown_course'; }
 8719:     # Make sure the user exists
 8720:     my $uhome=&homeserver($uname,$udom);
 8721:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8722: 	return 'error: no such user';
 8723:     }
 8724:     # Get student data if we were not given enough information
 8725:     if (!defined($first)  || $first  eq '' || 
 8726:         !defined($last)   || $last   eq '' || 
 8727:         !defined($uid)    || $uid    eq '' || 
 8728:         !defined($middle) || $middle eq '' || 
 8729:         !defined($gene)   || $gene   eq '') {
 8730:         # They did not supply us with enough data to enroll the student, so
 8731:         # we need to pick up more information.
 8732:         my %tmp = &get('environment',
 8733:                        ['firstname','middlename','lastname', 'generation','id']
 8734:                        ,$udom,$uname);
 8735: 
 8736:         #foreach my $key (keys(%tmp)) {
 8737:         #    &logthis("key $key = ".$tmp{$key});
 8738:         #}
 8739:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 8740:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 8741:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 8742:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 8743:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 8744:     }
 8745:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 8746:     my $user = "$uname:$udom";
 8747:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
 8748:     my $reply=cput('classlist',
 8749: 		   {$user => 
 8750: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
 8751: 		   $cdom,$cnum);
 8752:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
 8753:         &devalidate_getsection_cache($udom,$uname,$cid);
 8754:     } else { 
 8755: 	return 'error: '.$reply;
 8756:     }
 8757:     # Add student role to user
 8758:     my $uurl='/'.$cid;
 8759:     $uurl=~s/\_/\//g;
 8760:     if ($usec) {
 8761: 	$uurl.='/'.$usec;
 8762:     }
 8763:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
 8764:                              $selfenroll,$context);
 8765:     if ($result ne 'ok') {
 8766:         if ($old_entry{$user} ne '') {
 8767:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
 8768:         } else {
 8769:             $reply = &del('classlist',[$user],$cdom,$cnum);
 8770:         }
 8771:     }
 8772:     return $result; 
 8773: }
 8774: 
 8775: sub format_name {
 8776:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 8777:     my $name;
 8778:     if ($first ne 'lastname') {
 8779: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 8780:     } else {
 8781: 	if ($lastname=~/\S/) {
 8782: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 8783: 	    $name=~s/\s+,/,/;
 8784: 	} else {
 8785: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 8786: 	}
 8787:     }
 8788:     $name=~s/^\s+//;
 8789:     $name=~s/\s+$//;
 8790:     $name=~s/\s+/ /g;
 8791:     return $name;
 8792: }
 8793: 
 8794: # ------------------------------------------------- Write to course preferences
 8795: 
 8796: sub writecoursepref {
 8797:     my ($courseid,%prefs)=@_;
 8798:     $courseid=~s/^\///;
 8799:     $courseid=~s/\_/\//g;
 8800:     my ($cdomain,$cnum)=split(/\//,$courseid);
 8801:     my $chome=homeserver($cnum,$cdomain);
 8802:     if (($chome eq '') || ($chome eq 'no_host')) { 
 8803: 	return 'error: no such course';
 8804:     }
 8805:     my $cstring='';
 8806:     foreach my $pref (keys(%prefs)) {
 8807: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 8808:     }
 8809:     $cstring=~s/\&$//;
 8810:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 8811: }
 8812: 
 8813: # ---------------------------------------------------------- Make/modify course
 8814: 
 8815: sub createcourse {
 8816:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 8817:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 8818:     $url=&declutter($url);
 8819:     my $cid='';
 8820:     if ($context eq 'requestcourses') {
 8821:         my $can_create = 0;
 8822:         my ($ownername,$ownerdom) = split(':',$course_owner);
 8823:         if ($udom eq $ownerdom) {
 8824:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 8825:                                   $context)) {
 8826:                 $can_create = 1;
 8827:             }
 8828:         } else {
 8829:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 8830:                                            $category);
 8831:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 8832:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 8833:                 if (@curr > 0) {
 8834:                     my @options = qw(approval validate autolimit);
 8835:                     my $optregex = join('|',@options);
 8836:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 8837:                         $can_create = 1;
 8838:                     }
 8839:                 }
 8840:             }
 8841:         }
 8842:         if ($can_create) {
 8843:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 8844:                 unless (&allowed('ccc',$udom)) {
 8845:                     return 'refused'; 
 8846:                 }
 8847:             }
 8848:         } else {
 8849:             return 'refused';
 8850:         }
 8851:     } elsif (!&allowed('ccc',$udom)) {
 8852:         return 'refused';
 8853:     }
 8854: # --------------------------------------------------------------- Get Unique ID
 8855:     my $uname;
 8856:     if ($cnum =~ /^$match_courseid$/) {
 8857:         my $chome=&homeserver($cnum,$udom,'true');
 8858:         if (($chome eq '') || ($chome eq 'no_host')) {
 8859:             $uname = $cnum;
 8860:         } else {
 8861:             $uname = &generate_coursenum($udom,$crstype);
 8862:         }
 8863:     } else {
 8864:         $uname = &generate_coursenum($udom,$crstype);
 8865:     }
 8866:     return $uname if ($uname =~ /^error/);
 8867: # -------------------------------------------------- Check supplied server name
 8868:     if (!defined($course_server)) {
 8869:         if (defined(&domain($udom,'primary'))) {
 8870:             $course_server = &domain($udom,'primary');
 8871:         } else {
 8872:             $course_server = $env{'user.home'}; 
 8873:         }
 8874:     }
 8875:     my %host_servers =
 8876:         &Apache::lonnet::get_servers($udom,'library');
 8877:     unless ($host_servers{$course_server}) {
 8878:         return 'error: invalid home server for course: '.$course_server;
 8879:     }
 8880: # ------------------------------------------------------------- Make the course
 8881:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 8882:                       $course_server);
 8883:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 8884:     my $uhome=&homeserver($uname,$udom,'true');
 8885:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8886: 	return 'error: no such course';
 8887:     }
 8888: # ----------------------------------------------------------------- Course made
 8889: # log existence
 8890:     my $now = time;
 8891:     my $newcourse = {
 8892:                     $udom.'_'.$uname => {
 8893:                                      description => $description,
 8894:                                      inst_code   => $inst_code,
 8895:                                      owner       => $course_owner,
 8896:                                      type        => $crstype,
 8897:                                      creator     => $env{'user.name'}.':'.
 8898:                                                     $env{'user.domain'},
 8899:                                      created     => $now,
 8900:                                      context     => $context,
 8901:                                                 },
 8902:                     };
 8903:     &courseidput($udom,$newcourse,$uhome,'notime');
 8904: # set toplevel url
 8905:     my $topurl=$url;
 8906:     unless ($nonstandard) {
 8907: # ------------------------------------------ For standard courses, make top url
 8908:         my $mapurl=&clutter($url);
 8909:         if ($mapurl eq '/res/') { $mapurl=''; }
 8910:         $env{'form.initmap'}=(<<ENDINITMAP);
 8911: <map>
 8912: <resource id="1" type="start"></resource>
 8913: <resource id="2" src="$mapurl"></resource>
 8914: <resource id="3" type="finish"></resource>
 8915: <link index="1" from="1" to="2"></link>
 8916: <link index="2" from="2" to="3"></link>
 8917: </map>
 8918: ENDINITMAP
 8919:         $topurl=&declutter(
 8920:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 8921:                           );
 8922:     }
 8923: # ----------------------------------------------------------- Write preferences
 8924:     &writecoursepref($udom.'_'.$uname,
 8925:                      ('description'              => $description,
 8926:                       'url'                      => $topurl,
 8927:                       'internal.creator'         => $env{'user.name'}.':'.
 8928:                                                     $env{'user.domain'},
 8929:                       'internal.created'         => $now,
 8930:                       'internal.creationcontext' => $context)
 8931:                     );
 8932:     return '/'.$udom.'/'.$uname;
 8933: }
 8934: 
 8935: # ------------------------------------------------------------------- Create ID
 8936: sub generate_coursenum {
 8937:     my ($udom,$crstype) = @_;
 8938:     my $domdesc = &domain($udom);
 8939:     return 'error: invalid domain' if ($domdesc eq '');
 8940:     my $first;
 8941:     if ($crstype eq 'Community') {
 8942:         $first = '0';
 8943:     } else {
 8944:         $first = int(1+rand(9)); 
 8945:     } 
 8946:     my $uname=$first.
 8947:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8948:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8949:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8950: # ----------------------------------------------- Make sure that does not exist
 8951:     my $uhome=&homeserver($uname,$udom,'true');
 8952:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8953:         if ($crstype eq 'Community') {
 8954:             $first = '0';
 8955:         } else {
 8956:             $first = int(1+rand(9));
 8957:         }
 8958:         $uname=$first.
 8959:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8960:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8961:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8962:         $uhome=&homeserver($uname,$udom,'true');
 8963:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8964:             return 'error: unable to generate unique course-ID';
 8965:         }
 8966:     }
 8967:     return $uname;
 8968: }
 8969: 
 8970: sub is_course {
 8971:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
 8972:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
 8973: 
 8974:     return unless $cdom and $cnum;
 8975: 
 8976:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
 8977:         '.');
 8978: 
 8979:     return unless(exists($courses{$cdom.'_'.$cnum}));
 8980:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
 8981: }
 8982: 
 8983: sub store_userdata {
 8984:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
 8985:     my $result;
 8986:     if ($datakey ne '') {
 8987:         if (ref($storehash) eq 'HASH') {
 8988:             if ($udom eq '' || $uname eq '') {
 8989:                 $udom = $env{'user.domain'};
 8990:                 $uname = $env{'user.name'};
 8991:             }
 8992:             my $uhome=&homeserver($uname,$udom);
 8993:             if (($uhome eq '') || ($uhome eq 'no_host')) {
 8994:                 $result = 'error: no_host';
 8995:             } else {
 8996:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
 8997:                 $storehash->{'host'} = $perlvar{'lonHostID'};
 8998: 
 8999:                 my $namevalue='';
 9000:                 foreach my $key (keys(%{$storehash})) {
 9001:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 9002:                 }
 9003:                 $namevalue=~s/\&$//;
 9004:                 unless ($namespace eq 'courserequests') {
 9005:                     $datakey = &escape($datakey);
 9006:                 }
 9007:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
 9008:                                   $namevalue,$uhome);
 9009:             }
 9010:         } else {
 9011:             $result = 'error: data to store was not a hash reference'; 
 9012:         }
 9013:     } else {
 9014:         $result= 'error: invalid requestkey'; 
 9015:     }
 9016:     return $result;
 9017: }
 9018: 
 9019: # ---------------------------------------------------------- Assign Custom Role
 9020: 
 9021: sub assigncustomrole {
 9022:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 9023:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 9024:                        $end,$start,$deleteflag,$selfenroll,$context);
 9025: }
 9026: 
 9027: # ----------------------------------------------------------------- Revoke Role
 9028: 
 9029: sub revokerole {
 9030:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 9031:     my $now=time;
 9032:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 9033: }
 9034: 
 9035: # ---------------------------------------------------------- Revoke Custom Role
 9036: 
 9037: sub revokecustomrole {
 9038:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 9039:     my $now=time;
 9040:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 9041:            $deleteflag,$selfenroll,$context);
 9042: }
 9043: 
 9044: # ------------------------------------------------------------ Disk usage
 9045: sub diskusage {
 9046:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 9047:     $directorypath =~ s/\/$//;
 9048:     my $listing=&reply('du2:'.&escape($directorypath).':'
 9049:                        .&escape($getpropath).':'.&escape($uname).':'
 9050:                        .&escape($udom),homeserver($uname,$udom));
 9051:     if ($listing eq 'unknown_cmd') {
 9052:         if ($getpropath) {
 9053:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 9054:         }
 9055:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 9056:     }
 9057:     return $listing;
 9058: }
 9059: 
 9060: sub is_locked {
 9061:     my ($file_name, $domain, $user, $which) = @_;
 9062:     my @check;
 9063:     my $is_locked;
 9064:     push (@check,$file_name);
 9065:     my %locked = &get('file_permissions',\@check,
 9066: 		      $env{'user.domain'},$env{'user.name'});
 9067:     my ($tmp)=keys(%locked);
 9068:     if ($tmp=~/^error:/) { undef(%locked); }
 9069:     
 9070:     if (ref($locked{$file_name}) eq 'ARRAY') {
 9071:         $is_locked = 'false';
 9072:         foreach my $entry (@{$locked{$file_name}}) {
 9073:            if (ref($entry) eq 'ARRAY') {
 9074:                $is_locked = 'true';
 9075:                if (ref($which) eq 'ARRAY') {
 9076:                    push(@{$which},$entry);
 9077:                } else {
 9078:                    last;
 9079:                }
 9080:            }
 9081:        }
 9082:     } else {
 9083:         $is_locked = 'false';
 9084:     }
 9085:     return $is_locked;
 9086: }
 9087: 
 9088: sub declutter_portfile {
 9089:     my ($file) = @_;
 9090:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 9091:     return $file;
 9092: }
 9093: 
 9094: # ------------------------------------------------------------- Mark as Read Only
 9095: 
 9096: sub mark_as_readonly {
 9097:     my ($domain,$user,$files,$what) = @_;
 9098:     my %current_permissions = &dump('file_permissions',$domain,$user);
 9099:     my ($tmp)=keys(%current_permissions);
 9100:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9101:     foreach my $file (@{$files}) {
 9102: 	$file = &declutter_portfile($file);
 9103:         push(@{$current_permissions{$file}},$what);
 9104:     }
 9105:     &put('file_permissions',\%current_permissions,$domain,$user);
 9106:     return;
 9107: }
 9108: 
 9109: # ------------------------------------------------------------Save Selected Files
 9110: 
 9111: sub save_selected_files {
 9112:     my ($user, $path, @files) = @_;
 9113:     my $filename = $user."savedfiles";
 9114:     my @other_files = &files_not_in_path($user, $path);
 9115:     open (OUT, '>'.$tmpdir.$filename);
 9116:     foreach my $file (@files) {
 9117:         print (OUT $env{'form.currentpath'}.$file."\n");
 9118:     }
 9119:     foreach my $file (@other_files) {
 9120:         print (OUT $file."\n");
 9121:     }
 9122:     close (OUT);
 9123:     return 'ok';
 9124: }
 9125: 
 9126: sub clear_selected_files {
 9127:     my ($user) = @_;
 9128:     my $filename = $user."savedfiles";
 9129:     open (OUT, '>'.LONCAPA::tempdir().$filename);
 9130:     print (OUT undef);
 9131:     close (OUT);
 9132:     return ("ok");    
 9133: }
 9134: 
 9135: sub files_in_path {
 9136:     my ($user, $path) = @_;
 9137:     my $filename = $user."savedfiles";
 9138:     my %return_files;
 9139:     open (IN, '<'.LONCAPA::tempdir().$filename);
 9140:     while (my $line_in = <IN>) {
 9141:         chomp ($line_in);
 9142:         my @paths_and_file = split (m!/!, $line_in);
 9143:         my $file_part = pop (@paths_and_file);
 9144:         my $path_part = join ('/', @paths_and_file);
 9145:         $path_part.='/';
 9146:         my $path_and_file = $path_part.$file_part;
 9147:         if ($path_part eq $path) {
 9148:             $return_files{$file_part}= 'selected';
 9149:         }
 9150:     }
 9151:     close (IN);
 9152:     return (\%return_files);
 9153: }
 9154: 
 9155: # called in portfolio select mode, to show files selected NOT in current directory
 9156: sub files_not_in_path {
 9157:     my ($user, $path) = @_;
 9158:     my $filename = $user."savedfiles";
 9159:     my @return_files;
 9160:     my $path_part;
 9161:     open(IN, '<'.LONCAPA::.$filename);
 9162:     while (my $line = <IN>) {
 9163:         #ok, I know it's clunky, but I want it to work
 9164:         my @paths_and_file = split(m|/|, $line);
 9165:         my $file_part = pop(@paths_and_file);
 9166:         chomp($file_part);
 9167:         my $path_part = join('/', @paths_and_file);
 9168:         $path_part .= '/';
 9169:         my $path_and_file = $path_part.$file_part;
 9170:         if ($path_part ne $path) {
 9171:             push(@return_files, ($path_and_file));
 9172:         }
 9173:     }
 9174:     close(OUT);
 9175:     return (@return_files);
 9176: }
 9177: 
 9178: #------------------------------Submitted/Handedback Portfolio Files Versioning
 9179:  
 9180: sub portfiles_versioning {
 9181:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
 9182:     my $portfolio_root = '/userfiles/portfolio';
 9183:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
 9184:     foreach my $file (@{$portfiles}) {
 9185:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 9186:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 9187:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
 9188:         my $getpropath = 1;
 9189:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
 9190:                                              $stu_name,$getpropath);
 9191:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
 9192:         my $new_answer = 
 9193:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
 9194:         if ($new_answer ne 'problem getting file') {
 9195:             push(@{$versioned_portfiles}, $directory.$new_answer);
 9196:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
 9197:                               [$symb,$env{'request.course.id'},'graded']);
 9198:         }
 9199:     }
 9200: }
 9201: 
 9202: sub get_next_version {
 9203:     my ($answer_name, $answer_ext, $dir_list) = @_;
 9204:     my $version;
 9205:     if (ref($dir_list) eq 'ARRAY') {
 9206:         foreach my $row (@{$dir_list}) {
 9207:             my ($file) = split(/\&/,$row,2);
 9208:             my ($file_name,$file_version,$file_ext) =
 9209:                 &file_name_version_ext($file);
 9210:             if (($file_name eq $answer_name) &&
 9211:                 ($file_ext eq $answer_ext)) {
 9212:                      # gets here if filename and extension match,
 9213:                      # regardless of version
 9214:                 if ($file_version ne '') {
 9215:                     # a versioned file is found  so save it for later
 9216:                     if ($file_version > $version) {
 9217:                         $version = $file_version;
 9218:                     }
 9219:                 }
 9220:             }
 9221:         }
 9222:     }
 9223:     $version ++;
 9224:     return($version);
 9225: }
 9226: 
 9227: sub version_selected_portfile {
 9228:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 9229:     my ($answer_name,$answer_ver,$answer_ext) =
 9230:         &file_name_version_ext($file_name);
 9231:     my $new_answer;
 9232:     $env{'form.copy'} =
 9233:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 9234:     if($env{'form.copy'} eq '-1') {
 9235:         $new_answer = 'problem getting file';
 9236:     } else {
 9237:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 9238:         my $copy_result = 
 9239:             &finishuserfileupload($stu_name,$domain,'copy',
 9240:                                   '/portfolio'.$directory.$new_answer);
 9241:     }
 9242:     undef($env{'form.copy'});
 9243:     return ($new_answer);
 9244: }
 9245: 
 9246: sub file_name_version_ext {
 9247:     my ($file)=@_;
 9248:     my @file_parts = split(/\./, $file);
 9249:     my ($name,$version,$ext);
 9250:     if (@file_parts > 1) {
 9251:         $ext=pop(@file_parts);
 9252:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 9253:             $version=pop(@file_parts);
 9254:         }
 9255:         $name=join('.',@file_parts);
 9256:     } else {
 9257:         $name=join('.',@file_parts);
 9258:     }
 9259:     return($name,$version,$ext);
 9260: }
 9261: 
 9262: #----------------------------------------------Get portfolio file permissions
 9263: 
 9264: sub get_portfile_permissions {
 9265:     my ($domain,$user) = @_;
 9266:     my %current_permissions = &dump('file_permissions',$domain,$user);
 9267:     my ($tmp)=keys(%current_permissions);
 9268:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9269:     return \%current_permissions;
 9270: }
 9271: 
 9272: #---------------------------------------------Get portfolio file access controls
 9273: 
 9274: sub get_access_controls {
 9275:     my ($current_permissions,$group,$file) = @_;
 9276:     my %access;
 9277:     my $real_file = $file;
 9278:     $file =~ s/\.meta$//;
 9279:     if (defined($file)) {
 9280:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 9281:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 9282:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 9283:             }
 9284:         }
 9285:     } else {
 9286:         foreach my $key (keys(%{$current_permissions})) {
 9287:             if ($key =~ /\0accesscontrol$/) {
 9288:                 if (defined($group)) {
 9289:                     if ($key !~ m-^\Q$group\E/-) {
 9290:                         next;
 9291:                     }
 9292:                 }
 9293:                 my ($fullpath) = split(/\0/,$key);
 9294:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 9295:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 9296:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 9297:                     }
 9298:                 }
 9299:             }
 9300:         }
 9301:     }
 9302:     return %access;
 9303: }
 9304: 
 9305: sub modify_access_controls {
 9306:     my ($file_name,$changes,$domain,$user)=@_;
 9307:     my ($outcome,$deloutcome);
 9308:     my %store_permissions;
 9309:     my %new_values;
 9310:     my %new_control;
 9311:     my %translation;
 9312:     my @deletions = ();
 9313:     my $now = time;
 9314:     if (exists($$changes{'activate'})) {
 9315:         if (ref($$changes{'activate'}) eq 'HASH') {
 9316:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 9317:             my $numnew = scalar(@newitems);
 9318:             for (my $i=0; $i<$numnew; $i++) {
 9319:                 my $newkey = $newitems[$i];
 9320:                 my $newid = &Apache::loncommon::get_cgi_id();
 9321:                 if ($newkey =~ /^\d+:/) { 
 9322:                     $newkey =~ s/^(\d+)/$newid/;
 9323:                     $translation{$1} = $newid;
 9324:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 9325:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 9326:                     $translation{$1} = $newid;
 9327:                 }
 9328:                 $new_values{$file_name."\0".$newkey} = 
 9329:                                           $$changes{'activate'}{$newitems[$i]};
 9330:                 $new_control{$newkey} = $now;
 9331:             }
 9332:         }
 9333:     }
 9334:     my %todelete;
 9335:     my %changed_items;
 9336:     foreach my $action ('delete','update') {
 9337:         if (exists($$changes{$action})) {
 9338:             if (ref($$changes{$action}) eq 'HASH') {
 9339:                 foreach my $key (keys(%{$$changes{$action}})) {
 9340:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 9341:                     if ($action eq 'delete') { 
 9342:                         $todelete{$itemnum} = 1;
 9343:                     } else {
 9344:                         $changed_items{$itemnum} = $key;
 9345:                     }
 9346:                 }
 9347:             }
 9348:         }
 9349:     }
 9350:     # get lock on access controls for file.
 9351:     my $lockhash = {
 9352:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 9353:                                                        ':'.$env{'user.domain'},
 9354:                    }; 
 9355:     my $tries = 0;
 9356:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 9357:    
 9358:     while (($gotlock ne 'ok') && $tries <3) {
 9359:         $tries ++;
 9360:         sleep 1;
 9361:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 9362:     }
 9363:     if ($gotlock eq 'ok') {
 9364:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 9365:         my ($tmp)=keys(%curr_permissions);
 9366:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 9367:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 9368:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 9369:             if (ref($curr_controls) eq 'HASH') {
 9370:                 foreach my $control_item (keys(%{$curr_controls})) {
 9371:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 9372:                     if (defined($todelete{$itemnum})) {
 9373:                         push(@deletions,$file_name."\0".$control_item);
 9374:                     } else {
 9375:                         if (defined($changed_items{$itemnum})) {
 9376:                             $new_control{$changed_items{$itemnum}} = $now;
 9377:                             push(@deletions,$file_name."\0".$control_item);
 9378:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 9379:                         } else {
 9380:                             $new_control{$control_item} = $$curr_controls{$control_item};
 9381:                         }
 9382:                     }
 9383:                 }
 9384:             }
 9385:         }
 9386:         my ($group);
 9387:         if (&is_course($domain,$user)) {
 9388:             ($group,my $file) = split(/\//,$file_name,2);
 9389:         }
 9390:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 9391:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 9392:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 9393:         #  remove lock
 9394:         my @del_lock = ($file_name."\0".'locked_access_records');
 9395:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 9396:         my $sqlresult =
 9397:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 9398:                                     $group);
 9399:     } else {
 9400:         $outcome = "error: could not obtain lockfile\n";  
 9401:     }
 9402:     return ($outcome,$deloutcome,\%new_values,\%translation);
 9403: }
 9404: 
 9405: sub make_public_indefinitely {
 9406:     my (@requrl) = @_;
 9407:     return &automated_portfile_access('public',\@requrl);
 9408: }
 9409: 
 9410: sub automated_portfile_access {
 9411:     my ($accesstype,$addsref,$delsref,$info) = @_;
 9412:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
 9413:         return 'invalid';
 9414:     }
 9415:     my %urls;
 9416:     if (ref($addsref) eq 'ARRAY') {
 9417:         foreach my $requrl (@{$addsref}) {
 9418:             if (&is_portfolio_url($requrl)) {
 9419:                 unless (exists($urls{$requrl})) {
 9420:                     $urls{$requrl} = 'add';
 9421:                 }
 9422:             }
 9423:         }
 9424:     }
 9425:     if (ref($delsref) eq 'ARRAY') {
 9426:         foreach my $requrl (@{$delsref}) { 
 9427:             if (&is_portfolio_url($requrl)) {
 9428:                 unless (exists($urls{$requrl})) {
 9429:                     $urls{$requrl} = 'delete'; 
 9430:                 }
 9431:             }
 9432:         }
 9433:     }
 9434:     unless (keys(%urls)) {
 9435:         return 'invalid';
 9436:     }
 9437:     my $ip;
 9438:     if ($accesstype eq 'ip') {
 9439:         if (ref($info) eq 'HASH') {
 9440:             if ($info->{'ip'} ne '') {
 9441:                 $ip = $info->{'ip'};
 9442:             }
 9443:         }
 9444:         if ($ip eq '') {
 9445:             return 'invalid';
 9446:         }
 9447:     }
 9448:     my $errors;
 9449:     my $now = time;
 9450:     my %current_perms;
 9451:     foreach my $requrl (sort(keys(%urls))) {
 9452:         my $action;
 9453:         if ($urls{$requrl} eq 'add') {
 9454:             $action = 'activate';
 9455:         } else {
 9456:             $action = 'none';
 9457:         }
 9458:         my $aclnum = 0;
 9459:         my (undef,$udom,$unum,$file_name,$group) =
 9460:             &parse_portfolio_url($requrl);
 9461:         unless (exists($current_perms{$unum.':'.$udom})) {
 9462:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
 9463:         }
 9464:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
 9465:                                                    $group,$file_name);
 9466:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 9467:             my ($num,$scope,$end,$start) = 
 9468:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 9469:             if ($scope eq $accesstype) {
 9470:                 if (($start <= $now) && ($end == 0)) {
 9471:                     if ($accesstype eq 'ip') {
 9472:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
 9473:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
 9474:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
 9475:                                     if ($urls{$requrl} eq 'add') {
 9476:                                         $action = 'none';
 9477:                                         last;
 9478:                                     } else {
 9479:                                         $action = 'delete';
 9480:                                         $aclnum = $num;
 9481:                                         last;
 9482:                                     }
 9483:                                 }
 9484:                             }
 9485:                         }
 9486:                     } elsif ($accesstype eq 'public') {
 9487:                         if ($urls{$requrl} eq 'add') {
 9488:                             $action = 'none';
 9489:                             last;
 9490:                         } else {
 9491:                             $action = 'delete';
 9492:                             $aclnum = $num;
 9493:                             last;
 9494:                         }
 9495:                     }
 9496:                 } elsif ($accesstype eq 'public') {
 9497:                     $action = 'update';
 9498:                     $aclnum = $num;
 9499:                     last;
 9500:                 }
 9501:             }
 9502:         }
 9503:         if ($action eq 'none') {
 9504:             next;
 9505:         } else {
 9506:             my %changes;
 9507:             my $newend = 0;
 9508:             my $newstart = $now;
 9509:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
 9510:             $changes{$action}{$newkey} = {
 9511:                 type => $accesstype,
 9512:                 time => {
 9513:                     start => $newstart,
 9514:                     end   => $newend,
 9515:                 },
 9516:             };
 9517:             if ($accesstype eq 'ip') {
 9518:                 $changes{$action}{$newkey}{'ip'} = [$ip];
 9519:             }
 9520:             my ($outcome,$deloutcome,$new_values,$translation) =
 9521:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 9522:             unless ($outcome eq 'ok') {
 9523:                 $errors .= $outcome.' ';
 9524:             }
 9525:         }
 9526:     }
 9527:     if ($errors) {
 9528:         $errors =~ s/\s$//;
 9529:         return $errors;
 9530:     } else {
 9531:         return 'ok';
 9532:     }
 9533: }
 9534: 
 9535: #------------------------------------------------------Get Marked as Read Only
 9536: 
 9537: sub get_marked_as_readonly {
 9538:     my ($domain,$user,$what,$group) = @_;
 9539:     my $current_permissions = &get_portfile_permissions($domain,$user);
 9540:     my @readonly_files;
 9541:     my $cmp1=$what;
 9542:     if (ref($what)) { $cmp1=join('',@{$what}) };
 9543:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 9544:         if (defined($group)) {
 9545:             if ($file_name !~ m-^\Q$group\E/-) {
 9546:                 next;
 9547:             }
 9548:         }
 9549:         if (ref($value) eq "ARRAY"){
 9550:             foreach my $stored_what (@{$value}) {
 9551:                 my $cmp2=$stored_what;
 9552:                 if (ref($stored_what) eq 'ARRAY') {
 9553:                     $cmp2=join('',@{$stored_what});
 9554:                 }
 9555:                 if ($cmp1 eq $cmp2) {
 9556:                     push(@readonly_files, $file_name);
 9557:                     last;
 9558:                 } elsif (!defined($what)) {
 9559:                     push(@readonly_files, $file_name);
 9560:                     last;
 9561:                 }
 9562:             }
 9563:         }
 9564:     }
 9565:     return @readonly_files;
 9566: }
 9567: #-----------------------------------------------------------Get Marked as Read Only Hash
 9568: 
 9569: sub get_marked_as_readonly_hash {
 9570:     my ($current_permissions,$group,$what) = @_;
 9571:     my %readonly_files;
 9572:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 9573:         if (defined($group)) {
 9574:             if ($file_name !~ m-^\Q$group\E/-) {
 9575:                 next;
 9576:             }
 9577:         }
 9578:         if (ref($value) eq "ARRAY"){
 9579:             foreach my $stored_what (@{$value}) {
 9580:                 if (ref($stored_what) eq 'ARRAY') {
 9581:                     foreach my $lock_descriptor(@{$stored_what}) {
 9582:                         if ($lock_descriptor eq 'graded') {
 9583:                             $readonly_files{$file_name} = 'graded';
 9584:                         } elsif ($lock_descriptor eq 'handback') {
 9585:                             $readonly_files{$file_name} = 'handback';
 9586:                         } else {
 9587:                             if (!exists($readonly_files{$file_name})) {
 9588:                                 $readonly_files{$file_name} = 'locked';
 9589:                             }
 9590:                         }
 9591:                     }
 9592:                 } 
 9593:             }
 9594:         } 
 9595:     }
 9596:     return %readonly_files;
 9597: }
 9598: # ------------------------------------------------------------ Unmark as Read Only
 9599: 
 9600: sub unmark_as_readonly {
 9601:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 9602:     # for portfolio submissions, $what contains [$symb,$crsid] 
 9603:     my ($domain,$user,$what,$file_name,$group) = @_;
 9604:     $file_name = &declutter_portfile($file_name);
 9605:     my $symb_crs = $what;
 9606:     if (ref($what)) { $symb_crs=join('',@$what); }
 9607:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 9608:     my ($tmp)=keys(%current_permissions);
 9609:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9610:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 9611:     foreach my $file (@readonly_files) {
 9612: 	my $clean_file = &declutter_portfile($file);
 9613: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 9614: 	my $current_locks = $current_permissions{$file};
 9615:         my @new_locks;
 9616:         my @del_keys;
 9617:         if (ref($current_locks) eq "ARRAY"){
 9618:             foreach my $locker (@{$current_locks}) {
 9619:                 my $compare=$locker;
 9620:                 if (ref($locker) eq 'ARRAY') {
 9621:                     $compare=join('',@{$locker});
 9622:                     if ($compare ne $symb_crs) {
 9623:                         push(@new_locks, $locker);
 9624:                     }
 9625:                 }
 9626:             }
 9627:             if (scalar(@new_locks) > 0) {
 9628:                 $current_permissions{$file} = \@new_locks;
 9629:             } else {
 9630:                 push(@del_keys, $file);
 9631:                 &del('file_permissions',\@del_keys, $domain, $user);
 9632:                 delete($current_permissions{$file});
 9633:             }
 9634:         }
 9635:     }
 9636:     &put('file_permissions',\%current_permissions,$domain,$user);
 9637:     return;
 9638: }
 9639: 
 9640: # ------------------------------------------------------------ Directory lister
 9641: 
 9642: sub dirlist {
 9643:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 9644:     $uri=~s/^\///;
 9645:     $uri=~s/\/$//;
 9646:     my ($udom, $uname);
 9647:     if ($getuserdir) {
 9648:         $udom = $userdomain;
 9649:         $uname = $username;
 9650:     } else {
 9651:         (undef,$udom,$uname)=split(/\//,$uri);
 9652:         if(defined($userdomain)) {
 9653:             $udom = $userdomain;
 9654:         }
 9655:         if(defined($username)) {
 9656:             $uname = $username;
 9657:         }
 9658:     }
 9659:     my ($dirRoot,$listing,@listing_results);
 9660: 
 9661:     $dirRoot = $perlvar{'lonDocRoot'};
 9662:     if (defined($getpropath)) {
 9663:         $dirRoot = &propath($udom,$uname);
 9664:         $dirRoot =~ s/\/$//;
 9665:     } elsif (defined($getuserdir)) {
 9666:         my $subdir=$uname.'__';
 9667:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 9668:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 9669:                    ."/$udom/$subdir/$uname";
 9670:     } elsif (defined($alternateRoot)) {
 9671:         $dirRoot = $alternateRoot;
 9672:     }
 9673: 
 9674:     if($udom) {
 9675:         if($uname) {
 9676:             my $uhome = &homeserver($uname,$udom);
 9677:             if ($uhome eq 'no_host') {
 9678:                 return ([],'no_host');
 9679:             }
 9680:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 9681:                               .$getuserdir.':'.&escape($dirRoot)
 9682:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
 9683:             if ($listing eq 'unknown_cmd') {
 9684:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
 9685:             } else {
 9686:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 9687:             }
 9688:             if ($listing eq 'unknown_cmd') {
 9689:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
 9690:                 @listing_results = split(/:/,$listing);
 9691:             } else {
 9692:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 9693:             }
 9694:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
 9695:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
 9696:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 9697:                 return ([],$listing);
 9698:             } else {
 9699:                 return (\@listing_results);
 9700:             }
 9701:         } elsif(!$alternateRoot) {
 9702:             my (%allusers,%listerror);
 9703: 	    my %servers = &get_servers($udom,'library');
 9704:  	    foreach my $tryserver (keys(%servers)) {
 9705:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 9706:                                   &escape($udom),$tryserver);
 9707:                 if ($listing eq 'unknown_cmd') {
 9708: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 9709: 				      $udom, $tryserver);
 9710:                 } else {
 9711:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 9712:                 }
 9713: 		if ($listing eq 'unknown_cmd') {
 9714: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 9715: 				      $udom, $tryserver);
 9716: 		    @listing_results = split(/:/,$listing);
 9717: 		} else {
 9718: 		    @listing_results =
 9719: 			map { &unescape($_); } split(/:/,$listing);
 9720: 		}
 9721:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
 9722:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
 9723:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 9724:                     $listerror{$tryserver} = $listing;
 9725:                 } else {
 9726: 		    foreach my $line (@listing_results) {
 9727: 			my ($entry) = split(/&/,$line,2);
 9728: 			$allusers{$entry} = 1;
 9729: 		    }
 9730: 		}
 9731:             }
 9732:             my @alluserslist=();
 9733:             foreach my $user (sort(keys(%allusers))) {
 9734:                 push(@alluserslist,$user.'&user');
 9735:             }
 9736:             return (\@alluserslist);
 9737:         } else {
 9738:             return ([],'missing username');
 9739:         }
 9740:     } elsif(!defined($getpropath)) {
 9741:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
 9742:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
 9743:         return (\@all_domains);
 9744:     } else {
 9745:         return ([],'missing domain');
 9746:     }
 9747: }
 9748: 
 9749: # --------------------------------------------- GetFileTimestamp
 9750: # This function utilizes dirlist and returns the date stamp for
 9751: # when it was last modified.  It will also return an error of -1
 9752: # if an error occurs
 9753: 
 9754: sub GetFileTimestamp {
 9755:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 9756:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 9757:     $studentName   = &LONCAPA::clean_username($studentName);
 9758:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
 9759:                                     undef,$getuserdir);
 9760:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 9761:         return -1;
 9762:     }
 9763:     if (ref($fileref) eq 'ARRAY') {
 9764:         my @stats = split('&',$fileref->[0]);
 9765:         # @stats contains first the filename, then the stat output
 9766:         return $stats[10]; # so this is 10 instead of 9.
 9767:     } else {
 9768:         return -1;
 9769:     }
 9770: }
 9771: 
 9772: sub stat_file {
 9773:     my ($uri) = @_;
 9774:     $uri = &clutter_with_no_wrapper($uri);
 9775: 
 9776:     my ($udom,$uname,$file);
 9777:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 9778: 	($udom,$uname,$file) =
 9779: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 9780: 	$file = 'userfiles/'.$file;
 9781:     }
 9782:     if ($uri =~ m-^/res/-) {
 9783: 	($udom,$uname) = 
 9784: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 9785: 	$file = $uri;
 9786:     }
 9787: 
 9788:     if (!$udom || !$uname || !$file) {
 9789: 	# unable to handle the uri
 9790: 	return ();
 9791:     }
 9792:     my $getpropath;
 9793:     if ($file =~ /^userfiles\//) {
 9794:         $getpropath = 1;
 9795:     }
 9796:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
 9797:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 9798:         return ();
 9799:     } else {
 9800:         if (ref($listref) eq 'ARRAY') {
 9801:             my @stats = split('&',$listref->[0]);
 9802: 	    shift(@stats); #filename is first
 9803: 	    return @stats;
 9804:         }
 9805:     }
 9806:     return ();
 9807: }
 9808: 
 9809: # -------------------------------------------------------- Value of a Condition
 9810: 
 9811: # gets the value of a specific preevaluated condition
 9812: #    stored in the string  $env{user.state.<cid>}
 9813: # or looks up a condition reference in the bighash and if if hasn't
 9814: # already been evaluated recurses into docondval to get the value of
 9815: # the condition, then memoizing it to 
 9816: #   $env{user.state.<cid>.<condition>}
 9817: sub directcondval {
 9818:     my $number=shift;
 9819:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 9820: 	&Apache::lonuserstate::evalstate();
 9821:     }
 9822:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 9823: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 9824:     } elsif ($number =~ /^_/) {
 9825: 	my $sub_condition;
 9826: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9827: 		&GDBM_READER(),0640)) {
 9828: 	    $sub_condition=$bighash{'conditions'.$number};
 9829: 	    untie(%bighash);
 9830: 	}
 9831: 	my $value = &docondval($sub_condition);
 9832: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 9833: 	return $value;
 9834:     }
 9835:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 9836:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 9837:     } else {
 9838:        return 2;
 9839:     }
 9840: }
 9841: 
 9842: # get the collection of conditions for this resource
 9843: sub condval {
 9844:     my $condidx=shift;
 9845:     my $allpathcond='';
 9846:     foreach my $cond (split(/\|/,$condidx)) {
 9847: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 9848: 	    $allpathcond.=
 9849: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 9850: 	}
 9851:     }
 9852:     $allpathcond=~s/\|$//;
 9853:     return &docondval($allpathcond);
 9854: }
 9855: 
 9856: #evaluates an expression of conditions
 9857: sub docondval {
 9858:     my ($allpathcond) = @_;
 9859:     my $result=0;
 9860:     if ($env{'request.course.id'}
 9861: 	&& defined($allpathcond)) {
 9862: 	my $operand='|';
 9863: 	my @stack;
 9864: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 9865: 	    if ($chunk eq '(') {
 9866: 		push @stack,($operand,$result);
 9867: 	    } elsif ($chunk eq ')') {
 9868: 		my $before=pop @stack;
 9869: 		if (pop @stack eq '&') {
 9870: 		    $result=$result>$before?$before:$result;
 9871: 		} else {
 9872: 		    $result=$result>$before?$result:$before;
 9873: 		}
 9874: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 9875: 		$operand=$chunk;
 9876: 	    } else {
 9877: 		my $new=directcondval($chunk);
 9878: 		if ($operand eq '&') {
 9879: 		    $result=$result>$new?$new:$result;
 9880: 		} else {
 9881: 		    $result=$result>$new?$result:$new;
 9882: 		}
 9883: 	    }
 9884: 	}
 9885:     }
 9886:     return $result;
 9887: }
 9888: 
 9889: # ---------------------------------------------------- Devalidate courseresdata
 9890: 
 9891: sub devalidatecourseresdata {
 9892:     my ($coursenum,$coursedomain)=@_;
 9893:     my $hashid=$coursenum.':'.$coursedomain;
 9894:     &devalidate_cache_new('courseres',$hashid);
 9895: }
 9896: 
 9897: 
 9898: # --------------------------------------------------- Course Resourcedata Query
 9899: #
 9900: #  Parameters:
 9901: #      $coursenum    - Number of the course.
 9902: #      $coursedomain - Domain at which the course was created.
 9903: #  Returns:
 9904: #     A hash of the course parameters along (I think) with timestamps
 9905: #     and version info.
 9906: 
 9907: sub get_courseresdata {
 9908:     my ($coursenum,$coursedomain)=@_;
 9909:     my $coursehom=&homeserver($coursenum,$coursedomain);
 9910:     my $hashid=$coursenum.':'.$coursedomain;
 9911:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 9912:     my %dumpreply;
 9913:     unless (defined($cached)) {
 9914: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 9915: 	$result=\%dumpreply;
 9916: 	my ($tmp) = keys(%dumpreply);
 9917: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9918: 	    &do_cache_new('courseres',$hashid,$result,600);
 9919: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 9920: 	    return $tmp;
 9921: 	} elsif ($tmp =~ /^(error)/) {
 9922: 	    $result=undef;
 9923: 	    &do_cache_new('courseres',$hashid,$result,600);
 9924: 	}
 9925:     }
 9926:     return $result;
 9927: }
 9928: 
 9929: sub devalidateuserresdata {
 9930:     my ($uname,$udom)=@_;
 9931:     my $hashid="$udom:$uname";
 9932:     &devalidate_cache_new('userres',$hashid);
 9933: }
 9934: 
 9935: sub get_userresdata {
 9936:     my ($uname,$udom)=@_;
 9937:     #most student don\'t have any data set, check if there is some data
 9938:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 9939: 
 9940:     my $hashid="$udom:$uname";
 9941:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 9942:     if (!defined($cached)) {
 9943: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 9944: 	$result=\%resourcedata;
 9945: 	&do_cache_new('userres',$hashid,$result,600);
 9946:     }
 9947:     my ($tmp)=keys(%$result);
 9948:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 9949: 	return $result;
 9950:     }
 9951:     #error 2 occurs when the .db doesn't exist
 9952:     if ($tmp!~/error: 2 /) {
 9953: 	&logthis("<font color=\"blue\">WARNING:".
 9954: 		 " Trying to get resource data for ".
 9955: 		 $uname." at ".$udom.": ".
 9956: 		 $tmp."</font>");
 9957:     } elsif ($tmp=~/error: 2 /) {
 9958: 	#&EXT_cache_set($udom,$uname);
 9959: 	&do_cache_new('userres',$hashid,undef,600);
 9960: 	undef($tmp); # not really an error so don't send it back
 9961:     }
 9962:     return $tmp;
 9963: }
 9964: #----------------------------------------------- resdata - return resource data
 9965: #  Purpose:
 9966: #    Return resource data for either users or for a course.
 9967: #  Parameters:
 9968: #     $name      - Course/user name.
 9969: #     $domain    - Name of the domain the user/course is registered on.
 9970: #     $type      - Type of thing $name is (must be 'course' or 'user'
 9971: #     @which     - Array of names of resources desired.
 9972: #  Returns:
 9973: #     The value of the first reasource in @which that is found in the
 9974: #     resource hash.
 9975: #  Exceptional Conditions:
 9976: #     If the $type passed in is not valid (not the string 'course' or 
 9977: #     'user', an undefined  reference is returned.
 9978: #     If none of the resources are found, an undef is returned
 9979: sub resdata {
 9980:     my ($name,$domain,$type,@which)=@_;
 9981:     my $result;
 9982:     if ($type eq 'course') {
 9983: 	$result=&get_courseresdata($name,$domain);
 9984:     } elsif ($type eq 'user') {
 9985: 	$result=&get_userresdata($name,$domain);
 9986:     }
 9987:     if (!ref($result)) { return $result; }    
 9988:     foreach my $item (@which) {
 9989: 	if (defined($result->{$item->[0]})) {
 9990: 	    return [$result->{$item->[0]},$item->[1]];
 9991: 	}
 9992:     }
 9993:     return undef;
 9994: }
 9995: 
 9996: sub get_numsuppfiles {
 9997:     my ($cnum,$cdom,$ignorecache)=@_;
 9998:     my $hashid=$cnum.':'.$cdom;
 9999:     my ($suppcount,$cached);
10000:     unless ($ignorecache) {
10001:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
10002:     }
10003:     unless (defined($cached)) {
10004:         my $chome=&homeserver($cnum,$cdom);
10005:         unless ($chome eq 'no_host') {
10006:             ($suppcount,my $errors) = (0,0);
10007:             my $suppmap = 'supplemental.sequence';
10008:             ($suppcount,$errors) = 
10009:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
10010:         }
10011:         &do_cache_new('suppcount',$hashid,$suppcount,600);
10012:     }
10013:     return $suppcount;
10014: }
10015: 
10016: #
10017: # EXT resource caching routines
10018: #
10019: 
10020: sub clear_EXT_cache_status {
10021:     &delenv('cache.EXT.');
10022: }
10023: 
10024: sub EXT_cache_status {
10025:     my ($target_domain,$target_user) = @_;
10026:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
10027:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
10028:         # We know already the user has no data
10029:         return 1;
10030:     } else {
10031:         return 0;
10032:     }
10033: }
10034: 
10035: sub EXT_cache_set {
10036:     my ($target_domain,$target_user) = @_;
10037:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
10038:     #&appenv({$cachename => time});
10039: }
10040: 
10041: # --------------------------------------------------------- Value of a Variable
10042: sub EXT {
10043: 
10044:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
10045:     unless ($varname) { return ''; }
10046:     #get real user name/domain, courseid and symb
10047:     my $courseid;
10048:     my $publicuser;
10049:     if ($symbparm) {
10050: 	$symbparm=&get_symb_from_alias($symbparm);
10051:     }
10052:     if (!($uname && $udom)) {
10053:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
10054:       if (!$symbparm) {	$symbparm=$cursymb; }
10055:     } else {
10056: 	$courseid=$env{'request.course.id'};
10057:     }
10058:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
10059:     my $rest;
10060:     if (defined($therest[0])) {
10061:        $rest=join('.',@therest);
10062:     } else {
10063:        $rest='';
10064:     }
10065: 
10066:     my $qualifierrest=$qualifier;
10067:     if ($rest) { $qualifierrest.='.'.$rest; }
10068:     my $spacequalifierrest=$space;
10069:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
10070:     if ($realm eq 'user') {
10071: # --------------------------------------------------------------- user.resource
10072: 	if ($space eq 'resource') {
10073: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
10074: 		  || defined($Apache::lonhomework::parsing_a_task))
10075: 		 &&
10076: 		 ($symbparm eq &symbread()) ) {	
10077: 		# if we are in the middle of processing the resource the
10078: 		# get the value we are planning on committing
10079:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
10080:                     return $Apache::lonhomework::results{$qualifierrest};
10081:                 } else {
10082:                     return $Apache::lonhomework::history{$qualifierrest};
10083:                 }
10084: 	    } else {
10085: 		my %restored;
10086: 		if ($publicuser || $env{'request.state'} eq 'construct') {
10087: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
10088: 		} else {
10089: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
10090: 		}
10091: 		return $restored{$qualifierrest};
10092: 	    }
10093: # ----------------------------------------------------------------- user.access
10094:         } elsif ($space eq 'access') {
10095: 	    # FIXME - not supporting calls for a specific user
10096:             return &allowed($qualifier,$rest);
10097: # ------------------------------------------ user.preferences, user.environment
10098:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
10099: 	    if (($uname eq $env{'user.name'}) &&
10100: 		($udom eq $env{'user.domain'})) {
10101: 		return $env{join('.',('environment',$qualifierrest))};
10102: 	    } else {
10103: 		my %returnhash;
10104: 		if (!$publicuser) {
10105: 		    %returnhash=&userenvironment($udom,$uname,
10106: 						 $qualifierrest);
10107: 		}
10108: 		return $returnhash{$qualifierrest};
10109: 	    }
10110: # ----------------------------------------------------------------- user.course
10111:         } elsif ($space eq 'course') {
10112: 	    # FIXME - not supporting calls for a specific user
10113:             return $env{join('.',('request.course',$qualifier))};
10114: # ------------------------------------------------------------------- user.role
10115:         } elsif ($space eq 'role') {
10116: 	    # FIXME - not supporting calls for a specific user
10117:             my ($role,$where)=split(/\./,$env{'request.role'});
10118:             if ($qualifier eq 'value') {
10119: 		return $role;
10120:             } elsif ($qualifier eq 'extent') {
10121:                 return $where;
10122:             }
10123: # ----------------------------------------------------------------- user.domain
10124:         } elsif ($space eq 'domain') {
10125:             return $udom;
10126: # ------------------------------------------------------------------- user.name
10127:         } elsif ($space eq 'name') {
10128:             return $uname;
10129: # ---------------------------------------------------- Any other user namespace
10130:         } else {
10131: 	    my %reply;
10132: 	    if (!$publicuser) {
10133: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
10134: 	    }
10135: 	    return $reply{$qualifierrest};
10136:         }
10137:     } elsif ($realm eq 'query') {
10138: # ---------------------------------------------- pull stuff out of query string
10139:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
10140: 						[$spacequalifierrest]);
10141: 	return $env{'form.'.$spacequalifierrest}; 
10142:    } elsif ($realm eq 'request') {
10143: # ------------------------------------------------------------- request.browser
10144:         if ($space eq 'browser') {
10145:             return $env{'browser.'.$qualifier};
10146: # ------------------------------------------------------------ request.filename
10147:         } else {
10148:             return $env{'request.'.$spacequalifierrest};
10149:         }
10150:     } elsif ($realm eq 'course') {
10151: # ---------------------------------------------------------- course.description
10152:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
10153:     } elsif ($realm eq 'resource') {
10154: 
10155: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
10156: 	    if (!$symbparm) { $symbparm=&symbread(); }
10157: 	}
10158: 
10159:         if ($qualifier eq '') {
10160: 	    if ($space eq 'title') {
10161: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
10162: 	        return &gettitle($symbparm);
10163: 	    }
10164: 	
10165: 	    if ($space eq 'map') {
10166: 	        my ($map) = &decode_symb($symbparm);
10167: 	        return &symbread($map);
10168: 	    }
10169:             if ($space eq 'maptitle') {
10170:                 my ($map) = &decode_symb($symbparm);
10171:                 return &gettitle($map);
10172:             }
10173: 	    if ($space eq 'filename') {
10174: 	        if ($symbparm) {
10175: 		    return &clutter((&decode_symb($symbparm))[2]);
10176: 	        }
10177: 	        return &hreflocation('',$env{'request.filename'});
10178: 	    }
10179: 
10180:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
10181:                 if ($space eq 'visibleparts') {
10182:                     my $navmap = Apache::lonnavmaps::navmap->new();
10183:                     my $item;
10184:                     if (ref($navmap)) {
10185:                         my $res = $navmap->getBySymb($symbparm);
10186:                         my $parts = $res->parts();
10187:                         if (ref($parts) eq 'ARRAY') {
10188:                             $item = join(',',@{$parts});
10189:                         }
10190:                         undef($navmap);
10191:                     }
10192:                     return $item;
10193:                 }
10194:             }
10195:         }
10196: 
10197: 	my ($section, $group, @groups);
10198: 	my ($courselevelm,$courselevel);
10199:         if (($courseid eq '') && ($cid)) {
10200:             $courseid = $cid;
10201:         }
10202: 	if (($symbparm && $courseid) && 
10203: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
10204: 
10205: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
10206: 
10207: # ----------------------------------------------------- Cascading lookup scheme
10208: 	    my $symbp=$symbparm;
10209: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
10210: 
10211: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
10212: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
10213: 
10214: 	    if (($env{'user.name'} eq $uname) &&
10215: 		($env{'user.domain'} eq $udom)) {
10216: 		$section=$env{'request.course.sec'};
10217:                 @groups = split(/:/,$env{'request.course.groups'});  
10218:                 @groups=&sort_course_groups($courseid,@groups); 
10219: 	    } else {
10220: 		if (! defined($usection)) {
10221: 		    $section=&getsection($udom,$uname,$courseid);
10222: 		} else {
10223: 		    $section = $usection;
10224: 		}
10225:                 @groups = &get_users_groups($udom,$uname,$courseid);
10226: 	    }
10227: 
10228: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
10229: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
10230: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
10231: 
10232: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
10233: 	    my $courselevelr=$courseid.'.'.$symbparm;
10234: 	    $courselevelm=$courseid.'.'.$mapparm;
10235: 
10236: # ----------------------------------------------------------- first, check user
10237: 
10238: 	    my $userreply=&resdata($uname,$udom,'user',
10239: 				       ([$courselevelr,'resource'],
10240: 					[$courselevelm,'map'     ],
10241: 					[$courselevel, 'course'  ]));
10242: 	    if (defined($userreply)) { return &get_reply($userreply); }
10243: 
10244: # ------------------------------------------------ second, check some of course
10245:             my $coursereply;
10246:             if (@groups > 0) {
10247:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
10248:                                        $mapparm,$spacequalifierrest);
10249:                 if (defined($coursereply)) { return &get_reply($coursereply); }
10250:             }
10251: 
10252: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10253: 				  $env{'course.'.$courseid.'.domain'},
10254: 				  'course',
10255: 				  ([$seclevelr,   'resource'],
10256: 				   [$seclevelm,   'map'     ],
10257: 				   [$seclevel,    'course'  ],
10258: 				   [$courselevelr,'resource']));
10259: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
10260: 
10261: # ------------------------------------------------------ third, check map parms
10262: 	    my %parmhash=();
10263: 	    my $thisparm='';
10264: 	    if (tie(%parmhash,'GDBM_File',
10265: 		    $env{'request.course.fn'}.'_parms.db',
10266: 		    &GDBM_READER(),0640)) {
10267: 		$thisparm=$parmhash{$symbparm};
10268: 		untie(%parmhash);
10269: 	    }
10270: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
10271: 	}
10272: # ------------------------------------------ fourth, look in resource metadata
10273: 
10274: 	$spacequalifierrest=~s/\./\_/;
10275: 	my $filename;
10276: 	if (!$symbparm) { $symbparm=&symbread(); }
10277: 	if ($symbparm) {
10278: 	    $filename=(&decode_symb($symbparm))[2];
10279: 	} else {
10280: 	    $filename=$env{'request.filename'};
10281: 	}
10282: 	my $metadata=&metadata($filename,$spacequalifierrest);
10283: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
10284: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
10285: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
10286: 
10287: # ---------------------------------------------- fourth, look in rest of course
10288: 	if ($symbparm && defined($courseid) && 
10289: 	    $courseid eq $env{'request.course.id'}) {
10290: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10291: 				     $env{'course.'.$courseid.'.domain'},
10292: 				     'course',
10293: 				     ([$courselevelm,'map'   ],
10294: 				      [$courselevel, 'course']));
10295: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
10296: 	}
10297: # ------------------------------------------------------------------ Cascade up
10298: 	unless ($space eq '0') {
10299: 	    my @parts=split(/_/,$space);
10300: 	    my $id=pop(@parts);
10301: 	    my $part=join('_',@parts);
10302: 	    if ($part eq '') { $part='0'; }
10303: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
10304: 				 $symbparm,$udom,$uname,$section,1);
10305: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
10306: 	}
10307: 	if ($recurse) { return undef; }
10308: 	my $pack_def=&packages_tab_default($filename,$varname);
10309: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
10310: # ---------------------------------------------------- Any other user namespace
10311:     } elsif ($realm eq 'environment') {
10312: # ----------------------------------------------------------------- environment
10313: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
10314: 	    return $env{'environment.'.$spacequalifierrest};
10315: 	} else {
10316: 	    if ($uname eq 'anonymous' && $udom eq '') {
10317: 		return '';
10318: 	    }
10319: 	    my %returnhash=&userenvironment($udom,$uname,
10320: 					    $spacequalifierrest);
10321: 	    return $returnhash{$spacequalifierrest};
10322: 	}
10323:     } elsif ($realm eq 'system') {
10324: # ----------------------------------------------------------------- system.time
10325: 	if ($space eq 'time') {
10326: 	    return time;
10327:         }
10328:     } elsif ($realm eq 'server') {
10329: # ----------------------------------------------------------------- system.time
10330: 	if ($space eq 'name') {
10331: 	    return $ENV{'SERVER_NAME'};
10332:         }
10333:     }
10334:     return '';
10335: }
10336: 
10337: sub get_reply {
10338:     my ($reply_value) = @_;
10339:     if (ref($reply_value) eq 'ARRAY') {
10340:         if (wantarray) {
10341: 	    return @$reply_value;
10342:         }
10343:         return $reply_value->[0];
10344:     } else {
10345:         return $reply_value;
10346:     }
10347: }
10348: 
10349: sub check_group_parms {
10350:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10351:     my @groupitems = ();
10352:     my $resultitem;
10353:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
10354:     foreach my $group (@{$groups}) {
10355:         foreach my $level (@levels) {
10356:              my $item = $courseid.'.['.$group.'].'.$level->[0];
10357:              push(@groupitems,[$item,$level->[1]]);
10358:         }
10359:     }
10360:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10361:                             $env{'course.'.$courseid.'.domain'},
10362:                                      'course',@groupitems);
10363:     return $coursereply;
10364: }
10365: 
10366: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
10367:     my ($courseid,@groups) = @_;
10368:     @groups = sort(@groups);
10369:     return @groups;
10370: }
10371: 
10372: sub packages_tab_default {
10373:     my ($uri,$varname)=@_;
10374:     my (undef,$part,$name)=split(/\./,$varname);
10375: 
10376:     my (@extension,@specifics,$do_default);
10377:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
10378: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
10379: 	if ($pack_type eq 'default') {
10380: 	    $do_default=1;
10381: 	} elsif ($pack_type eq 'extension') {
10382: 	    push(@extension,[$package,$pack_type,$pack_part]);
10383: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
10384: 	    # only look at packages defaults for packages that this id is
10385: 	    push(@specifics,[$package,$pack_type,$pack_part]);
10386: 	}
10387:     }
10388:     # first look for a package that matches the requested part id
10389:     foreach my $package (@specifics) {
10390: 	my (undef,$pack_type,$pack_part)=@{$package};
10391: 	next if ($pack_part ne $part);
10392: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10393: 	    return $packagetab{"$pack_type&$name&default"};
10394: 	}
10395:     }
10396:     # look for any possible matching non extension_ package
10397:     foreach my $package (@specifics) {
10398: 	my (undef,$pack_type,$pack_part)=@{$package};
10399: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10400: 	    return $packagetab{"$pack_type&$name&default"};
10401: 	}
10402: 	if ($pack_type eq 'part') { $pack_part='0'; }
10403: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10404: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
10405: 	}
10406:     }
10407:     # look for any posible extension_ match
10408:     foreach my $package (@extension) {
10409: 	my ($package,$pack_type)=@{$package};
10410: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10411: 	    return $packagetab{"$pack_type&$name&default"};
10412: 	}
10413: 	if (defined($packagetab{$package."&$name&default"})) {
10414: 	    return $packagetab{$package."&$name&default"};
10415: 	}
10416:     }
10417:     # look for a global default setting
10418:     if ($do_default && defined($packagetab{"default&$name&default"})) {
10419: 	return $packagetab{"default&$name&default"};
10420:     }
10421:     return undef;
10422: }
10423: 
10424: sub add_prefix_and_part {
10425:     my ($prefix,$part)=@_;
10426:     my $keyroot;
10427:     if (defined($prefix) && $prefix !~ /^__/) {
10428: 	# prefix that has a part already
10429: 	$keyroot=$prefix;
10430:     } elsif (defined($prefix)) {
10431: 	# prefix that is missing a part
10432: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10433:     } else {
10434: 	# no prefix at all
10435: 	if (defined($part)) { $keyroot='_'.$part; }
10436:     }
10437:     return $keyroot;
10438: }
10439: 
10440: # ---------------------------------------------------------------- Get metadata
10441: 
10442: my %metaentry;
10443: my %importedpartids;
10444: sub metadata {
10445:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
10446:     $uri=&declutter($uri);
10447:     # if it is a non metadata possible uri return quickly
10448:     if (($uri eq '') || 
10449: 	(($uri =~ m|^/*adm/|) && 
10450: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
10451:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
10452: 	return undef;
10453:     }
10454:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
10455: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
10456: 	return undef;
10457:     }
10458:     my $filename=$uri;
10459:     $uri=~s/\.meta$//;
10460: #
10461: # Is the metadata already cached?
10462: # Look at timestamp of caching
10463: # Everything is cached by the main uri, libraries are never directly cached
10464: #
10465:     if (!defined($liburi)) {
10466: 	my ($result,$cached)=&is_cached_new('meta',$uri);
10467: 	if (defined($cached)) { return $result->{':'.$what}; }
10468:     }
10469:     {
10470: # Imported parts would go here
10471:         my %importedids=();
10472:         my @origfileimportpartids=();
10473:         my $importedparts=0;
10474: #
10475: # Is this a recursive call for a library?
10476: #
10477: #	if (! exists($metacache{$uri})) {
10478: #	    $metacache{$uri}={};
10479: #	}
10480: 	my $cachetime = 60*60;
10481:         if ($liburi) {
10482: 	    $liburi=&declutter($liburi);
10483:             $filename=$liburi;
10484:         } else {
10485: 	    &devalidate_cache_new('meta',$uri);
10486: 	    undef(%metaentry);
10487: 	}
10488:         my %metathesekeys=();
10489:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
10490: 	my $metastring;
10491: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
10492: 	    my $which = &hreflocation('','/'.($liburi || $uri));
10493: 	    $metastring = 
10494: 		&Apache::lonnet::ssi_body($which,
10495: 					  ('grade_target' => 'meta'));
10496: 	    $cachetime = 1; # only want this cached in the child not long term
10497: 	} elsif (($uri !~ m -^(editupload)/-) && 
10498:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
10499: 	    my $file=&filelocation('',&clutter($filename));
10500: 	    #push(@{$metaentry{$uri.'.file'}},$file);
10501: 	    $metastring=&getfile($file);
10502: 	}
10503:         my $parser=HTML::LCParser->new(\$metastring);
10504:         my $token;
10505:         undef %metathesekeys;
10506:         while ($token=$parser->get_token) {
10507: 	    if ($token->[0] eq 'S') {
10508: 		if (defined($token->[2]->{'package'})) {
10509: #
10510: # This is a package - get package info
10511: #
10512: 		    my $package=$token->[2]->{'package'};
10513: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10514: 		    if (defined($token->[2]->{'id'})) { 
10515: 			$keyroot.='_'.$token->[2]->{'id'}; 
10516: 		    }
10517: 		    if ($metaentry{':packages'}) {
10518: 			$metaentry{':packages'}.=','.$package.$keyroot;
10519: 		    } else {
10520: 			$metaentry{':packages'}=$package.$keyroot;
10521: 		    }
10522: 		    foreach my $pack_entry (keys(%packagetab)) {
10523: 			my $part=$keyroot;
10524: 			$part=~s/^\_//;
10525: 			if ($pack_entry=~/^\Q$package\E\&/ || 
10526: 			    $pack_entry=~/^\Q$package\E_0\&/) {
10527: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
10528: 			    # ignore package.tab specified default values
10529:                             # here &package_tab_default() will fetch those
10530: 			    if ($subp eq 'default') { next; }
10531: 			    my $value=$packagetab{$pack_entry};
10532: 			    my $unikey;
10533: 			    if ($pack =~ /_0$/) {
10534: 				$unikey='parameter_0_'.$name;
10535: 				$part=0;
10536: 			    } else {
10537: 				$unikey='parameter'.$keyroot.'_'.$name;
10538: 			    }
10539: 			    if ($subp eq 'display') {
10540: 				$value.=' [Part: '.$part.']';
10541: 			    }
10542: 			    $metaentry{':'.$unikey.'.part'}=$part;
10543: 			    $metathesekeys{$unikey}=1;
10544: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10545: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
10546: 			    }
10547: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
10548: 				$metaentry{':'.$unikey}=
10549: 				    $metaentry{':'.$unikey.'.default'};
10550: 			    }
10551: 			}
10552: 		    }
10553: 		} else {
10554: #
10555: # This is not a package - some other kind of start tag
10556: #
10557: 		    my $entry=$token->[1];
10558: 		    my $unikey='';
10559: 
10560: 		    if ($entry eq 'import') {
10561: #
10562: # Importing a library here
10563: #
10564:                         my $location=$parser->get_text('/import');
10565:                         my $dir=$filename;
10566:                         $dir=~s|[^/]*$||;
10567:                         $location=&filelocation($dir,$location);
10568:                        
10569:                         my $importmode=$token->[2]->{'importmode'};
10570:                         if ($importmode eq 'problem') {
10571: # Import as problem/response
10572:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10573:                         } elsif ($importmode eq 'part') {
10574: # Import as part(s)
10575:                            $importedparts=1;
10576: # We need to get the original file and the imported file to get the part order correct
10577: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10578: # Load and inspect original file
10579:                            if ($#origfileimportpartids<0) {
10580:                               undef(%importedpartids);
10581:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10582:                               my $origfile=&getfile($origfilelocation);
10583:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10584:                            }
10585: 
10586: # Load and inspect imported file
10587:                            my $impfile=&getfile($location);
10588:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10589:                            if ($#impfilepartids>=0) {
10590: # This problem had parts
10591:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
10592:                            } else {
10593: # Importing by turning a single problem into a problem part
10594: # It gets the import-tags ID as part-ID
10595:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
10596:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
10597:                            }
10598:                         } else {
10599: # Normal import
10600:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10601:                            if (defined($token->[2]->{'id'})) {
10602:                               $unikey.='_'.$token->[2]->{'id'};
10603:                            }
10604:                         }
10605: 
10606: 			if ($depthcount<20) {
10607: 			    my $metadata = 
10608: 				&metadata($uri,'keys', $location,$unikey,
10609: 					  $depthcount+1);
10610: 			    foreach my $meta (split(',',$metadata)) {
10611: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
10612: 				$metathesekeys{$meta}=1;
10613: 			    }
10614: 			
10615:                         }
10616: 		    } else {
10617: #
10618: # Not importing, some other kind of non-package, non-library start tag
10619: # 
10620:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10621:                         if (defined($token->[2]->{'id'})) {
10622:                             $unikey.='_'.$token->[2]->{'id'};
10623:                         }
10624: 			if (defined($token->[2]->{'name'})) { 
10625: 			    $unikey.='_'.$token->[2]->{'name'}; 
10626: 			}
10627: 			$metathesekeys{$unikey}=1;
10628: 			foreach my $param (@{$token->[3]}) {
10629: 			    $metaentry{':'.$unikey.'.'.$param} =
10630: 				$token->[2]->{$param};
10631: 			}
10632: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
10633: 			my $default=$metaentry{':'.$unikey.'.default'};
10634: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10635: 		 # only ws inside the tag, and not in default, so use default
10636: 		 # as value
10637: 			    $metaentry{':'.$unikey}=$default;
10638: 			} elsif ( $internaltext =~ /\S/ ) {
10639: 		  # something interesting inside the tag
10640: 			    $metaentry{':'.$unikey}=$internaltext;
10641: 			} else {
10642: 		  # no interesting values, don't set a default
10643: 			}
10644: # end of not-a-package not-a-library import
10645: 		    }
10646: # end of not-a-package start tag
10647: 		}
10648: # the next is the end of "start tag"
10649: 	    }
10650: 	}
10651: 	my ($extension) = ($uri =~ /\.(\w+)$/);
10652: 	$extension = lc($extension);
10653: 	if ($extension eq 'htm') { $extension='html'; }
10654: 
10655: 	foreach my $key (keys(%packagetab)) {
10656: 	    #no specific packages #how's our extension
10657: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
10658: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
10659: 					 \%metathesekeys);
10660: 	}
10661: 
10662: 	if (!exists($metaentry{':packages'})
10663: 	    || $packagetab{"import_defaults&extension_$extension"}) {
10664: 	    foreach my $key (keys(%packagetab)) {
10665: 		#no specific packages well let's get default then
10666: 		if ($key!~/^default&/) { next; }
10667: 		&metadata_create_package_def($uri,$key,'default',
10668: 					     \%metathesekeys);
10669: 	    }
10670: 	}
10671: # are there custom rights to evaluate
10672: 	if ($metaentry{':copyright'} eq 'custom') {
10673: 
10674:     #
10675:     # Importing a rights file here
10676:     #
10677: 	    unless ($depthcount) {
10678: 		my $location=$metaentry{':customdistributionfile'};
10679: 		my $dir=$filename;
10680: 		$dir=~s|[^/]*$||;
10681: 		$location=&filelocation($dir,$location);
10682: 		my $rights_metadata =
10683: 		    &metadata($uri,'keys',$location,'_rights',
10684: 			      $depthcount+1);
10685: 		foreach my $rights (split(',',$rights_metadata)) {
10686: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10687: 		    $metathesekeys{$rights}=1;
10688: 		}
10689: 	    }
10690: 	}
10691: 	# uniqifiy package listing
10692: 	my %seen;
10693: 	my @uniq_packages =
10694: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10695: 	$metaentry{':packages'} = join(',',@uniq_packages);
10696: 
10697:         if ($importedparts) {
10698: # We had imported parts and need to rebuild partorder
10699:            $metaentry{':partorder'}='';
10700:            $metathesekeys{'partorder'}=1;
10701:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10702:                if ($origfileimportpartids[$index] eq 'part') {
10703: # original part, part of the problem
10704:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10705:                } else {
10706: # we have imported parts at this position
10707:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10708:                }
10709:            }
10710:            $metaentry{':partorder'}=~s/^\,//;
10711:         }
10712: 
10713: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
10714: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
10715: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
10716: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
10717: # this is the end of "was not already recently cached
10718:     }
10719:     return $metaentry{':'.$what};
10720: }
10721: 
10722: sub metadata_create_package_def {
10723:     my ($uri,$key,$package,$metathesekeys)=@_;
10724:     my ($pack,$name,$subp)=split(/\&/,$key);
10725:     if ($subp eq 'default') { next; }
10726:     
10727:     if (defined($metaentry{':packages'})) {
10728: 	$metaentry{':packages'}.=','.$package;
10729:     } else {
10730: 	$metaentry{':packages'}=$package;
10731:     }
10732:     my $value=$packagetab{$key};
10733:     my $unikey;
10734:     $unikey='parameter_0_'.$name;
10735:     $metaentry{':'.$unikey.'.part'}=0;
10736:     $$metathesekeys{$unikey}=1;
10737:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10738: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
10739:     }
10740:     if (defined($metaentry{':'.$unikey.'.default'})) {
10741: 	$metaentry{':'.$unikey}=
10742: 	    $metaentry{':'.$unikey.'.default'};
10743:     }
10744: }
10745: 
10746: sub metadata_generate_part0 {
10747:     my ($metadata,$metacache,$uri) = @_;
10748:     my %allnames;
10749:     foreach my $metakey (keys(%$metadata)) {
10750: 	if ($metakey=~/^parameter\_(.*)/) {
10751: 	  my $part=$$metacache{':'.$metakey.'.part'};
10752: 	  my $name=$$metacache{':'.$metakey.'.name'};
10753: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
10754: 	    $allnames{$name}=$part;
10755: 	  }
10756: 	}
10757:     }
10758:     foreach my $name (keys(%allnames)) {
10759:       $$metadata{"parameter_0_$name"}=1;
10760:       my $key=":parameter_0_$name";
10761:       $$metacache{"$key.part"}='0';
10762:       $$metacache{"$key.name"}=$name;
10763:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
10764: 					   $allnames{$name}.'_'.$name.
10765: 					   '.type'};
10766:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
10767: 			     '.display'};
10768:       my $expr='[Part: '.$allnames{$name}.']';
10769:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
10770:       $$metacache{"$key.display"}=$olddis;
10771:     }
10772: }
10773: 
10774: # ------------------------------------------------------ Devalidate title cache
10775: 
10776: sub devalidate_title_cache {
10777:     my ($url)=@_;
10778:     if (!$env{'request.course.id'}) { return; }
10779:     my $symb=&symbread($url);
10780:     if (!$symb) { return; }
10781:     my $key=$env{'request.course.id'}."\0".$symb;
10782:     &devalidate_cache_new('title',$key);
10783: }
10784: 
10785: # ------------------------------------------------- Get the title of a course
10786: 
10787: sub current_course_title {
10788:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10789: }
10790: # ------------------------------------------------- Get the title of a resource
10791: 
10792: sub gettitle {
10793:     my $urlsymb=shift;
10794:     my $symb=&symbread($urlsymb);
10795:     if ($symb) {
10796: 	my $key=$env{'request.course.id'}."\0".$symb;
10797: 	my ($result,$cached)=&is_cached_new('title',$key);
10798: 	if (defined($cached)) { 
10799: 	    return $result;
10800: 	}
10801: 	my ($map,$resid,$url)=&decode_symb($symb);
10802: 	my $title='';
10803: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10804: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10805: 	} else {
10806: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10807: 		    &GDBM_READER(),0640)) {
10808: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
10809: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
10810: 		untie(%bighash);
10811: 	    }
10812: 	}
10813: 	$title=~s/\&colon\;/\:/gs;
10814: 	if ($title) {
10815: # Remember both $symb and $title for dynamic metadata
10816:             $accesshash{$symb.'___crstitle'}=$title;
10817:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
10818: # Cache this title and then return it
10819: 	    return &do_cache_new('title',$key,$title,600);
10820: 	}
10821: 	$urlsymb=$url;
10822:     }
10823:     my $title=&metadata($urlsymb,'title');
10824:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
10825:     return $title;
10826: }
10827: 
10828: sub get_slot {
10829:     my ($which,$cnum,$cdom)=@_;
10830:     if (!$cnum || !$cdom) {
10831: 	(undef,my $courseid)=&whichuser();
10832: 	$cdom=$env{'course.'.$courseid.'.domain'};
10833: 	$cnum=$env{'course.'.$courseid.'.num'};
10834:     }
10835:     my $key=join("\0",'slots',$cdom,$cnum,$which);
10836:     my %slotinfo;
10837:     if (exists($remembered{$key})) {
10838: 	$slotinfo{$which} = $remembered{$key};
10839:     } else {
10840: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
10841: 	&Apache::lonhomework::showhash(%slotinfo);
10842: 	my ($tmp)=keys(%slotinfo);
10843: 	if ($tmp=~/^error:/) { return (); }
10844: 	$remembered{$key} = $slotinfo{$which};
10845:     }
10846:     if (ref($slotinfo{$which}) eq 'HASH') {
10847: 	return %{$slotinfo{$which}};
10848:     }
10849:     return $slotinfo{$which};
10850: }
10851: 
10852: sub get_reservable_slots {
10853:     my ($cnum,$cdom,$uname,$udom) = @_;
10854:     my $now = time;
10855:     my $reservable_info;
10856:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10857:     if (exists($remembered{$key})) {
10858:         $reservable_info = $remembered{$key};
10859:     } else {
10860:         my %resv;
10861:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10862:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10863:         $reservable_info = \%resv;
10864:         $remembered{$key} = $reservable_info;
10865:     }
10866:     return $reservable_info;
10867: }
10868: 
10869: sub get_course_slots {
10870:     my ($cnum,$cdom) = @_;
10871:     my $hashid=$cnum.':'.$cdom;
10872:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10873:     if (defined($cached)) {
10874:         if (ref($result) eq 'HASH') {
10875:             return %{$result};
10876:         }
10877:     } else {
10878:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10879:         my ($tmp) = keys(%slots);
10880:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10881:             &do_cache_new('allslots',$hashid,\%slots,600);
10882:             return %slots;
10883:         }
10884:     }
10885:     return;
10886: }
10887: 
10888: sub devalidate_slots_cache {
10889:     my ($cnum,$cdom)=@_;
10890:     my $hashid=$cnum.':'.$cdom;
10891:     &devalidate_cache_new('allslots',$hashid);
10892: }
10893: 
10894: sub get_coursechange {
10895:     my ($cdom,$cnum) = @_;
10896:     if ($cdom eq '' || $cnum eq '') {
10897:         return unless ($env{'request.course.id'});
10898:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10899:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10900:     }
10901:     my $hashid=$cdom.'_'.$cnum;
10902:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
10903:     if ((defined($cached)) && ($change ne '')) {
10904:         return $change;
10905:     } else {
10906:         my %crshash;
10907:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10908:         if ($crshash{'internal.contentchange'} eq '') {
10909:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
10910:             if ($change eq '') {
10911:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
10912:                 $change = $crshash{'internal.created'};
10913:             }
10914:         } else {
10915:             $change = $crshash{'internal.contentchange'};
10916:         }
10917:         my $cachetime = 600;
10918:         &do_cache_new('crschange',$hashid,$change,$cachetime);
10919:     }
10920:     return $change;
10921: }
10922: 
10923: sub devalidate_coursechange_cache {
10924:     my ($cnum,$cdom)=@_;
10925:     my $hashid=$cnum.':'.$cdom;
10926:     &devalidate_cache_new('crschange',$hashid);
10927: }
10928: 
10929: # ------------------------------------------------- Update symbolic store links
10930: 
10931: sub symblist {
10932:     my ($mapname,%newhash)=@_;
10933:     $mapname=&deversion(&declutter($mapname));
10934:     my %hash;
10935:     if (($env{'request.course.fn'}) && (%newhash)) {
10936:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10937:                       &GDBM_WRCREAT(),0640)) {
10938: 	    foreach my $url (keys(%newhash)) {
10939: 		next if ($url eq 'last_known'
10940: 			 && $env{'form.no_update_last_known'});
10941: 		$hash{declutter($url)}=&encode_symb($mapname,
10942: 						    $newhash{$url}->[1],
10943: 						    $newhash{$url}->[0]);
10944:             }
10945:             if (untie(%hash)) {
10946: 		return 'ok';
10947:             }
10948:         }
10949:     }
10950:     return 'error';
10951: }
10952: 
10953: # --------------------------------------------------------------- Verify a symb
10954: 
10955: sub symbverify {
10956:     my ($symb,$thisurl,$encstate)=@_;
10957:     my $thisfn=$thisurl;
10958:     $thisfn=&declutter($thisfn);
10959: # direct jump to resource in page or to a sequence - will construct own symbs
10960:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10961: # check URL part
10962:     my ($map,$resid,$url)=&decode_symb($symb);
10963: 
10964:     unless ($url eq $thisfn) { return 0; }
10965: 
10966:     $symb=&symbclean($symb);
10967:     $thisurl=&deversion($thisurl);
10968:     $thisfn=&deversion($thisfn);
10969: 
10970:     my %bighash;
10971:     my $okay=0;
10972: 
10973:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10974:                             &GDBM_READER(),0640)) {
10975:         my $noclutter;
10976:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10977:             $thisurl =~ s/\?.+$//;
10978:             if ($map =~ m{^uploaded/.+\.page$}) {
10979:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
10980:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
10981:                 $noclutter = 1;
10982:             }
10983:         }
10984:         my $ids;
10985:         if ($noclutter) {
10986:             $ids=$bighash{'ids_'.$thisurl};
10987:         } else {
10988:             $ids=$bighash{'ids_'.&clutter($thisurl)};
10989:         }
10990:         unless ($ids) {
10991:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
10992:             $ids=$bighash{$idkey};
10993:         }
10994:         if ($ids) {
10995: # ------------------------------------------------------------------- Has ID(s)
10996:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
10997:                 $symb =~ s/\?.+$//;
10998:             }
10999: 	    foreach my $id (split(/\,/,$ids)) {
11000: 	       my ($mapid,$resid)=split(/\./,$id);
11001:                if (
11002:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
11003:    eq $symb) {
11004:                    if (ref($encstate)) {
11005:                        $$encstate = $bighash{'encrypted_'.$id};
11006:                    }
11007: 		   if (($env{'request.role.adv'}) ||
11008: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
11009:                        ($thisurl eq '/adm/navmaps')) {
11010: 		       $okay=1;
11011:                        last;
11012: 		   }
11013: 	       }
11014: 	   }
11015:         }
11016: 	untie(%bighash);
11017:     }
11018:     return $okay;
11019: }
11020: 
11021: # --------------------------------------------------------------- Clean-up symb
11022: 
11023: sub symbclean {
11024:     my $symb=shift;
11025:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
11026: # remove version from map
11027:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
11028: 
11029: # remove version from URL
11030:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
11031: 
11032: # remove wrapper
11033: 
11034:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
11035:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
11036:     return $symb;
11037: }
11038: 
11039: # ---------------------------------------------- Split symb to find map and url
11040: 
11041: sub encode_symb {
11042:     my ($map,$resid,$url)=@_;
11043:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
11044: }
11045: 
11046: sub decode_symb {
11047:     my $symb=shift;
11048:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
11049:     my ($map,$resid,$url)=split(/___/,$symb);
11050:     return (&fixversion($map),$resid,&fixversion($url));
11051: }
11052: 
11053: sub fixversion {
11054:     my $fn=shift;
11055:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
11056:     my %bighash;
11057:     my $uri=&clutter($fn);
11058:     my $key=$env{'request.course.id'}.'_'.$uri;
11059: # is this cached?
11060:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
11061:     if (defined($cached)) { return $result; }
11062: # unfortunately not cached, or expired
11063:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11064: 	    &GDBM_READER(),0640)) {
11065:  	if ($bighash{'version_'.$uri}) {
11066:  	    my $version=$bighash{'version_'.$uri};
11067:  	    unless (($version eq 'mostrecent') || 
11068: 		    ($version==&getversion($uri))) {
11069:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
11070:  	    }
11071:  	}
11072:  	untie %bighash;
11073:     }
11074:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
11075: }
11076: 
11077: sub deversion {
11078:     my $url=shift;
11079:     $url=~s/\.\d+\.(\w+)$/\.$1/;
11080:     return $url;
11081: }
11082: 
11083: # ------------------------------------------------------ Return symb list entry
11084: 
11085: sub symbread {
11086:     my ($thisfn,$donotrecurse)=@_;
11087:     my $cache_str='request.symbread.cached.'.$thisfn;
11088:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
11089: # no filename provided? try from environment
11090:     unless ($thisfn) {
11091:         if ($env{'request.symb'}) {
11092: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
11093: 	}
11094: 	$thisfn=$env{'request.filename'};
11095:     }
11096:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
11097: # is that filename actually a symb? Verify, clean, and return
11098:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
11099: 	if (&symbverify($thisfn,$1)) {
11100: 	    return $env{$cache_str}=&symbclean($thisfn);
11101: 	}
11102:     }
11103:     $thisfn=declutter($thisfn);
11104:     my %hash;
11105:     my %bighash;
11106:     my $syval='';
11107:     if (($env{'request.course.fn'}) && ($thisfn)) {
11108:         my $targetfn = $thisfn;
11109:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
11110:             $targetfn = 'adm/wrapper/'.$thisfn;
11111:         }
11112: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
11113: 	    $targetfn=$1;
11114: 	}
11115:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
11116:                       &GDBM_READER(),0640)) {
11117: 	    $syval=$hash{$targetfn};
11118:             untie(%hash);
11119:         }
11120: # ---------------------------------------------------------- There was an entry
11121:         if ($syval) {
11122: 	    #unless ($syval=~/\_\d+$/) {
11123: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
11124: 		    #&appenv({'request.ambiguous' => $thisfn});
11125: 		    #return $env{$cache_str}='';
11126: 		#}    
11127: 		#$syval.=$1;
11128: 	    #}
11129:         } else {
11130: # ------------------------------------------------------- Was not in symb table
11131:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11132:                             &GDBM_READER(),0640)) {
11133: # ---------------------------------------------- Get ID(s) for current resource
11134:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
11135:               unless ($ids) { 
11136:                  $ids=$bighash{'ids_/'.$thisfn};
11137:               }
11138:               unless ($ids) {
11139: # alias?
11140: 		  $ids=$bighash{'mapalias_'.$thisfn};
11141:               }
11142:               if ($ids) {
11143: # ------------------------------------------------------------------- Has ID(s)
11144:                  my @possibilities=split(/\,/,$ids);
11145:                  if ($#possibilities==0) {
11146: # ----------------------------------------------- There is only one possibility
11147: 		     my ($mapid,$resid)=split(/\./,$ids);
11148: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
11149: 						    $resid,$thisfn);
11150:                  } elsif (!$donotrecurse) {
11151: # ------------------------------------------ There is more than one possibility
11152:                      my $realpossible=0;
11153:                      foreach my $id (@possibilities) {
11154: 			 my $file=$bighash{'src_'.$id};
11155:                          if (&allowed('bre',$file)) {
11156:          		    my ($mapid,$resid)=split(/\./,$id);
11157:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
11158: 				$realpossible++;
11159:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
11160: 						    $resid,$thisfn);
11161:                             }
11162: 			 }
11163:                      }
11164: 		     if ($realpossible!=1) { $syval=''; }
11165:                  } else {
11166:                      $syval='';
11167:                  }
11168: 	      }
11169:               untie(%bighash)
11170:            }
11171:         }
11172:         if ($syval) {
11173: 	    return $env{$cache_str}=$syval;
11174:         }
11175:     }
11176:     &appenv({'request.ambiguous' => $thisfn});
11177:     return $env{$cache_str}='';
11178: }
11179: 
11180: # ---------------------------------------------------------- Return random seed
11181: 
11182: sub numval {
11183:     my $txt=shift;
11184:     $txt=~tr/A-J/0-9/;
11185:     $txt=~tr/a-j/0-9/;
11186:     $txt=~tr/K-T/0-9/;
11187:     $txt=~tr/k-t/0-9/;
11188:     $txt=~tr/U-Z/0-5/;
11189:     $txt=~tr/u-z/0-5/;
11190:     $txt=~s/\D//g;
11191:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
11192:     return int($txt);
11193: }
11194: 
11195: sub numval2 {
11196:     my $txt=shift;
11197:     $txt=~tr/A-J/0-9/;
11198:     $txt=~tr/a-j/0-9/;
11199:     $txt=~tr/K-T/0-9/;
11200:     $txt=~tr/k-t/0-9/;
11201:     $txt=~tr/U-Z/0-5/;
11202:     $txt=~tr/u-z/0-5/;
11203:     $txt=~s/\D//g;
11204:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11205:     my $total;
11206:     foreach my $val (@txts) { $total+=$val; }
11207:     if ($_64bit) { if ($total > 2**32) { return -1; } }
11208:     return int($total);
11209: }
11210: 
11211: sub numval3 {
11212:     use integer;
11213:     my $txt=shift;
11214:     $txt=~tr/A-J/0-9/;
11215:     $txt=~tr/a-j/0-9/;
11216:     $txt=~tr/K-T/0-9/;
11217:     $txt=~tr/k-t/0-9/;
11218:     $txt=~tr/U-Z/0-5/;
11219:     $txt=~tr/u-z/0-5/;
11220:     $txt=~s/\D//g;
11221:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11222:     my $total;
11223:     foreach my $val (@txts) { $total+=$val; }
11224:     if ($_64bit) { $total=(($total<<32)>>32); }
11225:     return $total;
11226: }
11227: 
11228: sub digest {
11229:     my ($data)=@_;
11230:     my $digest=&Digest::MD5::md5($data);
11231:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
11232:     my ($e,$f);
11233:     {
11234:         use integer;
11235:         $e=($a+$b);
11236:         $f=($c+$d);
11237:         if ($_64bit) {
11238:             $e=(($e<<32)>>32);
11239:             $f=(($f<<32)>>32);
11240:         }
11241:     }
11242:     if (wantarray) {
11243: 	return ($e,$f);
11244:     } else {
11245: 	my $g;
11246: 	{
11247: 	    use integer;
11248: 	    $g=($e+$f);
11249: 	    if ($_64bit) {
11250: 		$g=(($g<<32)>>32);
11251: 	    }
11252: 	}
11253: 	return $g;
11254:     }
11255: }
11256: 
11257: sub latest_rnd_algorithm_id {
11258:     return '64bit5';
11259: }
11260: 
11261: sub get_rand_alg {
11262:     my ($courseid)=@_;
11263:     if (!$courseid) { $courseid=(&whichuser())[1]; }
11264:     if ($courseid) {
11265: 	return $env{"course.$courseid.rndseed"};
11266:     }
11267:     return &latest_rnd_algorithm_id();
11268: }
11269: 
11270: sub validCODE {
11271:     my ($CODE)=@_;
11272:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
11273:     return 0;
11274: }
11275: 
11276: sub getCODE {
11277:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
11278:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
11279: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
11280: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
11281: 	return $Apache::lonhomework::history{'resource.CODE'};
11282:     }
11283:     return undef;
11284: }
11285: #
11286: #  Determines the random seed for a specific context:
11287: #
11288: # parameters:
11289: #   symb      - in course context the symb for the seed.
11290: #   course_id - The course id of the form domain_coursenum.
11291: #   domain    - Domain for the user.
11292: #   course    - Course for the user.
11293: #   cenv      - environment of the course.
11294: #
11295: # NOTE:
11296: #   All parameters are picked out of the environment if missing
11297: #   or not defined.
11298: #   If a symb cannot be determined the current time is used instead.
11299: #
11300: #  For a given well defined symb, courside, domain, username,
11301: #  and course environment, the seed is reproducible.
11302: #
11303: sub rndseed {
11304:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
11305:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
11306:     if (!defined($symb)) {
11307: 	unless ($symb=$wsymb) { return time; }
11308:     }
11309:     if (!defined $courseid) { 
11310: 	$courseid=$wcourseid; 
11311:     }
11312:     if (!defined $domain) { $domain=$wdomain; }
11313:     if (!defined $username) { $username=$wusername }
11314: 
11315:     my $which;
11316:     if (defined($cenv->{'rndseed'})) {
11317: 	$which = $cenv->{'rndseed'};
11318:     } else {
11319: 	$which =&get_rand_alg($courseid);
11320:     }
11321:     if (defined(&getCODE())) {
11322: 
11323: 	if ($which eq '64bit5') {
11324: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
11325: 	} elsif ($which eq '64bit4') {
11326: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
11327: 	} else {
11328: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
11329: 	}
11330:     } elsif ($which eq '64bit5') {
11331: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
11332:     } elsif ($which eq '64bit4') {
11333: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
11334:     } elsif ($which eq '64bit3') {
11335: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
11336:     } elsif ($which eq '64bit2') {
11337: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
11338:     } elsif ($which eq '64bit') {
11339: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
11340:     }
11341:     return &rndseed_32bit($symb,$courseid,$domain,$username);
11342: }
11343: 
11344: sub rndseed_32bit {
11345:     my ($symb,$courseid,$domain,$username)=@_;
11346:     {
11347: 	use integer;
11348: 	my $symbchck=unpack("%32C*",$symb) << 27;
11349: 	my $symbseed=numval($symb) << 22;
11350: 	my $namechck=unpack("%32C*",$username) << 17;
11351: 	my $nameseed=numval($username) << 12;
11352: 	my $domainseed=unpack("%32C*",$domain) << 7;
11353: 	my $courseseed=unpack("%32C*",$courseid);
11354: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
11355: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11356: 	#&logthis("rndseed :$num:$symb");
11357: 	if ($_64bit) { $num=(($num<<32)>>32); }
11358: 	return $num;
11359:     }
11360: }
11361: 
11362: sub rndseed_64bit {
11363:     my ($symb,$courseid,$domain,$username)=@_;
11364:     {
11365: 	use integer;
11366: 	my $symbchck=unpack("%32S*",$symb) << 21;
11367: 	my $symbseed=numval($symb) << 10;
11368: 	my $namechck=unpack("%32S*",$username);
11369: 	
11370: 	my $nameseed=numval($username) << 21;
11371: 	my $domainseed=unpack("%32S*",$domain) << 10;
11372: 	my $courseseed=unpack("%32S*",$courseid);
11373: 	
11374: 	my $num1=$symbchck+$symbseed+$namechck;
11375: 	my $num2=$nameseed+$domainseed+$courseseed;
11376: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11377: 	#&logthis("rndseed :$num:$symb");
11378: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11379: 	return "$num1,$num2";
11380:     }
11381: }
11382: 
11383: sub rndseed_64bit2 {
11384:     my ($symb,$courseid,$domain,$username)=@_;
11385:     {
11386: 	use integer;
11387: 	# strings need to be an even # of cahracters long, it it is odd the
11388:         # last characters gets thrown away
11389: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11390: 	my $symbseed=numval($symb) << 10;
11391: 	my $namechck=unpack("%32S*",$username.' ');
11392: 	
11393: 	my $nameseed=numval($username) << 21;
11394: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11395: 	my $courseseed=unpack("%32S*",$courseid.' ');
11396: 	
11397: 	my $num1=$symbchck+$symbseed+$namechck;
11398: 	my $num2=$nameseed+$domainseed+$courseseed;
11399: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11400: 	#&logthis("rndseed :$num:$symb");
11401: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11402: 	return "$num1,$num2";
11403:     }
11404: }
11405: 
11406: sub rndseed_64bit3 {
11407:     my ($symb,$courseid,$domain,$username)=@_;
11408:     {
11409: 	use integer;
11410: 	# strings need to be an even # of cahracters long, it it is odd the
11411:         # last characters gets thrown away
11412: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11413: 	my $symbseed=numval2($symb) << 10;
11414: 	my $namechck=unpack("%32S*",$username.' ');
11415: 	
11416: 	my $nameseed=numval2($username) << 21;
11417: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11418: 	my $courseseed=unpack("%32S*",$courseid.' ');
11419: 	
11420: 	my $num1=$symbchck+$symbseed+$namechck;
11421: 	my $num2=$nameseed+$domainseed+$courseseed;
11422: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11423: 	#&logthis("rndseed :$num1:$num2:$_64bit");
11424: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11425: 	
11426: 	return "$num1:$num2";
11427:     }
11428: }
11429: 
11430: sub rndseed_64bit4 {
11431:     my ($symb,$courseid,$domain,$username)=@_;
11432:     {
11433: 	use integer;
11434: 	# strings need to be an even # of cahracters long, it it is odd the
11435:         # last characters gets thrown away
11436: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11437: 	my $symbseed=numval3($symb) << 10;
11438: 	my $namechck=unpack("%32S*",$username.' ');
11439: 	
11440: 	my $nameseed=numval3($username) << 21;
11441: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11442: 	my $courseseed=unpack("%32S*",$courseid.' ');
11443: 	
11444: 	my $num1=$symbchck+$symbseed+$namechck;
11445: 	my $num2=$nameseed+$domainseed+$courseseed;
11446: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11447: 	#&logthis("rndseed :$num1:$num2:$_64bit");
11448: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11449: 	
11450: 	return "$num1:$num2";
11451:     }
11452: }
11453: 
11454: sub rndseed_64bit5 {
11455:     my ($symb,$courseid,$domain,$username)=@_;
11456:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11457:     return "$num1:$num2";
11458: }
11459: 
11460: sub rndseed_CODE_64bit {
11461:     my ($symb,$courseid,$domain,$username)=@_;
11462:     {
11463: 	use integer;
11464: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
11465: 	my $symbseed=numval2($symb);
11466: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11467: 	my $CODEseed=numval(&getCODE());
11468: 	my $courseseed=unpack("%32S*",$courseid.' ');
11469: 	my $num1=$symbseed+$CODEchck;
11470: 	my $num2=$CODEseed+$courseseed+$symbchck;
11471: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11472: 	#&logthis("rndseed :$num1:$num2:$symb");
11473: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
11474: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
11475: 	return "$num1:$num2";
11476:     }
11477: }
11478: 
11479: sub rndseed_CODE_64bit4 {
11480:     my ($symb,$courseid,$domain,$username)=@_;
11481:     {
11482: 	use integer;
11483: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
11484: 	my $symbseed=numval3($symb);
11485: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11486: 	my $CODEseed=numval3(&getCODE());
11487: 	my $courseseed=unpack("%32S*",$courseid.' ');
11488: 	my $num1=$symbseed+$CODEchck;
11489: 	my $num2=$CODEseed+$courseseed+$symbchck;
11490: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11491: 	#&logthis("rndseed :$num1:$num2:$symb");
11492: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
11493: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
11494: 	return "$num1:$num2";
11495:     }
11496: }
11497: 
11498: sub rndseed_CODE_64bit5 {
11499:     my ($symb,$courseid,$domain,$username)=@_;
11500:     my $code = &getCODE();
11501:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
11502:     return "$num1:$num2";
11503: }
11504: 
11505: sub setup_random_from_rndseed {
11506:     my ($rndseed)=@_;
11507:     if ($rndseed =~/([,:])/) {
11508:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
11509:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
11510:             &Math::Random::random_set_seed_from_phrase($rndseed);
11511:         } else {
11512:             &Math::Random::random_set_seed($num1,$num2);
11513:         }
11514:     } else {
11515: 	&Math::Random::random_set_seed_from_phrase($rndseed);
11516:     }
11517: }
11518: 
11519: sub latest_receipt_algorithm_id {
11520:     return 'receipt3';
11521: }
11522: 
11523: sub recunique {
11524:     my $fucourseid=shift;
11525:     my $unique;
11526:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11527: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11528: 	$unique=$env{"course.$fucourseid.internal.encseed"};
11529:     } else {
11530: 	$unique=$perlvar{'lonReceipt'};
11531:     }
11532:     return unpack("%32C*",$unique);
11533: }
11534: 
11535: sub recprefix {
11536:     my $fucourseid=shift;
11537:     my $prefix;
11538:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11539: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11540: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
11541:     } else {
11542: 	$prefix=$perlvar{'lonHostID'};
11543:     }
11544:     return unpack("%32C*",$prefix);
11545: }
11546: 
11547: sub ireceipt {
11548:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
11549: 
11550:     my $return =&recprefix($fucourseid).'-';
11551: 
11552:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11553: 	$env{'request.state'} eq 'construct') {
11554: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11555: 	return $return;
11556:     }
11557: 
11558:     my $cuname=unpack("%32C*",$funame);
11559:     my $cudom=unpack("%32C*",$fudom);
11560:     my $cucourseid=unpack("%32C*",$fucourseid);
11561:     my $cusymb=unpack("%32C*",$fusymb);
11562:     my $cunique=&recunique($fucourseid);
11563:     my $cpart=unpack("%32S*",$part);
11564:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11565: 
11566: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
11567: 			       
11568: 	$return.= ($cunique%$cuname+
11569: 		   $cunique%$cudom+
11570: 		   $cusymb%$cuname+
11571: 		   $cusymb%$cudom+
11572: 		   $cucourseid%$cuname+
11573: 		   $cucourseid%$cudom+
11574: 		   $cpart%$cuname+
11575: 		   $cpart%$cudom);
11576:     } else {
11577: 	$return.= ($cunique%$cuname+
11578: 		   $cunique%$cudom+
11579: 		   $cusymb%$cuname+
11580: 		   $cusymb%$cudom+
11581: 		   $cucourseid%$cuname+
11582: 		   $cucourseid%$cudom);
11583:     }
11584:     return $return;
11585: }
11586: 
11587: sub receipt {
11588:     my ($part)=@_;
11589:     my ($symb,$courseid,$domain,$name) = &whichuser();
11590:     return &ireceipt($name,$domain,$courseid,$symb,$part);
11591: }
11592: 
11593: sub whichuser {
11594:     my ($passedsymb)=@_;
11595:     my ($symb,$courseid,$domain,$name,$publicuser);
11596:     if (defined($env{'form.grade_symb'})) {
11597: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11598: 	my $allowed=&allowed('vgr',$tmp_courseid);
11599: 	if (!$allowed &&
11600: 	    exists($env{'request.course.sec'}) &&
11601: 	    $env{'request.course.sec'} !~ /^\s*$/) {
11602: 	    $allowed=&allowed('vgr',$tmp_courseid.
11603: 			      '/'.$env{'request.course.sec'});
11604: 	}
11605: 	if ($allowed) {
11606: 	    ($symb)=&get_env_multiple('form.grade_symb');
11607: 	    $courseid=$tmp_courseid;
11608: 	    ($domain)=&get_env_multiple('form.grade_domain');
11609: 	    ($name)=&get_env_multiple('form.grade_username');
11610: 	    return ($symb,$courseid,$domain,$name,$publicuser);
11611: 	}
11612:     }
11613:     if (!$passedsymb) {
11614: 	$symb=&symbread();
11615:     } else {
11616: 	$symb=$passedsymb;
11617:     }
11618:     $courseid=$env{'request.course.id'};
11619:     $domain=$env{'user.domain'};
11620:     $name=$env{'user.name'};
11621:     if ($name eq 'public' && $domain eq 'public') {
11622: 	if (!defined($env{'form.username'})) {
11623: 	    $env{'form.username'}.=time.rand(10000000);
11624: 	}
11625: 	$name.=$env{'form.username'};
11626:     }
11627:     return ($symb,$courseid,$domain,$name,$publicuser);
11628: 
11629: }
11630: 
11631: # ------------------------------------------------------------ Serves up a file
11632: # returns either the contents of the file or 
11633: # -1 if the file doesn't exist
11634: #
11635: # if the target is a file that was uploaded via DOCS, 
11636: # a check will be made to see if a current copy exists on the local server,
11637: # if it does this will be served, otherwise a copy will be retrieved from
11638: # the home server for the course and stored in /home/httpd/html/userfiles on
11639: # the local server.   
11640: 
11641: sub getfile {
11642:     my ($file) = @_;
11643:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
11644:     &repcopy($file);
11645:     return &readfile($file);
11646: }
11647: 
11648: sub repcopy_userfile {
11649:     my ($file)=@_;
11650:     my $londocroot = $perlvar{'lonDocRoot'};
11651:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
11652:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
11653:     my ($cdom,$cnum,$filename) = 
11654: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
11655:     my $uri="/uploaded/$cdom/$cnum/$filename";
11656:     if (-e "$file") {
11657: # we already have a local copy, check it out
11658: 	my @fileinfo = stat($file);
11659: 	my $rtncode;
11660: 	my $info;
11661: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
11662: 	if ($lwpresp ne 'ok') {
11663: # there is no such file anymore, even though we had a local copy
11664: 	    if ($rtncode eq '404') {
11665: 		unlink($file);
11666: 	    }
11667: 	    return -1;
11668: 	}
11669: 	if ($info < $fileinfo[9]) {
11670: # nice, the file we have is up-to-date, just say okay
11671: 	    return 'ok';
11672: 	} else {
11673: # the file is outdated, get rid of it
11674: 	    unlink($file);
11675: 	}
11676:     }
11677: # one way or the other, at this point, we don't have the file
11678: # construct the correct path for the file
11679:     my @parts = ($cdom,$cnum); 
11680:     if ($filename =~ m|^(.+)/[^/]+$|) {
11681: 	push @parts, split(/\//,$1);
11682:     }
11683:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11684:     foreach my $part (@parts) {
11685: 	$path .= '/'.$part;
11686: 	if (!-e $path) {
11687: 	    mkdir($path,0770);
11688: 	}
11689:     }
11690: # now the path exists for sure
11691: # get a user agent
11692:     my $ua=new LWP::UserAgent;
11693:     my $transferfile=$file.'.in.transfer';
11694: # FIXME: this should flock
11695:     if (-e $transferfile) { return 'ok'; }
11696:     my $request;
11697:     $uri=~s/^\///;
11698:     my $homeserver = &homeserver($cnum,$cdom);
11699:     my $protocol = $protocol{$homeserver};
11700:     $protocol = 'http' if ($protocol ne 'https');
11701:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
11702:     my $response=$ua->request($request,$transferfile);
11703: # did it work?
11704:     if ($response->is_error()) {
11705: 	unlink($transferfile);
11706: 	&logthis("Userfile repcopy failed for $uri");
11707: 	return -1;
11708:     }
11709: # worked, rename the transfer file
11710:     rename($transferfile,$file);
11711:     return 'ok';
11712: }
11713: 
11714: sub tokenwrapper {
11715:     my $uri=shift;
11716:     $uri=~s|^https?\://([^/]+)||;
11717:     $uri=~s|^/||;
11718:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
11719:     my $token=$1;
11720:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
11721:     if ($udom && $uname && $file) {
11722: 	$file=~s|(\?\.*)*$||;
11723:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
11724:         my $homeserver = &homeserver($uname,$udom);
11725:         my $protocol = $protocol{$homeserver};
11726:         $protocol = 'http' if ($protocol ne 'https');
11727:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
11728:                (($uri=~/\?/)?'&':'?').'token='.$token.
11729:                                '&tokenissued='.$perlvar{'lonHostID'};
11730:     } else {
11731:         return '/adm/notfound.html';
11732:     }
11733: }
11734: 
11735: # call with reqtype HEAD: get last modification time
11736: # call with reqtype GET: get the file contents
11737: # Do not call this with reqtype GET for large files! It loads everything into memory
11738: #
11739: sub getuploaded {
11740:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11741:     $uri=~s/^\///;
11742:     my $homeserver = &homeserver($cnum,$cdom);
11743:     my $protocol = $protocol{$homeserver};
11744:     $protocol = 'http' if ($protocol ne 'https');
11745:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
11746:     my $ua=new LWP::UserAgent;
11747:     my $request=new HTTP::Request($reqtype,$uri);
11748:     my $response=$ua->request($request);
11749:     $$rtncode = $response->code;
11750:     if (! $response->is_success()) {
11751: 	return 'failed';
11752:     }      
11753:     if ($reqtype eq 'HEAD') {
11754: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
11755:     } elsif ($reqtype eq 'GET') {
11756: 	$$info = $response->content;
11757:     }
11758:     return 'ok';
11759: }
11760: 
11761: sub readfile {
11762:     my $file = shift;
11763:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
11764:     my $fh;
11765:     open($fh,"<$file");
11766:     my $a='';
11767:     while (my $line = <$fh>) { $a .= $line; }
11768:     return $a;
11769: }
11770: 
11771: sub filelocation {
11772:     my ($dir,$file) = @_;
11773:     my $location;
11774:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
11775: 
11776:     if ($file =~ m-^/adm/-) {
11777: 	$file=~s-^/adm/wrapper/-/-;
11778: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
11779:     }
11780: 
11781:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
11782:         $location = $file;
11783:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
11784:         my ($udom,$uname,$filename)=
11785:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
11786:         my $home=&homeserver($uname,$udom);
11787:         my $is_me=0;
11788:         my @ids=&current_machine_ids();
11789:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11790:         if ($is_me) {
11791:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
11792:         } else {
11793:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11794:   	      $udom.'/'.$uname.'/'.$filename;
11795:         }
11796:     } elsif ($file =~ m-^/adm/-) {
11797: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
11798:     } else {
11799:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
11800:         $file=~s:^/(res|priv)/:/:;
11801:         my $space=$1;
11802:         if ( !( $file =~ m:^/:) ) {
11803:             $location = $dir. '/'.$file;
11804:         } else {
11805:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
11806:         }
11807:     }
11808:     $location=~s://+:/:g; # remove duplicate /
11809:     while ($location=~m{/\.\./}) {
11810: 	if ($location =~ m{/[^/]+/\.\./}) {
11811: 	    $location=~ s{/[^/]+/\.\./}{/}g;
11812: 	} else {
11813: 	    $location=~ s{/\.\./}{/}g;
11814: 	}
11815:     } #remove dir/..
11816:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11817:     return $location;
11818: }
11819: 
11820: sub hreflocation {
11821:     my ($dir,$file)=@_;
11822:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
11823: 	$file=filelocation($dir,$file);
11824:     } elsif ($file=~m-^/adm/-) {
11825: 	$file=~s-^/adm/wrapper/-/-;
11826: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
11827:     }
11828:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11829: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11830:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
11831: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11832: 	        {/uploaded/$1/$2/}x;
11833:     }
11834:     if ($file=~ m{^/userfiles/}) {
11835: 	$file =~ s{^/userfiles/}{/uploaded/};
11836:     }
11837:     return $file;
11838: }
11839: 
11840: 
11841: 
11842: 
11843: 
11844: sub current_machine_domains {
11845:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
11846: }
11847: 
11848: sub machine_domains {
11849:     my ($hostname) = @_;
11850:     my @domains;
11851:     my %hostname = &all_hostnames();
11852:     while( my($id, $name) = each(%hostname)) {
11853: #	&logthis("-$id-$name-$hostname-");
11854: 	if ($hostname eq $name) {
11855: 	    push(@domains,&host_domain($id));
11856: 	}
11857:     }
11858:     return @domains;
11859: }
11860: 
11861: sub current_machine_ids {
11862:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
11863: }
11864: 
11865: sub machine_ids {
11866:     my ($hostname) = @_;
11867:     $hostname ||= &hostname($perlvar{'lonHostID'});
11868:     my @ids;
11869:     my %name_to_host = &all_names();
11870:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11871: 	return @{ $name_to_host{$hostname} };
11872:     }
11873:     return;
11874: }
11875: 
11876: sub additional_machine_domains {
11877:     my @domains;
11878:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
11879:     while( my $line = <$fh>) {
11880:         $line =~ s/\s//g;
11881:         push(@domains,$line);
11882:     }
11883:     return @domains;
11884: }
11885: 
11886: sub default_login_domain {
11887:     my $domain = $perlvar{'lonDefDomain'};
11888:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
11889:     foreach my $posdom (&current_machine_domains(),
11890:                         &additional_machine_domains()) {
11891:         if (lc($posdom) eq lc($testdomain)) {
11892:             $domain=$posdom;
11893:             last;
11894:         }
11895:     }
11896:     return $domain;
11897: }
11898: 
11899: # ------------------------------------------------------------- Declutters URLs
11900: 
11901: sub declutter {
11902:     my $thisfn=shift;
11903:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
11904:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
11905:         $thisfn=~s{^/home/httpd/html}{};
11906:     }
11907:     $thisfn=~s/^\///;
11908:     $thisfn=~s|^adm/wrapper/||;
11909:     $thisfn=~s|^adm/coursedocs/showdoc/||;
11910:     $thisfn=~s/^res\///;
11911:     $thisfn=~s/^priv\///;
11912:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
11913:         $thisfn=~s/\?.+$//;
11914:     }
11915:     return $thisfn;
11916: }
11917: 
11918: # ------------------------------------------------------------- Clutter up URLs
11919: 
11920: sub clutter {
11921:     my $thisfn='/'.&declutter(shift);
11922:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
11923: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
11924:        $thisfn='/res'.$thisfn; 
11925:     }
11926:     if ($thisfn !~m|^/adm|) {
11927: 	if ($thisfn =~ m|^/ext/|) {
11928: 	    $thisfn='/adm/wrapper'.$thisfn;
11929: 	} else {
11930: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
11931: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
11932: 	    if ($embstyle eq 'ssi'
11933: 		|| ($embstyle eq 'hdn')
11934: 		|| ($embstyle eq 'rat')
11935: 		|| ($embstyle eq 'prv')
11936: 		|| ($embstyle eq 'ign')) {
11937: 		#do nothing with these
11938: 	    } elsif (($embstyle eq 'img') 
11939: 		|| ($embstyle eq 'emb')
11940: 		|| ($embstyle eq 'wrp')) {
11941: 		$thisfn='/adm/wrapper'.$thisfn;
11942: 	    } elsif ($embstyle eq 'unk'
11943: 		     && $thisfn!~/\.(sequence|page)$/) {
11944: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
11945: 	    } else {
11946: #		&logthis("Got a blank emb style");
11947: 	    }
11948: 	}
11949:     }
11950:     return $thisfn;
11951: }
11952: 
11953: sub clutter_with_no_wrapper {
11954:     my $uri = &clutter(shift);
11955:     if ($uri =~ m-^/adm/-) {
11956: 	$uri =~ s-^/adm/wrapper/-/-;
11957: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
11958:     }
11959:     return $uri;
11960: }
11961: 
11962: sub freeze_escape {
11963:     my ($value)=@_;
11964:     if (ref($value)) {
11965: 	$value=&nfreeze($value);
11966: 	return '__FROZEN__'.&escape($value);
11967:     }
11968:     return &escape($value);
11969: }
11970: 
11971: 
11972: sub thaw_unescape {
11973:     my ($value)=@_;
11974:     if ($value =~ /^__FROZEN__/) {
11975: 	substr($value,0,10,undef);
11976: 	$value=&unescape($value);
11977: 	return &thaw($value);
11978:     }
11979:     return &unescape($value);
11980: }
11981: 
11982: sub correct_line_ends {
11983:     my ($result)=@_;
11984:     $$result =~s/\r\n/\n/mg;
11985:     $$result =~s/\r/\n/mg;
11986: }
11987: # ================================================================ Main Program
11988: 
11989: sub goodbye {
11990:    &logthis("Starting Shut down");
11991: #not converted to using infrastruture and probably shouldn't be
11992:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
11993: #converted
11994: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
11995:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
11996: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
11997: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
11998: #1.1 only
11999: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
12000: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
12001: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
12002: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
12003:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
12004:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
12005:    &logthis(sprintf("%-20s is %s",'hits',$hits));
12006:    &flushcourselogs();
12007:    &logthis("Shutting down");
12008: }
12009: 
12010: sub get_dns {
12011:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
12012:     if (!$ignore_cache) {
12013: 	my ($content,$cached)=
12014: 	    &Apache::lonnet::is_cached_new('dns',$url);
12015: 	if ($cached) {
12016: 	    &$func($content,$hashref);
12017: 	    return;
12018: 	}
12019:     }
12020: 
12021:     my %alldns;
12022:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12023:     foreach my $dns (<$config>) {
12024: 	next if ($dns !~ /^\^(\S*)/x);
12025:         my $line = $1;
12026:         my ($host,$protocol) = split(/:/,$line);
12027:         if ($protocol ne 'https') {
12028:             $protocol = 'http';
12029:         }
12030: 	$alldns{$host} = $protocol;
12031:     }
12032:     while (%alldns) {
12033: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
12034: 	my $ua=new LWP::UserAgent;
12035:         $ua->timeout(30);
12036: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
12037: 	my $response=$ua->request($request);
12038:         delete($alldns{$dns});
12039: 	next if ($response->is_error());
12040: 	my @content = split("\n",$response->content);
12041: 	unless ($nocache) {
12042: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
12043: 	}
12044: 	&$func(\@content,$hashref);
12045: 	return;
12046:     }
12047:     close($config);
12048:     my $which = (split('/',$url))[3];
12049:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
12050:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
12051:     my @content = <$config>;
12052:     &$func(\@content,$hashref);
12053:     return;
12054: }
12055: 
12056: # ------------------------------------------------------Get DNS checksums file
12057: sub parse_dns_checksums_tab {
12058:     my ($lines,$hashref) = @_;
12059:     my $lonhost = $perlvar{'lonHostID'};
12060:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
12061:     my $loncaparev = &get_server_loncaparev($machine_dom);
12062:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
12063:     my $webconfdir = '/etc/httpd/conf';
12064:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
12065:         $webconfdir = '/etc/apache2';
12066:     } elsif ($distro =~ /^sles(\d+)$/) {
12067:         if ($1 >= 10) {
12068:             $webconfdir = '/etc/apache2';
12069:         }
12070:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
12071:         if ($1 >= 10.0) {
12072:             $webconfdir = '/etc/apache2';
12073:         }
12074:     }
12075:     my ($release,$timestamp) = split(/\-/,$loncaparev);
12076:     my (%chksum,%revnum);
12077:     if (ref($lines) eq 'ARRAY') {
12078:         chomp(@{$lines});
12079:         my $version = shift(@{$lines});
12080:         if ($version eq $release) {  
12081:             foreach my $line (@{$lines}) {
12082:                 my ($file,$version,$shasum) = split(/,/,$line);
12083:                 if ($file =~ m{^/etc/httpd/conf}) {
12084:                     if ($webconfdir eq '/etc/apache2') {
12085:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
12086:                     }
12087:                 }
12088:                 $chksum{$file} = $shasum;
12089:                 $revnum{$file} = $version;
12090:             }
12091:             if (ref($hashref) eq 'HASH') {
12092:                 %{$hashref} = (
12093:                                 sums     => \%chksum,
12094:                                 versions => \%revnum,
12095:                               );
12096:             }
12097:         }
12098:     }
12099:     return;
12100: }
12101: 
12102: sub fetch_dns_checksums {
12103:     my %checksums;
12104:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
12105:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
12106:     my ($release,$timestamp) = split(/\-/,$loncaparev);
12107:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
12108:              \%checksums);
12109:     return \%checksums;
12110: }
12111: 
12112: # ------------------------------------------------------------ Read domain file
12113: {
12114:     my $loaded;
12115:     my %domain;
12116: 
12117:     sub parse_domain_tab {
12118: 	my ($lines) = @_;
12119: 	foreach my $line (@$lines) {
12120: 	    next if ($line =~ /^(\#|\s*$ )/x);
12121: 
12122: 	    chomp($line);
12123: 	    my ($name,@elements) = split(/:/,$line,9);
12124: 	    my %this_domain;
12125: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
12126: 			       'lang_def', 'city', 'longi', 'lati',
12127: 			       'primary') {
12128: 		$this_domain{$field} = shift(@elements);
12129: 	    }
12130: 	    $domain{$name} = \%this_domain;
12131: 	}
12132:     }
12133: 
12134:     sub reset_domain_info {
12135: 	undef($loaded);
12136: 	undef(%domain);
12137:     }
12138: 
12139:     sub load_domain_tab {
12140: 	my ($ignore_cache) = @_;
12141: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
12142: 	my $fh;
12143: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
12144: 	    my @lines = <$fh>;
12145: 	    &parse_domain_tab(\@lines);
12146: 	}
12147: 	close($fh);
12148: 	$loaded = 1;
12149:     }
12150: 
12151:     sub domain {
12152: 	&load_domain_tab() if (!$loaded);
12153: 
12154: 	my ($name,$what) = @_;
12155: 	return if ( !exists($domain{$name}) );
12156: 
12157: 	if (!$what) {
12158: 	    return $domain{$name}{'description'};
12159: 	}
12160: 	return $domain{$name}{$what};
12161:     }
12162: 
12163:     sub domain_info {
12164:         &load_domain_tab() if (!$loaded);
12165:         return %domain;
12166:     }
12167: 
12168: }
12169: 
12170: 
12171: # ------------------------------------------------------------- Read hosts file
12172: {
12173:     my %hostname;
12174:     my %hostdom;
12175:     my %libserv;
12176:     my $loaded;
12177:     my %name_to_host;
12178:     my %internetdom;
12179:     my %LC_dns_serv;
12180: 
12181:     sub parse_hosts_tab {
12182: 	my ($file) = @_;
12183: 	foreach my $configline (@$file) {
12184: 	    next if ($configline =~ /^(\#|\s*$ )/x);
12185:             chomp($configline);
12186: 	    if ($configline =~ /^\^/) {
12187:                 if ($configline =~ /^\^([\w.\-]+)/) {
12188:                     $LC_dns_serv{$1} = 1;
12189:                 }
12190:                 next;
12191:             }
12192: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
12193: 	    $name=~s/\s//g;
12194: 	    if ($id && $domain && $role && $name) {
12195: 		$hostname{$id}=$name;
12196: 		push(@{$name_to_host{$name}}, $id);
12197: 		$hostdom{$id}=$domain;
12198: 		if ($role eq 'library') { $libserv{$id}=$name; }
12199:                 if (defined($protocol)) {
12200:                     if ($protocol eq 'https') {
12201:                         $protocol{$id} = $protocol;
12202:                     } else {
12203:                         $protocol{$id} = 'http'; 
12204:                     }
12205:                 } else {
12206:                     $protocol{$id} = 'http';
12207:                 }
12208:                 if (defined($intdom)) {
12209:                     $internetdom{$id} = $intdom;
12210:                 }
12211: 	    }
12212: 	}
12213:     }
12214:     
12215:     sub reset_hosts_info {
12216: 	&purge_remembered();
12217: 	&reset_domain_info();
12218: 	&reset_hosts_ip_info();
12219: 	undef(%name_to_host);
12220: 	undef(%hostname);
12221: 	undef(%hostdom);
12222: 	undef(%libserv);
12223: 	undef($loaded);
12224:     }
12225: 
12226:     sub load_hosts_tab {
12227: 	my ($ignore_cache) = @_;
12228: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
12229: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12230: 	my @config = <$config>;
12231: 	&parse_hosts_tab(\@config);
12232: 	close($config);
12233: 	$loaded=1;
12234:     }
12235: 
12236:     sub hostname {
12237: 	&load_hosts_tab() if (!$loaded);
12238: 
12239: 	my ($lonid) = @_;
12240: 	return $hostname{$lonid};
12241:     }
12242: 
12243:     sub all_hostnames {
12244: 	&load_hosts_tab() if (!$loaded);
12245: 
12246: 	return %hostname;
12247:     }
12248: 
12249:     sub all_names {
12250: 	&load_hosts_tab() if (!$loaded);
12251: 
12252: 	return %name_to_host;
12253:     }
12254: 
12255:     sub all_host_domain {
12256:         &load_hosts_tab() if (!$loaded);
12257:         return %hostdom;
12258:     }
12259: 
12260:     sub is_library {
12261: 	&load_hosts_tab() if (!$loaded);
12262: 
12263: 	return exists($libserv{$_[0]});
12264:     }
12265: 
12266:     sub all_library {
12267: 	&load_hosts_tab() if (!$loaded);
12268: 
12269: 	return %libserv;
12270:     }
12271: 
12272:     sub unique_library {
12273: 	#2x reverse removes all hostnames that appear more than once
12274:         my %unique = reverse &all_library();
12275:         return reverse %unique;
12276:     }
12277: 
12278:     sub get_servers {
12279: 	&load_hosts_tab() if (!$loaded);
12280: 
12281: 	my ($domain,$type) = @_;
12282: 	my %possible_hosts = ($type eq 'library') ? %libserv
12283: 	                                          : %hostname;
12284: 	my %result;
12285: 	if (ref($domain) eq 'ARRAY') {
12286: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
12287: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
12288: 		    $result{$host} = $hostname;
12289: 		}
12290: 	    }
12291: 	} else {
12292: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
12293: 		if ($hostdom{$host} eq $domain) {
12294: 		    $result{$host} = $hostname;
12295: 		}
12296: 	    }
12297: 	}
12298: 	return %result;
12299:     }
12300: 
12301:     sub get_unique_servers {
12302:         my %unique = reverse &get_servers(@_);
12303: 	return reverse %unique;
12304:     }
12305: 
12306:     sub host_domain {
12307: 	&load_hosts_tab() if (!$loaded);
12308: 
12309: 	my ($lonid) = @_;
12310: 	return $hostdom{$lonid};
12311:     }
12312: 
12313:     sub all_domains {
12314: 	&load_hosts_tab() if (!$loaded);
12315: 
12316: 	my %seen;
12317: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
12318: 	return @uniq;
12319:     }
12320: 
12321:     sub internet_dom {
12322:         &load_hosts_tab() if (!$loaded);
12323: 
12324:         my ($lonid) = @_;
12325:         return $internetdom{$lonid};
12326:     }
12327: 
12328:     sub is_LC_dns {
12329:         &load_hosts_tab() if (!$loaded);
12330: 
12331:         my ($hostname) = @_;
12332:         return exists($LC_dns_serv{$hostname});
12333:     }
12334: 
12335: }
12336: 
12337: { 
12338:     my %iphost;
12339:     my %name_to_ip;
12340:     my %lonid_to_ip;
12341: 
12342:     sub get_hosts_from_ip {
12343: 	my ($ip) = @_;
12344: 	my %iphosts = &get_iphost();
12345: 	if (ref($iphosts{$ip})) {
12346: 	    return @{$iphosts{$ip}};
12347: 	}
12348: 	return;
12349:     }
12350:     
12351:     sub reset_hosts_ip_info {
12352: 	undef(%iphost);
12353: 	undef(%name_to_ip);
12354: 	undef(%lonid_to_ip);
12355:     }
12356: 
12357:     sub get_host_ip {
12358: 	my ($lonid) = @_;
12359: 	if (exists($lonid_to_ip{$lonid})) {
12360: 	    return $lonid_to_ip{$lonid};
12361: 	}
12362: 	my $name=&hostname($lonid);
12363:    	my $ip = gethostbyname($name);
12364: 	return if (!$ip || length($ip) ne 4);
12365: 	$ip=inet_ntoa($ip);
12366: 	$name_to_ip{$name}   = $ip;
12367: 	$lonid_to_ip{$lonid} = $ip;
12368: 	return $ip;
12369:     }
12370:     
12371:     sub get_iphost {
12372: 	my ($ignore_cache) = @_;
12373: 
12374: 	if (!$ignore_cache) {
12375: 	    if (%iphost) {
12376: 		return %iphost;
12377: 	    }
12378: 	    my ($ip_info,$cached)=
12379: 		&Apache::lonnet::is_cached_new('iphost','iphost');
12380: 	    if ($cached) {
12381: 		%iphost      = %{$ip_info->[0]};
12382: 		%name_to_ip  = %{$ip_info->[1]};
12383: 		%lonid_to_ip = %{$ip_info->[2]};
12384: 		return %iphost;
12385: 	    }
12386: 	}
12387: 
12388: 	# get yesterday's info for fallback
12389: 	my %old_name_to_ip;
12390: 	my ($ip_info,$cached)=
12391: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
12392: 	if ($cached) {
12393: 	    %old_name_to_ip = %{$ip_info->[1]};
12394: 	}
12395: 
12396: 	my %name_to_host = &all_names();
12397: 	foreach my $name (keys(%name_to_host)) {
12398: 	    my $ip;
12399: 	    if (!exists($name_to_ip{$name})) {
12400: 		$ip = gethostbyname($name);
12401: 		if (!$ip || length($ip) ne 4) {
12402: 		    if (defined($old_name_to_ip{$name})) {
12403: 			$ip = $old_name_to_ip{$name};
12404: 			&logthis("Can't find $name defaulting to old $ip");
12405: 		    } else {
12406: 			&logthis("Name $name no IP found");
12407: 			next;
12408: 		    }
12409: 		} else {
12410: 		    $ip=inet_ntoa($ip);
12411: 		}
12412: 		$name_to_ip{$name} = $ip;
12413: 	    } else {
12414: 		$ip = $name_to_ip{$name};
12415: 	    }
12416: 	    foreach my $id (@{ $name_to_host{$name} }) {
12417: 		$lonid_to_ip{$id} = $ip;
12418: 	    }
12419: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
12420: 	}
12421: 	&do_cache_new('iphost','iphost',
12422: 		      [\%iphost,\%name_to_ip,\%lonid_to_ip],
12423: 		      48*60*60);
12424: 
12425: 	return %iphost;
12426:     }
12427: 
12428:     #
12429:     #  Given a DNS returns the loncapa host name for that DNS 
12430:     # 
12431:     sub host_from_dns {
12432:         my ($dns) = @_;
12433:         my @hosts;
12434:         my $ip;
12435: 
12436:         if (exists($name_to_ip{$dns})) {
12437:             $ip = $name_to_ip{$dns};
12438:         }
12439:         if (!$ip) {
12440:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12441:             if (length($ip) == 4) { 
12442: 	        $ip   = &IO::Socket::inet_ntoa($ip);
12443:             }
12444:         }
12445:         if ($ip) {
12446: 	    @hosts = get_hosts_from_ip($ip);
12447: 	    return $hosts[0];
12448:         }
12449:         return undef;
12450:     }
12451: 
12452:     sub get_internet_names {
12453:         my ($lonid) = @_;
12454:         return if ($lonid eq '');
12455:         my ($idnref,$cached)=
12456:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
12457:         if ($cached) {
12458:             return $idnref;
12459:         }
12460:         my $ip = &get_host_ip($lonid);
12461:         my @hosts = &get_hosts_from_ip($ip);
12462:         my %iphost = &get_iphost();
12463:         my (@idns,%seen);
12464:         foreach my $id (@hosts) {
12465:             my $dom = &host_domain($id);
12466:             my $prim_id = &domain($dom,'primary');
12467:             my $prim_ip = &get_host_ip($prim_id);
12468:             next if ($seen{$prim_ip});
12469:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12470:                 foreach my $id (@{$iphost{$prim_ip}}) {
12471:                     my $intdom = &internet_dom($id);
12472:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
12473:                         push(@idns,$intdom);
12474:                     }
12475:                 }
12476:             }
12477:             $seen{$prim_ip} = 1;
12478:         }
12479:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
12480:     }
12481: 
12482: }
12483: 
12484: sub all_loncaparevs {
12485:     return qw(1.1 1.2 1.3 2.0 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 2.10 2.11);
12486: }
12487: 
12488: # ---------------------------------------------------------- Read loncaparev table
12489: {
12490:     sub load_loncaparevs { 
12491:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12492:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12493:                 while (my $configline=<$config>) {
12494:                     chomp($configline);
12495:                     my ($hostid,$loncaparev)=split(/:/,$configline);
12496:                     $loncaparevs{$hostid}=$loncaparev;
12497:                 }
12498:                 close($config);
12499:             }
12500:         }
12501:     }
12502: }
12503: 
12504: # ---------------------------------------------------------- Read serverhostID table
12505: {
12506:     sub load_serverhomeIDs {
12507:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12508:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12509:                 while (my $configline=<$config>) {
12510:                     chomp($configline);
12511:                     my ($name,$id)=split(/:/,$configline);
12512:                     $serverhomeIDs{$name}=$id;
12513:                 }
12514:                 close($config);
12515:             }
12516:         }
12517:     }
12518: }
12519: 
12520: 
12521: BEGIN {
12522: 
12523: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12524:     unless ($readit) {
12525: {
12526:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12527:     %perlvar = (%perlvar,%{$configvars});
12528: }
12529: 
12530: 
12531: # ------------------------------------------------------ Read spare server file
12532: {
12533:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
12534: 
12535:     while (my $configline=<$config>) {
12536:        chomp($configline);
12537:        if ($configline) {
12538: 	   my ($host,$type) = split(':',$configline,2);
12539: 	   if (!defined($type) || $type eq '') { $type = 'default' };
12540: 	   push(@{ $spareid{$type} }, $host);
12541:        }
12542:     }
12543:     close($config);
12544: }
12545: # ------------------------------------------------------------ Read permissions
12546: {
12547:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
12548: 
12549:     while (my $configline=<$config>) {
12550: 	chomp($configline);
12551: 	if ($configline) {
12552: 	    my ($role,$perm)=split(/ /,$configline);
12553: 	    if ($perm ne '') { $pr{$role}=$perm; }
12554: 	}
12555:     }
12556:     close($config);
12557: }
12558: 
12559: # -------------------------------------------- Read plain texts for permissions
12560: {
12561:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
12562: 
12563:     while (my $configline=<$config>) {
12564: 	chomp($configline);
12565: 	if ($configline) {
12566: 	    my ($short,@plain)=split(/:/,$configline);
12567:             %{$prp{$short}} = ();
12568: 	    if (@plain > 0) {
12569:                 $prp{$short}{'std'} = $plain[0];
12570:                 for (my $i=1; $i<@plain; $i++) {
12571:                     $prp{$short}{'alt'.$i} = $plain[$i];  
12572:                 }
12573:             }
12574: 	}
12575:     }
12576:     close($config);
12577: }
12578: 
12579: # ---------------------------------------------------------- Read package table
12580: {
12581:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
12582: 
12583:     while (my $configline=<$config>) {
12584: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
12585: 	chomp($configline);
12586: 	my ($short,$plain)=split(/:/,$configline);
12587: 	my ($pack,$name)=split(/\&/,$short);
12588: 	if ($plain ne '') {
12589: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
12590: 	    $packagetab{$short}=$plain; 
12591: 	}
12592:     }
12593:     close($config);
12594: }
12595: 
12596: # ---------------------------------------------------------- Read loncaparev table
12597: 
12598: &load_loncaparevs();
12599: 
12600: # ---------------------------------------------------------- Read serverhostID table
12601: 
12602: &load_serverhomeIDs();
12603: 
12604: # ---------------------------------------------------------- Read releaseslist XML
12605: {
12606:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12607:     if (-e $file) {
12608:         my $parser = HTML::LCParser->new($file);
12609:         while (my $token = $parser->get_token()) {
12610:             if ($token->[0] eq 'S') {
12611:                 my $item = $token->[1];
12612:                 my $name = $token->[2]{'name'};
12613:                 my $value = $token->[2]{'value'};
12614:                 if ($item ne '' && $name ne '' && $value ne '') {
12615:                     my $release = $parser->get_text();
12616:                     $release =~ s/(^\s*|\s*$ )//gx;
12617:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
12618:                 }
12619:             }
12620:         }
12621:     }
12622: }
12623: 
12624: # ---------------------------------------------------------- Read managers table
12625: {
12626:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12627:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12628:             while (my $configline=<$config>) {
12629:                 chomp($configline);
12630:                 next if ($configline =~ /^\#/);
12631:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12632:                     $managerstab{$configline} = 1;
12633:                 }
12634:             }
12635:             close($config);
12636:         }
12637:     }
12638: }
12639: 
12640: # ------------- set up temporary directory
12641: {
12642:     $tmpdir = LONCAPA::tempdir();
12643: 
12644: }
12645: 
12646: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
12647: 				'compress_threshold'=> 20_000,
12648:  			        });
12649: 
12650: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
12651: $dumpcount=0;
12652: $locknum=0;
12653: 
12654: &logtouch();
12655: &logthis('<font color="yellow">INFO: Read configuration</font>');
12656: $readit=1;
12657:     {
12658: 	use integer;
12659: 	my $test=(2**32)+1;
12660: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
12661: 	&logthis(" Detected 64bit platform ($_64bit)");
12662:     }
12663: }
12664: }
12665: 
12666: 1;
12667: __END__
12668: 
12669: =pod
12670: 
12671: =head1 NAME
12672: 
12673: Apache::lonnet - Subroutines to ask questions about things in the network.
12674: 
12675: =head1 SYNOPSIS
12676: 
12677: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
12678: 
12679:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12680: 
12681: Common parameters:
12682: 
12683: =over 4
12684: 
12685: =item *
12686: 
12687: $uname : an internal username (if $cname expecting a course Id specifically)
12688: 
12689: =item *
12690: 
12691: $udom : a domain (if $cdom expecting a course's domain specifically)
12692: 
12693: =item *
12694: 
12695: $symb : a resource instance identifier
12696: 
12697: =item *
12698: 
12699: $namespace : the name of a .db file that contains the data needed or
12700: being set.
12701: 
12702: =back
12703: 
12704: =head1 OVERVIEW
12705: 
12706: lonnet provides subroutines which interact with the
12707: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12708: about classes, users, and resources.
12709: 
12710: For many of these objects you can also use this to store data about
12711: them or modify them in various ways.
12712: 
12713: =head2 Symbs
12714: 
12715: To identify a specific instance of a resource, LON-CAPA uses symbols
12716: or "symbs"X<symb>. These identifiers are built from the URL of the
12717: map, the resource number of the resource in the map, and the URL of
12718: the resource itself. The latter is somewhat redundant, but might help
12719: if maps change.
12720: 
12721: An example is
12722: 
12723:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12724: 
12725: The respective map entry is
12726: 
12727:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
12728:   title="Problem 2">
12729:  </resource>
12730: 
12731: Symbs are used by the random number generator, as well as to store and
12732: restore data specific to a certain instance of for example a problem.
12733: 
12734: =head2 Storing And Retrieving Data
12735: 
12736: X<store()>X<cstore()>X<restore()>Three of the most important functions
12737: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12738: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12739: is is the non-critical message twin of cstore. These functions are for
12740: handlers to store a perl hash to a user's permanent data space in an
12741: easy manner, and to retrieve it again on another call. It is expected
12742: that a handler would use this once at the beginning to retrieve data,
12743: and then again once at the end to send only the new data back.
12744: 
12745: The data is stored in the user's data directory on the user's
12746: homeserver under the ID of the course.
12747: 
12748: The hash that is returned by restore will have all of the previous
12749: value for all of the elements of the hash.
12750: 
12751: Example:
12752: 
12753:  #creating a hash
12754:  my %hash;
12755:  $hash{'foo'}='bar';
12756: 
12757:  #storing it
12758:  &Apache::lonnet::cstore(\%hash);
12759: 
12760:  #changing a value
12761:  $hash{'foo'}='notbar';
12762: 
12763:  #adding a new value
12764:  $hash{'bar'}='foo';
12765:  &Apache::lonnet::cstore(\%hash);
12766: 
12767:  #retrieving the hash
12768:  my %history=&Apache::lonnet::restore();
12769: 
12770:  #print the hash
12771:  foreach my $key (sort(keys(%history))) {
12772:    print("\%history{$key} = $history{$key}");
12773:  }
12774: 
12775: Will print out:
12776: 
12777:  %history{1:foo} = bar
12778:  %history{1:keys} = foo:timestamp
12779:  %history{1:timestamp} = 990455579
12780:  %history{2:bar} = foo
12781:  %history{2:foo} = notbar
12782:  %history{2:keys} = foo:bar:timestamp
12783:  %history{2:timestamp} = 990455580
12784:  %history{bar} = foo
12785:  %history{foo} = notbar
12786:  %history{timestamp} = 990455580
12787:  %history{version} = 2
12788: 
12789: Note that the special hash entries C<keys>, C<version> and
12790: C<timestamp> were added to the hash. C<version> will be equal to the
12791: total number of versions of the data that have been stored. The
12792: C<timestamp> attribute will be the UNIX time the hash was
12793: stored. C<keys> is available in every historical section to list which
12794: keys were added or changed at a specific historical revision of a
12795: hash.
12796: 
12797: B<Warning>: do not store the hash that restore returns directly. This
12798: will cause a mess since it will restore the historical keys as if the
12799: were new keys. I.E. 1:foo will become 1:1:foo etc.
12800: 
12801: Calling convention:
12802: 
12803:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
12804:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
12805: 
12806: For more detailed information, see lonnet specific documentation.
12807: 
12808: =head1 RETURN MESSAGES
12809: 
12810: =over 4
12811: 
12812: =item * B<con_lost>: unable to contact remote host
12813: 
12814: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12815: when the connection is brought back up
12816: 
12817: =item * B<con_failed>: unable to contact remote host and unable to save message
12818: for later delivery
12819: 
12820: =item * B<error:>: an error a occurred, a description of the error follows the :
12821: 
12822: =item * B<no_such_host>: unable to fund a host associated with the user/domain
12823: that was requested
12824: 
12825: =back
12826: 
12827: =head1 PUBLIC SUBROUTINES
12828: 
12829: =head2 Session Environment Functions
12830: 
12831: =over 4
12832: 
12833: =item * 
12834: X<appenv()>
12835: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
12836: the user envirnoment file, and will be restored for each access this
12837: user makes during this session, also modifies the %env for the current
12838: process. Optional rolesarrayref - if defined contains a reference to an array
12839: of roles which are exempt from the restriction on modifying user.role entries 
12840: in the user's environment.db and in %env.    
12841: 
12842: =item *
12843: X<delenv()>
12844: B<delenv($delthis,$regexp)>: removes all items from the session
12845: environment file that begin with $delthis. If the 
12846: optional second arg - $regexp - is true, $delthis is treated as a 
12847: regular expression, otherwise \Q$delthis\E is used. 
12848: The values are also deleted from the current processes %env.
12849: 
12850: =item * get_env_multiple($name) 
12851: 
12852: gets $name from the %env hash, it seemlessly handles the cases where multiple
12853: values may be defined and end up as an array ref.
12854: 
12855: returns an array of values
12856: 
12857: =back
12858: 
12859: =head2 User Information
12860: 
12861: =over 4
12862: 
12863: =item *
12864: X<queryauthenticate()>
12865: B<queryauthenticate($uname,$udom)>: try to determine user's current 
12866: authentication scheme
12867: 
12868: =item *
12869: X<authenticate()>
12870: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
12871: authenticate user from domain's lib servers (first use the current
12872: one). C<$upass> should be the users password.
12873: $checkdefauth is optional (value is 1 if a check should be made to
12874:    authenticate user using default authentication method, and allow
12875:    account creation if username does not have account in the domain).
12876: $clientcancheckhost is optional (value is 1 if checking whether the
12877:    server can host will occur on the client side in lonauth.pm).   
12878: 
12879: =item *
12880: X<homeserver()>
12881: B<homeserver($uname,$udom)>: find the server which has
12882: the user's directory and files (there must be only one), this caches
12883: the answer, and also caches if there is a borken connection.
12884: 
12885: =item *
12886: X<idget()>
12887: B<idget($udom,@ids)>: find the usernames behind a list of IDs
12888: (IDs are a unique resource in a domain, there must be only 1 ID per
12889: username, and only 1 username per ID in a specific domain) (returns
12890: hash: id=>name,id=>name)
12891: 
12892: =item *
12893: X<idrget()>
12894: B<idrget($udom,@unames)>: find the IDs behind a list of
12895: usernames (returns hash: name=>id,name=>id)
12896: 
12897: =item *
12898: X<idput()>
12899: B<idput($udom,%ids)>: store away a list of names and associated IDs
12900: 
12901: =item *
12902: X<rolesinit()>
12903: B<rolesinit($udom,$username)>: get user privileges.
12904: returns user role, first access and timer interval hashes
12905: 
12906: =item *
12907: X<privileged()>
12908: B<privileged($username,$domain)>: returns a true if user has a
12909: privileged and active role (i.e. su or dc), false otherwise.
12910: 
12911: =item *
12912: X<getsection()>
12913: B<getsection($udom,$uname,$cname)>: finds the section of student in the
12914: course $cname, return section name/number or '' for "not in course"
12915: and '-1' for "no section"
12916: 
12917: =item *
12918: X<userenvironment()>
12919: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
12920: passed in @what from the requested user's environment, returns a hash
12921: 
12922: =item * 
12923: X<userlog_query()>
12924: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
12925: activity.log file. %filters defines filters applied when parsing the
12926: log file. These can be start or end timestamps, or the type of action
12927: - log to look for Login or Logout events, check for Checkin or
12928: Checkout, role for role selection. The response is in the form
12929: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
12930: escaped strings of the action recorded in the activity.log file.
12931: 
12932: =back
12933: 
12934: =head2 User Roles
12935: 
12936: =over 4
12937: 
12938: =item *
12939: 
12940: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
12941:  F: full access
12942:  U,I,K: authentication modes (cxx only)
12943:  '': forbidden
12944:  1: user needs to choose course
12945:  2: browse allowed
12946:  A: passphrase authentication needed
12947: 
12948: =item *
12949: 
12950: constructaccess($url,$setpriv) : check for access to construction space URL
12951: 
12952: See if the owner domain and name in the URL match those in the
12953: expected environment.  If so, return three element list
12954: ($ownername,$ownerdomain,$ownerhome).
12955: 
12956: Otherwise return the null string.
12957: 
12958: If second argument 'setpriv' is true, it assigns the privileges,
12959: and returns the same three element list, unless the owner has
12960: blocked "ad hoc" Domain Coordinator access to the Author Space,
12961: in which case the null string is returned.
12962: 
12963: =item *
12964: 
12965: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
12966: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
12967: and course level
12968: 
12969: =item *
12970: 
12971: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
12972: (rolesplain.tab); plain text explanation of a user role term.
12973: $type is Course (default) or Community.
12974: If $forcedefault evaluates to true, text returned will be default 
12975: text for $type. Otherwise, if this is a course, the text returned 
12976: will be a custom name for the role (if defined in the course's 
12977: environment).  If no custom name is defined the default is returned.
12978:    
12979: =item *
12980: 
12981: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
12982: All arguments are optional. Returns a hash of a roles, either for
12983: co-author/assistant author roles for a user's Construction Space
12984: (default), or if $context is 'userroles', roles for the user himself,
12985: In the hash, keys are set to colon-separated $uname,$udom,$role, and
12986: (optionally) if $withsec is true, a fourth colon-separated item - $section.
12987: For each key, value is set to colon-separated start and end times for
12988: the role.  If no username and domain are specified, will default to
12989: current user/domain. Types, roles, and roledoms are references to arrays
12990: of role statuses (active, future or previous), roles 
12991: (e.g., cc,in, st etc.) and domains of the roles which can be used
12992: to restrict the list of roles reported. If no array ref is 
12993: provided for types, will default to return only active roles.
12994: 
12995: =item *
12996: 
12997: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
12998: user: $uname:$udom has a role in the course: $cdom_$cnum. 
12999: 
13000: Additional optional arguments are: $type (if role checking is to be restricted 
13001: to certain user status types -- previous (expired roles), active (currently
13002: available roles) or future (roles available in the future), and
13003: $hideprivileged -- if true will not report course roles for users who
13004: have active Domain Coordinator role in course's domain or in additional
13005: domains (specified in 'Domains to check for privileged users' in course
13006: environment -- set via:  Course Settings -> Classlists and staff listing).
13007: 
13008: =item *
13009: 
13010: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
13011: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
13012: $possdomains and $possroles are optional array refs -- to domains to check and
13013: roles to check.  If $possdomains is not specified, a dump will be done of the
13014: users' roles.db to check for a dc or su role in any domain. This can be
13015: time consuming if &privileged is called repeatedly (e.g., when displaying a
13016: classlist), so in such cases, supplying a $possdomains array is preferred, as
13017: this then allows &privileged_by_domain() to be used, which caches the identity
13018: of privileged users, eliminating the need for repeated calls to &dump().
13019: 
13020: =item *
13021: 
13022: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
13023: where the outer hash keys are domains specified in the $possdomains array ref,
13024: next inner hash keys are privileged roles specified in the $roles array ref,
13025: and the innermost hash contains key = value pairs for username:domain = end:start
13026: for active or future "privileged" users with that role in that domain. To avoid
13027: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
13028: innerhash are cached using priv_$role and $dom as the identifiers.
13029: 
13030: =back
13031: 
13032: =head2 User Modification
13033: 
13034: =over 4
13035: 
13036: =item *
13037: 
13038: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
13039: user for the level given by URL.  Optional start and end dates (leave empty
13040: string or zero for "no date")
13041: 
13042: =item *
13043: 
13044: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
13045: change a users, password, possible return values are: ok,
13046: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
13047: refused
13048: 
13049: =item *
13050: 
13051: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
13052: 
13053: =item *
13054: 
13055: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
13056:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
13057: 
13058: will update user information (firstname,middlename,lastname,generation,
13059: permanentemail), and if forceid is true, student/employee ID also.
13060: A user's institutional affiliation(s) can also be updated.
13061: User information fields will not be overwritten with empty entries 
13062: unless the field is included in the $candelete array reference.
13063: This array is included when a single user is modified via "Manage Users",
13064: or when Autoupdate.pl is run by cron in a domain.
13065: 
13066: =item *
13067: 
13068: modifystudent
13069: 
13070: modify a student's enrollment and identification information.
13071: The course id is resolved based on the current user's environment.  
13072: This means the invoking user must be a course coordinator or otherwise
13073: associated with a course.
13074: 
13075: This call is essentially a wrapper for lonnet::modifyuser and
13076: lonnet::modify_student_enrollment
13077: 
13078: Inputs: 
13079: 
13080: =over 4
13081: 
13082: =item B<$udom> Student's loncapa domain
13083: 
13084: =item B<$uname> Student's loncapa login name
13085: 
13086: =item B<$uid> Student/Employee ID
13087: 
13088: =item B<$umode> Student's authentication mode
13089: 
13090: =item B<$upass> Student's password
13091: 
13092: =item B<$first> Student's first name
13093: 
13094: =item B<$middle> Student's middle name
13095: 
13096: =item B<$last> Student's last name
13097: 
13098: =item B<$gene> Student's generation
13099: 
13100: =item B<$usec> Student's section in course
13101: 
13102: =item B<$end> Unix time of the roles expiration
13103: 
13104: =item B<$start> Unix time of the roles start date
13105: 
13106: =item B<$forceid> If defined, allow $uid to be changed
13107: 
13108: =item B<$desiredhome> server to use as home server for student
13109: 
13110: =item B<$email> Student's permanent e-mail address
13111: 
13112: =item B<$type> Type of enrollment (auto or manual)
13113: 
13114: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
13115: 
13116: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
13117: 
13118: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
13119: 
13120: =item B<$context> role change context (shown in User Management Logs display in a course)
13121: 
13122: =item B<$inststatus> institutional status of user - : separated string of escaped status types
13123: 
13124: =item B<$credits> Number of credits student will earn from this class - only needs to be supplied if value needs to be different from default credits for class.
13125: 
13126: =back
13127: 
13128: =item *
13129: 
13130: modify_student_enrollment
13131: 
13132: Change a student's enrollment status in a class.  The environment variable
13133: 'role.request.course' must be defined for this function to proceed.
13134: 
13135: Inputs:
13136: 
13137: =over 4
13138: 
13139: =item $udom, student's domain
13140: 
13141: =item $uname, student's name
13142: 
13143: =item $uid, student's user id
13144: 
13145: =item $first, student's first name
13146: 
13147: =item $middle
13148: 
13149: =item $last
13150: 
13151: =item $gene
13152: 
13153: =item $usec
13154: 
13155: =item $end
13156: 
13157: =item $start
13158: 
13159: =item $type
13160: 
13161: =item $locktype
13162: 
13163: =item $cid
13164: 
13165: =item $selfenroll
13166: 
13167: =item $context
13168: 
13169: =item $credits, number of credits student will earn from this class
13170: 
13171: =back
13172: 
13173: 
13174: =item *
13175: 
13176: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
13177: custom role; give a custom role to a user for the level given by URL.  Specify
13178: name and domain of role author, and role name
13179: 
13180: =item *
13181: 
13182: revokerole($udom,$uname,$url,$role) : revoke a role for url
13183: 
13184: =item *
13185: 
13186: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
13187: 
13188: =back
13189: 
13190: =head2 Course Infomation
13191: 
13192: =over 4
13193: 
13194: =item *
13195: 
13196: coursedescription($courseid,$options) : returns a hash of information about the
13197: specified course id, including all environment settings for the
13198: course, the description of the course will be in the hash under the
13199: key 'description'
13200: 
13201: $options is an optional parameter that if supplied is a hash reference that controls
13202: what how this function works.  It has the following key/values:
13203: 
13204: =over 4
13205: 
13206: =item freshen_cache
13207: 
13208: If defined, and the environment cache for the course is valid, it is 
13209: returned in the returned hash.
13210: 
13211: =item one_time
13212: 
13213: If defined, the last cache time is set to _now_
13214: 
13215: =item user
13216: 
13217: If defined, the supplied username is used instead of the current user.
13218: 
13219: 
13220: =back
13221: 
13222: =item *
13223: 
13224: resdata($name,$domain,$type,@which) : request for current parameter
13225: setting for a specific $type, where $type is either 'course' or 'user',
13226: @what should be a list of parameters to ask about. This routine caches
13227: answers for 10 minutes.
13228: 
13229: =item *
13230: 
13231: get_courseresdata($courseid, $domain) : dump the entire course resource
13232: data base, returning a hash that is keyed by the resource name and has
13233: values that are the resource value.  I believe that the timestamps and
13234: versions are also returned.
13235: 
13236: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
13237: supplemental content area. This routine caches the number of files for 
13238: 10 minutes.
13239: 
13240: =back
13241: 
13242: =head2 Course Modification
13243: 
13244: =over 4
13245: 
13246: =item *
13247: 
13248: writecoursepref($courseid,%prefs) : write preferences (environment
13249: database) for a course
13250: 
13251: =item *
13252: 
13253: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
13254: 
13255: =item *
13256: 
13257: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
13258: 
13259: =item *
13260: 
13261: is_course($courseid), is_course($cdom, $cnum)
13262: 
13263: Accepts either a combined $courseid (in the form of domain_courseid) or the
13264: two component version $cdom, $cnum. It checks if the specified course exists.
13265: 
13266: Returns:
13267:     undef if the course doesn't exist, otherwise
13268:     in scalar context the combined courseid.
13269:     in list context the two components of the course identifier, domain and 
13270:     courseid.    
13271: 
13272: =back
13273: 
13274: =head2 Resource Subroutines
13275: 
13276: =over 4
13277: 
13278: =item *
13279: 
13280: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
13281: 
13282: =item *
13283: 
13284: repcopy($filename) : subscribes to the requested file, and attempts to
13285: replicate from the owning library server, Might return
13286: 'unavailable', 'not_found', 'forbidden', 'ok', or
13287: 'bad_request', also attempts to grab the metadata for the
13288: resource. Expects the local filesystem pathname
13289: (/home/httpd/html/res/....)
13290: 
13291: =back
13292: 
13293: =head2 Resource Information
13294: 
13295: =over 4
13296: 
13297: =item *
13298: 
13299: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
13300: and returns the value of a variety of different possible values,
13301: $varname should be a request string, and the other parameters can be
13302: used to specify who and what one is asking about. Ordinarily, $cid 
13303: does not need to be specified, as it is retrived from 
13304: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
13305: within lonuserstate::loadmap() when initializing a course, before
13306: $env{'request.course.id'} has been set, so it needs to be provided
13307: in that one case.
13308: 
13309: Possible values for $varname are environment.lastname (or other item
13310: from the envirnment hash), user.name (or someother aspect about the
13311: user), resource.0.maxtries (or some other part and parameter of a
13312: resource)
13313: 
13314: =item *
13315: 
13316: directcondval($number) : get current value of a condition; reads from a state
13317: string
13318: 
13319: =item *
13320: 
13321: condval($condidx) : value of condition index based on state
13322: 
13323: =item *
13324: 
13325: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
13326: resource's metadata, $what should be either a specific key, or either
13327: 'keys' (to get a list of possible keys) or 'packages' to get a list of
13328: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
13329: 
13330: this function automatically caches all requests
13331: 
13332: =item *
13333: 
13334: metadata_query($query,$custom,$customshow) : make a metadata query against the
13335: network of library servers; returns file handle of where SQL and regex results
13336: will be stored for query
13337: 
13338: =item *
13339: 
13340: symbread($filename) : return symbolic list entry (filename argument optional);
13341: returns the data handle
13342: 
13343: =item *
13344: 
13345: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
13346: and is a possible symb for the URL in $thisfn, and if is an encrypted
13347: resource that the user accessed using /enc/ returns a 1 on success, 0
13348: on failure, user must be in a course, as it assumes the existence of
13349: the course initial hash, and uses $env('request.course.id'}.  The third
13350: arg is an optional reference to a scalar.  If this arg is passed in the 
13351: call to symbverify, it will be set to 1 if the symb has been set to be 
13352: encrypted; otherwise it will be null.  
13353: 
13354: =item *
13355: 
13356: symbclean($symb) : removes versions numbers from a symb, returns the
13357: cleaned symb
13358: 
13359: =item *
13360: 
13361: is_on_map($uri) : checks if the $uri is somewhere on the current
13362: course map, user must be in a course for it to work.
13363: 
13364: =item *
13365: 
13366: numval($salt) : return random seed value (addend for rndseed)
13367: 
13368: =item *
13369: 
13370: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13371: a random seed, all arguments are optional, if they aren't sent it uses the
13372: environment to derive them. Note: if symb isn't sent and it can't get one
13373: from &symbread it will use the current time as its return value
13374: 
13375: =item *
13376: 
13377: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13378: unfakeable, receipt
13379: 
13380: =item *
13381: 
13382: receipt() : API to ireceipt working off of env values; given out to users
13383: 
13384: =item *
13385: 
13386: countacc($url) : count the number of accesses to a given URL
13387: 
13388: =item *
13389: 
13390: 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
13391: 
13392: =item *
13393: 
13394: 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)
13395: 
13396: =item *
13397: 
13398: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
13399: 
13400: =item *
13401: 
13402: devalidate($symb) : devalidate temporary spreadsheet calculations,
13403: forcing spreadsheet to reevaluate the resource scores next time.
13404: 
13405: =item * 
13406: 
13407: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13408: when viewing in course context.
13409: 
13410:  input: six args -- filename (decluttered), course number, course domain,
13411:                     url, symb (if registered) and group (if this is a 
13412:                     group item -- e.g., bulletin board, group page etc.).
13413: 
13414:  output: array of five scalars --
13415:          $cfile -- url for file editing if editable on current server
13416:          $home -- homeserver of resource (i.e., for author if published,
13417:                                           or course if uploaded.).
13418:          $switchserver --  1 if server switch will be needed.
13419:          $forceedit -- 1 if icon/link should be to go to edit mode 
13420:          $forceview -- 1 if icon/link should be to go to view mode
13421: 
13422: =item *
13423: 
13424: is_course_upload($file,$cnum,$cdom)
13425: 
13426: Used in course context to determine if current file was uploaded to 
13427: the course (i.e., would be found in /userfiles/docs on the course's 
13428: homeserver.
13429: 
13430:   input: 3 args -- filename (decluttered), course number and course domain.
13431:   output: boolean -- 1 if file was uploaded.
13432: 
13433: =back
13434: 
13435: =head2 Storing/Retreiving Data
13436: 
13437: =over 4
13438: 
13439: =item *
13440: 
13441: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
13442: permanently for this url; hashref needs to be given and should be a \%hashname;
13443: the remaining args aren't required and if they aren't passed or are '' they will
13444: be derived from the env (with the exception of $laststore, which is an 
13445: optional arg used when a user's submission is stored in grading).
13446: $laststore is $version=$timestamp, where $version is the most recent version
13447: number retrieved for the corresponding $symb in the $namespace db file, and
13448: $timestamp is the timestamp for that transaction (UNIX time).
13449: $laststore is currently only passed when cstore() is called by 
13450: structuretags::finalize_storage().
13451: 
13452: =item *
13453: 
13454: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
13455: but uses critical subroutine
13456: 
13457: =item *
13458: 
13459: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13460: all args are optional
13461: 
13462: =item *
13463: 
13464: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
13465: dumps the complete (or key matching regexp) namespace into a hash
13466: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13467: normally &store()ed into
13468: 
13469: $range should be either an integer '100' (give me the first 100
13470:                                            matching records)
13471:               or be  two integers sperated by a - with no spaces
13472:                  '30-50' (give me the 30th through the 50th matching
13473:                           records)
13474: 
13475: 
13476: =item *
13477: 
13478: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
13479: replaces a &store() version of data with a replacement set of data
13480: for a particular resource in a namespace passed in the $storehash hash 
13481: reference. If $tolog is true, the transaction is logged in the courselog
13482: with an action=PUTSTORE.
13483: 
13484: =item *
13485: 
13486: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13487: works very similar to store/cstore, but all data is stored in a
13488: temporary location and can be reset using tmpreset, $storehash should
13489: be a hash reference, returns nothing on success
13490: 
13491: =item *
13492: 
13493: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13494: similar to restore, but all data is stored in a temporary location and
13495: can be reset using tmpreset. Returns a hash of values on success,
13496: error string otherwise.
13497: 
13498: =item *
13499: 
13500: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13501: deltes all keys for $symb form the temporary storage hash.
13502: 
13503: =item *
13504: 
13505: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13506: reference filled in from namesp ($udom and $uname are optional)
13507: 
13508: =item *
13509: 
13510: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13511: namesp ($udom and $uname are optional)
13512: 
13513: =item *
13514: 
13515: dump($namespace,$udom,$uname,$regexp,$range) : 
13516: dumps the complete (or key matching regexp) namespace into a hash
13517: ($udom, $uname, $regexp, $range are optional)
13518: 
13519: $range should be either an integer '100' (give me the first 100
13520:                                            matching records)
13521:               or be  two integers sperated by a - with no spaces
13522:                  '30-50' (give me the 30th through the 50th matching
13523:                           records)
13524: =item *
13525: 
13526: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13527: $store can be a scalar, an array reference, or if the amount to be 
13528: incremented is > 1, a hash reference.
13529: 
13530: ($udom and $uname are optional)
13531: 
13532: =item *
13533: 
13534: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13535: ($udom and $uname are optional)
13536: 
13537: =item *
13538: 
13539: cput($namespace,$storehash,$udom,$uname) : critical put
13540: ($udom and $uname are optional)
13541: 
13542: =item *
13543: 
13544: newput($namespace,$storehash,$udom,$uname) :
13545: 
13546: Attempts to store the items in the $storehash, but only if they don't
13547: currently exist, if this succeeds you can be certain that you have 
13548: successfully created a new key value pair in the $namespace db.
13549: 
13550: 
13551: Args:
13552:  $namespace: name of database to store values to
13553:  $storehash: hashref to store to the db
13554:  $udom: (optional) domain of user containing the db
13555:  $uname: (optional) name of user caontaining the db
13556: 
13557: Returns:
13558:  'ok' -> succeeded in storing all keys of $storehash
13559:  'key_exists: <key>' -> failed to anything out of $storehash, as at
13560:                         least <key> already existed in the db (other
13561:                         requested keys may also already exist)
13562:  'error: <msg>' -> unable to tie the DB or other error occurred
13563:  'con_lost' -> unable to contact request server
13564:  'refused' -> action was not allowed by remote machine
13565: 
13566: 
13567: =item *
13568: 
13569: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13570: reference filled in from namesp (encrypts the return communication)
13571: ($udom and $uname are optional)
13572: 
13573: =item *
13574: 
13575: log($udom,$name,$home,$message) : write to permanent log for user; use
13576: critical subroutine
13577: 
13578: =item *
13579: 
13580: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13581: array reference filled in from namespace found in domain level on either
13582: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
13583: 
13584: =item *
13585: 
13586: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
13587: domain level either on specified domain server ($uhome) or primary domain 
13588: server ($udom and $uhome are optional)
13589: 
13590: =item * 
13591: 
13592: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
13593: for: authentication, language, quotas, timezone, date locale, and portal URL in
13594: the target domain.
13595: 
13596: May also include additional key => value pairs for the following groups:
13597: 
13598: =over
13599: 
13600: =item
13601: disk quotas (MB allocated by default to portfolios and authoring spaces).
13602: 
13603: =over
13604: 
13605: =item defaultquota, authorquota
13606: 
13607: =back
13608: 
13609: =item
13610: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
13611: portfolio for users).
13612: 
13613: =over
13614: 
13615: =item
13616: aboutme, blog, webdav, portfolio
13617: 
13618: =back
13619: 
13620: =item
13621: requestcourses: ability to request courses, and how requests are processed.
13622: 
13623: =over
13624: 
13625: =item
13626: official, unofficial, community, textbook
13627: 
13628: =back
13629: 
13630: =item
13631: inststatus: types of institutional affiliation, and order in which they are displayed.
13632: 
13633: =over
13634: 
13635: =item
13636: inststatustypes, inststatusorder, inststatusguest
13637: 
13638: =back
13639: 
13640: =item
13641: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
13642: for course's uploaded content.
13643: 
13644: =over
13645: 
13646: =item
13647: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
13648: communityquota, textbookquota
13649: 
13650: =back
13651: 
13652: =item
13653: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
13654: on your servers.
13655: 
13656: =over
13657: 
13658: =item 
13659: remotesessions, hostedsessions
13660: 
13661: =back
13662: 
13663: =back
13664: 
13665: In cases where a domain coordinator has never used the "Set Domain Configuration"
13666: utility to create a configuration.db file on a domain's primary library server 
13667: only the following domain defaults: auth_def, auth_arg_def, lang_def
13668: -- corresponding values are authentication type (internal, krb4, krb5,
13669: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
13670: will be available. Values are retrieved from cache (if current), unless the
13671: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
13672: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
13673: 
13674: Typical usage:
13675: 
13676: %domdefaults = &get_domain_defaults($target_domain);
13677: 
13678: =back
13679: 
13680: =head2 Network Status Functions
13681: 
13682: =over 4
13683: 
13684: =item *
13685: 
13686: dirlist() : return directory list based on URI (first arg).
13687: 
13688: Inputs: 1 required, 5 optional.
13689: 
13690: =over
13691: 
13692: =item 
13693: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13694: 
13695: =item
13696: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
13697: 
13698: =item
13699: $username -  username of user/course to be listed. Extracted from $uri if absent. 
13700: 
13701: =item
13702: $getpropath - boolean: 1 if prepend path using &propath(). 
13703: 
13704: =item
13705: $getuserdir - boolean: 1 if prepend path for "userfiles".
13706: 
13707: =item 
13708: $alternateRoot - path to prepend in place of path from $uri.
13709: 
13710: =back
13711: 
13712: Returns: Array of up to two items.
13713: 
13714: =over
13715: 
13716: a reference to an array of files/subdirectories
13717: 
13718: =over
13719: 
13720: Each element in the array of files/subdirectories is a & separated list of
13721: item name and the result of running stat on the item.  If dirlist was requested
13722: for a file instead of a directory, the item name will be ''. For a directory 
13723: listing, if the item is a metadata file, the element will end &N&M 
13724: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13725: default copyright set (1).  
13726: 
13727: =back
13728: 
13729: a scalar containing error condition (if encountered).
13730: 
13731: =over
13732: 
13733: =item 
13734: no_host (no homeserver identified for $username:$domain).
13735: 
13736: =item 
13737: no_such_host (server contacted for listing not identified as valid host).
13738: 
13739: =item 
13740: con_lost (connection to remote server failed).
13741: 
13742: =item 
13743: refused (invalid $username:$domain received on lond side).
13744: 
13745: =item 
13746: no_such_dir (directory at specified path on lond side does not exist). 
13747: 
13748: =item 
13749: empty (directory at specified path on lond side is empty).
13750: 
13751: =over
13752: 
13753: This is currently not encountered because the &ls3, &ls2, 
13754: &ls (_handler) routines on the lond side do not filter out
13755: . and .. from a directory listing. 
13756: 
13757: =back
13758: 
13759: =back
13760: 
13761: =back
13762: 
13763: =item *
13764: 
13765: spareserver() : find server with least workload from spare.tab
13766: 
13767: 
13768: =item *
13769: 
13770: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13771: if there is no corresponding loncapa host.
13772: 
13773: =back
13774: 
13775: 
13776: =head2 Apache Request
13777: 
13778: =over 4
13779: 
13780: =item *
13781: 
13782: ssi($url,%hash) : server side include, does a complete request cycle on url to
13783: localhost, posts hash
13784: 
13785: =back
13786: 
13787: =head2 Data to String to Data
13788: 
13789: =over 4
13790: 
13791: =item *
13792: 
13793: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13794: and '&' separators, supports elements that are arrayrefs and hashrefs
13795: 
13796: =item *
13797: 
13798: hashref2str($hashref) : convert a hashref into a string complete with
13799: escaping and '=' and '&' separators, supports elements that are
13800: arrayrefs and hashrefs
13801: 
13802: =item *
13803: 
13804: arrayref2str($arrayref) : convert an arrayref into a string complete
13805: with escaping and '&' separators, supports elements that are arrayrefs
13806: and hashrefs
13807: 
13808: =item *
13809: 
13810: str2hash($string) : convert string to hash using unescaping and
13811: splitting on '=' and '&', supports elements that are arrayrefs and
13812: hashrefs
13813: 
13814: =item *
13815: 
13816: str2array($string) : convert string to hash using unescaping and
13817: splitting on '&', supports elements that are arrayrefs and hashrefs
13818: 
13819: =back
13820: 
13821: =head2 Logging Routines
13822: 
13823: 
13824: These routines allow one to make log messages in the lonnet.log and
13825: lonnet.perm logfiles.
13826: 
13827: =over 4
13828: 
13829: =item *
13830: 
13831: logtouch() : make sure the logfile, lonnet.log, exists
13832: 
13833: =item *
13834: 
13835: logthis() : append message to the normal lonnet.log file, it gets
13836: preiodically rolled over and deleted.
13837: 
13838: =item *
13839: 
13840: logperm() : append a permanent message to lonnet.perm.log, this log
13841: file never gets deleted by any automated portion of the system, only
13842: messages of critical importance should go in here.
13843: 
13844: 
13845: =back
13846: 
13847: =head2 General File Helper Routines
13848: 
13849: =over 4
13850: 
13851: =item *
13852: 
13853: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
13854: (a) files in /uploaded
13855:   (i) If a local copy of the file exists - 
13856:       compares modification date of local copy with last-modified date for 
13857:       definitive version stored on home server for course. If local copy is 
13858:       stale, requests a new version from the home server and stores it. 
13859:       If the original has been removed from the home server, then local copy 
13860:       is unlinked.
13861:   (ii) If local copy does not exist -
13862:       requests the file from the home server and stores it. 
13863:   
13864:   If $caller is 'uploadrep':  
13865:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
13866:     for request for files originally uploaded via DOCS. 
13867:      - returns 'ok' if fresh local copy now available, -1 otherwise.
13868:   
13869:   Otherwise:
13870:      This indicates a call from the content generation phase of the request.
13871:      -  returns the entire contents of the file or -1.
13872:      
13873: (b) files in /res
13874:    - returns the entire contents of a file or -1; 
13875:    it properly subscribes to and replicates the file if neccessary.
13876: 
13877: 
13878: =item *
13879: 
13880: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
13881:                   reference
13882: 
13883: returns either a stat() list of data about the file or an empty list
13884: if the file doesn't exist or couldn't find out about it (connection
13885: problems or user unknown)
13886: 
13887: =item *
13888: 
13889: filelocation($dir,$file) : returns file system location of a file
13890: based on URI; meant to be "fairly clean" absolute reference, $dir is a
13891: directory that relative $file lookups are to looked in ($dir of /a/dir
13892: and a file of ../bob will become /a/bob)
13893: 
13894: =item *
13895: 
13896: hreflocation($dir,$file) : returns file system location or a URL; same as
13897: filelocation except for hrefs
13898: 
13899: =item *
13900: 
13901: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
13902: also removes beginning /home/httpd/html unless /priv/ follows it.
13903: 
13904: =back
13905: 
13906: =head2 Usererfile file routines (/uploaded*)
13907: 
13908: =over 4
13909: 
13910: =item *
13911: 
13912: userfileupload(): main rotine for putting a file in a user or course's
13913:                   filespace, arguments are,
13914: 
13915:  formname - required - this is the name of the element in $env where the
13916:            filename, and the contents of the file to create/modifed exist
13917:            the filename is in $env{'form.'.$formname.'.filename'} and the
13918:            contents of the file is located in $env{'form.'.$formname}
13919:  context - if coursedoc, store the file in the course of the active role
13920:              of the current user; 
13921:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
13922:            if 'canceloverwrite': delete file in tmp/overwrites directory
13923:  subdir - required - subdirectory to put the file in under ../userfiles/
13924:          if undefined, it will be placed in "unknown"
13925: 
13926:  (This routine calls clean_filename() to remove any dangerous
13927:  characters from the filename, and then calls finuserfileupload() to
13928:  complete the transaction)
13929: 
13930:  returns either the url of the uploaded file (/uploaded/....) if successful
13931:  and /adm/notfound.html if unsuccessful
13932: 
13933: =item *
13934: 
13935: clean_filename(): routine for cleaing a filename up for storage in
13936:                  userfile space, argument is:
13937: 
13938:  filename - proposed filename
13939: 
13940: returns: the new clean filename
13941: 
13942: =item *
13943: 
13944: finishuserfileupload(): routine that creates and sends the file to
13945: userspace, probably shouldn't be called directly
13946: 
13947:   docuname: username or courseid of destination for the file
13948:   docudom: domain of user/course of destination for the file
13949:   formname: same as for userfileupload()
13950:   fname: filename (including subdirectories) for the file
13951:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
13952:   allfiles: reference to hash used to store objects found by parser
13953:   codebase: reference to hash used for codebases of java objects found by parser
13954:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
13955:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
13956:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
13957:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
13958:   context: if 'overwrite', will move the uploaded file from its temporary location to
13959:             userfiles to facilitate overwriting a previously uploaded file with same name.
13960:   mimetype: reference to scalar to accommodate mime type determined
13961:             from File::MMagic if $parser = parse.
13962: 
13963:  returns either the url of the uploaded file (/uploaded/....) if successful
13964:  and /adm/notfound.html if unsuccessful (or an error message if context 
13965:  was 'overwrite').
13966:  
13967: 
13968: =item *
13969: 
13970: renameuserfile(): renames an existing userfile to a new name
13971: 
13972:   Args:
13973:    docuname: username or courseid of destination for the file
13974:    docudom: domain of user/course of destination for the file
13975:    old: current file name (including any subdirs under userfiles)
13976:    new: desired file name (including any subdirs under userfiles)
13977: 
13978: =item *
13979: 
13980: mkdiruserfile(): creates a directory is a userfiles dir
13981: 
13982:   Args:
13983:    docuname: username or courseid of destination for the file
13984:    docudom: domain of user/course of destination for the file
13985:    dir: dir to create (including any subdirs under userfiles)
13986: 
13987: =item *
13988: 
13989: removeuserfile(): removes a file that exists in userfiles
13990: 
13991:   Args:
13992:    docuname: username or courseid of destination for the file
13993:    docudom: domain of user/course of destination for the file
13994:    fname: filname to delete (including any subdirs under userfiles)
13995: 
13996: =item *
13997: 
13998: removeuploadedurl(): convience function for removeuserfile()
13999: 
14000:   Args:
14001:    url:  a full /uploaded/... url to delete
14002: 
14003: =item * 
14004: 
14005: get_portfile_permissions():
14006:   Args:
14007:     domain: domain of user or course contain the portfolio files
14008:     user: name of user or num of course contain the portfolio files
14009:   Returns:
14010:     hashref of a dump of the proper file_permissions.db
14011:    
14012: 
14013: =item * 
14014: 
14015: get_access_controls():
14016: 
14017: Args:
14018:   current_permissions: the hash ref returned from get_portfile_permissions()
14019:   group: (optional) the group you want the files associated with
14020:   file: (optional) the file you want access info on
14021: 
14022: Returns:
14023:     a hash (keys are file names) of hashes containing
14024:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
14025:         values are XML containing access control settings (see below) 
14026: 
14027: Internal notes:
14028: 
14029:  access controls are stored in file_permissions.db as key=value pairs.
14030:     key -> path to file/file_name\0uniqueID:scope_end_start
14031:         where scope -> public,guest,course,group,domains or users.
14032:               end -> UNIX time for end of access (0 -> no end date)
14033:               start -> UNIX time for start of access
14034: 
14035:     value -> XML description of access control
14036:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
14037:             <start></start>
14038:             <end></end>
14039: 
14040:             <password></password>  for scope type = guest
14041: 
14042:             <domain></domain>     for scope type = course or group
14043:             <number></number>
14044:             <roles id="">
14045:              <role></role>
14046:              <access></access>
14047:              <section></section>
14048:              <group></group>
14049:             </roles>
14050: 
14051:             <dom></dom>         for scope type = domains
14052: 
14053:             <users>             for scope type = users
14054:              <user>
14055:               <uname></uname>
14056:               <udom></udom>
14057:              </user>
14058:             </users>
14059:            </scope> 
14060:               
14061:  Access data is also aggregated for each file in an additional key=value pair:
14062:  key -> path to file/file_name\0accesscontrol 
14063:  value -> reference to hash
14064:           hash contains key = value pairs
14065:           where key = uniqueID:scope_end_start
14066:                 value = UNIX time record was last updated
14067: 
14068:           Used to improve speed of look-ups of access controls for each file.  
14069:  
14070:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
14071: 
14072: =item *
14073: 
14074: modify_access_controls():
14075: 
14076: Modifies access controls for a portfolio file
14077: Args
14078: 1. file name
14079: 2. reference to hash of required changes,
14080: 3. domain
14081: 4. username
14082:   where domain,username are the domain of the portfolio owner 
14083:   (either a user or a course) 
14084: 
14085: Returns:
14086: 1. result of additions or updates ('ok' or 'error', with error message). 
14087: 2. result of deletions ('ok' or 'error', with error message).
14088: 3. reference to hash of any new or updated access controls.
14089: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
14090:    key = integer (inbound ID)
14091:    value = uniqueID
14092: 
14093: =item *
14094: 
14095: get_timebased_id():
14096: 
14097: Attempts to get a unique timestamp-based suffix for use with items added to a 
14098: course via the Course Editor (e.g., folders, composite pages, 
14099: group bulletin boards).
14100: 
14101: Args: (first three required; six others optional)
14102: 
14103: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
14104:    docssequence, or name of group
14105: 
14106: 2. keyid (alphanumeric): name of temporary locking key in hash,
14107:    e.g., num, boardids
14108: 
14109: 3. namespace: name of gdbm file used to store suffixes already assigned;  
14110:    file will be named nohist_namespace.db
14111: 
14112: 4. cdom: domain of course; default is current course domain from %env
14113: 
14114: 5. cnum: course number; default is current course number from %env
14115: 
14116: 6. idtype: set to concat if an additional digit is to be appended to the 
14117:    unix timestamp to form the suffix, if the plain timestamp is already
14118:    in use.  Default is to not do this, but simply increment the unix 
14119:    timestamp by 1 until a unique key is obtained.
14120: 
14121: 7. who: holder of locking key; defaults to user:domain for user.
14122: 
14123: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
14124:    retrying); default is 3.
14125: 
14126: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
14127: 
14128: Returns:
14129: 
14130: 1. suffix obtained (numeric)
14131: 
14132: 2. result of deleting locking key (ok if deleted, or lock never obtained)
14133: 
14134: 3. error: contains (localized) error message if an error occurred.
14135: 
14136: 
14137: =back
14138: 
14139: =head2 HTTP Helper Routines
14140: 
14141: =over 4
14142: 
14143: =item *
14144: 
14145: escape() : unpack non-word characters into CGI-compatible hex codes
14146: 
14147: =item *
14148: 
14149: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
14150: 
14151: =back
14152: 
14153: =head1 PRIVATE SUBROUTINES
14154: 
14155: =head2 Underlying communication routines (Shouldn't call)
14156: 
14157: =over 4
14158: 
14159: =item *
14160: 
14161: subreply() : tries to pass a message to lonc, returns con_lost if incapable
14162: 
14163: =item *
14164: 
14165: reply() : uses subreply to send a message to remote machine, logs all failures
14166: 
14167: =item *
14168: 
14169: critical() : passes a critical message to another server; if cannot
14170: get through then place message in connection buffer directory and
14171: returns con_delayed, if incapable of saving message, returns
14172: con_failed
14173: 
14174: =item *
14175: 
14176: reconlonc() : tries to reconnect lonc client processes.
14177: 
14178: =back
14179: 
14180: =head2 Resource Access Logging
14181: 
14182: =over 4
14183: 
14184: =item *
14185: 
14186: flushcourselogs() : flush (save) buffer logs and access logs
14187: 
14188: =item *
14189: 
14190: courselog($what) : save message for course in hash
14191: 
14192: =item *
14193: 
14194: courseacclog($what) : save message for course using &courselog().  Perform
14195: special processing for specific resource types (problems, exams, quizzes, etc).
14196: 
14197: =item *
14198: 
14199: goodbye() : flush course logs and log shutting down; it is called in srm.conf
14200: as a PerlChildExitHandler
14201: 
14202: =back
14203: 
14204: =head2 Other
14205: 
14206: =over 4
14207: 
14208: =item *
14209: 
14210: symblist($mapname,%newhash) : update symbolic storage links
14211: 
14212: =back
14213: 
14214: =cut
14215: 

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