File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1298: download - view: text, annotated - select for diffs
Tue Jan 26 20:17:53 2016 UTC (8 years, 5 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 6754. Make LON-CAPA an LTI Tool Consumer (LTI 1.1). Work in progress.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1298 2016/01/26 20:17:53 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( sleep 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 = 20;     # 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(0.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(0.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:     if ($lonid) {
  426:         my $hostname = &hostname($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($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 1;
  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:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  853:                                              $try_server));
  854: 	        ($spare_server, $lowest_load) =
  855: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  856:             }
  857:         }
  858: 
  859:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
  860: 
  861:         if (!$found_server) {
  862:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
  863: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
  864:                     next unless (&spare_can_host($udom,$uint_dom,
  865:                                                  $remotesessions,$try_server));
  866: 	            ($spare_server, $lowest_load) =
  867: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
  868:                 }
  869: 	    }
  870:         }
  871:     }
  872: 
  873:     if (!$want_server_name) {
  874:         my $protocol = 'http';
  875:         if ($protocol{$spare_server} eq 'https') {
  876:             $protocol = $protocol{$spare_server};
  877:         }
  878:         if (defined($spare_server)) {
  879:             my $hostname = &hostname($spare_server);
  880:             if (defined($hostname)) {
  881: 	        $spare_server = $protocol.'://'.$hostname;
  882:             }
  883:         }
  884:     }
  885:     return $spare_server;
  886: }
  887: 
  888: sub compare_server_load {
  889:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
  890: 
  891:     if ($required) {
  892:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
  893:         my $remoterev = &get_server_loncaparev(undef,$try_server);
  894:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
  895:         if (($major eq '' && $minor eq '') ||
  896:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
  897:             return ($spare_server,$lowest_load);
  898:         }
  899:     }
  900: 
  901:     my $loadans     = &reply('load',    $try_server);
  902:     my $userloadans = &reply('userload',$try_server);
  903: 
  904:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  905: 	return ($spare_server, $lowest_load); #didn't get a number from the server
  906:     }
  907: 
  908:     my $load;
  909:     if ($loadans =~ /\d/) {
  910: 	if ($userloadans =~ /\d/) {
  911: 	    #both are numbers, pick the bigger one
  912: 	    $load = ($loadans > $userloadans) ? $loadans 
  913: 		                              : $userloadans;
  914: 	} else {
  915: 	    $load = $loadans;
  916: 	}
  917:     } else {
  918: 	$load = $userloadans;
  919:     }
  920: 
  921:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  922: 	$spare_server = $try_server;
  923: 	$lowest_load  = $load;
  924:     }
  925:     return ($spare_server,$lowest_load);
  926: }
  927: 
  928: # --------------------------- ask offload servers if user already has a session
  929: sub find_existing_session {
  930:     my ($udom,$uname) = @_;
  931:     my $spareshash = &this_host_spares($udom);
  932:     if (ref($spareshash) eq 'HASH') {
  933:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  934:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  935:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  936:             }
  937:         }
  938:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
  939:             foreach my $try_server (@{ $spareshash->{'default'} }) {
  940:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  941:             }
  942:         }
  943:     }
  944:     return;
  945: }
  946: 
  947: # -------------------------------- ask if server already has a session for user
  948: sub has_user_session {
  949:     my ($lonid,$udom,$uname) = @_;
  950:     my $result = &reply(join(':','userhassession',
  951: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  952:     return 1 if ($result eq 'ok');
  953: 
  954:     return 0;
  955: }
  956: 
  957: # --------- determine least loaded server in a user's domain which allows login
  958: 
  959: sub choose_server {
  960:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
  961:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
  962:     my %servers = &get_servers($udom);
  963:     my $lowest_load = 30000;
  964:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
  965:     if ($skiploadbal) {
  966:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
  967:         unless (defined($cached)) {
  968:             my $cachetime = 60*60*24;
  969:             my %domconfig =
  970:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
  971:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
  972:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
  973:                                            $cachetime);
  974:             }
  975:         }
  976:     }
  977:     foreach my $lonhost (keys(%servers)) {
  978:         if ($skiploadbal) {
  979:             if (ref($balancers) eq 'HASH') {
  980:                 next if (exists($balancers->{$lonhost}));
  981:             }
  982:         }   
  983:         my $loginvia;
  984:         if ($checkloginvia) {
  985:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
  986:             if ($loginvia) {
  987:                 my ($server,$path) = split(/:/,$loginvia);
  988:                 ($login_host, $lowest_load) =
  989:                     &compare_server_load($server, $login_host, $lowest_load, $required);
  990:                 if ($login_host eq $server) {
  991:                     $portal_path = $path;
  992:                     $isredirect = 1;
  993:                 }
  994:             } else {
  995:                 ($login_host, $lowest_load) =
  996:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
  997:                 if ($login_host eq $lonhost) {
  998:                     $portal_path = '';
  999:                     $isredirect = ''; 
 1000:                 }
 1001:             }
 1002:         } else {
 1003:             ($login_host, $lowest_load) =
 1004:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1005:         }
 1006:     }
 1007:     if ($login_host ne '') {
 1008:         $hostname = &hostname($login_host);
 1009:     }
 1010:     return ($login_host,$hostname,$portal_path,$isredirect);
 1011: }
 1012: 
 1013: # --------------------------------------------- Try to change a user's password
 1014: 
 1015: sub changepass {
 1016:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
 1017:     $currentpass = &escape($currentpass);
 1018:     $newpass     = &escape($newpass);
 1019:     my $lonhost = $perlvar{'lonHostID'};
 1020:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
 1021: 		       $server);
 1022:     if (! $answer) {
 1023: 	&logthis("No reply on password change request to $server ".
 1024: 		 "by $uname in domain $udom.");
 1025:     } elsif ($answer =~ "^ok") {
 1026:         &logthis("$uname in $udom successfully changed their password ".
 1027: 		 "on $server.");
 1028:     } elsif ($answer =~ "^pwchange_failure") {
 1029: 	&logthis("$uname in $udom was unable to change their password ".
 1030: 		 "on $server.  The action was blocked by either lcpasswd ".
 1031: 		 "or pwchange");
 1032:     } elsif ($answer =~ "^non_authorized") {
 1033:         &logthis("$uname in $udom did not get their password correct when ".
 1034: 		 "attempting to change it on $server.");
 1035:     } elsif ($answer =~ "^auth_mode_error") {
 1036:         &logthis("$uname in $udom attempted to change their password despite ".
 1037: 		 "not being locally or internally authenticated on $server.");
 1038:     } elsif ($answer =~ "^unknown_user") {
 1039:         &logthis("$uname in $udom attempted to change their password ".
 1040: 		 "on $server but were unable to because $server is not ".
 1041: 		 "their home server.");
 1042:     } elsif ($answer =~ "^refused") {
 1043: 	&logthis("$server refused to change $uname in $udom password because ".
 1044: 		 "it was sent an unencrypted request to change the password.");
 1045:     } elsif ($answer =~ "invalid_client") {
 1046:         &logthis("$server refused to change $uname in $udom password because ".
 1047:                  "it was a reset by e-mail originating from an invalid server.");
 1048:     }
 1049:     return $answer;
 1050: }
 1051: 
 1052: # ----------------------- Try to determine user's current authentication scheme
 1053: 
 1054: sub queryauthenticate {
 1055:     my ($uname,$udom)=@_;
 1056:     my $uhome=&homeserver($uname,$udom);
 1057:     if (!$uhome) {
 1058: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1059: 	return 'no_host';
 1060:     }
 1061:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1062:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1063: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1064:     }
 1065:     return $answer;
 1066: }
 1067: 
 1068: # --------- Try to authenticate user from domain's lib servers (first this one)
 1069: 
 1070: sub authenticate {
 1071:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1072:     $upass=&escape($upass);
 1073:     $uname= &LONCAPA::clean_username($uname);
 1074:     my $uhome=&homeserver($uname,$udom,1);
 1075:     my $newhome;
 1076:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1077: # Maybe the machine was offline and only re-appeared again recently?
 1078:         &reconlonc();
 1079: # One more
 1080: 	$uhome=&homeserver($uname,$udom,1);
 1081:         if (($uhome eq 'no_host') && $checkdefauth) {
 1082:             if (defined(&domain($udom,'primary'))) {
 1083:                 $newhome=&domain($udom,'primary');
 1084:             }
 1085:             if ($newhome ne '') {
 1086:                 $uhome = $newhome;
 1087:             }
 1088:         }
 1089: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1090: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1091: 	    return 'no_host';
 1092:         }
 1093:     }
 1094:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1095:     if ($answer eq 'authorized') {
 1096:         if ($newhome) {
 1097:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1098:             return 'no_account_on_host'; 
 1099:         } else {
 1100:             &logthis("User $uname at $udom authorized by $uhome");
 1101:             return $uhome;
 1102:         }
 1103:     }
 1104:     if ($answer eq 'non_authorized') {
 1105: 	&logthis("User $uname at $udom rejected by $uhome");
 1106: 	return 'no_host'; 
 1107:     }
 1108:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1109:     return 'no_host';
 1110: }
 1111: 
 1112: sub can_host_session {
 1113:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1114:     my $canhost = 1;
 1115:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1116:     if (ref($remotesessions) eq 'HASH') {
 1117:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1118:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1119:                 $canhost = 0;
 1120:             } else {
 1121:                 $canhost = 1;
 1122:             }
 1123:         }
 1124:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1125:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1126:                 $canhost = 1;
 1127:             } else {
 1128:                 $canhost = 0;
 1129:             }
 1130:         }
 1131:         if ($canhost) {
 1132:             if ($remotesessions->{'version'} ne '') {
 1133:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1134:                 if ($reqmajor ne '' && $reqminor ne '') {
 1135:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1136:                         my $major = $1;
 1137:                         my $minor = $2;
 1138:                         if (($major < $reqmajor ) ||
 1139:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1140:                             $canhost = 0;
 1141:                         }
 1142:                     } else {
 1143:                         $canhost = 0;
 1144:                     }
 1145:                 }
 1146:             }
 1147:         }
 1148:     }
 1149:     if ($canhost) {
 1150:         if (ref($hostedsessions) eq 'HASH') {
 1151:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1152:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1153:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1154:                 if (($uint_dom ne '') && 
 1155:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1156:                     $canhost = 0;
 1157:                 } else {
 1158:                     $canhost = 1;
 1159:                 }
 1160:             }
 1161:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1162:                 if (($uint_dom ne '') && 
 1163:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1164:                     $canhost = 1;
 1165:                 } else {
 1166:                     $canhost = 0;
 1167:                 }
 1168:             }
 1169:         }
 1170:     }
 1171:     return $canhost;
 1172: }
 1173: 
 1174: sub spare_can_host {
 1175:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1176:     my $canhost=1;
 1177:     my $try_server_hostname = &hostname($try_server);
 1178:     my $serverhomeID = &get_server_homeID($try_server_hostname);
 1179:     my $serverhomedom = &host_domain($serverhomeID);
 1180:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
 1181:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
 1182:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
 1183:             $canhost = 0;
 1184:         }
 1185:     }
 1186:     if (($canhost) && ($uint_dom)) {
 1187:         my @intdoms;
 1188:         my $internet_names = &get_internet_names($try_server);
 1189:         if (ref($internet_names) eq 'ARRAY') {
 1190:             @intdoms = @{$internet_names};
 1191:         }
 1192:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1193:             my $remoterev = &get_server_loncaparev(undef,$try_server);
 1194:             $canhost = &can_host_session($udom,$try_server,$remoterev,
 1195:                                          $remotesessions,
 1196:                                          $defdomdefaults{'hostedsessions'});
 1197:         }
 1198:     }
 1199:     return $canhost;
 1200: }
 1201: 
 1202: sub this_host_spares {
 1203:     my ($dom) = @_;
 1204:     my ($dom_in_use,$lonhost_in_use,$result);
 1205:     my @hosts = &current_machine_ids();
 1206:     foreach my $lonhost (@hosts) {
 1207:         if (&host_domain($lonhost) eq $dom) {
 1208:             $dom_in_use = $dom;
 1209:             $lonhost_in_use = $lonhost;
 1210:             last;
 1211:         }
 1212:     }
 1213:     if ($dom_in_use ne '') {
 1214:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1215:     }
 1216:     if (ref($result) ne 'HASH') {
 1217:         $lonhost_in_use = $perlvar{'lonHostID'};
 1218:         $dom_in_use = &host_domain($lonhost_in_use);
 1219:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1220:         if (ref($result) ne 'HASH') {
 1221:             $result = \%spareid;
 1222:         }
 1223:     }
 1224:     return $result;
 1225: }
 1226: 
 1227: sub spares_for_offload  {
 1228:     my ($dom_in_use,$lonhost_in_use) = @_;
 1229:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1230:     if (defined($cached)) {
 1231:         return $result;
 1232:     } else {
 1233:         my $cachetime = 60*60*24;
 1234:         my %domconfig =
 1235:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1236:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1237:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1238:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1239:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1240:                 }
 1241:             }
 1242:         }
 1243:     }
 1244:     return;
 1245: }
 1246: 
 1247: sub get_lonbalancer_config {
 1248:     my ($servers) = @_;
 1249:     my ($currbalancer,$currtargets);
 1250:     if (ref($servers) eq 'HASH') {
 1251:         foreach my $server (keys(%{$servers})) {
 1252:             my %what = (
 1253:                          spareid => 1,
 1254:                          perlvar => 1,
 1255:                        );
 1256:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1257:             if ($result eq 'ok') {
 1258:                 if (ref($returnhash) eq 'HASH') {
 1259:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1260:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1261:                             $currbalancer = $server;
 1262:                             $currtargets = {};
 1263:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1264:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1265:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1266:                                 }
 1267:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1268:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1269:                                 }
 1270:                             }
 1271:                             last;
 1272:                         }
 1273:                     }
 1274:                 }
 1275:             }
 1276:         }
 1277:     }
 1278:     return ($currbalancer,$currtargets);
 1279: }
 1280: 
 1281: sub check_loadbalancing {
 1282:     my ($uname,$udom) = @_;
 1283:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1284:         $rule_in_effect,$offloadto,$otherserver);
 1285:     my $lonhost = $perlvar{'lonHostID'};
 1286:     my @hosts = &current_machine_ids();
 1287:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1288:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1289:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1290:     my $serverhomedom = &host_domain($lonhost);
 1291: 
 1292:     my $cachetime = 60*60*24;
 1293: 
 1294:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1295:         $dom_in_use = $udom;
 1296:         $homeintdom = 1;
 1297:     } else {
 1298:         $dom_in_use = $serverhomedom;
 1299:     }
 1300:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1301:     unless (defined($cached)) {
 1302:         my %domconfig =
 1303:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1304:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1305:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1306:         }
 1307:     }
 1308:     if (ref($result) eq 'HASH') {
 1309:         ($is_balancer,$currtargets,$currrules) = 
 1310:             &check_balancer_result($result,@hosts);
 1311:         if ($is_balancer) {
 1312:             if (ref($currrules) eq 'HASH') {
 1313:                 if ($homeintdom) {
 1314:                     if ($uname ne '') {
 1315:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1316:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1317:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1318:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1319:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1320:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1321:                             }
 1322:                         }
 1323:                         if ($rule_in_effect eq '') {
 1324:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1325:                             if ($userenv{'inststatus'} ne '') {
 1326:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1327:                                 my ($othertitle,$usertypes,$types) =
 1328:                                     &Apache::loncommon::sorted_inst_types($udom);
 1329:                                 if (ref($types) eq 'ARRAY') {
 1330:                                     foreach my $type (@{$types}) {
 1331:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1332:                                             if (exists($currrules->{$type})) {
 1333:                                                 $rule_in_effect = $currrules->{$type};
 1334:                                             }
 1335:                                         }
 1336:                                     }
 1337:                                 }
 1338:                             } else {
 1339:                                 if (exists($currrules->{'default'})) {
 1340:                                     $rule_in_effect = $currrules->{'default'};
 1341:                                 }
 1342:                             }
 1343:                         }
 1344:                     } else {
 1345:                         if (exists($currrules->{'default'})) {
 1346:                             $rule_in_effect = $currrules->{'default'};
 1347:                         }
 1348:                     }
 1349:                 } else {
 1350:                     if ($currrules->{'_LC_external'} ne '') {
 1351:                         $rule_in_effect = $currrules->{'_LC_external'};
 1352:                     }
 1353:                 }
 1354:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1355:                                                        $uname,$udom);
 1356:             }
 1357:         }
 1358:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1359:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1360:         unless (defined($cached)) {
 1361:             my %domconfig =
 1362:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1363:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1364:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1365:             }
 1366:         }
 1367:         if (ref($result) eq 'HASH') {
 1368:             ($is_balancer,$currtargets,$currrules) = 
 1369:                 &check_balancer_result($result,@hosts);
 1370:             if ($is_balancer) {
 1371:                 if (ref($currrules) eq 'HASH') {
 1372:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1373:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1374:                     }
 1375:                 }
 1376:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1377:                                                        $uname,$udom);
 1378:             }
 1379:         } else {
 1380:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1381:                 $is_balancer = 1;
 1382:                 $offloadto = &this_host_spares($dom_in_use);
 1383:             }
 1384:         }
 1385:     } else {
 1386:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1387:             $is_balancer = 1;
 1388:             $offloadto = &this_host_spares($dom_in_use);
 1389:         }
 1390:     }
 1391:     if ($is_balancer) {
 1392:         my $lowest_load = 30000;
 1393:         if (ref($offloadto) eq 'HASH') {
 1394:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1395:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1396:                     ($otherserver,$lowest_load) =
 1397:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1398:                 }
 1399:             }
 1400:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1401: 
 1402:             if (!$found_server) {
 1403:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1404:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1405:                         ($otherserver,$lowest_load) =
 1406:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1407:                     }
 1408:                 }
 1409:             }
 1410:         } elsif (ref($offloadto) eq 'ARRAY') {
 1411:             if (@{$offloadto} == 1) {
 1412:                 $otherserver = $offloadto->[0];
 1413:             } elsif (@{$offloadto} > 1) {
 1414:                 foreach my $try_server (@{$offloadto}) {
 1415:                     ($otherserver,$lowest_load) =
 1416:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1417:                 }
 1418:             }
 1419:         }
 1420:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1421:             $is_balancer = 0;
 1422:             if ($uname ne '' && $udom ne '') {
 1423:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1424:                     
 1425:                     &appenv({'user.loadbalexempt'     => $lonhost,  
 1426:                              'user.loadbalcheck.time' => time});
 1427:                 }
 1428:             }
 1429:         }
 1430:     }
 1431:     return ($is_balancer,$otherserver);
 1432: }
 1433: 
 1434: sub check_balancer_result {
 1435:     my ($result,@hosts) = @_;
 1436:     my ($is_balancer,$currtargets,$currrules);
 1437:     if (ref($result) eq 'HASH') {
 1438:         if ($result->{'lonhost'} ne '') {
 1439:             my $currbalancer = $result->{'lonhost'};
 1440:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1441:                 $is_balancer = 1;
 1442:                 $currtargets = $result->{'targets'};
 1443:                 $currrules = $result->{'rules'};
 1444:             }
 1445:         } else {
 1446:             foreach my $key (keys(%{$result})) {
 1447:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1448:                     (ref($result->{$key}) eq 'HASH')) {
 1449:                     $is_balancer = 1;
 1450:                     $currrules = $result->{$key}{'rules'};
 1451:                     $currtargets = $result->{$key}{'targets'};
 1452:                     last;
 1453:                 }
 1454:             }
 1455:         }
 1456:     }
 1457:     return ($is_balancer,$currtargets,$currrules);
 1458: }
 1459: 
 1460: sub get_loadbalancer_targets {
 1461:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1462:     my $offloadto;
 1463:     if ($rule_in_effect eq 'none') {
 1464:         return [$perlvar{'lonHostID'}];
 1465:     } elsif ($rule_in_effect eq '') {
 1466:         $offloadto = $currtargets;
 1467:     } else {
 1468:         if ($rule_in_effect eq 'homeserver') {
 1469:             my $homeserver = &homeserver($uname,$udom);
 1470:             if ($homeserver ne 'no_host') {
 1471:                 $offloadto = [$homeserver];
 1472:             }
 1473:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1474:             my %domconfig =
 1475:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1476:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1477:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1478:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1479:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1480:                     }
 1481:                 }
 1482:             } else {
 1483:                 my %servers = &internet_dom_servers($udom);
 1484:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1485:                 if (&hostname($remotebalancer) ne '') {
 1486:                     $offloadto = [$remotebalancer];
 1487:                 }
 1488:             }
 1489:         } elsif (&hostname($rule_in_effect) ne '') {
 1490:             $offloadto = [$rule_in_effect];
 1491:         }
 1492:     }
 1493:     return $offloadto;
 1494: }
 1495: 
 1496: sub internet_dom_servers {
 1497:     my ($dom) = @_;
 1498:     my (%uniqservers,%servers);
 1499:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1500:     my @machinedoms = &machine_domains($primaryserver);
 1501:     foreach my $mdom (@machinedoms) {
 1502:         my %currservers = %servers;
 1503:         my %server = &get_servers($mdom);
 1504:         %servers = (%currservers,%server);
 1505:     }
 1506:     my %by_hostname;
 1507:     foreach my $id (keys(%servers)) {
 1508:         push(@{$by_hostname{$servers{$id}}},$id);
 1509:     }
 1510:     foreach my $hostname (sort(keys(%by_hostname))) {
 1511:         if (@{$by_hostname{$hostname}} > 1) {
 1512:             my $match = 0;
 1513:             foreach my $id (@{$by_hostname{$hostname}}) {
 1514:                 if (&host_domain($id) eq $dom) {
 1515:                     $uniqservers{$id} = $hostname;
 1516:                     $match = 1;
 1517:                 }
 1518:             }
 1519:             unless ($match) {
 1520:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1521:             }
 1522:         } else {
 1523:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1524:         }
 1525:     }
 1526:     return %uniqservers;
 1527: }
 1528: 
 1529: # ---------------------- Find the homebase for a user from domain's lib servers
 1530: 
 1531: my %homecache;
 1532: sub homeserver {
 1533:     my ($uname,$udom,$ignoreBadCache)=@_;
 1534:     my $index="$uname:$udom";
 1535: 
 1536:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1537: 
 1538:     my %servers = &get_servers($udom,'library');
 1539:     foreach my $tryserver (keys(%servers)) {
 1540:         next if ($ignoreBadCache ne 'true' && 
 1541: 		 exists($badServerCache{$tryserver}));
 1542: 
 1543: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1544: 	if ($answer eq 'found') {
 1545: 	    delete($badServerCache{$tryserver}); 
 1546: 	    return $homecache{$index}=$tryserver;
 1547: 	} elsif ($answer eq 'no_host') {
 1548: 	    $badServerCache{$tryserver}=1;
 1549: 	}
 1550:     }    
 1551:     return 'no_host';
 1552: }
 1553: 
 1554: # ------------------------------------- Find the usernames behind a list of IDs
 1555: 
 1556: sub idget {
 1557:     my ($udom,@ids)=@_;
 1558:     my %returnhash=();
 1559:     
 1560:     my %servers = &get_servers($udom,'library');
 1561:     foreach my $tryserver (keys(%servers)) {
 1562: 	my $idlist=join('&',@ids);
 1563: 	$idlist=~tr/A-Z/a-z/; 
 1564: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1565: 	my @answer=();
 1566: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1567: 	    @answer=split(/\&/,$reply);
 1568: 	}                    ;
 1569: 	my $i;
 1570: 	for ($i=0;$i<=$#ids;$i++) {
 1571: 	    if ($answer[$i]) {
 1572: 		$returnhash{$ids[$i]}=$answer[$i];
 1573: 	    } 
 1574: 	}
 1575:     } 
 1576:     return %returnhash;
 1577: }
 1578: 
 1579: # ------------------------------------- Find the IDs behind a list of usernames
 1580: 
 1581: sub idrget {
 1582:     my ($udom,@unames)=@_;
 1583:     my %returnhash=();
 1584:     foreach my $uname (@unames) {
 1585:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1586:     }
 1587:     return %returnhash;
 1588: }
 1589: 
 1590: # ------------------------------- Store away a list of names and associated IDs
 1591: 
 1592: sub idput {
 1593:     my ($udom,%ids)=@_;
 1594:     my %servers=();
 1595:     foreach my $uname (keys(%ids)) {
 1596: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1597:         my $uhom=&homeserver($uname,$udom);
 1598:         if ($uhom ne 'no_host') {
 1599:             my $id=&escape($ids{$uname});
 1600:             $id=~tr/A-Z/a-z/;
 1601:             my $esc_unam=&escape($uname);
 1602: 	    if ($servers{$uhom}) {
 1603: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
 1604:             } else {
 1605:                 $servers{$uhom}=$id.'='.$esc_unam;
 1606:             }
 1607:         }
 1608:     }
 1609:     foreach my $server (keys(%servers)) {
 1610:         &critical('idput:'.$udom.':'.$servers{$server},$server);
 1611:     }
 1612: }
 1613: 
 1614: # ---------------------------------------- Delete unwanted IDs from ids.db file 
 1615: 
 1616: sub iddel {
 1617:     my ($udom,$idshashref,$uhome)=@_;
 1618:     my %result=();
 1619:     unless (ref($idshashref) eq 'HASH') {
 1620:         return %result;
 1621:     }
 1622:     my %servers=();
 1623:     while (my ($id,$uname) = each(%{$idshashref})) {
 1624:         my $uhom;
 1625:         if ($uhome) {
 1626:             $uhom = $uhome;
 1627:         } else {
 1628:             $uhom=&homeserver($uname,$udom);
 1629:         }
 1630:         if ($uhom ne 'no_host') {
 1631:             if ($servers{$uhom}) {
 1632:                 $servers{$uhom}.='&'.&escape($id);
 1633:             } else {
 1634:                 $servers{$uhom}=&escape($id);
 1635:             }
 1636:         }
 1637:     }
 1638:     foreach my $server (keys(%servers)) {
 1639:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
 1640:     }
 1641:     return %result;
 1642: }
 1643: 
 1644: # ------------------------------dump from db file owned by domainconfig user
 1645: sub dump_dom {
 1646:     my ($namespace, $udom, $regexp) = @_;
 1647: 
 1648:     $udom ||= $env{'user.domain'};
 1649: 
 1650:     return () unless $udom;
 1651: 
 1652:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 1653: }
 1654: 
 1655: # ------------------------------------------ get items from domain db files   
 1656: 
 1657: sub get_dom {
 1658:     my ($namespace,$storearr,$udom,$uhome)=@_;
 1659:     return if ($udom eq 'public');
 1660:     my $items='';
 1661:     foreach my $item (@$storearr) {
 1662:         $items.=&escape($item).'&';
 1663:     }
 1664:     $items=~s/\&$//;
 1665:     if (!$udom) {
 1666:         $udom=$env{'user.domain'};
 1667:         return if ($udom eq 'public');
 1668:         if (defined(&domain($udom,'primary'))) {
 1669:             $uhome=&domain($udom,'primary');
 1670:         } else {
 1671:             undef($uhome);
 1672:         }
 1673:     } else {
 1674:         if (!$uhome) {
 1675:             if (defined(&domain($udom,'primary'))) {
 1676:                 $uhome=&domain($udom,'primary');
 1677:             }
 1678:         }
 1679:     }
 1680:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1681:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 1682:         my %returnhash;
 1683:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 1684:             return %returnhash;
 1685:         }
 1686:         my @pairs=split(/\&/,$rep);
 1687:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1688:             return @pairs;
 1689:         }
 1690:         my $i=0;
 1691:         foreach my $item (@$storearr) {
 1692:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 1693:             $i++;
 1694:         }
 1695:         return %returnhash;
 1696:     } else {
 1697:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1698:     }
 1699: }
 1700: 
 1701: # -------------------------------------------- put items in domain db files 
 1702: 
 1703: sub put_dom {
 1704:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1705:     if (!$udom) {
 1706:         $udom=$env{'user.domain'};
 1707:         if (defined(&domain($udom,'primary'))) {
 1708:             $uhome=&domain($udom,'primary');
 1709:         } else {
 1710:             undef($uhome);
 1711:         }
 1712:     } else {
 1713:         if (!$uhome) {
 1714:             if (defined(&domain($udom,'primary'))) {
 1715:                 $uhome=&domain($udom,'primary');
 1716:             }
 1717:         }
 1718:     } 
 1719:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1720:         my $items='';
 1721:         foreach my $item (keys(%$storehash)) {
 1722:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 1723:         }
 1724:         $items=~s/\&$//;
 1725:         return &reply("putdom:$udom:$namespace:$items",$uhome);
 1726:     } else {
 1727:         &logthis("put_dom failed - no homeserver and/or domain");
 1728:     }
 1729: }
 1730: 
 1731: # --------------------- newput for items in db file owned by domainconfig user
 1732: sub newput_dom {
 1733:     my ($namespace,$storehash,$udom) = @_;
 1734:     my $result;
 1735:     if (!$udom) {
 1736:         $udom=$env{'user.domain'};
 1737:     }
 1738:     if ($udom) {
 1739:         my $uname = &get_domainconfiguser($udom);
 1740:         $result = &newput($namespace,$storehash,$udom,$uname);
 1741:     }
 1742:     return $result;
 1743: }
 1744: 
 1745: # --------------------- delete for items in db file owned by domainconfig user
 1746: sub del_dom {
 1747:     my ($namespace,$storearr,$udom)=@_;
 1748:     if (ref($storearr) eq 'ARRAY') {
 1749:         if (!$udom) {
 1750:             $udom=$env{'user.domain'};
 1751:         }
 1752:         if ($udom) {
 1753:             my $uname = &get_domainconfiguser($udom); 
 1754:             return &del($namespace,$storearr,$udom,$uname);
 1755:         }
 1756:     }
 1757: }
 1758: 
 1759: # ----------------------------------construct domainconfig user for a domain 
 1760: sub get_domainconfiguser {
 1761:     my ($udom) = @_;
 1762:     return $udom.'-domainconfig';
 1763: }
 1764: 
 1765: sub retrieve_inst_usertypes {
 1766:     my ($udom) = @_;
 1767:     my (%returnhash,@order);
 1768:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 1769:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 1770:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 1771:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
 1772:     } else {
 1773:         if (defined(&domain($udom,'primary'))) {
 1774:             my $uhome=&domain($udom,'primary');
 1775:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 1776:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 1777:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
 1778:                 return (\%returnhash,\@order);
 1779:             }
 1780:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 1781:             my @pairs=split(/\&/,$hashitems);
 1782:             foreach my $item (@pairs) {
 1783:                 my ($key,$value)=split(/=/,$item,2);
 1784:                 $key = &unescape($key);
 1785:                 next if ($key =~ /^error: 2 /);
 1786:                 $returnhash{$key}=&thaw_unescape($value);
 1787:             }
 1788:             my @esc_order = split(/\&/,$orderitems);
 1789:             foreach my $item (@esc_order) {
 1790:                 push(@order,&unescape($item));
 1791:             }
 1792:         } else {
 1793:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
 1794:         }
 1795:         return (\%returnhash,\@order);
 1796:     }
 1797: }
 1798: 
 1799: sub is_domainimage {
 1800:     my ($url) = @_;
 1801:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1802:         if (&domain($1) ne '') {
 1803:             return '1';
 1804:         }
 1805:     }
 1806:     return;
 1807: }
 1808: 
 1809: sub inst_directory_query {
 1810:     my ($srch) = @_;
 1811:     my $udom = $srch->{'srchdomain'};
 1812:     my %results;
 1813:     my $homeserver = &domain($udom,'primary');
 1814:     my $outcome;
 1815:     if ($homeserver ne '') {
 1816: 	my $queryid=&reply("querysend:instdirsearch:".
 1817: 			   &escape($srch->{'srchby'}).':'.
 1818: 			   &escape($srch->{'srchterm'}).':'.
 1819: 			   &escape($srch->{'srchtype'}),$homeserver);
 1820: 	my $host=&hostname($homeserver);
 1821: 	if ($queryid !~/^\Q$host\E\_/) {
 1822: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1823: 	    return;
 1824: 	}
 1825: 	my $response = &get_query_reply($queryid);
 1826: 	my $maxtries = 5;
 1827: 	my $tries = 1;
 1828: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1829: 	    $response = &get_query_reply($queryid);
 1830: 	    $tries ++;
 1831: 	}
 1832: 
 1833:         if (!&error($response) && $response ne 'refused') {
 1834:             if ($response eq 'unavailable') {
 1835:                 $outcome = $response;
 1836:             } else {
 1837:                 $outcome = 'ok';
 1838:                 my @matches = split(/\n/,$response);
 1839:                 foreach my $match (@matches) {
 1840:                     my ($key,$value) = split(/=/,$match);
 1841:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1842:                 }
 1843:             }
 1844:         }
 1845:     }
 1846:     return ($outcome,%results);
 1847: }
 1848: 
 1849: sub usersearch {
 1850:     my ($srch) = @_;
 1851:     my $dom = $srch->{'srchdomain'};
 1852:     my %results;
 1853:     my %libserv = &all_library();
 1854:     my $query = 'usersearch';
 1855:     foreach my $tryserver (keys(%libserv)) {
 1856:         if (&host_domain($tryserver) eq $dom) {
 1857:             my $host=&hostname($tryserver);
 1858:             my $queryid=
 1859:                 &reply("querysend:".&escape($query).':'.
 1860:                        &escape($srch->{'srchby'}).':'.
 1861:                        &escape($srch->{'srchtype'}).':'.
 1862:                        &escape($srch->{'srchterm'}),$tryserver);
 1863:             if ($queryid !~/^\Q$host\E\_/) {
 1864:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1865:                 next;
 1866:             }
 1867:             my $reply = &get_query_reply($queryid);
 1868:             my $maxtries = 1;
 1869:             my $tries = 1;
 1870:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1871:                 $reply = &get_query_reply($queryid);
 1872:                 $tries ++;
 1873:             }
 1874:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1875:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1876:             } else {
 1877:                 my @matches;
 1878:                 if ($reply =~ /\n/) {
 1879:                     @matches = split(/\n/,$reply);
 1880:                 } else {
 1881:                     @matches = split(/\&/,$reply);
 1882:                 }
 1883:                 foreach my $match (@matches) {
 1884:                     my ($uname,$udom,%userhash);
 1885:                     foreach my $entry (split(/:/,$match)) {
 1886:                         my ($key,$value) =
 1887:                             map {&unescape($_);} split(/=/,$entry);
 1888:                         $userhash{$key} = $value;
 1889:                         if ($key eq 'username') {
 1890:                             $uname = $value;
 1891:                         } elsif ($key eq 'domain') {
 1892:                             $udom = $value;
 1893:                         }
 1894:                     }
 1895:                     $results{$uname.':'.$udom} = \%userhash;
 1896:                 }
 1897:             }
 1898:         }
 1899:     }
 1900:     return %results;
 1901: }
 1902: 
 1903: sub get_instuser {
 1904:     my ($udom,$uname,$id) = @_;
 1905:     my $homeserver = &domain($udom,'primary');
 1906:     my ($outcome,%results);
 1907:     if ($homeserver ne '') {
 1908:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1909:                            &escape($id).':'.&escape($udom),$homeserver);
 1910:         my $host=&hostname($homeserver);
 1911:         if ($queryid !~/^\Q$host\E\_/) {
 1912:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1913:             return;
 1914:         }
 1915:         my $response = &get_query_reply($queryid);
 1916:         my $maxtries = 5;
 1917:         my $tries = 1;
 1918:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1919:             $response = &get_query_reply($queryid);
 1920:             $tries ++;
 1921:         }
 1922:         if (!&error($response) && $response ne 'refused') {
 1923:             if ($response eq 'unavailable') {
 1924:                 $outcome = $response;
 1925:             } else {
 1926:                 $outcome = 'ok';
 1927:                 my @matches = split(/\n/,$response);
 1928:                 foreach my $match (@matches) {
 1929:                     my ($key,$value) = split(/=/,$match);
 1930:                     $results{&unescape($key)} = &thaw_unescape($value);
 1931:                 }
 1932:             }
 1933:         }
 1934:     }
 1935:     my %userinfo;
 1936:     if (ref($results{$uname}) eq 'HASH') {
 1937:         %userinfo = %{$results{$uname}};
 1938:     } 
 1939:     return ($outcome,%userinfo);
 1940: }
 1941: 
 1942: sub get_multiple_instusers {
 1943:     my ($udom,$users,$caller) = @_;
 1944:     my ($outcome,$results);
 1945:     if (ref($users) eq 'HASH') {
 1946:         my $count = keys(%{$users}); 
 1947:         my $requested = &freeze_escape($users);
 1948:         my $homeserver = &domain($udom,'primary');
 1949:         if ($homeserver ne '') {
 1950:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
 1951:             my $host=&hostname($homeserver);
 1952:             if ($queryid !~/^\Q$host\E\_/) {
 1953:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
 1954:                          ' for host: '.$homeserver.'in domain '.$udom);
 1955:                 return ($outcome,$results);
 1956:             }
 1957:             my $response = &get_query_reply($queryid);
 1958:             my $maxtries = 5;
 1959:             if ($count > 100) {
 1960:                 $maxtries = 1+int($count/20);
 1961:             }
 1962:             my $tries = 1;
 1963:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
 1964:                 $response = &get_query_reply($queryid);
 1965:                 $tries ++;
 1966:             }
 1967:             if ($response eq '') {
 1968:                 $results = {};
 1969:                 foreach my $key (keys(%{$users})) {
 1970:                     my ($uname,$id);
 1971:                     if ($caller eq 'id') {
 1972:                         $id = $key;
 1973:                     } else {
 1974:                         $uname = $key;
 1975:                     }
 1976:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
 1977:                     $outcome = $resp;
 1978:                     if ($resp eq 'ok') {
 1979:                         %{$results} = (%{$results}, %info);
 1980:                     } else {
 1981:                         last;
 1982:                     }
 1983:                 }
 1984:             } elsif(!&error($response) && ($response ne 'refused')) {
 1985:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
 1986:                     $outcome = $response;
 1987:                 } else {
 1988:                     ($outcome,my $userdata) = split(/=/,$response,2);
 1989:                     if ($outcome eq 'ok') {
 1990:                         $results = &thaw_unescape($userdata); 
 1991:                     }
 1992:                 }
 1993:             }
 1994:         }
 1995:     }
 1996:     return ($outcome,$results);
 1997: }
 1998: 
 1999: sub inst_rulecheck {
 2000:     my ($udom,$uname,$id,$item,$rules) = @_;
 2001:     my %returnhash;
 2002:     if ($udom ne '') {
 2003:         if (ref($rules) eq 'ARRAY') {
 2004:             @{$rules} = map {&escape($_);} (@{$rules});
 2005:             my $rulestr = join(':',@{$rules});
 2006:             my $homeserver=&domain($udom,'primary');
 2007:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2008:                 my $response;
 2009:                 if ($item eq 'username') {                
 2010:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 2011:                                               ':'.&escape($uname).':'.$rulestr,
 2012:                                               $homeserver));
 2013:                 } elsif ($item eq 'id') {
 2014:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 2015:                                               ':'.&escape($id).':'.$rulestr,
 2016:                                               $homeserver));
 2017:                 } elsif ($item eq 'selfcreate') {
 2018:                     $response=&unescape(&reply('instselfcreatecheck:'.
 2019:                                                &escape($udom).':'.&escape($uname).
 2020:                                               ':'.$rulestr,$homeserver));
 2021:                 }
 2022:                 if ($response ne 'refused') {
 2023:                     my @pairs=split(/\&/,$response);
 2024:                     foreach my $item (@pairs) {
 2025:                         my ($key,$value)=split(/=/,$item,2);
 2026:                         $key = &unescape($key);
 2027:                         next if ($key =~ /^error: 2 /);
 2028:                         $returnhash{$key}=&thaw_unescape($value);
 2029:                     }
 2030:                 }
 2031:             }
 2032:         }
 2033:     }
 2034:     return %returnhash;
 2035: }
 2036: 
 2037: sub inst_userrules {
 2038:     my ($udom,$check) = @_;
 2039:     my (%ruleshash,@ruleorder);
 2040:     if ($udom ne '') {
 2041:         my $homeserver=&domain($udom,'primary');
 2042:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 2043:             my $response;
 2044:             if ($check eq 'id') {
 2045:                 $response=&reply('instidrules:'.&escape($udom),
 2046:                                  $homeserver);
 2047:             } elsif ($check eq 'email') {
 2048:                 $response=&reply('instemailrules:'.&escape($udom),
 2049:                                  $homeserver);
 2050:             } else {
 2051:                 $response=&reply('instuserrules:'.&escape($udom),
 2052:                                  $homeserver);
 2053:             }
 2054:             if (($response ne 'refused') && ($response ne 'error') && 
 2055:                 ($response ne 'unknown_cmd') && 
 2056:                 ($response ne 'no_such_host')) {
 2057:                 my ($hashitems,$orderitems) = split(/:/,$response);
 2058:                 my @pairs=split(/\&/,$hashitems);
 2059:                 foreach my $item (@pairs) {
 2060:                     my ($key,$value)=split(/=/,$item,2);
 2061:                     $key = &unescape($key);
 2062:                     next if ($key =~ /^error: 2 /);
 2063:                     $ruleshash{$key}=&thaw_unescape($value);
 2064:                 }
 2065:                 my @esc_order = split(/\&/,$orderitems);
 2066:                 foreach my $item (@esc_order) {
 2067:                     push(@ruleorder,&unescape($item));
 2068:                 }
 2069:             }
 2070:         }
 2071:     }
 2072:     return (\%ruleshash,\@ruleorder);
 2073: }
 2074: 
 2075: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 2076: 
 2077: sub get_domain_defaults {
 2078:     my ($domain,$ignore_cache) = @_;
 2079:     return if (($domain eq '') || ($domain eq 'public'));
 2080:     my $cachetime = 60*60*24;
 2081:     unless ($ignore_cache) {
 2082:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 2083:         if (defined($cached)) {
 2084:             if (ref($result) eq 'HASH') {
 2085:                 return %{$result};
 2086:             }
 2087:         }
 2088:     }
 2089:     my %domdefaults;
 2090:     my %domconfig =
 2091:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 2092:                                   'requestcourses','inststatus',
 2093:                                   'coursedefaults','usersessions',
 2094:                                   'requestauthor','selfenrollment',
 2095:                                   'coursecategories'],$domain);
 2096:     my @coursetypes = ('official','unofficial','community','textbook');
 2097:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2098:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2099:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2100:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2101:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2102:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2103:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2104:     } else {
 2105:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2106:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2107:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2108:     }
 2109:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2110:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2111:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2112:         } else {
 2113:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2114:         }
 2115:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2116:         foreach my $item (@usertools) {
 2117:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2118:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2119:             }
 2120:         }
 2121:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2122:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2123:         }
 2124:     }
 2125:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2126:         foreach my $item ('official','unofficial','community','textbook') {
 2127:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2128:         }
 2129:     }
 2130:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2131:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2132:     }
 2133:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2134:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
 2135:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2136:         }
 2137:     }
 2138:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2139:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
 2140:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
 2141:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
 2142:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
 2143:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
 2144:         }
 2145:         foreach my $type (@coursetypes) {
 2146:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2147:                 unless ($type eq 'community') {
 2148:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
 2149:                 }
 2150:             }
 2151:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2152:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
 2153:             }
 2154:             if ($domdefaults{'postsubmit'} eq 'on') {
 2155:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
 2156:                     $domdefaults{$type.'postsubtimeout'} = 
 2157:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
 2158:                 }
 2159:             }
 2160:         }
 2161:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
 2162:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
 2163:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
 2164:                 if (@clonecodes) {
 2165:                     $domdefaults{'canclone'} = join('+',@clonecodes);
 2166:                 }
 2167:             }
 2168:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
 2169:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
 2170:         }
 2171:     }
 2172:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2173:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2174:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2175:         }
 2176:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2177:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2178:         }
 2179:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
 2180:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
 2181:         }
 2182:     }
 2183:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
 2184:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
 2185:             my @settings = ('types','registered','enroll_dates','access_dates','section',
 2186:                             'approval','limit');
 2187:             foreach my $type (@coursetypes) {
 2188:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
 2189:                     my @mgrdc = ();
 2190:                     foreach my $item (@settings) {
 2191:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
 2192:                             push(@mgrdc,$item);
 2193:                         }
 2194:                     }
 2195:                     if (@mgrdc) {
 2196:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
 2197:                     }
 2198:                 }
 2199:             }
 2200:         }
 2201:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
 2202:             foreach my $type (@coursetypes) {
 2203:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
 2204:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
 2205:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
 2206:                     }
 2207:                 }
 2208:             }
 2209:         }
 2210:     }
 2211:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2212:         $domdefaults{'catauth'} = 'std';
 2213:         $domdefaults{'catunauth'} = 'std';
 2214:         if ($domconfig{'coursecategories'}{'auth'}) { 
 2215:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
 2216:         }
 2217:         if ($domconfig{'coursecategories'}{'unauth'}) {
 2218:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
 2219:         }
 2220:     }
 2221:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2222:     return %domdefaults;
 2223: }
 2224: 
 2225: # --------------------------------------------------- Assign a key to a student
 2226: 
 2227: sub assign_access_key {
 2228: #
 2229: # a valid key looks like uname:udom#comments
 2230: # comments are being appended
 2231: #
 2232:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2233:     $kdom=
 2234:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2235:     $knum=
 2236:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2237:     $cdom=
 2238:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2239:     $cnum=
 2240:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2241:     $udom=$env{'user.name'} unless (defined($udom));
 2242:     $uname=$env{'user.domain'} unless (defined($uname));
 2243:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2244:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2245:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2246:                                                   # assigned to this person
 2247:                                                   # - this should not happen,
 2248:                                                   # unless something went wrong
 2249:                                                   # the first time around
 2250: # ready to assign
 2251:         $logentry=$1.'; '.$logentry;
 2252:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2253:                                                  $kdom,$knum) eq 'ok') {
 2254: # key now belongs to user
 2255: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2256:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2257:                 &appenv({'environment.'.$envkey => $ckey});
 2258:                 return 'ok';
 2259:             } else {
 2260:                 return 
 2261:   'error: Count not permanently assign key, will need to be re-entered later.';
 2262: 	    }
 2263:         } else {
 2264:             return 'error: Could not assign key, try again later.';
 2265:         }
 2266:     } elsif (!$existing{$ckey}) {
 2267: # the key does not exist
 2268: 	return 'error: The key does not exist';
 2269:     } else {
 2270: # the key is somebody else's
 2271: 	return 'error: The key is already in use';
 2272:     }
 2273: }
 2274: 
 2275: # ------------------------------------------ put an additional comment on a key
 2276: 
 2277: sub comment_access_key {
 2278: #
 2279: # a valid key looks like uname:udom#comments
 2280: # comments are being appended
 2281: #
 2282:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2283:     $cdom=
 2284:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2285:     $cnum=
 2286:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2287:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2288:     if ($existing{$ckey}) {
 2289:         $existing{$ckey}.='; '.$logentry;
 2290: # ready to assign
 2291:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2292:                                                  $cdom,$cnum) eq 'ok') {
 2293: 	    return 'ok';
 2294:         } else {
 2295: 	    return 'error: Count not store comment.';
 2296:         }
 2297:     } else {
 2298: # the key does not exist
 2299: 	return 'error: The key does not exist';
 2300:     }
 2301: }
 2302: 
 2303: # ------------------------------------------------------ Generate a set of keys
 2304: 
 2305: sub generate_access_keys {
 2306:     my ($number,$cdom,$cnum,$logentry)=@_;
 2307:     $cdom=
 2308:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2309:     $cnum=
 2310:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2311:     unless (&allowed('mky',$cdom)) { return 0; }
 2312:     unless (($cdom) && ($cnum)) { return 0; }
 2313:     if ($number>10000) { return 0; }
 2314:     sleep(2); # make sure don't get same seed twice
 2315:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2316:     my $total=0;
 2317:     for (my $i=1;$i<=$number;$i++) {
 2318:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2319:                   sprintf("%lx",int(100000*rand)).'-'.
 2320:                   sprintf("%lx",int(100000*rand));
 2321:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2322:        $newkey=~s/0/h/g; # and also 0 and O
 2323:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2324:        if ($existing{$newkey}) {
 2325:            $i--;
 2326:        } else {
 2327: 	  if (&put('accesskeys',
 2328:               { $newkey => '# generated '.localtime().
 2329:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2330:                            '; '.$logentry },
 2331: 		   $cdom,$cnum) eq 'ok') {
 2332:               $total++;
 2333: 	  }
 2334:        }
 2335:     }
 2336:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2337:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2338:     return $total;
 2339: }
 2340: 
 2341: # ------------------------------------------------------- Validate an accesskey
 2342: 
 2343: sub validate_access_key {
 2344:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2345:     $cdom=
 2346:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2347:     $cnum=
 2348:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2349:     $udom=$env{'user.domain'} unless (defined($udom));
 2350:     $uname=$env{'user.name'} unless (defined($uname));
 2351:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2352:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2353: }
 2354: 
 2355: # ------------------------------------- Find the section of student in a course
 2356: sub devalidate_getsection_cache {
 2357:     my ($udom,$unam,$courseid)=@_;
 2358:     my $hashid="$udom:$unam:$courseid";
 2359:     &devalidate_cache_new('getsection',$hashid);
 2360: }
 2361: 
 2362: sub courseid_to_courseurl {
 2363:     my ($courseid) = @_;
 2364:     #already url style courseid
 2365:     return $courseid if ($courseid =~ m{^/});
 2366: 
 2367:     if (exists($env{'course.'.$courseid.'.num'})) {
 2368: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2369: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2370: 	return "/$cdom/$cnum";
 2371:     }
 2372: 
 2373:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2374:     if (exists($courseinfo{'num'})) {
 2375: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2376:     }
 2377: 
 2378:     return undef;
 2379: }
 2380: 
 2381: sub getsection {
 2382:     my ($udom,$unam,$courseid)=@_;
 2383:     my $cachetime=1800;
 2384: 
 2385:     my $hashid="$udom:$unam:$courseid";
 2386:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2387:     if (defined($cached)) { return $result; }
 2388: 
 2389:     my %Pending; 
 2390:     my %Expired;
 2391:     #
 2392:     # Each role can either have not started yet (pending), be active, 
 2393:     #    or have expired.
 2394:     #
 2395:     # If there is an active role, we are done.
 2396:     #
 2397:     # If there is more than one role which has not started yet, 
 2398:     #     choose the one which will start sooner
 2399:     # If there is one role which has not started yet, return it.
 2400:     #
 2401:     # If there is more than one expired role, choose the one which ended last.
 2402:     # If there is a role which has expired, return it.
 2403:     #
 2404:     $courseid = &courseid_to_courseurl($courseid);
 2405:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 2406:     foreach my $key (keys(%roleshash)) {
 2407:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2408:         my $section=$1;
 2409:         if ($key eq $courseid.'_st') { $section=''; }
 2410:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2411:         my $now=time;
 2412:         if (defined($end) && $end && ($now > $end)) {
 2413:             $Expired{$end}=$section;
 2414:             next;
 2415:         }
 2416:         if (defined($start) && $start && ($now < $start)) {
 2417:             $Pending{$start}=$section;
 2418:             next;
 2419:         }
 2420:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2421:     }
 2422:     #
 2423:     # Presumedly there will be few matching roles from the above
 2424:     # loop and the sorting time will be negligible.
 2425:     if (scalar(keys(%Pending))) {
 2426:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2427:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2428:     } 
 2429:     if (scalar(keys(%Expired))) {
 2430:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2431:         my $time = pop(@sorted);
 2432:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2433:     }
 2434:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2435: }
 2436: 
 2437: sub save_cache {
 2438:     &purge_remembered();
 2439:     #&Apache::loncommon::validate_page();
 2440:     undef(%env);
 2441:     undef($env_loaded);
 2442: }
 2443: 
 2444: my $to_remember=-1;
 2445: my %remembered;
 2446: my %accessed;
 2447: my $kicks=0;
 2448: my $hits=0;
 2449: sub make_key {
 2450:     my ($name,$id) = @_;
 2451:     if (length($id) > 65 
 2452: 	&& length(&escape($id)) > 200) {
 2453: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2454:     }
 2455:     return &escape($name.':'.$id);
 2456: }
 2457: 
 2458: sub devalidate_cache_new {
 2459:     my ($name,$id,$debug) = @_;
 2460:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2461:     $id=&make_key($name,$id);
 2462:     $memcache->delete($id);
 2463:     delete($remembered{$id});
 2464:     delete($accessed{$id});
 2465: }
 2466: 
 2467: sub is_cached_new {
 2468:     my ($name,$id,$debug) = @_;
 2469:     $id=&make_key($name,$id);
 2470:     if (exists($remembered{$id})) {
 2471: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
 2472: 	$accessed{$id}=[&gettimeofday()];
 2473: 	$hits++;
 2474: 	return ($remembered{$id},1);
 2475:     }
 2476:     my $value = $memcache->get($id);
 2477:     if (!(defined($value))) {
 2478: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2479: 	return (undef,undef);
 2480:     }
 2481:     if ($value eq '__undef__') {
 2482: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2483: 	$value=undef;
 2484:     }
 2485:     &make_room($id,$value,$debug);
 2486:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2487:     return ($value,1);
 2488: }
 2489: 
 2490: sub do_cache_new {
 2491:     my ($name,$id,$value,$time,$debug) = @_;
 2492:     $id=&make_key($name,$id);
 2493:     my $setvalue=$value;
 2494:     if (!defined($setvalue)) {
 2495: 	$setvalue='__undef__';
 2496:     }
 2497:     if (!defined($time) ) {
 2498: 	$time=600;
 2499:     }
 2500:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 2501:     my $result = $memcache->set($id,$setvalue,$time);
 2502:     if (! $result) {
 2503: 	&logthis("caching of id -> $id  failed");
 2504: 	$memcache->disconnect_all();
 2505:     }
 2506:     # need to make a copy of $value
 2507:     &make_room($id,$value,$debug);
 2508:     return $value;
 2509: }
 2510: 
 2511: sub make_room {
 2512:     my ($id,$value,$debug)=@_;
 2513: 
 2514:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 2515:                                     : $value;
 2516:     if ($to_remember<0) { return; }
 2517:     $accessed{$id}=[&gettimeofday()];
 2518:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 2519:     my $to_kick;
 2520:     my $max_time=0;
 2521:     foreach my $other (keys(%accessed)) {
 2522: 	if (&tv_interval($accessed{$other}) > $max_time) {
 2523: 	    $to_kick=$other;
 2524: 	    $max_time=&tv_interval($accessed{$other});
 2525: 	}
 2526:     }
 2527:     delete($remembered{$to_kick});
 2528:     delete($accessed{$to_kick});
 2529:     $kicks++;
 2530:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 2531:     return;
 2532: }
 2533: 
 2534: sub purge_remembered {
 2535:     #&logthis("Tossing ".scalar(keys(%remembered)));
 2536:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 2537:     undef(%remembered);
 2538:     undef(%accessed);
 2539: }
 2540: # ------------------------------------- Read an entry from a user's environment
 2541: 
 2542: sub userenvironment {
 2543:     my ($udom,$unam,@what)=@_;
 2544:     my $items;
 2545:     foreach my $item (@what) {
 2546:         $items.=&escape($item).'&';
 2547:     }
 2548:     $items=~s/\&$//;
 2549:     my %returnhash=();
 2550:     my $uhome = &homeserver($unam,$udom);
 2551:     unless ($uhome eq 'no_host') {
 2552:         my @answer=split(/\&/, 
 2553:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 2554:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 2555:             return %returnhash;
 2556:         }
 2557:         my $i;
 2558:         for ($i=0;$i<=$#what;$i++) {
 2559: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 2560:         }
 2561:     }
 2562:     return %returnhash;
 2563: }
 2564: 
 2565: # ---------------------------------------------------------- Get a studentphoto
 2566: sub studentphoto {
 2567:     my ($udom,$unam,$ext) = @_;
 2568:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2569:     if (defined($env{'request.course.id'})) {
 2570:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 2571:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 2572:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 2573:             } else {
 2574:                 my ($result,$perm_reqd)=
 2575: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2576:                 if ($result eq 'ok') {
 2577:                     if (!($perm_reqd eq 'yes')) {
 2578:                         return(&retrievestudentphoto($udom,$unam,$ext));
 2579:                     }
 2580:                 }
 2581:             }
 2582:         }
 2583:     } else {
 2584:         my ($result,$perm_reqd) = 
 2585: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2586:         if ($result eq 'ok') {
 2587:             if (!($perm_reqd eq 'yes')) {
 2588:                 return(&retrievestudentphoto($udom,$unam,$ext));
 2589:             }
 2590:         }
 2591:     }
 2592:     return '/adm/lonKaputt/lonlogo_broken.gif';
 2593: }
 2594: 
 2595: sub retrievestudentphoto {
 2596:     my ($udom,$unam,$ext,$type) = @_;
 2597:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2598:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 2599:     if ($ret eq 'ok') {
 2600:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 2601:         if ($type eq 'thumbnail') {
 2602:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 2603:         }
 2604:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 2605:         return $tokenurl;
 2606:     } else {
 2607:         if ($type eq 'thumbnail') {
 2608:             return '/adm/lonKaputt/genericstudent_tn.gif';
 2609:         } else { 
 2610:             return '/adm/lonKaputt/lonlogo_broken.gif';
 2611:         }
 2612:     }
 2613: }
 2614: 
 2615: # -------------------------------------------------------------------- New chat
 2616: 
 2617: sub chatsend {
 2618:     my ($newentry,$anon,$group)=@_;
 2619:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 2620:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2621:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 2622:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 2623: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 2624: 		   &escape($newentry)).':'.$group,$chome);
 2625: }
 2626: 
 2627: # ------------------------------------------ Find current version of a resource
 2628: 
 2629: sub getversion {
 2630:     my $fname=&clutter(shift);
 2631:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 2632:     return &currentversion(&filelocation('',$fname));
 2633: }
 2634: 
 2635: sub currentversion {
 2636:     my $fname=shift;
 2637:     my $author=$fname;
 2638:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2639:     my ($udom,$uname)=split(/\//,$author);
 2640:     my $home=&homeserver($uname,$udom);
 2641:     if ($home eq 'no_host') { 
 2642:         return -1; 
 2643:     }
 2644:     my $answer=&reply("currentversion:$fname",$home);
 2645:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2646: 	return -1;
 2647:     }
 2648:     return $answer;
 2649: }
 2650: 
 2651: #
 2652: # Return special version number of resource if set by override, empty otherwise
 2653: #
 2654: sub usedversion {
 2655:     my $fname=shift;
 2656:     unless ($fname) { $fname=$env{'request.uri'}; }
 2657:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 2658:     if ($urlversion) { return $urlversion; }
 2659:     return '';
 2660: }
 2661: 
 2662: # ----------------------------- Subscribe to a resource, return URL if possible
 2663: 
 2664: sub subscribe {
 2665:     my $fname=shift;
 2666:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 2667:     $fname=~s/[\n\r]//g;
 2668:     my $author=$fname;
 2669:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2670:     my ($udom,$uname)=split(/\//,$author);
 2671:     my $home=homeserver($uname,$udom);
 2672:     if ($home eq 'no_host') {
 2673:         return 'not_found';
 2674:     }
 2675:     my $answer=reply("sub:$fname",$home);
 2676:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2677: 	$answer.=' by '.$home;
 2678:     }
 2679:     return $answer;
 2680: }
 2681:     
 2682: # -------------------------------------------------------------- Replicate file
 2683: 
 2684: sub repcopy {
 2685:     my $filename=shift;
 2686:     $filename=~s/\/+/\//g;
 2687:     my $londocroot = $perlvar{'lonDocRoot'};
 2688:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 2689:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 2690:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 2691: 	$filename=~m{^/*(uploaded|editupload)/}) {
 2692: 	return &repcopy_userfile($filename);
 2693:     }
 2694:     $filename=~s/[\n\r]//g;
 2695:     my $transname="$filename.in.transfer";
 2696: # FIXME: this should flock
 2697:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 2698:     my $remoteurl=subscribe($filename);
 2699:     if ($remoteurl =~ /^con_lost by/) {
 2700: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2701:            return 'unavailable';
 2702:     } elsif ($remoteurl eq 'not_found') {
 2703: 	   #&logthis("Subscribe returned not_found: $filename");
 2704: 	   return 'not_found';
 2705:     } elsif ($remoteurl =~ /^rejected by/) {
 2706: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2707:            return 'forbidden';
 2708:     } elsif ($remoteurl eq 'directory') {
 2709:            return 'ok';
 2710:     } else {
 2711:         my $author=$filename;
 2712:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2713:         my ($udom,$uname)=split(/\//,$author);
 2714:         my $home=homeserver($uname,$udom);
 2715:         unless ($home eq $perlvar{'lonHostID'}) {
 2716:            my @parts=split(/\//,$filename);
 2717:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 2718:            if ($path ne "$londocroot/res") {
 2719:                &logthis("Malconfiguration for replication: $filename");
 2720: 	       return 'bad_request';
 2721:            }
 2722:            my $count;
 2723:            for ($count=5;$count<$#parts;$count++) {
 2724:                $path.="/$parts[$count]";
 2725:                if ((-e $path)!=1) {
 2726: 		   mkdir($path,0777);
 2727:                }
 2728:            }
 2729:            my $ua=new LWP::UserAgent;
 2730:            my $request=new HTTP::Request('GET',"$remoteurl");
 2731:            my $response=$ua->request($request,$transname);
 2732:            if ($response->is_error()) {
 2733: 	       unlink($transname);
 2734:                my $message=$response->status_line;
 2735:                &logthis("<font color=\"blue\">WARNING:"
 2736:                        ." LWP get: $message: $filename</font>");
 2737:                return 'unavailable';
 2738:            } else {
 2739: 	       if ($remoteurl!~/\.meta$/) {
 2740:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 2741:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 2742:                   if ($mresponse->is_error()) {
 2743: 		      unlink($filename.'.meta');
 2744:                       &logthis(
 2745:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 2746:                   }
 2747: 	       }
 2748:                rename($transname,$filename);
 2749:                return 'ok';
 2750:            }
 2751:        }
 2752:     }
 2753: }
 2754: 
 2755: # ------------------------------------------------ Get server side include body
 2756: sub ssi_body {
 2757:     my ($filelink,%form)=@_;
 2758:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 2759:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 2760:     }
 2761:     my $output='';
 2762:     my $response;
 2763:     if ($filelink=~/^https?\:/) {
 2764:        ($output,$response)=&externalssi($filelink);
 2765:     } else {
 2766:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 2767:        $filelink .= 'inhibitmenu=yes';
 2768:        ($output,$response)=&ssi($filelink,%form);
 2769:     }
 2770:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 2771:     $output=~s/^.*?\<body[^\>]*\>//si;
 2772:     $output=~s/\<\/body\s*\>.*?$//si;
 2773:     if (wantarray) {
 2774:         return ($output, $response);
 2775:     } else {
 2776:         return $output;
 2777:     }
 2778: }
 2779: 
 2780: # --------------------------------------------------------- Server Side Include
 2781: 
 2782: sub absolute_url {
 2783:     my ($host_name) = @_;
 2784:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 2785:     if ($host_name eq '') {
 2786: 	$host_name = $ENV{'SERVER_NAME'};
 2787:     }
 2788:     return $protocol.$host_name;
 2789: }
 2790: 
 2791: #
 2792: #   Server side include.
 2793: # Parameters:
 2794: #  fn     Possibly encrypted resource name/id.
 2795: #  form   Hash that describes how the rendering should be done
 2796: #         and other things.
 2797: # Returns:
 2798: #   Scalar context: The content of the response.
 2799: #   Array context:  2 element list of the content and the full response object.
 2800: #     
 2801: sub ssi {
 2802: 
 2803:     my ($fn,%form)=@_;
 2804:     my $ua=new LWP::UserAgent;
 2805:     my $request;
 2806: 
 2807:     $form{'no_update_last_known'}=1;
 2808:     &Apache::lonenc::check_encrypt(\$fn);
 2809:     if (%form) {
 2810:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 2811:       $request->content(join('&',map { 
 2812:             my $name = escape($_);
 2813:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
 2814:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
 2815:             : &escape($form{$_}) );    
 2816:         } keys(%form)));
 2817:     } else {
 2818:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 2819:     }
 2820: 
 2821:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 2822:     my $response= $ua->request($request);
 2823:     my $content = $response->content;
 2824: 
 2825: 
 2826:     if (wantarray) {
 2827: 	return ($content, $response);
 2828:     } else {
 2829: 	return $content;
 2830:     }
 2831: }
 2832: 
 2833: sub externalssi {
 2834:     my ($url)=@_;
 2835:     my $ua=new LWP::UserAgent;
 2836:     my $request=new HTTP::Request('GET',$url);
 2837:     my $response=$ua->request($request);
 2838:     if (wantarray) {
 2839:         return ($response->content, $response);
 2840:     } else {
 2841:         return $response->content;
 2842:     }
 2843: }
 2844: 
 2845: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 2846: 
 2847: sub allowuploaded {
 2848:     my ($srcurl,$url)=@_;
 2849:     $url=&clutter(&declutter($url));
 2850:     my $dir=$url;
 2851:     $dir=~s/\/[^\/]+$//;
 2852:     my %httpref=();
 2853:     my $httpurl=&hreflocation('',$url);
 2854:     $httpref{'httpref.'.$httpurl}=$srcurl;
 2855:     &Apache::lonnet::appenv(\%httpref);
 2856: }
 2857: 
 2858: #
 2859: # Determine if the current user should be able to edit a particular resource,
 2860: # when viewing in course context.
 2861: # (a) When viewing resource used to determine if "Edit" item is included in 
 2862: #     Functions.
 2863: # (b) When displaying folder contents in course editor, used to determine if
 2864: #     "Edit" link will be displayed alongside resource.
 2865: #
 2866: #  input: six args -- filename (decluttered), course number, course domain,
 2867: #                   url, symb (if registered) and group (if this is a group
 2868: #                   item -- e.g., bulletin board, group page etc.).
 2869: #  output: array of five scalars -- 
 2870: #          $cfile -- url for file editing if editable on current server
 2871: #          $home -- homeserver of resource (i.e., for author if published,
 2872: #                                           or course if uploaded.).
 2873: #          $switchserver --  1 if server switch will be needed.
 2874: #          $forceedit -- 1 if icon/link should be to go to edit mode 
 2875: #          $forceview -- 1 if icon/link should be to go to view mode
 2876: #
 2877: 
 2878: sub can_edit_resource {
 2879:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 2880:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 2881: #
 2882: # For aboutme pages user can only edit his/her own.
 2883: #
 2884:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 2885:         my ($sdom,$sname) = ($1,$2);
 2886:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 2887:             $home = $env{'user.home'};
 2888:             $cfile = $resurl;
 2889:             if ($env{'form.forceedit'}) {
 2890:                 $forceview = 1;
 2891:             } else {
 2892:                 $forceedit = 1;
 2893:             }
 2894:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 2895:         } else {
 2896:             return;
 2897:         }
 2898:     }
 2899: 
 2900:     if ($env{'request.course.id'}) {
 2901:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 2902:         if ($group ne '') {
 2903: # if this is a group homepage or group bulletin board, check group privs
 2904:             my $allowed = 0;
 2905:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 2906:                 if ((&allowed('mdg',$env{'request.course.id'}.
 2907:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 2908:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 2909:                     $allowed = 1;
 2910:                 }
 2911:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 2912:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 2913:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 2914:                     $allowed = 1;
 2915:                 }
 2916:             }
 2917:             if ($allowed) {
 2918:                 $home=&homeserver($cnum,$cdom);
 2919:                 if ($env{'form.forceedit'}) {
 2920:                     $forceview = 1;
 2921:                 } else {
 2922:                     $forceedit = 1;
 2923:                 }
 2924:                 $cfile = $resurl;
 2925:             } else {
 2926:                 return;
 2927:             }
 2928:         } else {
 2929:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 2930:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 2931:                     return;
 2932:                 }
 2933:             } elsif (!$crsedit) {
 2934: #
 2935: # No edit allowed where CC has switched to student role.
 2936: #
 2937:                 return;
 2938:             }
 2939:         }
 2940:     }
 2941: 
 2942:     if ($file ne '') {
 2943:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 2944:             if (&is_course_upload($file,$cnum,$cdom)) {
 2945:                 $uploaded = 1;
 2946:                 $incourse = 1;
 2947:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 2948:                     $cfile = &hreflocation('',$file);
 2949:                     if ($env{'form.forceedit'}) {
 2950:                         $forceview = 1;
 2951:                     } else {
 2952:                         $forceedit = 1;
 2953:                     }
 2954:                 }
 2955:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 2956:                 $incourse = 1;
 2957:                 if ($env{'form.forceedit'}) {
 2958:                     $forceview = 1;
 2959:                 } else {
 2960:                     $forceedit = 1;
 2961:                 }
 2962:                 $cfile = $resurl;
 2963:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
 2964:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 2965:                     $incourse = 1;
 2966:                     if ($env{'form.forceedit'}) {
 2967:                         $forceview = 1;
 2968:                     } else {
 2969:                         $forceedit = 1;
 2970:                     }
 2971:                     $cfile = $resurl;
 2972:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 2973:                     $incourse = 1;
 2974:                     $cfile = $resurl.'/smpedit';
 2975:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 2976:                     $incourse = 1;
 2977:                     if ($env{'form.forceedit'}) {
 2978:                         $forceview = 1;
 2979:                     } else {
 2980:                         $forceedit = 1;
 2981:                     }
 2982:                     $cfile = $resurl;
 2983:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/exttools?$}) {
 2984:                     $incourse = 1;
 2985:                     if ($env{'form.forceedit'}) {
 2986:                         $forceview = 1;
 2987:                     } else {
 2988:                         $forceedit = 1;
 2989:                     }
 2990:                     $cfile = $resurl;
 2991:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 2992:                     $incourse = 1;
 2993:                     if ($env{'form.forceedit'}) {
 2994:                         $forceview = 1;
 2995:                     } else {
 2996:                         $forceedit = 1;
 2997:                     }
 2998:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 2999:                 }
 3000:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 3001:                 my $template = '/res/lib/templates/simpleproblem.problem';
 3002:                 if (&is_on_map($template)) { 
 3003:                     $incourse = 1;
 3004:                     $forceview = 1;
 3005:                     $cfile = $template;
 3006:                 }
 3007:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3008:                     $incourse = 1;
 3009:                     if ($env{'form.forceedit'}) {
 3010:                         $forceview = 1;
 3011:                     } else {
 3012:                         $forceedit = 1;
 3013:                     }
 3014:                     $cfile = $resurl;
 3015:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/exttools?$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 3016:                 $incourse = 1;
 3017:                 if ($env{'form.forceedit'}) {
 3018:                     $forceview = 1;
 3019:                 } else {
 3020:                     $forceedit = 1;
 3021:                 }
 3022:                 $cfile = $resurl;
 3023:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 3024:                 $incourse = 1;
 3025:                 $forceview = 1;
 3026:                 if ($symb) {
 3027:                     my ($map,$id,$res)=&decode_symb($symb);
 3028:                     $env{'request.symb'} = $symb;
 3029:                     $cfile = &clutter($res);
 3030:                 } else {
 3031:                     $cfile = $env{'form.suppurl'};
 3032:                     my $escfile = &unescape($cfile);
 3033:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/exttools?$}) {
 3034:                         $cfile = '/adm/wrapper'.$escfile;
 3035:                     } else {
 3036:                         $escfile =~ s{^http://}{};
 3037:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
 3038:                     }
 3039:                 }
 3040:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 3041:                 if ($env{'form.forceedit'}) {
 3042:                     $forceview = 1;
 3043:                 } else {
 3044:                     $forceedit = 1;
 3045:                 }
 3046:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 3047:             }
 3048:         }
 3049:         if ($uploaded || $incourse) {
 3050:             $home=&homeserver($cnum,$cdom);
 3051:         } elsif ($file !~ m{/$}) {
 3052:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 3053:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 3054:             # Check that the user has permission to edit this resource
 3055:             my $setpriv = 1;
 3056:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 3057:             if (defined($cfudom)) {
 3058:                 $home=&homeserver($cfuname,$cfudom);
 3059:                 $cfile=$file;
 3060:             }
 3061:         }
 3062:         if (($cfile ne '') && (!$incourse || $uploaded) && 
 3063:             (($home ne '') && ($home ne 'no_host'))) {
 3064:             my @ids=&current_machine_ids();
 3065:             unless (grep(/^\Q$home\E$/,@ids)) {
 3066:                 $switchserver=1;
 3067:             }
 3068:         }
 3069:     }
 3070:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 3071: }
 3072: 
 3073: sub is_course_upload {
 3074:     my ($file,$cnum,$cdom) = @_;
 3075:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 3076:     $uploadpath =~ s{^\/}{};
 3077:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 3078:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 3079:         return 1;
 3080:     }
 3081:     return;
 3082: }
 3083: 
 3084: sub in_course {
 3085:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 3086:     if ($hideprivileged) {
 3087:         my $skipuser;
 3088:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 3089:         my @possdoms = ($cdom);  
 3090:         if ($coursehash{'checkforpriv'}) { 
 3091:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
 3092:         }
 3093:         if (&privileged($uname,$udom,\@possdoms)) {
 3094:             $skipuser = 1;
 3095:             if ($coursehash{'nothideprivileged'}) {
 3096:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3097:                     my $user;
 3098:                     if ($item =~ /:/) {
 3099:                         $user = $item;
 3100:                     } else {
 3101:                         $user = join(':',split(/[\@]/,$item));
 3102:                     }
 3103:                     if ($user eq $uname.':'.$udom) {
 3104:                         undef($skipuser);
 3105:                         last;
 3106:                     }
 3107:                 }
 3108:             }
 3109:             if ($skipuser) {
 3110:                 return 0;
 3111:             }
 3112:         }
 3113:     }
 3114:     $type ||= 'any';
 3115:     if (!defined($cdom) || !defined($cnum)) {
 3116:         my $cid  = $env{'request.course.id'};
 3117:         $cdom = $env{'course.'.$cid.'.domain'};
 3118:         $cnum = $env{'course.'.$cid.'.num'};
 3119:     }
 3120:     my $typesref;
 3121:     if (($type eq 'any') || ($type eq 'all')) {
 3122:         $typesref = ['active','previous','future'];
 3123:     } elsif ($type eq 'previous' || $type eq 'future') {
 3124:         $typesref = [$type];
 3125:     }
 3126:     my %roles = &get_my_roles($uname,$udom,'userroles',
 3127:                               $typesref,undef,[$cdom]);
 3128:     my ($tmp) = keys(%roles);
 3129:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 3130:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 3131:     if (@course_roles > 0) {
 3132:         return 1;
 3133:     }
 3134:     return 0;
 3135: }
 3136: 
 3137: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 3138: # input: action, courseID, current domain, intended
 3139: #        path to file, source of file, instruction to parse file for objects,
 3140: #        ref to hash for embedded objects,
 3141: #        ref to hash for codebase of java objects.
 3142: #        reference to scalar to accommodate mime type determined
 3143: #          from File::MMagic if $parser = parse.
 3144: #
 3145: # output: url to file (if action was uploaddoc), 
 3146: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 3147: #
 3148: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 3149: # course.
 3150: #
 3151: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3152: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 3153: #          course's home server.
 3154: #
 3155: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 3156: #          be copied from $source (current location) to 
 3157: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3158: #         and will then be copied to
 3159: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 3160: #         course's home server.
 3161: #
 3162: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3163: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 3164: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3165: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 3166: #         in course's home server.
 3167: #
 3168: 
 3169: sub process_coursefile {
 3170:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 3171:         $mimetype)=@_;
 3172:     my $fetchresult;
 3173:     my $home=&homeserver($docuname,$docudom);
 3174:     if ($action eq 'propagate') {
 3175:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3176: 			     $home);
 3177:     } else {
 3178:         my $fpath = '';
 3179:         my $fname = $file;
 3180:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3181:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3182:         my $filepath = &build_filepath($fpath);
 3183:         if ($action eq 'copy') {
 3184:             if ($source eq '') {
 3185:                 $fetchresult = 'no source file';
 3186:                 return $fetchresult;
 3187:             } else {
 3188:                 my $destination = $filepath.'/'.$fname;
 3189:                 rename($source,$destination);
 3190:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3191:                                  $home);
 3192:             }
 3193:         } elsif ($action eq 'uploaddoc') {
 3194:             open(my $fh,'>'.$filepath.'/'.$fname);
 3195:             print $fh $env{'form.'.$source};
 3196:             close($fh);
 3197:             if ($parser eq 'parse') {
 3198:                 my $mm = new File::MMagic;
 3199:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 3200:                 if ($type eq 'text/html') {
 3201:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 3202:                     unless ($parse_result eq 'ok') {
 3203:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 3204:                     }
 3205:                 }
 3206:                 if (ref($mimetype)) {
 3207:                     $$mimetype = $type;
 3208:                 } 
 3209:             }
 3210:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3211:                                  $home);
 3212:             if ($fetchresult eq 'ok') {
 3213:                 return '/uploaded/'.$fpath.'/'.$fname;
 3214:             } else {
 3215:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3216:                         ' to host '.$home.': '.$fetchresult);
 3217:                 return '/adm/notfound.html';
 3218:             }
 3219:         }
 3220:     }
 3221:     unless ( $fetchresult eq 'ok') {
 3222:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3223:              ' to host '.$home.': '.$fetchresult);
 3224:     }
 3225:     return $fetchresult;
 3226: }
 3227: 
 3228: sub build_filepath {
 3229:     my ($fpath) = @_;
 3230:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 3231:     unless ($fpath eq '') {
 3232:         my @parts=split('/',$fpath);
 3233:         foreach my $part (@parts) {
 3234:             $filepath.= '/'.$part;
 3235:             if ((-e $filepath)!=1) {
 3236:                 mkdir($filepath,0777);
 3237:             }
 3238:         }
 3239:     }
 3240:     return $filepath;
 3241: }
 3242: 
 3243: sub store_edited_file {
 3244:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 3245:     my $file = $primary_url;
 3246:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 3247:     my $fpath = '';
 3248:     my $fname = $file;
 3249:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3250:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3251:     my $filepath = &build_filepath($fpath);
 3252:     open(my $fh,'>'.$filepath.'/'.$fname);
 3253:     print $fh $content;
 3254:     close($fh);
 3255:     my $home=&homeserver($docuname,$docudom);
 3256:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3257: 			  $home);
 3258:     if ($$fetchresult eq 'ok') {
 3259:         return '/uploaded/'.$fpath.'/'.$fname;
 3260:     } else {
 3261:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3262: 		 ' to host '.$home.': '.$$fetchresult);
 3263:         return '/adm/notfound.html';
 3264:     }
 3265: }
 3266: 
 3267: sub clean_filename {
 3268:     my ($fname,$args)=@_;
 3269: # Replace Windows backslashes by forward slashes
 3270:     $fname=~s/\\/\//g;
 3271:     if (!$args->{'keep_path'}) {
 3272:         # Get rid of everything but the actual filename
 3273: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 3274:     }
 3275: # Replace spaces by underscores
 3276:     $fname=~s/\s+/\_/g;
 3277: # Replace all other weird characters by nothing
 3278:     $fname=~s{[^/\w\.\-]}{}g;
 3279: # Replace all .\d. sequences with _\d. so they no longer look like version
 3280: # numbers
 3281:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 3282:     return $fname;
 3283: }
 3284: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 3285: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 3286: # image with the same aspect ratio as the original, but with dimensions which do 
 3287: # not exceed $resizewidth and $resizeheight.
 3288:  
 3289: sub resizeImage {
 3290:     my ($img_path,$resizewidth,$resizeheight) = @_;
 3291:     my $ima = Image::Magick->new;
 3292:     my $resized;
 3293:     if (-e $img_path) {
 3294:         $ima->Read($img_path);
 3295:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 3296:             my $width = $ima->Get('width');
 3297:             my $height = $ima->Get('height');
 3298:             if ($width > $resizewidth) {
 3299: 	        my $factor = $width/$resizewidth;
 3300:                 my $newheight = $height/$factor;
 3301:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 3302:                 $resized = 1;
 3303:             }
 3304:         }
 3305:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 3306:             my $width = $ima->Get('width');
 3307:             my $height = $ima->Get('height');
 3308:             if ($height > $resizeheight) {
 3309:                 my $factor = $height/$resizeheight;
 3310:                 my $newwidth = $width/$factor;
 3311:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 3312:                 $resized = 1;
 3313:             }
 3314:         }
 3315:         if ($resized) {
 3316:             $ima->Write($img_path);
 3317:         }
 3318:     }
 3319:     return;
 3320: }
 3321: 
 3322: # --------------- Take an uploaded file and put it into the userfiles directory
 3323: # input: $formname - the contents of the file are in $env{"form.$formname"}
 3324: #                    the desired filename is in $env{"form.$formname.filename"}
 3325: #        $context - possible values: coursedoc, existingfile, overwrite, 
 3326: #                                    canceloverwrite, or ''. 
 3327: #                   if 'coursedoc': upload to the current course
 3328: #                   if 'existingfile': write file to tmp/overwrites directory 
 3329: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 3330: #                   $context is passed as argument to &finishuserfileupload
 3331: #        $subdir - directory in userfile to store the file into
 3332: #        $parser - instruction to parse file for objects ($parser = parse)    
 3333: #        $allfiles - reference to hash for embedded objects
 3334: #        $codebase - reference to hash for codebase of java objects
 3335: #        $desuname - username for permanent storage of uploaded file
 3336: #        $dsetudom - domain for permanaent storage of uploaded file
 3337: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 3338: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 3339: #        $resizewidth - width (pixels) to which to resize uploaded image
 3340: #        $resizeheight - height (pixels) to which to resize uploaded image
 3341: #        $mimetype - reference to scalar to accommodate mime type determined
 3342: #                    from File::MMagic.
 3343: # 
 3344: # output: url of file in userspace, or error: <message> 
 3345: #             or /adm/notfound.html if failure to upload occurse
 3346: 
 3347: sub userfileupload {
 3348:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 3349:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 3350:     if (!defined($subdir)) { $subdir='unknown'; }
 3351:     my $fname=$env{'form.'.$formname.'.filename'};
 3352:     $fname=&clean_filename($fname);
 3353:     # See if there is anything left
 3354:     unless ($fname) { return 'error: no uploaded file'; }
 3355:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 3356:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 3357:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 3358:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3359:         my $now = time;
 3360:         my $filepath;
 3361:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 3362:              $filepath = 'tmp/helprequests/'.$now;
 3363:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 3364:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 3365:                          '_'.$env{'user.domain'}.'/pending';
 3366:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3367:             my ($docuname,$docudom);
 3368:             if ($destudom) {
 3369:                 $docudom = $destudom;
 3370:             } else {
 3371:                 $docudom = $env{'user.domain'};
 3372:             }
 3373:             if ($destuname) {
 3374:                 $docuname = $destuname;
 3375:             } else {
 3376:                 $docuname = $env{'user.name'};
 3377:             }
 3378:             if (exists($env{'form.group'})) {
 3379:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3380:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3381:             }
 3382:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 3383:             if ($context eq 'canceloverwrite') {
 3384:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 3385:                 if (-e  $tempfile) {
 3386:                     my @info = stat($tempfile);
 3387:                     if ($info[9] eq $env{'form.timestamp'}) {
 3388:                         unlink($tempfile);
 3389:                     }
 3390:                 }
 3391:                 return;
 3392:             }
 3393:         }
 3394:         # Create the directory if not present
 3395:         my @parts=split(/\//,$filepath);
 3396:         my $fullpath = $perlvar{'lonDaemons'};
 3397:         for (my $i=0;$i<@parts;$i++) {
 3398:             $fullpath .= '/'.$parts[$i];
 3399:             if ((-e $fullpath)!=1) {
 3400:                 mkdir($fullpath,0777);
 3401:             }
 3402:         }
 3403:         open(my $fh,'>'.$fullpath.'/'.$fname);
 3404:         print $fh $env{'form.'.$formname};
 3405:         close($fh);
 3406:         if ($context eq 'existingfile') {
 3407:             my @info = stat($fullpath.'/'.$fname);
 3408:             return ($fullpath.'/'.$fname,$info[9]);
 3409:         } else {
 3410:             return $fullpath.'/'.$fname;
 3411:         }
 3412:     }
 3413:     if ($subdir eq 'scantron') {
 3414:         $fname = 'scantron_orig_'.$fname;
 3415:     } else {
 3416:         $fname="$subdir/$fname";
 3417:     }
 3418:     if ($context eq 'coursedoc') {
 3419: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3420: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3421:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 3422:             return &finishuserfileupload($docuname,$docudom,
 3423: 					 $formname,$fname,$parser,$allfiles,
 3424: 					 $codebase,$thumbwidth,$thumbheight,
 3425:                                          $resizewidth,$resizeheight,$context,$mimetype);
 3426:         } else {
 3427:             if ($env{'form.folder'}) {
 3428:                 $fname=$env{'form.folder'}.'/'.$fname;
 3429:             }
 3430:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 3431: 				       $fname,$formname,$parser,
 3432: 				       $allfiles,$codebase,$mimetype);
 3433:         }
 3434:     } elsif (defined($destuname)) {
 3435:         my $docuname=$destuname;
 3436:         my $docudom=$destudom;
 3437: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3438: 				     $parser,$allfiles,$codebase,
 3439:                                      $thumbwidth,$thumbheight,
 3440:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3441:     } else {
 3442:         my $docuname=$env{'user.name'};
 3443:         my $docudom=$env{'user.domain'};
 3444:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 3445:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3446:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3447:         }
 3448: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3449: 				     $parser,$allfiles,$codebase,
 3450:                                      $thumbwidth,$thumbheight,
 3451:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3452:     }
 3453: }
 3454: 
 3455: sub finishuserfileupload {
 3456:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 3457:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 3458:     my $path=$docudom.'/'.$docuname.'/';
 3459:     my $filepath=$perlvar{'lonDocRoot'};
 3460:   
 3461:     my ($fnamepath,$file,$fetchthumb);
 3462:     $file=$fname;
 3463:     if ($fname=~m|/|) {
 3464:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 3465: 	$path.=$fnamepath.'/';
 3466:     }
 3467:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 3468:     my $count;
 3469:     for ($count=4;$count<=$#parts;$count++) {
 3470:         $filepath.="/$parts[$count]";
 3471:         if ((-e $filepath)!=1) {
 3472: 	    mkdir($filepath,0777);
 3473:         }
 3474:     }
 3475: 
 3476: # Save the file
 3477:     {
 3478: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 3479: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 3480: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 3481: 	    return '/adm/notfound.html';
 3482: 	}
 3483:         if ($context eq 'overwrite') {
 3484:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 3485:             my $target = $filepath.'/'.$file;
 3486:             if (-e $source) {
 3487:                 my @info = stat($source);
 3488:                 if ($info[9] eq $env{'form.timestamp'}) {   
 3489:                     unless (&File::Copy::move($source,$target)) {
 3490:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 3491:                         return "Moving from $source failed";
 3492:                     }
 3493:                 } else {
 3494:                     return "Temporary file: $source had unexpected date/time for last modification";
 3495:                 }
 3496:             } else {
 3497:                 return "Temporary file: $source missing";
 3498:             }
 3499:         } elsif (!print FH ($env{'form.'.$formname})) {
 3500: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 3501: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 3502: 	    return '/adm/notfound.html';
 3503: 	}
 3504: 	close(FH);
 3505:         if ($resizewidth && $resizeheight) {
 3506:             my $mm = new File::MMagic;
 3507:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 3508:             if ($mime_type =~ m{^image/}) {
 3509: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 3510:             }  
 3511: 	}
 3512:     }
 3513:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 3514:         if (ref($mimetype)) {
 3515:             if ($$mimetype eq '') {
 3516:                 my $mm = new File::MMagic;
 3517:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 3518:                 $$mimetype = $type;
 3519:             }
 3520:         }
 3521:     }
 3522:     if ($parser eq 'parse') {
 3523:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 3524:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 3525:                                                        $allfiles,$codebase);
 3526:             unless ($parse_result eq 'ok') {
 3527:                 &logthis('Failed to parse '.$filepath.$file.
 3528: 	   	         ' for embedded media: '.$parse_result); 
 3529:             }
 3530:         }
 3531:     }
 3532:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 3533:         my $input = $filepath.'/'.$file;
 3534:         my $output = $filepath.'/'.'tn-'.$file;
 3535:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 3536:         system("convert -sample $thumbsize $input $output");
 3537:         if (-e $filepath.'/'.'tn-'.$file) {
 3538:             $fetchthumb  = 1; 
 3539:         }
 3540:     }
 3541:  
 3542: # Notify homeserver to grep it
 3543: #
 3544:     my $docuhome=&homeserver($docuname,$docudom);	
 3545:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 3546:     if ($fetchresult eq 'ok') {
 3547:         if ($fetchthumb) {
 3548:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 3549:             if ($thumbresult ne 'ok') {
 3550:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 3551:                          $docuhome.': '.$thumbresult);
 3552:             }
 3553:         }
 3554: #
 3555: # Return the URL to it
 3556:         return '/uploaded/'.$path.$file;
 3557:     } else {
 3558:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 3559: 		 ': '.$fetchresult);
 3560:         return '/adm/notfound.html';
 3561:     }
 3562: }
 3563: 
 3564: sub extract_embedded_items {
 3565:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 3566:     my @state = ();
 3567:     my (%lastids,%related,%shockwave,%flashvars);
 3568:     my %javafiles = (
 3569:                       codebase => '',
 3570:                       code => '',
 3571:                       archive => ''
 3572:                     );
 3573:     my %mediafiles = (
 3574:                       src => '',
 3575:                       movie => '',
 3576:                      );
 3577:     my $p;
 3578:     if ($content) {
 3579:         $p = HTML::LCParser->new($content);
 3580:     } else {
 3581:         $p = HTML::LCParser->new($fullpath);
 3582:     }
 3583:     while (my $t=$p->get_token()) {
 3584: 	if ($t->[0] eq 'S') {
 3585: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 3586: 	    push(@state, $tagname);
 3587:             if (lc($tagname) eq 'allow') {
 3588:                 &add_filetype($allfiles,$attr->{'src'},'src');
 3589:             }
 3590: 	    if (lc($tagname) eq 'img') {
 3591: 		&add_filetype($allfiles,$attr->{'src'},'src');
 3592: 	    }
 3593: 	    if (lc($tagname) eq 'a') {
 3594:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 3595:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3596:                 }
 3597: 	    }
 3598:             if (lc($tagname) eq 'script') {
 3599:                 my $src;
 3600:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 3601:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 3602:                 } else {
 3603:                     if ($attr->{'src'} ne '') {
 3604:                         $src = $attr->{'src'};
 3605:                         &add_filetype($allfiles,$src,'src');
 3606:                     }
 3607:                 }
 3608:                 my $text = $p->get_trimmed_text();
 3609:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 3610:                     my @swfargs = split(/,/,$1);
 3611:                     foreach my $item (@swfargs) {
 3612:                         $item =~ s/["']//g;
 3613:                         $item =~ s/^\s+//;
 3614:                         $item =~ s/\s+$//;
 3615:                     }
 3616:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 3617:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 3618:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 3619:                         } else {
 3620:                             $related{$swfargs[0]} = [$swfargs[2]];
 3621:                         }
 3622:                     }
 3623:                 }
 3624:             }
 3625:             if (lc($tagname) eq 'link') {
 3626:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 3627:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3628:                 }
 3629:             }
 3630: 	    if (lc($tagname) eq 'object' ||
 3631: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 3632: 		foreach my $item (keys(%javafiles)) {
 3633: 		    $javafiles{$item} = '';
 3634: 		}
 3635:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 3636:                     $lastids{lc($tagname)} = $attr->{'id'};
 3637:                 }
 3638: 	    }
 3639: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 3640: 		my $name = lc($attr->{'name'});
 3641: 		foreach my $item (keys(%javafiles)) {
 3642: 		    if ($name eq $item) {
 3643: 			$javafiles{$item} = $attr->{'value'};
 3644: 			last;
 3645: 		    }
 3646: 		}
 3647:                 my $pathfrom;
 3648: 		foreach my $item (keys(%mediafiles)) {
 3649: 		    if ($name eq $item) {
 3650:                         $pathfrom = $attr->{'value'};
 3651:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 3652: 			&add_filetype($allfiles,$pathfrom,$name);
 3653: 			last;
 3654: 		    }
 3655: 		}
 3656:                 if ($name eq 'flashvars') {
 3657:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 3658:                 }
 3659:                 if ($pathfrom ne '') {
 3660:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 3661:                                          $pathfrom);
 3662:                 }
 3663: 	    }
 3664: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 3665: 		foreach my $item (keys(%javafiles)) {
 3666: 		    if ($attr->{$item}) {
 3667: 			$javafiles{$item} = $attr->{$item};
 3668: 			last;
 3669: 		    }
 3670: 		}
 3671: 		foreach my $item (keys(%mediafiles)) {
 3672: 		    if ($attr->{$item}) {
 3673: 			&add_filetype($allfiles,$attr->{$item},$item);
 3674: 			last;
 3675: 		    }
 3676: 		}
 3677:                 if (lc($tagname) eq 'embed') {
 3678:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 3679:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 3680:                                              $attr->{'src'});
 3681:                     }
 3682:                 }
 3683: 	    }
 3684:             if (lc($tagname) eq 'iframe') {
 3685:                 my $src = $attr->{'src'} ;
 3686:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 3687:                     &add_filetype($allfiles,$src,'src');
 3688:                 } elsif ($src =~ m{^/}) {
 3689:                     if ($env{'request.course.id'}) {
 3690:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3691:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3692:                         my $url = &hreflocation('',$fullpath);
 3693:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 3694:                             my $relpath = $1;
 3695:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 3696:                                 &add_filetype($allfiles,$1,'src');
 3697:                             }
 3698:                         }
 3699:                     }
 3700:                 }
 3701:             }
 3702:             if ($t->[4] =~ m{/>$}) {
 3703:                 pop(@state);
 3704:             }
 3705: 	} elsif ($t->[0] eq 'E') {
 3706: 	    my ($tagname) = ($t->[1]);
 3707: 	    if ($javafiles{'codebase'} ne '') {
 3708: 		$javafiles{'codebase'} .= '/';
 3709: 	    }  
 3710: 	    if (lc($tagname) eq 'applet' ||
 3711: 		lc($tagname) eq 'object' ||
 3712: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 3713: 		) {
 3714: 		foreach my $item (keys(%javafiles)) {
 3715: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 3716: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 3717: 			&add_filetype($allfiles,$file,$item);
 3718: 		    }
 3719: 		}
 3720: 	    } 
 3721: 	    pop @state;
 3722: 	}
 3723:     }
 3724:     foreach my $id (sort(keys(%flashvars))) {
 3725:         if ($shockwave{$id} ne '') {
 3726:             my @pairs = split(/\&/,$flashvars{$id});
 3727:             foreach my $pair (@pairs) {
 3728:                 my ($key,$value) = split(/\=/,$pair);
 3729:                 if ($key eq 'thumb') {
 3730:                     &add_filetype($allfiles,$value,$key);
 3731:                 } elsif ($key eq 'content') {
 3732:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 3733:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 3734:                     if ($ext ne '') {
 3735:                         &add_filetype($allfiles,$path.$value,$ext);
 3736:                     }
 3737:                 }
 3738:             }
 3739:         }
 3740:     }
 3741:     return 'ok';
 3742: }
 3743: 
 3744: sub add_filetype {
 3745:     my ($allfiles,$file,$type)=@_;
 3746:     if (exists($allfiles->{$file})) {
 3747: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 3748: 	    push(@{$allfiles->{$file}}, &escape($type));
 3749: 	}
 3750:     } else {
 3751: 	@{$allfiles->{$file}} = (&escape($type));
 3752:     }
 3753: }
 3754: 
 3755: sub embedded_dependency {
 3756:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 3757:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 3758:         if (($identifier ne '') &&
 3759:             (ref($related->{$identifier}) eq 'ARRAY') &&
 3760:             ($pathfrom ne '')) {
 3761:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 3762:             foreach my $dep (@{$related->{$identifier}}) {
 3763:                 &add_filetype($allfiles,$path.$dep,'object');
 3764:             }
 3765:         }
 3766:     }
 3767:     return;
 3768: }
 3769: 
 3770: sub removeuploadedurl {
 3771:     my ($url)=@_;	
 3772:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 3773:     return &removeuserfile($uname,$udom,$fname);
 3774: }
 3775: 
 3776: sub removeuserfile {
 3777:     my ($docuname,$docudom,$fname)=@_;
 3778:     my $home=&homeserver($docuname,$docudom);    
 3779:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 3780:     if ($result eq 'ok') {	
 3781:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 3782:             my $metafile = $fname.'.meta';
 3783:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 3784: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 3785:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 3786:             my $sqlresult = 
 3787:                 &update_portfolio_table($docuname,$docudom,$file,
 3788:                                         'portfolio_metadata',$group,
 3789:                                         'delete');
 3790:         }
 3791:     }
 3792:     return $result;
 3793: }
 3794: 
 3795: sub mkdiruserfile {
 3796:     my ($docuname,$docudom,$dir)=@_;
 3797:     my $home=&homeserver($docuname,$docudom);
 3798:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 3799: }
 3800: 
 3801: sub renameuserfile {
 3802:     my ($docuname,$docudom,$old,$new)=@_;
 3803:     my $home=&homeserver($docuname,$docudom);
 3804:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 3805:                         &escape("$old").':'.&escape("$new"),$home);
 3806:     if ($result eq 'ok') {
 3807:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 3808:             my $oldmeta = $old.'.meta';
 3809:             my $newmeta = $new.'.meta';
 3810:             my $metaresult = 
 3811:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 3812: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 3813:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 3814:             my $sqlresult = 
 3815:                 &update_portfolio_table($docuname,$docudom,$file,
 3816:                                         'portfolio_metadata',$group,
 3817:                                         'delete');
 3818:         }
 3819:     }
 3820:     return $result;
 3821: }
 3822: 
 3823: # ------------------------------------------------------------------------- Log
 3824: 
 3825: sub log {
 3826:     my ($dom,$nam,$hom,$what)=@_;
 3827:     return critical("log:$dom:$nam:$what",$hom);
 3828: }
 3829: 
 3830: # ------------------------------------------------------------------ Course Log
 3831: #
 3832: # This routine flushes several buffers of non-mission-critical nature
 3833: #
 3834: 
 3835: sub flushcourselogs {
 3836:     &logthis('Flushing log buffers');
 3837: #
 3838: # course logs
 3839: # This is a log of all transactions in a course, which can be used
 3840: # for data mining purposes
 3841: #
 3842: # It also collects the courseid database, which lists last transaction
 3843: # times and course titles for all courseids
 3844: #
 3845:     my %courseidbuffer=();
 3846:     foreach my $crsid (keys(%courselogs)) {
 3847:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 3848: 		          &escape($courselogs{$crsid}),
 3849: 		          $coursehombuf{$crsid}) eq 'ok') {
 3850: 	    delete $courselogs{$crsid};
 3851:         } else {
 3852:             &logthis('Failed to flush log buffer for '.$crsid);
 3853:             if (length($courselogs{$crsid})>40000) {
 3854:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 3855:                         " exceeded maximum size, deleting.</font>");
 3856:                delete $courselogs{$crsid};
 3857:             }
 3858:         }
 3859:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 3860:             'description' => $coursedescrbuf{$crsid},
 3861:             'inst_code'    => $courseinstcodebuf{$crsid},
 3862:             'type'        => $coursetypebuf{$crsid},
 3863:             'owner'       => $courseownerbuf{$crsid},
 3864:         };
 3865:     }
 3866: #
 3867: # Write course id database (reverse lookup) to homeserver of courses 
 3868: # Is used in pickcourse
 3869: #
 3870:     foreach my $crs_home (keys(%courseidbuffer)) {
 3871:         my $response = &courseidput(&host_domain($crs_home),
 3872:                                     $courseidbuffer{$crs_home},
 3873:                                     $crs_home,'timeonly');
 3874:     }
 3875: #
 3876: # File accesses
 3877: # Writes to the dynamic metadata of resources to get hit counts, etc.
 3878: #
 3879:     foreach my $entry (keys(%accesshash)) {
 3880:         if ($entry =~ /___count$/) {
 3881:             my ($dom,$name);
 3882:             ($dom,$name,undef)=
 3883: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 3884:             if (! defined($dom) || $dom eq '' || 
 3885:                 ! defined($name) || $name eq '') {
 3886:                 my $cid = $env{'request.course.id'};
 3887:                 $dom  = $env{'request.'.$cid.'.domain'};
 3888:                 $name = $env{'request.'.$cid.'.num'};
 3889:             }
 3890:             my $value = $accesshash{$entry};
 3891:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 3892:             my %temphash=($url => $value);
 3893:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 3894:             if ($result eq 'ok') {
 3895:                 delete $accesshash{$entry};
 3896:             }
 3897:         } else {
 3898:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 3899:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 3900:             my %temphash=($entry => $accesshash{$entry});
 3901:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 3902:                 delete $accesshash{$entry};
 3903:             }
 3904:         }
 3905:     }
 3906: #
 3907: # Roles
 3908: # Reverse lookup of user roles for course faculty/staff and co-authorship
 3909: #
 3910:     foreach my $entry (keys(%userrolehash)) {
 3911:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 3912: 	    split(/\:/,$entry);
 3913:         if (&Apache::lonnet::put('nohist_userroles',
 3914:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 3915:                 $rudom,$runame) eq 'ok') {
 3916: 	    delete $userrolehash{$entry};
 3917:         }
 3918:     }
 3919: #
 3920: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 3921: #
 3922:     my %domrolebuffer = ();
 3923:     foreach my $entry (keys(%domainrolehash)) {
 3924:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 3925:         if ($domrolebuffer{$rudom}) {
 3926:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 3927:                       '='.&escape($domainrolehash{$entry});
 3928:         } else {
 3929:             $domrolebuffer{$rudom}.=&escape($entry).
 3930:                       '='.&escape($domainrolehash{$entry});
 3931:         }
 3932:         delete $domainrolehash{$entry};
 3933:     }
 3934:     foreach my $dom (keys(%domrolebuffer)) {
 3935: 	my %servers = &get_servers($dom,'library');
 3936: 	foreach my $tryserver (keys(%servers)) {
 3937: 	    unless (&reply('domroleput:'.$dom.':'.
 3938: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 3939: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 3940: 	    }
 3941:         }
 3942:     }
 3943:     $dumpcount++;
 3944: }
 3945: 
 3946: sub courselog {
 3947:     my $what=shift;
 3948:     $what=time.':'.$what;
 3949:     unless ($env{'request.course.id'}) { return ''; }
 3950:     $coursedombuf{$env{'request.course.id'}}=
 3951:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 3952:     $coursenumbuf{$env{'request.course.id'}}=
 3953:        $env{'course.'.$env{'request.course.id'}.'.num'};
 3954:     $coursehombuf{$env{'request.course.id'}}=
 3955:        $env{'course.'.$env{'request.course.id'}.'.home'};
 3956:     $coursedescrbuf{$env{'request.course.id'}}=
 3957:        $env{'course.'.$env{'request.course.id'}.'.description'};
 3958:     $courseinstcodebuf{$env{'request.course.id'}}=
 3959:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 3960:     $courseownerbuf{$env{'request.course.id'}}=
 3961:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 3962:     $coursetypebuf{$env{'request.course.id'}}=
 3963:        $env{'course.'.$env{'request.course.id'}.'.type'};
 3964:     if (defined $courselogs{$env{'request.course.id'}}) {
 3965: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 3966:     } else {
 3967: 	$courselogs{$env{'request.course.id'}}.=$what;
 3968:     }
 3969:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 3970: 	&flushcourselogs();
 3971:     }
 3972: }
 3973: 
 3974: sub courseacclog {
 3975:     my $fnsymb=shift;
 3976:     unless ($env{'request.course.id'}) { return ''; }
 3977:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 3978:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 3979:         $what.=':POST';
 3980:         # FIXME: Probably ought to escape things....
 3981: 	foreach my $key (keys(%env)) {
 3982:             if ($key=~/^form\.(.*)/) {
 3983:                 my $formitem = $1;
 3984:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 3985:                     $what.=':'.$formitem.'='.$env{$key};
 3986:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 3987:                     $what.=':'.$formitem.'='.$env{$key};
 3988:                 }
 3989:             }
 3990:         }
 3991:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 3992:         # FIXME: We should not be depending on a form parameter that someone
 3993:         # editing lonsearchcat.pm might change in the future.
 3994:         if ($env{'form.phase'} eq 'course_search') {
 3995:             $what.= ':POST';
 3996:             # FIXME: Probably ought to escape things....
 3997:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 3998:                                  'crsdiscuss') {
 3999:                 $what.=':'.$element.'='.$env{'form.'.$element};
 4000:             }
 4001:         }
 4002:     }
 4003:     &courselog($what);
 4004: }
 4005: 
 4006: sub countacc {
 4007:     my $url=&declutter(shift);
 4008:     return if (! defined($url) || $url eq '');
 4009:     unless ($env{'request.course.id'}) { return ''; }
 4010: #
 4011: # Mark that this url was used in this course
 4012: #
 4013:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 4014: #
 4015: # Increase the access count for this resource in this child process
 4016: #
 4017:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 4018:     $accesshash{$key}++;
 4019: }
 4020: 
 4021: sub linklog {
 4022:     my ($from,$to)=@_;
 4023:     $from=&declutter($from);
 4024:     $to=&declutter($to);
 4025:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 4026:     $accesshash{$to.'___'.$from.'___goto'}=1;
 4027: }
 4028: 
 4029: sub statslog {
 4030:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 4031:     if ($users<2) { return; }
 4032:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 4033:             'course'       => $env{'request.course.id'},
 4034:             'sections'     => '"all"',
 4035:             'num_students' => $users,
 4036:             'part'         => $part,
 4037:             'symb'         => $symb,
 4038:             'mean_tries'   => $av_attempts,
 4039:             'deg_of_diff'  => $degdiff});
 4040:     foreach my $key (keys(%dynstore)) {
 4041:         $accesshash{$key}=$dynstore{$key};
 4042:     }
 4043: }
 4044:   
 4045: sub userrolelog {
 4046:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 4047:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 4048:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4049:        $userrolehash
 4050:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4051:                     =$tend.':'.$tstart;
 4052:     }
 4053:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 4054:        $userrolehash
 4055:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 4056:                     =$tend.':'.$tstart;
 4057:     }
 4058:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
 4059:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 4060:        $domainrolehash
 4061:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 4062:                     = $tend.':'.$tstart;
 4063:     }
 4064: }
 4065: 
 4066: sub courserolelog {
 4067:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 4068:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 4069:         my $cdom = $1;
 4070:         my $cnum = $2;
 4071:         my $sec = $3;
 4072:         my $namespace = 'rolelog';
 4073:         my %storehash = (
 4074:                            role    => $trole,
 4075:                            start   => $tstart,
 4076:                            end     => $tend,
 4077:                            selfenroll => $selfenroll,
 4078:                            context    => $context,
 4079:                         );
 4080:         if ($trole eq 'gr') {
 4081:             $namespace = 'groupslog';
 4082:             $storehash{'group'} = $sec;
 4083:         } else {
 4084:             $storehash{'section'} = $sec;
 4085:         }
 4086:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 4087:                    $domain,$cnum,$cdom);
 4088:         if (($trole ne 'st') || ($sec ne '')) {
 4089:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 4090:         }
 4091:     }
 4092:     return;
 4093: }
 4094: 
 4095: sub domainrolelog {
 4096:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4097:     if ($area =~ m{^/($match_domain)/$}) {
 4098:         my $cdom = $1;
 4099:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 4100:         my $namespace = 'rolelog';
 4101:         my %storehash = (
 4102:                            role    => $trole,
 4103:                            start   => $tstart,
 4104:                            end     => $tend,
 4105:                            context => $context,
 4106:                         );
 4107:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 4108:                    $domain,$domconfiguser,$cdom);
 4109:     }
 4110:     return;
 4111: 
 4112: }
 4113: 
 4114: sub coauthorrolelog {
 4115:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4116:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 4117:         my $audom = $1;
 4118:         my $auname = $2;
 4119:         my $namespace = 'rolelog';
 4120:         my %storehash = (
 4121:                            role    => $trole,
 4122:                            start   => $tstart,
 4123:                            end     => $tend,
 4124:                            context => $context,
 4125:                         );
 4126:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 4127:                    $domain,$auname,$audom);
 4128:     }
 4129:     return;
 4130: }
 4131: 
 4132: sub get_course_adv_roles {
 4133:     my ($cid,$codes) = @_;
 4134:     $cid=$env{'request.course.id'} unless (defined($cid));
 4135:     my %coursehash=&coursedescription($cid);
 4136:     my $crstype = &Apache::loncommon::course_type($cid);
 4137:     my %nothide=();
 4138:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4139:         if ($user !~ /:/) {
 4140: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 4141:         } else {
 4142:             $nothide{$user}=1;
 4143:         }
 4144:     }
 4145:     my @possdoms = ($coursehash{'domain'});
 4146:     if ($coursehash{'checkforpriv'}) {
 4147:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 4148:     }
 4149:     my %returnhash=();
 4150:     my %dumphash=
 4151:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 4152:     my $now=time;
 4153:     my %privileged;
 4154:     foreach my $entry (keys(%dumphash)) {
 4155: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4156:         if (($tstart) && ($tstart<0)) { next; }
 4157:         if (($tend) && ($tend<$now)) { next; }
 4158:         if (($tstart) && ($now<$tstart)) { next; }
 4159:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 4160: 	if ($username eq '' || $domain eq '') { next; }
 4161:         if ((&privileged($username,$domain,\@possdoms)) &&
 4162:             (!$nothide{$username.':'.$domain})) { next; }
 4163: 	if ($role eq 'cr') { next; }
 4164:         if ($codes) {
 4165:             if ($section) { $role .= ':'.$section; }
 4166:             if ($returnhash{$role}) {
 4167:                 $returnhash{$role}.=','.$username.':'.$domain;
 4168:             } else {
 4169:                 $returnhash{$role}=$username.':'.$domain;
 4170:             }
 4171:         } else {
 4172:             my $key=&plaintext($role,$crstype);
 4173:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 4174:             if ($returnhash{$key}) {
 4175: 	        $returnhash{$key}.=','.$username.':'.$domain;
 4176:             } else {
 4177:                 $returnhash{$key}=$username.':'.$domain;
 4178:             }
 4179:         }
 4180:     }
 4181:     return %returnhash;
 4182: }
 4183: 
 4184: sub get_my_roles {
 4185:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 4186:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 4187:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 4188:     my (%dumphash,%nothide);
 4189:     if ($context eq 'userroles') {
 4190:         %dumphash = &dump('roles',$udom,$uname);
 4191:     } else {
 4192:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 4193:         if ($hidepriv) {
 4194:             my %coursehash=&coursedescription($udom.'_'.$uname);
 4195:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4196:                 if ($user !~ /:/) {
 4197:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 4198:                 } else {
 4199:                     $nothide{$user} = 1;
 4200:                 }
 4201:             }
 4202:         }
 4203:     }
 4204:     my %returnhash=();
 4205:     my $now=time;
 4206:     my %privileged;
 4207:     foreach my $entry (keys(%dumphash)) {
 4208:         my ($role,$tend,$tstart);
 4209:         if ($context eq 'userroles') {
 4210:             next if ($entry =~ /^rolesdef/);
 4211: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 4212:         } else {
 4213:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4214:         }
 4215:         if (($tstart) && ($tstart<0)) { next; }
 4216:         my $status = 'active';
 4217:         if (($tend) && ($tend<=$now)) {
 4218:             $status = 'previous';
 4219:         } 
 4220:         if (($tstart) && ($now<$tstart)) {
 4221:             $status = 'future';
 4222:         }
 4223:         if (ref($types) eq 'ARRAY') {
 4224:             if (!grep(/^\Q$status\E$/,@{$types})) {
 4225:                 next;
 4226:             } 
 4227:         } else {
 4228:             if ($status ne 'active') {
 4229:                 next;
 4230:             }
 4231:         }
 4232:         my ($rolecode,$username,$domain,$section,$area);
 4233:         if ($context eq 'userroles') {
 4234:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 4235:             (undef,$domain,$username,$section) = split(/\//,$area);
 4236:         } else {
 4237:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 4238:         }
 4239:         if (ref($roledoms) eq 'ARRAY') {
 4240:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 4241:                 next;
 4242:             }
 4243:         }
 4244:         if (ref($roles) eq 'ARRAY') {
 4245:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 4246:                 if ($role =~ /^cr\//) {
 4247:                     if (!grep(/^cr$/,@{$roles})) {
 4248:                         next;
 4249:                     }
 4250:                 } elsif ($role =~ /^gr\//) {
 4251:                     if (!grep(/^gr$/,@{$roles})) {
 4252:                         next;
 4253:                     }
 4254:                 } else {
 4255:                     next;
 4256:                 }
 4257:             }
 4258:         }
 4259:         if ($hidepriv) {
 4260:             my @privroles = ('dc','su');
 4261:             if ($context eq 'userroles') {
 4262:                 next if (grep(/^\Q$role\E$/,@privroles));
 4263:             } else {
 4264:                 my $possdoms = [$domain];
 4265:                 if (ref($roledoms) eq 'ARRAY') {
 4266:                    push(@{$possdoms},@{$roledoms}); 
 4267:                 }
 4268:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 4269:                     if (!$nothide{$username.':'.$domain}) {
 4270:                         next;
 4271:                     }
 4272:                 }
 4273:             }
 4274:         }
 4275:         if ($withsec) {
 4276:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 4277:                 $tstart.':'.$tend;
 4278:         } else {
 4279:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 4280:         }
 4281:     }
 4282:     return %returnhash;
 4283: }
 4284: 
 4285: # ----------------------------------------------------- Frontpage Announcements
 4286: #
 4287: #
 4288: 
 4289: sub postannounce {
 4290:     my ($server,$text)=@_;
 4291:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 4292:     unless ($text=~/\w/) { $text=''; }
 4293:     return &reply('setannounce:'.&escape($text),$server);
 4294: }
 4295: 
 4296: sub getannounce {
 4297: 
 4298:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 4299: 	my $announcement='';
 4300: 	while (my $line = <$fh>) { $announcement .= $line; }
 4301: 	close($fh);
 4302: 	if ($announcement=~/\w/) { 
 4303: 	    return 
 4304:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 4305:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 4306: 	} else {
 4307: 	    return '';
 4308: 	}
 4309:     } else {
 4310: 	return '';
 4311:     }
 4312: }
 4313: 
 4314: # ---------------------------------------------------------- Course ID routines
 4315: # Deal with domain's nohist_courseid.db files
 4316: #
 4317: 
 4318: sub courseidput {
 4319:     my ($domain,$storehash,$coursehome,$caller) = @_;
 4320:     return unless (ref($storehash) eq 'HASH');
 4321:     my $outcome;
 4322:     if ($caller eq 'timeonly') {
 4323:         my $cids = '';
 4324:         foreach my $item (keys(%$storehash)) {
 4325:             $cids.=&escape($item).'&';
 4326:         }
 4327:         $cids=~s/\&$//;
 4328:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 4329:                           $coursehome);       
 4330:     } else {
 4331:         my $items = '';
 4332:         foreach my $item (keys(%$storehash)) {
 4333:             $items.= &escape($item).'='.
 4334:                      &freeze_escape($$storehash{$item}).'&';
 4335:         }
 4336:         $items=~s/\&$//;
 4337:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 4338:                           $coursehome);
 4339:     }
 4340:     if ($outcome eq 'unknown_cmd') {
 4341:         my $what;
 4342:         foreach my $cid (keys(%$storehash)) {
 4343:             $what .= &escape($cid).'=';
 4344:             foreach my $item ('description','inst_code','owner','type') {
 4345:                 $what .= &escape($storehash->{$cid}{$item}).':';
 4346:             }
 4347:             $what =~ s/\:$/&/;
 4348:         }
 4349:         $what =~ s/\&$//;  
 4350:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 4351:     } else {
 4352:         return $outcome;
 4353:     }
 4354: }
 4355: 
 4356: sub courseiddump {
 4357:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 4358:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 4359:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 4360:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 4361:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
 4362:     my $as_hash = 1;
 4363:     my %returnhash;
 4364:     if (!$domfilter) { $domfilter=''; }
 4365:     my %libserv = &all_library();
 4366:     foreach my $tryserver (keys(%libserv)) {
 4367:         if ( (  $hostidflag == 1 
 4368: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 4369: 	     || (!defined($hostidflag)) ) {
 4370: 
 4371: 	    if (($domfilter eq '') ||
 4372: 		(&host_domain($tryserver) eq $domfilter)) {
 4373:                 my $rep;
 4374:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 4375:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 4376:                         join(":", (&host_domain($tryserver), $sincefilter, 
 4377:                                 &escape($descfilter), &escape($instcodefilter), 
 4378:                                 &escape($ownerfilter), &escape($coursefilter),
 4379:                                 &escape($typefilter), &escape($regexp_ok), 
 4380:                                 $as_hash, &escape($selfenrollonly), 
 4381:                                 &escape($catfilter), $showhidden, $caller, 
 4382:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 4383:                                 &escape($createdbefore), &escape($createdafter), 
 4384:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
 4385:                                 $reqcrsdom,&escape($reqinstcode))));
 4386:                 } else {
 4387:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 4388:                              $sincefilter.':'.&escape($descfilter).':'.
 4389:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 4390:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 4391:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 4392:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 4393:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 4394:                              &escape($cc_clone).':'.$cloneonly.':'.
 4395:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 4396:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
 4397:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
 4398:                 }
 4399:                      
 4400:                 my @pairs=split(/\&/,$rep);
 4401:                 foreach my $item (@pairs) {
 4402:                     my ($key,$value)=split(/\=/,$item,2);
 4403:                     $key = &unescape($key);
 4404:                     next if ($key =~ /^error: 2 /);
 4405:                     my $result = &thaw_unescape($value);
 4406:                     if (ref($result) eq 'HASH') {
 4407:                         $returnhash{$key}=$result;
 4408:                     } else {
 4409:                         my @responses = split(/:/,$value);
 4410:                         my @items = ('description','inst_code','owner','type');
 4411:                         for (my $i=0; $i<@responses; $i++) {
 4412:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 4413:                         }
 4414:                     }
 4415:                 }
 4416:             }
 4417:         }
 4418:     }
 4419:     return %returnhash;
 4420: }
 4421: 
 4422: sub courselastaccess {
 4423:     my ($cdom,$cnum,$hostidref) = @_;
 4424:     my %returnhash;
 4425:     if ($cdom && $cnum) {
 4426:         my $chome = &homeserver($cnum,$cdom);
 4427:         if ($chome ne 'no_host') {
 4428:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 4429:             &extract_lastaccess(\%returnhash,$rep);
 4430:         }
 4431:     } else {
 4432:         if (!$cdom) { $cdom=''; }
 4433:         my %libserv = &all_library();
 4434:         foreach my $tryserver (keys(%libserv)) {
 4435:             if (ref($hostidref) eq 'ARRAY') {
 4436:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 4437:             } 
 4438:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 4439:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 4440:                 &extract_lastaccess(\%returnhash,$rep);
 4441:             }
 4442:         }
 4443:     }
 4444:     return %returnhash;
 4445: }
 4446: 
 4447: sub extract_lastaccess {
 4448:     my ($returnhash,$rep) = @_;
 4449:     if (ref($returnhash) eq 'HASH') {
 4450:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 4451:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 4452:                  $rep eq '') {
 4453:             my @pairs=split(/\&/,$rep);
 4454:             foreach my $item (@pairs) {
 4455:                 my ($key,$value)=split(/\=/,$item,2);
 4456:                 $key = &unescape($key);
 4457:                 next if ($key =~ /^error: 2 /);
 4458:                 $returnhash->{$key} = &thaw_unescape($value);
 4459:             }
 4460:         }
 4461:     }
 4462:     return;
 4463: }
 4464: 
 4465: # ---------------------------------------------------------- DC e-mail
 4466: 
 4467: sub dcmailput {
 4468:     my ($domain,$msgid,$message,$server)=@_;
 4469:     my $status = &Apache::lonnet::critical(
 4470:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 4471:        &escape($message),$server);
 4472:     return $status;
 4473: }
 4474: 
 4475: sub dcmaildump {
 4476:     my ($dom,$startdate,$enddate,$senders) = @_;
 4477:     my %returnhash=();
 4478: 
 4479:     if (defined(&domain($dom,'primary'))) {
 4480:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 4481:                                                          &escape($enddate).':';
 4482: 	my @esc_senders=map { &escape($_)} @$senders;
 4483: 	$cmd.=&escape(join('&',@esc_senders));
 4484: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 4485:             my ($key,$value) = split(/\=/,$line,2);
 4486:             if (($key) && ($value)) {
 4487:                 $returnhash{&unescape($key)} = &unescape($value);
 4488:             }
 4489:         }
 4490:     }
 4491:     return %returnhash;
 4492: }
 4493: # ---------------------------------------------------------- Domain roles
 4494: 
 4495: sub get_domain_roles {
 4496:     my ($dom,$roles,$startdate,$enddate)=@_;
 4497:     if ((!defined($startdate)) || ($startdate eq '')) {
 4498:         $startdate = '.';
 4499:     }
 4500:     if ((!defined($enddate)) || ($enddate eq '')) {
 4501:         $enddate = '.';
 4502:     }
 4503:     my $rolelist;
 4504:     if (ref($roles) eq 'ARRAY') {
 4505:         $rolelist = join('&',@{$roles});
 4506:     }
 4507:     my %personnel = ();
 4508: 
 4509:     my %servers = &get_servers($dom,'library');
 4510:     foreach my $tryserver (keys(%servers)) {
 4511: 	%{$personnel{$tryserver}}=();
 4512: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 4513: 					    &escape($startdate).':'.
 4514: 					    &escape($enddate).':'.
 4515: 					    &escape($rolelist), $tryserver))) {
 4516: 	    my ($key,$value) = split(/\=/,$line,2);
 4517: 	    if (($key) && ($value)) {
 4518: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 4519: 	    }
 4520: 	}
 4521:     }
 4522:     return %personnel;
 4523: }
 4524: 
 4525: # ----------------------------------------------------------- Interval timing 
 4526: 
 4527: {
 4528: # Caches needed for speedup of navmaps
 4529: # We don't want to cache this for very long at all (5 seconds at most)
 4530: # 
 4531: # The user for whom we cache
 4532: my $cachedkey='';
 4533: # The cached times for this user
 4534: my %cachedtimes=();
 4535: # When this was last done
 4536: my $cachedtime='';
 4537: 
 4538: sub load_all_first_access {
 4539:     my ($uname,$udom)=@_;
 4540:     if (($cachedkey eq $uname.':'.$udom) &&
 4541:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
 4542:         return;
 4543:     }
 4544:     $cachedtime=time;
 4545:     $cachedkey=$uname.':'.$udom;
 4546:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 4547: }
 4548: 
 4549: sub get_first_access {
 4550:     my ($type,$argsymb,$argmap)=@_;
 4551:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4552:     if ($argsymb) { $symb=$argsymb; }
 4553:     my ($map,$id,$res)=&decode_symb($symb);
 4554:     if ($argmap) { $map = $argmap; }
 4555:     if ($type eq 'course') {
 4556: 	$res='course';
 4557:     } elsif ($type eq 'map') {
 4558: 	$res=&symbread($map);
 4559:     } else {
 4560: 	$res=$symb;
 4561:     }
 4562:     &load_all_first_access($uname,$udom);
 4563:     return $cachedtimes{"$courseid\0$res"};
 4564: }
 4565: 
 4566: sub set_first_access {
 4567:     my ($type,$interval)=@_;
 4568:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4569:     my ($map,$id,$res)=&decode_symb($symb);
 4570:     if ($type eq 'course') {
 4571: 	$res='course';
 4572:     } elsif ($type eq 'map') {
 4573: 	$res=&symbread($map);
 4574:     } else {
 4575: 	$res=$symb;
 4576:     }
 4577:     $cachedkey='';
 4578:     my $firstaccess=&get_first_access($type,$symb,$map);
 4579:     if (!$firstaccess) {
 4580:         my $start = time;
 4581: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 4582:                           $udom,$uname);
 4583:         if ($putres eq 'ok') {
 4584:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 4585:                  $udom,$uname); 
 4586:             &appenv(
 4587:                      {
 4588:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 4589:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 4590:                      }
 4591:                   );
 4592:         }
 4593:         return $putres;
 4594:     }
 4595:     return 'already_set';
 4596: }
 4597: }
 4598: 
 4599: # --------------------------------------------- Set Expire Date for Spreadsheet
 4600: 
 4601: sub expirespread {
 4602:     my ($uname,$udom,$stype,$usymb)=@_;
 4603:     my $cid=$env{'request.course.id'}; 
 4604:     if ($cid) {
 4605:        my $now=time;
 4606:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 4607:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 4608:                             $env{'course.'.$cid.'.num'}.
 4609: 	        	    ':nohist_expirationdates:'.
 4610:                             &escape($key).'='.$now,
 4611:                             $env{'course.'.$cid.'.home'})
 4612:     }
 4613:     return 'ok';
 4614: }
 4615: 
 4616: # ----------------------------------------------------- Devalidate Spreadsheets
 4617: 
 4618: sub devalidate {
 4619:     my ($symb,$uname,$udom)=@_;
 4620:     my $cid=$env{'request.course.id'}; 
 4621:     if ($cid) {
 4622:         # delete the stored spreadsheets for
 4623:         # - the student level sheet of this user in course's homespace
 4624:         # - the assessment level sheet for this resource 
 4625:         #   for this user in user's homespace
 4626: 	# - current conditional state info
 4627: 	my $key=$uname.':'.$udom.':';
 4628:         my $status=
 4629: 	    &del('nohist_calculatedsheets',
 4630: 		 [$key.'studentcalc:'],
 4631: 		 $env{'course.'.$cid.'.domain'},
 4632: 		 $env{'course.'.$cid.'.num'})
 4633: 		.' '.
 4634: 	    &del('nohist_calculatedsheets_'.$cid,
 4635: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 4636:         unless ($status eq 'ok ok') {
 4637:            &logthis('Could not devalidate spreadsheet '.
 4638:                     $uname.' at '.$udom.' for '.
 4639: 		    $symb.': '.$status);
 4640:         }
 4641: 	&delenv('user.state.'.$cid);
 4642:     }
 4643: }
 4644: 
 4645: sub get_scalar {
 4646:     my ($string,$end) = @_;
 4647:     my $value;
 4648:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 4649: 	$value = $1;
 4650:     } elsif ($$string =~ s/^([^&]*?)&//) {
 4651: 	$value = $1;
 4652:     }
 4653:     return &unescape($value);
 4654: }
 4655: 
 4656: sub array2str {
 4657:   my (@array) = @_;
 4658:   my $result=&arrayref2str(\@array);
 4659:   $result=~s/^__ARRAY_REF__//;
 4660:   $result=~s/__END_ARRAY_REF__$//;
 4661:   return $result;
 4662: }
 4663: 
 4664: sub arrayref2str {
 4665:   my ($arrayref) = @_;
 4666:   my $result='__ARRAY_REF__';
 4667:   foreach my $elem (@$arrayref) {
 4668:     if(ref($elem) eq 'ARRAY') {
 4669:       $result.=&arrayref2str($elem).'&';
 4670:     } elsif(ref($elem) eq 'HASH') {
 4671:       $result.=&hashref2str($elem).'&';
 4672:     } elsif(ref($elem)) {
 4673:       #print("Got a ref of ".(ref($elem))." skipping.");
 4674:     } else {
 4675:       $result.=&escape($elem).'&';
 4676:     }
 4677:   }
 4678:   $result=~s/\&$//;
 4679:   $result .= '__END_ARRAY_REF__';
 4680:   return $result;
 4681: }
 4682: 
 4683: sub hash2str {
 4684:   my (%hash) = @_;
 4685:   my $result=&hashref2str(\%hash);
 4686:   $result=~s/^__HASH_REF__//;
 4687:   $result=~s/__END_HASH_REF__$//;
 4688:   return $result;
 4689: }
 4690: 
 4691: sub hashref2str {
 4692:   my ($hashref)=@_;
 4693:   my $result='__HASH_REF__';
 4694:   foreach my $key (sort(keys(%$hashref))) {
 4695:     if (ref($key) eq 'ARRAY') {
 4696:       $result.=&arrayref2str($key).'=';
 4697:     } elsif (ref($key) eq 'HASH') {
 4698:       $result.=&hashref2str($key).'=';
 4699:     } elsif (ref($key)) {
 4700:       $result.='=';
 4701:       #print("Got a ref of ".(ref($key))." skipping.");
 4702:     } else {
 4703: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 4704:     }
 4705: 
 4706:     if(ref($hashref->{$key}) eq 'ARRAY') {
 4707:       $result.=&arrayref2str($hashref->{$key}).'&';
 4708:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 4709:       $result.=&hashref2str($hashref->{$key}).'&';
 4710:     } elsif(ref($hashref->{$key})) {
 4711:        $result.='&';
 4712:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 4713:     } else {
 4714:       $result.=&escape($hashref->{$key}).'&';
 4715:     }
 4716:   }
 4717:   $result=~s/\&$//;
 4718:   $result .= '__END_HASH_REF__';
 4719:   return $result;
 4720: }
 4721: 
 4722: sub str2hash {
 4723:     my ($string)=@_;
 4724:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 4725:     return %$hash;
 4726: }
 4727: 
 4728: sub str2hashref {
 4729:   my ($string) = @_;
 4730: 
 4731:   my %hash;
 4732: 
 4733:   if($string !~ /^__HASH_REF__/) {
 4734:       if (! ($string eq '' || !defined($string))) {
 4735: 	  $hash{'error'}='Not hash reference';
 4736:       }
 4737:       return (\%hash, $string);
 4738:   }
 4739: 
 4740:   $string =~ s/^__HASH_REF__//;
 4741: 
 4742:   while($string !~ /^__END_HASH_REF__/) {
 4743:       #key
 4744:       my $key='';
 4745:       if($string =~ /^__HASH_REF__/) {
 4746:           ($key, $string)=&str2hashref($string);
 4747:           if(defined($key->{'error'})) {
 4748:               $hash{'error'}='Bad data';
 4749:               return (\%hash, $string);
 4750:           }
 4751:       } elsif($string =~ /^__ARRAY_REF__/) {
 4752:           ($key, $string)=&str2arrayref($string);
 4753:           if($key->[0] eq 'Array reference error') {
 4754:               $hash{'error'}='Bad data';
 4755:               return (\%hash, $string);
 4756:           }
 4757:       } else {
 4758:           $string =~ s/^(.*?)=//;
 4759: 	  $key=&unescape($1);
 4760:       }
 4761:       $string =~ s/^=//;
 4762: 
 4763:       #value
 4764:       my $value='';
 4765:       if($string =~ /^__HASH_REF__/) {
 4766:           ($value, $string)=&str2hashref($string);
 4767:           if(defined($value->{'error'})) {
 4768:               $hash{'error'}='Bad data';
 4769:               return (\%hash, $string);
 4770:           }
 4771:       } elsif($string =~ /^__ARRAY_REF__/) {
 4772:           ($value, $string)=&str2arrayref($string);
 4773:           if($value->[0] eq 'Array reference error') {
 4774:               $hash{'error'}='Bad data';
 4775:               return (\%hash, $string);
 4776:           }
 4777:       } else {
 4778: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 4779:       }
 4780:       $string =~ s/^&//;
 4781: 
 4782:       $hash{$key}=$value;
 4783:   }
 4784: 
 4785:   $string =~ s/^__END_HASH_REF__//;
 4786: 
 4787:   return (\%hash, $string);
 4788: }
 4789: 
 4790: sub str2array {
 4791:     my ($string)=@_;
 4792:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 4793:     return @$array;
 4794: }
 4795: 
 4796: sub str2arrayref {
 4797:   my ($string) = @_;
 4798:   my @array;
 4799: 
 4800:   if($string !~ /^__ARRAY_REF__/) {
 4801:       if (! ($string eq '' || !defined($string))) {
 4802: 	  $array[0]='Array reference error';
 4803:       }
 4804:       return (\@array, $string);
 4805:   }
 4806: 
 4807:   $string =~ s/^__ARRAY_REF__//;
 4808: 
 4809:   while($string !~ /^__END_ARRAY_REF__/) {
 4810:       my $value='';
 4811:       if($string =~ /^__HASH_REF__/) {
 4812:           ($value, $string)=&str2hashref($string);
 4813:           if(defined($value->{'error'})) {
 4814:               $array[0] ='Array reference error';
 4815:               return (\@array, $string);
 4816:           }
 4817:       } elsif($string =~ /^__ARRAY_REF__/) {
 4818:           ($value, $string)=&str2arrayref($string);
 4819:           if($value->[0] eq 'Array reference error') {
 4820:               $array[0] ='Array reference error';
 4821:               return (\@array, $string);
 4822:           }
 4823:       } else {
 4824: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 4825:       }
 4826:       $string =~ s/^&//;
 4827: 
 4828:       push(@array, $value);
 4829:   }
 4830: 
 4831:   $string =~ s/^__END_ARRAY_REF__//;
 4832: 
 4833:   return (\@array, $string);
 4834: }
 4835: 
 4836: # -------------------------------------------------------------------Temp Store
 4837: 
 4838: sub tmpreset {
 4839:   my ($symb,$namespace,$domain,$stuname) = @_;
 4840:   if (!$symb) {
 4841:     $symb=&symbread();
 4842:     if (!$symb) { $symb= $env{'request.url'}; }
 4843:   }
 4844:   $symb=escape($symb);
 4845: 
 4846:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4847:   $namespace=~s/\//\_/g;
 4848:   $namespace=~s/\W//g;
 4849: 
 4850:   if (!$domain) { $domain=$env{'user.domain'}; }
 4851:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4852:   if ($domain eq 'public' && $stuname eq 'public') {
 4853:       $stuname=$ENV{'REMOTE_ADDR'};
 4854:   }
 4855:   my $path=LONCAPA::tempdir();
 4856:   my %hash;
 4857:   if (tie(%hash,'GDBM_File',
 4858: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4859: 	  &GDBM_WRCREAT(),0640)) {
 4860:     foreach my $key (keys(%hash)) {
 4861:       if ($key=~ /:$symb/) {
 4862: 	delete($hash{$key});
 4863:       }
 4864:     }
 4865:   }
 4866: }
 4867: 
 4868: sub tmpstore {
 4869:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4870: 
 4871:   if (!$symb) {
 4872:     $symb=&symbread();
 4873:     if (!$symb) { $symb= $env{'request.url'}; }
 4874:   }
 4875:   $symb=escape($symb);
 4876: 
 4877:   if (!$namespace) {
 4878:     # I don't think we would ever want to store this for a course.
 4879:     # it seems this will only be used if we don't have a course.
 4880:     #$namespace=$env{'request.course.id'};
 4881:     #if (!$namespace) {
 4882:       $namespace=$env{'request.state'};
 4883:     #}
 4884:   }
 4885:   $namespace=~s/\//\_/g;
 4886:   $namespace=~s/\W//g;
 4887:   if (!$domain) { $domain=$env{'user.domain'}; }
 4888:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4889:   if ($domain eq 'public' && $stuname eq 'public') {
 4890:       $stuname=$ENV{'REMOTE_ADDR'};
 4891:   }
 4892:   my $now=time;
 4893:   my %hash;
 4894:   my $path=LONCAPA::tempdir();
 4895:   if (tie(%hash,'GDBM_File',
 4896: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4897: 	  &GDBM_WRCREAT(),0640)) {
 4898:     $hash{"version:$symb"}++;
 4899:     my $version=$hash{"version:$symb"};
 4900:     my $allkeys=''; 
 4901:     foreach my $key (keys(%$storehash)) {
 4902:       $allkeys.=$key.':';
 4903:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 4904:     }
 4905:     $hash{"$version:$symb:timestamp"}=$now;
 4906:     $allkeys.='timestamp';
 4907:     $hash{"$version:keys:$symb"}=$allkeys;
 4908:     if (untie(%hash)) {
 4909:       return 'ok';
 4910:     } else {
 4911:       return "error:$!";
 4912:     }
 4913:   } else {
 4914:     return "error:$!";
 4915:   }
 4916: }
 4917: 
 4918: # -----------------------------------------------------------------Temp Restore
 4919: 
 4920: sub tmprestore {
 4921:   my ($symb,$namespace,$domain,$stuname) = @_;
 4922: 
 4923:   if (!$symb) {
 4924:     $symb=&symbread();
 4925:     if (!$symb) { $symb= $env{'request.url'}; }
 4926:   }
 4927:   $symb=escape($symb);
 4928: 
 4929:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4930: 
 4931:   if (!$domain) { $domain=$env{'user.domain'}; }
 4932:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4933:   if ($domain eq 'public' && $stuname eq 'public') {
 4934:       $stuname=$ENV{'REMOTE_ADDR'};
 4935:   }
 4936:   my %returnhash;
 4937:   $namespace=~s/\//\_/g;
 4938:   $namespace=~s/\W//g;
 4939:   my %hash;
 4940:   my $path=LONCAPA::tempdir();
 4941:   if (tie(%hash,'GDBM_File',
 4942: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4943: 	  &GDBM_READER(),0640)) {
 4944:     my $version=$hash{"version:$symb"};
 4945:     $returnhash{'version'}=$version;
 4946:     my $scope;
 4947:     for ($scope=1;$scope<=$version;$scope++) {
 4948:       my $vkeys=$hash{"$scope:keys:$symb"};
 4949:       my @keys=split(/:/,$vkeys);
 4950:       my $key;
 4951:       $returnhash{"$scope:keys"}=$vkeys;
 4952:       foreach $key (@keys) {
 4953: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4954: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4955:       }
 4956:     }
 4957:     if (!(untie(%hash))) {
 4958:       return "error:$!";
 4959:     }
 4960:   } else {
 4961:     return "error:$!";
 4962:   }
 4963:   return %returnhash;
 4964: }
 4965: 
 4966: # ----------------------------------------------------------------------- Store
 4967: 
 4968: sub store {
 4969:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 4970:     my $home='';
 4971: 
 4972:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4973: 
 4974:     $symb=&symbclean($symb);
 4975:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4976: 
 4977:     if (!$domain) { $domain=$env{'user.domain'}; }
 4978:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4979: 
 4980:     &devalidate($symb,$stuname,$domain);
 4981: 
 4982:     $symb=escape($symb);
 4983:     if (!$namespace) { 
 4984:        unless ($namespace=$env{'request.course.id'}) { 
 4985:           return ''; 
 4986:        } 
 4987:     }
 4988:     if (!$home) { $home=$env{'user.home'}; }
 4989: 
 4990:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4991:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4992: 
 4993:     my $namevalue='';
 4994:     foreach my $key (keys(%$storehash)) {
 4995:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4996:     }
 4997:     $namevalue=~s/\&$//;
 4998:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 4999:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 5000: }
 5001: 
 5002: # -------------------------------------------------------------- Critical Store
 5003: 
 5004: sub cstore {
 5005:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
 5006:     my $home='';
 5007: 
 5008:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 5009: 
 5010:     $symb=&symbclean($symb);
 5011:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 5012: 
 5013:     if (!$domain) { $domain=$env{'user.domain'}; }
 5014:     if (!$stuname) { $stuname=$env{'user.name'}; }
 5015: 
 5016:     &devalidate($symb,$stuname,$domain);
 5017: 
 5018:     $symb=escape($symb);
 5019:     if (!$namespace) { 
 5020:        unless ($namespace=$env{'request.course.id'}) { 
 5021:           return ''; 
 5022:        } 
 5023:     }
 5024:     if (!$home) { $home=$env{'user.home'}; }
 5025: 
 5026:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 5027:     $$storehash{'host'}=$perlvar{'lonHostID'};
 5028: 
 5029:     my $namevalue='';
 5030:     foreach my $key (keys(%$storehash)) {
 5031:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5032:     }
 5033:     $namevalue=~s/\&$//;
 5034:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 5035:     return critical
 5036:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
 5037: }
 5038: 
 5039: # --------------------------------------------------------------------- Restore
 5040: 
 5041: sub restore {
 5042:     my ($symb,$namespace,$domain,$stuname) = @_;
 5043:     my $home='';
 5044: 
 5045:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 5046: 
 5047:     if (!$symb) {
 5048:         return if ($namespace eq 'courserequests');
 5049:         unless ($symb=escape(&symbread())) { return ''; }
 5050:     } else {
 5051:         unless ($namespace eq 'courserequests') {
 5052:             $symb=&escape(&symbclean($symb));
 5053:         }
 5054:     }
 5055:     if (!$namespace) { 
 5056:        unless ($namespace=$env{'request.course.id'}) { 
 5057:           return ''; 
 5058:        } 
 5059:     }
 5060:     if (!$domain) { $domain=$env{'user.domain'}; }
 5061:     if (!$stuname) { $stuname=$env{'user.name'}; }
 5062:     if (!$home) { $home=$env{'user.home'}; }
 5063:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 5064: 
 5065:     my %returnhash=();
 5066:     foreach my $line (split(/\&/,$answer)) {
 5067: 	my ($name,$value)=split(/\=/,$line);
 5068:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 5069:     }
 5070:     my $version;
 5071:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 5072:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 5073:           $returnhash{$item}=$returnhash{$version.':'.$item};
 5074:        }
 5075:     }
 5076:     return %returnhash;
 5077: }
 5078: 
 5079: # ---------------------------------------------------------- Course Description
 5080: #
 5081: #  
 5082: 
 5083: sub coursedescription {
 5084:     my ($courseid,$args)=@_;
 5085:     $courseid=~s/^\///;
 5086:     $courseid=~s/\_/\//g;
 5087:     my ($cdomain,$cnum)=split(/\//,$courseid);
 5088:     my $chome=&homeserver($cnum,$cdomain);
 5089:     my $normalid=$cdomain.'_'.$cnum;
 5090:     # need to always cache even if we get errors otherwise we keep 
 5091:     # trying and trying and trying to get the course description.
 5092:     my %envhash=();
 5093:     my %returnhash=();
 5094:     
 5095:     my $expiretime=600;
 5096:     if ($env{'request.course.id'} eq $normalid) {
 5097: 	$expiretime=120;
 5098:     }
 5099: 
 5100:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 5101:     if (!$args->{'freshen_cache'}
 5102: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 5103: 	foreach my $key (keys(%env)) {
 5104: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 5105: 	    my ($setting) = $1;
 5106: 	    $returnhash{$setting} = $env{$key};
 5107: 	}
 5108: 	return %returnhash;
 5109:     }
 5110: 
 5111:     # get the data again
 5112: 
 5113:     if (!$args->{'one_time'}) {
 5114: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 5115:     }
 5116: 
 5117:     if ($chome ne 'no_host') {
 5118:        %returnhash=&dump('environment',$cdomain,$cnum);
 5119:        if (!exists($returnhash{'con_lost'})) {
 5120: 	   my $username = $env{'user.name'}; # Defult username
 5121: 	   if(defined $args->{'user'}) {
 5122: 	       $username = $args->{'user'};
 5123: 	   }
 5124:            $returnhash{'home'}= $chome;
 5125: 	   $returnhash{'domain'} = $cdomain;
 5126: 	   $returnhash{'num'} = $cnum;
 5127:            if (!defined($returnhash{'type'})) {
 5128:                $returnhash{'type'} = 'Course';
 5129:            }
 5130:            while (my ($name,$value) = each %returnhash) {
 5131:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 5132:            }
 5133:            $returnhash{'url'}=&clutter($returnhash{'url'});
 5134:            $returnhash{'fn'}=LONCAPA::tempdir() .
 5135: 	       $username.'_'.$cdomain.'_'.$cnum;
 5136:            $envhash{'course.'.$normalid.'.home'}=$chome;
 5137:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 5138:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 5139:        }
 5140:     }
 5141:     if (!$args->{'one_time'}) {
 5142: 	&appenv(\%envhash);
 5143:     }
 5144:     return %returnhash;
 5145: }
 5146: 
 5147: sub update_released_required {
 5148:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 5149:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 5150:         $cid = $env{'request.course.id'};
 5151:         $cdom = $env{'course.'.$cid.'.domain'};
 5152:         $cnum = $env{'course.'.$cid.'.num'};
 5153:         $chome = $env{'course.'.$cid.'.home'};
 5154:     }
 5155:     if ($needsrelease) {
 5156:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 5157:         my $needsupdate;
 5158:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 5159:             $needsupdate = 1;
 5160:         } else {
 5161:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 5162:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 5163:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 5164:                 $needsupdate = 1;
 5165:             }
 5166:         }
 5167:         if ($needsupdate) {
 5168:             my %needshash = (
 5169:                              'internal.releaserequired' => $needsrelease,
 5170:                             );
 5171:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 5172:             if ($putresult eq 'ok') {
 5173:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 5174:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 5175:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 5176:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 5177:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 5178:                 }
 5179:             }
 5180:         }
 5181:     }
 5182:     return;
 5183: }
 5184: 
 5185: # -------------------------------------------------See if a user is privileged
 5186: 
 5187: sub privileged {
 5188:     my ($username,$domain,$possdomains,$possroles)=@_;
 5189:     my $now = time;
 5190:     my $roles;
 5191:     if (ref($possroles) eq 'ARRAY') {
 5192:         $roles = $possroles; 
 5193:     } else {
 5194:         $roles = ['dc','su'];
 5195:     }
 5196:     if (ref($possdomains) eq 'ARRAY') {
 5197:         my %privileged = &privileged_by_domain($possdomains,$roles);
 5198:         foreach my $dom (@{$possdomains}) {
 5199:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 5200:                 (ref($privileged{$dom}) eq 'HASH')) {
 5201:                 foreach my $role (@{$roles}) {
 5202:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5203:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 5204:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 5205:                             return 1 unless (($end && $end < $now) ||
 5206:                                              ($start && $start > $now));
 5207:                         }
 5208:                     }
 5209:                 }
 5210:             }
 5211:         }
 5212:     } else {
 5213:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 5214:         my $now = time;
 5215: 
 5216:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
 5217:             my ($trole, $tend, $tstart) = split(/_/, $role);
 5218:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 5219:                 return 1 unless ($tend && $tend < $now) 
 5220:                         or ($tstart && $tstart > $now);
 5221:             }
 5222:         }
 5223:     }
 5224:     return 0;
 5225: }
 5226: 
 5227: sub privileged_by_domain {
 5228:     my ($domains,$roles) = @_;
 5229:     my %privileged = ();
 5230:     my $cachetime = 60*60*24;
 5231:     my $now = time;
 5232:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 5233:         return %privileged;
 5234:     }
 5235:     foreach my $dom (@{$domains}) {
 5236:         next if (ref($privileged{$dom}) eq 'HASH');
 5237:         my $needroles;
 5238:         foreach my $role (@{$roles}) {
 5239:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 5240:             if (defined($cached)) {
 5241:                 if (ref($result) eq 'HASH') {
 5242:                     $privileged{$dom}{$role} = $result;
 5243:                 }
 5244:             } else {
 5245:                 $needroles = 1;
 5246:             }
 5247:         }
 5248:         if ($needroles) {
 5249:             my %dompersonnel = &get_domain_roles($dom,$roles);
 5250:             $privileged{$dom} = {};
 5251:             foreach my $server (keys(%dompersonnel)) {
 5252:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 5253:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 5254:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 5255:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 5256:                         next if ($end && $end < $now);
 5257:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
 5258:                             $dompersonnel{$server}{$item};
 5259:                     }
 5260:                 }
 5261:             }
 5262:             if (ref($privileged{$dom}) eq 'HASH') {
 5263:                 foreach my $role (@{$roles}) {
 5264:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5265:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 5266:                     } else {
 5267:                         my %hash = ();
 5268:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 5269:                     }
 5270:                 }
 5271:             }
 5272:         }
 5273:     }
 5274:     return %privileged;
 5275: }
 5276: 
 5277: # -------------------------------------------------------- Get user privileges
 5278: 
 5279: sub rolesinit {
 5280:     my ($domain, $username) = @_;
 5281:     my %userroles = ('user.login.time' => time);
 5282:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 5283: 
 5284:     # firstaccess and timerinterval are related to timed maps/resources. 
 5285:     # also, blocking can be triggered by an activating timer
 5286:     # it's saved in the user's %env.
 5287:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 5288:     my %timerinterval = &dump('timerinterval', $domain, $username);
 5289:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 5290:         %timerintchk, %timerintenv);
 5291: 
 5292:     foreach my $key (keys(%firstaccess)) {
 5293:         my ($cid, $rest) = split(/\0/, $key);
 5294:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 5295:     }
 5296: 
 5297:     foreach my $key (keys(%timerinterval)) {
 5298:         my ($cid,$rest) = split(/\0/,$key);
 5299:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 5300:     }
 5301: 
 5302:     my %allroles=();
 5303:     my %allgroups=();
 5304: 
 5305:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
 5306:         my $role = $rolesdump{$area};
 5307:         $area =~ s/\_\w\w$//;
 5308: 
 5309:         my ($trole, $tend, $tstart, $group_privs);
 5310: 
 5311:         if ($role =~ /^cr/) {
 5312:         # Custom role, defined by a user 
 5313:         # e.g., user.role.cr/msu/smith/mynewrole
 5314:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 5315:                 $trole = $1;
 5316:                 ($tend, $tstart) = split('_', $2);
 5317:             } else {
 5318:                 $trole = $role;
 5319:             }
 5320:         } elsif ($role =~ m|^gr/|) {
 5321:         # Role of member in a group, defined within a course/community
 5322:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 5323:             ($trole, $tend, $tstart) = split(/_/, $role);
 5324:             next if $tstart eq '-1';
 5325:             ($trole, $group_privs) = split(/\//, $trole);
 5326:             $group_privs = &unescape($group_privs);
 5327:         } else {
 5328:         # Just a normal role, defined in roles.tab
 5329:             ($trole, $tend, $tstart) = split(/_/,$role);
 5330:         }
 5331: 
 5332:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 5333:                  $username);
 5334:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 5335: 
 5336:         # role expired or not available yet?
 5337:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 5338:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 5339: 
 5340:         next if $area eq '' or $trole eq '';
 5341: 
 5342:         my $spec = "$trole.$area";
 5343:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 5344: 
 5345:         if ($trole =~ /^cr\//) {
 5346:         # Custom role, defined by a user
 5347:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 5348:         } elsif ($trole eq 'gr') {
 5349:         # Role of a member in a group, defined within a course/community
 5350:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 5351:             next;
 5352:         } else {
 5353:         # Normal role, defined in roles.tab
 5354:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 5355:         }
 5356: 
 5357:         my $cid = $tdomain.'_'.$trest;
 5358:         unless ($firstaccchk{$cid}) {
 5359:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 5360:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 5361:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 5362:                         $coursetimerstarts{$cid}{$item}; 
 5363:                 }
 5364:             }
 5365:             $firstaccchk{$cid} = 1;
 5366:         }
 5367:         unless ($timerintchk{$cid}) {
 5368:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 5369:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 5370:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 5371:                        $coursetimerintervals{$cid}{$item};
 5372:                 }
 5373:             }
 5374:             $timerintchk{$cid} = 1;
 5375:         }
 5376:     }
 5377: 
 5378:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
 5379:         \%allroles, \%allgroups);
 5380:     $env{'user.adv'} = $userroles{'user.adv'};
 5381: 
 5382:     return (\%userroles,\%firstaccenv,\%timerintenv);
 5383: }
 5384: 
 5385: sub set_arearole {
 5386:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 5387:     unless ($nolog) {
 5388: # log the associated role with the area
 5389:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 5390:     }
 5391:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 5392: }
 5393: 
 5394: sub custom_roleprivs {
 5395:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 5396:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 5397:     my $homsvr = &homeserver($rauthor,$rdomain);
 5398:     if (&hostname($homsvr) ne '') {
 5399:         my ($rdummy,$roledef)=
 5400:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 5401:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 5402:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 5403:             if (defined($syspriv)) {
 5404:                 if ($trest =~ /^$match_community$/) {
 5405:                     $syspriv =~ s/bre\&S//; 
 5406:                 }
 5407:                 $$allroles{'cm./'}.=':'.$syspriv;
 5408:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 5409:             }
 5410:             if ($tdomain ne '') {
 5411:                 if (defined($dompriv)) {
 5412:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 5413:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 5414:                 }
 5415:                 if (($trest ne '') && (defined($coursepriv))) {
 5416:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 5417:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 5418:                 }
 5419:             }
 5420:         }
 5421:     }
 5422: }
 5423: 
 5424: sub group_roleprivs {
 5425:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 5426:     my $access = 1;
 5427:     my $now = time;
 5428:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 5429:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 5430:     if ($access) {
 5431:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 5432:         $$allgroups{$course}{$group} .=':'.$group_privs;
 5433:     }
 5434: }
 5435: 
 5436: sub standard_roleprivs {
 5437:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 5438:     if (defined($pr{$trole.':s'})) {
 5439:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 5440:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 5441:     }
 5442:     if ($tdomain ne '') {
 5443:         if (defined($pr{$trole.':d'})) {
 5444:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 5445:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 5446:         }
 5447:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 5448:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 5449:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 5450:         }
 5451:     }
 5452: }
 5453: 
 5454: sub set_userprivs {
 5455:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 5456:     my $author=0;
 5457:     my $adv=0;
 5458:     my %grouproles = ();
 5459:     if (keys(%{$allgroups}) > 0) {
 5460:         my @groupkeys; 
 5461:         foreach my $role (keys(%{$allroles})) {
 5462:             push(@groupkeys,$role);
 5463:         }
 5464:         if (ref($groups_roles) eq 'HASH') {
 5465:             foreach my $key (keys(%{$groups_roles})) {
 5466:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 5467:                     push(@groupkeys,$key);
 5468:                 }
 5469:             }
 5470:         }
 5471:         if (@groupkeys > 0) {
 5472:             foreach my $role (@groupkeys) {
 5473:                 my ($trole,$area,$sec,$extendedarea);
 5474:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 5475:                     $trole = $1;
 5476:                     $area = $2;
 5477:                     $sec = $3;
 5478:                     $extendedarea = $area.$sec;
 5479:                     if (exists($$allgroups{$area})) {
 5480:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 5481:                             my $spec = $trole.'.'.$extendedarea;
 5482:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 5483:                                                 $$allgroups{$area}{$group};
 5484:                         }
 5485:                     }
 5486:                 }
 5487:             }
 5488:         }
 5489:     }
 5490:     foreach my $group (keys(%grouproles)) {
 5491:         $$allroles{$group} = $grouproles{$group};
 5492:     }
 5493:     foreach my $role (keys(%{$allroles})) {
 5494:         my %thesepriv;
 5495:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 5496:         foreach my $item (split(/:/,$$allroles{$role})) {
 5497:             if ($item ne '') {
 5498:                 my ($privilege,$restrictions)=split(/&/,$item);
 5499:                 if ($restrictions eq '') {
 5500:                     $thesepriv{$privilege}='F';
 5501:                 } elsif ($thesepriv{$privilege} ne 'F') {
 5502:                     $thesepriv{$privilege}.=$restrictions;
 5503:                 }
 5504:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 5505:             }
 5506:         }
 5507:         my $thesestr='';
 5508:         foreach my $priv (sort(keys(%thesepriv))) {
 5509: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 5510: 	}
 5511:         $userroles->{'user.priv.'.$role} = $thesestr;
 5512:     }
 5513:     return ($author,$adv);
 5514: }
 5515: 
 5516: sub role_status {
 5517:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 5518:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 5519:         my ($one,$two) = split(m{\./},$rolekey,2);
 5520:         (undef,undef,$$role) = split(/\./,$one,3);
 5521:         unless (!defined($$role) || $$role eq '') {
 5522:             $$where = '/'.$two;
 5523:             $$trolecode=$$role.'.'.$$where;
 5524:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 5525:             $$tstatus='is';
 5526:             if ($$tstart && $$tstart>$update) {
 5527:                 $$tstatus='future';
 5528:                 if ($$tstart<$now) {
 5529:                     if ($$tstart && $$tstart>$refresh) {
 5530:                         if (($$where ne '') && ($$role ne '')) {
 5531:                             my (%allroles,%allgroups,$group_privs,
 5532:                                 %groups_roles,@rolecodes);
 5533:                             my %userroles = (
 5534:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 5535:                             );
 5536:                             @rolecodes = ('cm'); 
 5537:                             my $spec=$$role.'.'.$$where;
 5538:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 5539:                             if ($$role =~ /^cr\//) {
 5540:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 5541:                                 push(@rolecodes,'cr');
 5542:                             } elsif ($$role eq 'gr') {
 5543:                                 push(@rolecodes,$$role);
 5544:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 5545:                                                     $env{'user.name'});
 5546:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 5547:                                 (undef,my $group_privs) = split(/\//,$trole);
 5548:                                 $group_privs = &unescape($group_privs);
 5549:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 5550:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 5551:                                 &get_groups_roles($tdomain,$trest,
 5552:                                                   \%course_roles,\@rolecodes,
 5553:                                                   \%groups_roles);
 5554:                             } else {
 5555:                                 push(@rolecodes,$$role);
 5556:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 5557:                             }
 5558:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
 5559:                             &appenv(\%userroles,\@rolecodes);
 5560:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5561:                         }
 5562:                     }
 5563:                     $$tstatus = 'is';
 5564:                 }
 5565:             }
 5566:             if ($$tend) {
 5567:                 if ($$tend<$update) {
 5568:                     $$tstatus='expired';
 5569:                 } elsif ($$tend<$now) {
 5570:                     $$tstatus='will_not';
 5571:                 }
 5572:             }
 5573:         }
 5574:     }
 5575: }
 5576: 
 5577: sub get_groups_roles {
 5578:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 5579:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 5580:                   (ref($rolecodes) eq 'ARRAY') && 
 5581:                   (ref($groups_roles) eq 'HASH')); 
 5582:     if (keys(%{$cdom_courseroles}) > 0) {
 5583:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 5584:         if ($cdom ne '' && $cnum ne '') {
 5585:             foreach my $key (keys(%{$cdom_courseroles})) {
 5586:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 5587:                     my $crsrole = $1;
 5588:                     my $crssec = $2;
 5589:                     if ($crsrole =~ /^cr/) {
 5590:                         unless (grep(/^cr$/,@{$rolecodes})) {
 5591:                             push(@{$rolecodes},'cr');
 5592:                         }
 5593:                     } else {
 5594:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 5595:                             push(@{$rolecodes},$crsrole);
 5596:                         }
 5597:                     }
 5598:                     my $rolekey = "$crsrole./$cdom/$cnum";
 5599:                     if ($crssec ne '') {
 5600:                         $rolekey .= "/$crssec";
 5601:                     }
 5602:                     $rolekey .= './';
 5603:                     $groups_roles->{$rolekey} = $rolecodes;
 5604:                 }
 5605:             }
 5606:         }
 5607:     }
 5608:     return;
 5609: }
 5610: 
 5611: sub delete_env_groupprivs {
 5612:     my ($where,$courseroles,$possroles) = @_;
 5613:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 5614:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 5615:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 5616:         %{$courseroles->{$udom}} =
 5617:             &get_my_roles('','','userroles',['active'],
 5618:                           $possroles,[$udom],1);
 5619:     }
 5620:     if (ref($courseroles->{$udom}) eq 'HASH') {
 5621:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 5622:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 5623:             my $area = '/'.$cdom.'/'.$cnum;
 5624:             my $privkey = "user.priv.$crsrole.$area";
 5625:             if ($crssec ne '') {
 5626:                 $privkey .= '/'.$crssec;
 5627:             }
 5628:             $privkey .= ".$area/$group";
 5629:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 5630:         }
 5631:     }
 5632:     return;
 5633: }
 5634: 
 5635: sub check_adhoc_privs {
 5636:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
 5637:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 5638:     my $setprivs;
 5639:     if ($env{$cckey}) {
 5640:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 5641:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 5642:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 5643:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5644:             $setprivs = 1;
 5645:         }
 5646:     } else {
 5647:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5648:         $setprivs = 1;
 5649:     }
 5650:     return $setprivs;
 5651: }
 5652: 
 5653: sub set_adhoc_privileges {
 5654: # role can be cc or ca
 5655:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
 5656:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 5657:     my $spec = $role.'.'.$area;
 5658:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 5659:                                   $env{'user.name'},1);
 5660:     my %ccrole = ();
 5661:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
 5662:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
 5663:     &appenv(\%userroles,[$role,'cm']);
 5664:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5665:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 5666:         &appenv( {'request.role'        => $spec,
 5667:                   'request.role.domain' => $dcdom,
 5668:                   'request.course.sec'  => ''
 5669:                  }
 5670:                );
 5671:         my $tadv=0;
 5672:         if (&allowed('adv') eq 'F') { $tadv=1; }
 5673:         &appenv({'request.role.adv'    => $tadv});
 5674:     }
 5675: }
 5676: 
 5677: # --------------------------------------------------------------- get interface
 5678: 
 5679: sub get {
 5680:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5681:    my $items='';
 5682:    foreach my $item (@$storearr) {
 5683:        $items.=&escape($item).'&';
 5684:    }
 5685:    $items=~s/\&$//;
 5686:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5687:    if (!$uname) { $uname=$env{'user.name'}; }
 5688:    my $uhome=&homeserver($uname,$udomain);
 5689: 
 5690:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 5691:    my @pairs=split(/\&/,$rep);
 5692:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 5693:      return @pairs;
 5694:    }
 5695:    my %returnhash=();
 5696:    my $i=0;
 5697:    foreach my $item (@$storearr) {
 5698:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5699:       $i++;
 5700:    }
 5701:    return %returnhash;
 5702: }
 5703: 
 5704: # --------------------------------------------------------------- del interface
 5705: 
 5706: sub del {
 5707:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5708:    my $items='';
 5709:    foreach my $item (@$storearr) {
 5710:        $items.=&escape($item).'&';
 5711:    }
 5712: 
 5713:    $items=~s/\&$//;
 5714:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5715:    if (!$uname) { $uname=$env{'user.name'}; }
 5716:    my $uhome=&homeserver($uname,$udomain);
 5717:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 5718: }
 5719: 
 5720: # -------------------------------------------------------------- dump interface
 5721: 
 5722: sub unserialize {
 5723:     my ($rep, $escapedkeys) = @_;
 5724: 
 5725:     return {} if $rep =~ /^error/;
 5726: 
 5727:     my %returnhash=();
 5728: 	foreach my $item (split(/\&/,$rep)) {
 5729: 	    my ($key, $value) = split(/=/, $item, 2);
 5730: 	    $key = unescape($key) unless $escapedkeys;
 5731: 	    next if $key =~ /^error: 2 /;
 5732: 	    $returnhash{$key} = &thaw_unescape($value);
 5733: 	}
 5734:     #return %returnhash;
 5735:     return \%returnhash;
 5736: }        
 5737: 
 5738: # see Lond::dump_with_regexp
 5739: # if $escapedkeys hash keys won't get unescaped.
 5740: sub dump {
 5741:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 5742:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5743:     if (!$uname) { $uname=$env{'user.name'}; }
 5744:     my $uhome=&homeserver($uname,$udomain);
 5745: 
 5746:     if ($regexp) {
 5747:         $regexp=&escape($regexp);
 5748:     } else {
 5749:         $regexp='.';
 5750:     }
 5751:     if (grep { $_ eq $uhome } current_machine_ids()) {
 5752:         # user is hosted on this machine
 5753:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 5754:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 5755:         return %{unserialize($reply, $escapedkeys)};
 5756:     }
 5757:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 5758:     my @pairs=split(/\&/,$rep);
 5759:     my %returnhash=();
 5760:     if (!($rep =~ /^error/ )) {
 5761: 	foreach my $item (@pairs) {
 5762: 	    my ($key,$value)=split(/=/,$item,2);
 5763:         $key = unescape($key) unless $escapedkeys;
 5764:         #$key = &unescape($key);
 5765: 	    next if ($key =~ /^error: 2 /);
 5766: 	    $returnhash{$key}=&thaw_unescape($value);
 5767: 	}
 5768:     }
 5769:     return %returnhash;
 5770: }
 5771: 
 5772: 
 5773: # --------------------------------------------------------- dumpstore interface
 5774: 
 5775: sub dumpstore {
 5776:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 5777:    # same as dump but keys must be escaped. They may contain colon separated
 5778:    # lists of values that may themself contain colons (e.g. symbs).
 5779:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 5780: }
 5781: 
 5782: # -------------------------------------------------------------- keys interface
 5783: 
 5784: sub getkeys {
 5785:    my ($namespace,$udomain,$uname)=@_;
 5786:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5787:    if (!$uname) { $uname=$env{'user.name'}; }
 5788:    my $uhome=&homeserver($uname,$udomain);
 5789:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 5790:    my @keyarray=();
 5791:    foreach my $key (split(/\&/,$rep)) {
 5792:       next if ($key =~ /^error: 2 /);
 5793:       push(@keyarray,&unescape($key));
 5794:    }
 5795:    return @keyarray;
 5796: }
 5797: 
 5798: # --------------------------------------------------------------- currentdump
 5799: sub currentdump {
 5800:    my ($courseid,$sdom,$sname)=@_;
 5801:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 5802:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 5803:    $sname    = $env{'user.name'}         if (! defined($sname));
 5804:    my $uhome = &homeserver($sname,$sdom);
 5805:    my $rep;
 5806: 
 5807:    if (grep { $_ eq $uhome } current_machine_ids()) {
 5808:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 5809:                    $courseid)));
 5810:    } else {
 5811:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 5812:    }
 5813: 
 5814:    return if ($rep =~ /^(error:|no_such_host)/);
 5815:    #
 5816:    my %returnhash=();
 5817:    #
 5818:    if ($rep eq "unknown_cmd") { 
 5819:        # an old lond will not know currentdump
 5820:        # Do a dump and make it look like a currentdump
 5821:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 5822:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 5823:        my %hash = @tmp;
 5824:        @tmp=();
 5825:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 5826:    } else {
 5827:        my @pairs=split(/\&/,$rep);
 5828:        foreach my $pair (@pairs) {
 5829:            my ($key,$value)=split(/=/,$pair,2);
 5830:            my ($symb,$param) = split(/:/,$key);
 5831:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 5832:                                                         &thaw_unescape($value);
 5833:        }
 5834:    }
 5835:    return %returnhash;
 5836: }
 5837: 
 5838: sub convert_dump_to_currentdump{
 5839:     my %hash = %{shift()};
 5840:     my %returnhash;
 5841:     # Code ripped from lond, essentially.  The only difference
 5842:     # here is the unescaping done by lonnet::dump().  Conceivably
 5843:     # we might run in to problems with parameter names =~ /^v\./
 5844:     while (my ($key,$value) = each(%hash)) {
 5845:         my ($v,$symb,$param) = split(/:/,$key);
 5846: 	$symb  = &unescape($symb);
 5847: 	$param = &unescape($param);
 5848:         next if ($v eq 'version' || $symb eq 'keys');
 5849:         next if (exists($returnhash{$symb}) &&
 5850:                  exists($returnhash{$symb}->{$param}) &&
 5851:                  $returnhash{$symb}->{'v.'.$param} > $v);
 5852:         $returnhash{$symb}->{$param}=$value;
 5853:         $returnhash{$symb}->{'v.'.$param}=$v;
 5854:     }
 5855:     #
 5856:     # Remove all of the keys in the hashes which keep track of
 5857:     # the version of the parameter.
 5858:     while (my ($symb,$param_hash) = each(%returnhash)) {
 5859:         # use a foreach because we are going to delete from the hash.
 5860:         foreach my $key (keys(%$param_hash)) {
 5861:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 5862:         }
 5863:     }
 5864:     return \%returnhash;
 5865: }
 5866: 
 5867: # ------------------------------------------------------ critical inc interface
 5868: 
 5869: sub cinc {
 5870:     return &inc(@_,'critical');
 5871: }
 5872: 
 5873: # --------------------------------------------------------------- inc interface
 5874: 
 5875: sub inc {
 5876:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 5877:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5878:     if (!$uname) { $uname=$env{'user.name'}; }
 5879:     my $uhome=&homeserver($uname,$udomain);
 5880:     my $items='';
 5881:     if (! ref($store)) {
 5882:         # got a single value, so use that instead
 5883:         $items = &escape($store).'=&';
 5884:     } elsif (ref($store) eq 'SCALAR') {
 5885:         $items = &escape($$store).'=&';        
 5886:     } elsif (ref($store) eq 'ARRAY') {
 5887:         $items = join('=&',map {&escape($_);} @{$store});
 5888:     } elsif (ref($store) eq 'HASH') {
 5889:         while (my($key,$value) = each(%{$store})) {
 5890:             $items.= &escape($key).'='.&escape($value).'&';
 5891:         }
 5892:     }
 5893:     $items=~s/\&$//;
 5894:     if ($critical) {
 5895: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 5896:     } else {
 5897: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 5898:     }
 5899: }
 5900: 
 5901: # --------------------------------------------------------------- put interface
 5902: 
 5903: sub put {
 5904:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5905:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5906:    if (!$uname) { $uname=$env{'user.name'}; }
 5907:    my $uhome=&homeserver($uname,$udomain);
 5908:    my $items='';
 5909:    foreach my $item (keys(%$storehash)) {
 5910:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5911:    }
 5912:    $items=~s/\&$//;
 5913:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5914: }
 5915: 
 5916: # ------------------------------------------------------------ newput interface
 5917: 
 5918: sub newput {
 5919:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5920:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5921:    if (!$uname) { $uname=$env{'user.name'}; }
 5922:    my $uhome=&homeserver($uname,$udomain);
 5923:    my $items='';
 5924:    foreach my $key (keys(%$storehash)) {
 5925:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5926:    }
 5927:    $items=~s/\&$//;
 5928:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 5929: }
 5930: 
 5931: # ---------------------------------------------------------  putstore interface
 5932: 
 5933: sub putstore {
 5934:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
 5935:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5936:    if (!$uname) { $uname=$env{'user.name'}; }
 5937:    my $uhome=&homeserver($uname,$udomain);
 5938:    my $items='';
 5939:    foreach my $key (keys(%$storehash)) {
 5940:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 5941:    }
 5942:    $items=~s/\&$//;
 5943:    my $esc_symb=&escape($symb);
 5944:    my $esc_v=&escape($version);
 5945:    my $reply =
 5946:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 5947: 	      $uhome);
 5948:    if (($tolog) && ($reply eq 'ok')) {
 5949:        my $namevalue='';
 5950:        foreach my $key (keys(%{$storehash})) {
 5951:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 5952:        }
 5953:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
 5954:                      '&host='.&escape($perlvar{'lonHostID'}).
 5955:                      '&version='.$esc_v.
 5956:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
 5957:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
 5958:    }
 5959:    if ($reply eq 'unknown_cmd') {
 5960:        # gfall back to way things use to be done
 5961:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 5962: 			    $uname);
 5963:    }
 5964:    return $reply;
 5965: }
 5966: 
 5967: sub old_putstore {
 5968:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5969:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5970:     if (!$uname) { $uname=$env{'user.name'}; }
 5971:     my $uhome=&homeserver($uname,$udomain);
 5972:     my %newstorehash;
 5973:     foreach my $item (keys(%$storehash)) {
 5974: 	my $key = $version.':'.&escape($symb).':'.$item;
 5975: 	$newstorehash{$key} = $storehash->{$item};
 5976:     }
 5977:     my $items='';
 5978:     my %allitems = ();
 5979:     foreach my $item (keys(%newstorehash)) {
 5980: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 5981: 	    my $key = $1.':keys:'.$2;
 5982: 	    $allitems{$key} .= $3.':';
 5983: 	}
 5984: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 5985:     }
 5986:     foreach my $item (keys(%allitems)) {
 5987: 	$allitems{$item} =~ s/\:$//;
 5988: 	$items.= $item.'='.$allitems{$item}.'&';
 5989:     }
 5990:     $items=~s/\&$//;
 5991:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5992: }
 5993: 
 5994: # ------------------------------------------------------ critical put interface
 5995: 
 5996: sub cput {
 5997:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5998:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5999:    if (!$uname) { $uname=$env{'user.name'}; }
 6000:    my $uhome=&homeserver($uname,$udomain);
 6001:    my $items='';
 6002:    foreach my $item (keys(%$storehash)) {
 6003:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 6004:    }
 6005:    $items=~s/\&$//;
 6006:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 6007: }
 6008: 
 6009: # -------------------------------------------------------------- eget interface
 6010: 
 6011: sub eget {
 6012:    my ($namespace,$storearr,$udomain,$uname)=@_;
 6013:    my $items='';
 6014:    foreach my $item (@$storearr) {
 6015:        $items.=&escape($item).'&';
 6016:    }
 6017:    $items=~s/\&$//;
 6018:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6019:    if (!$uname) { $uname=$env{'user.name'}; }
 6020:    my $uhome=&homeserver($uname,$udomain);
 6021:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 6022:    my @pairs=split(/\&/,$rep);
 6023:    my %returnhash=();
 6024:    my $i=0;
 6025:    foreach my $item (@$storearr) {
 6026:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 6027:       $i++;
 6028:    }
 6029:    return %returnhash;
 6030: }
 6031: 
 6032: # ------------------------------------------------------------ tmpput interface
 6033: sub tmpput {
 6034:     my ($storehash,$server,$context)=@_;
 6035:     my $items='';
 6036:     foreach my $item (keys(%$storehash)) {
 6037: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 6038:     }
 6039:     $items=~s/\&$//;
 6040:     if (defined($context)) {
 6041:         $items .= ':'.&escape($context);
 6042:     }
 6043:     return &reply("tmpput:$items",$server);
 6044: }
 6045: 
 6046: # ------------------------------------------------------------ tmpget interface
 6047: sub tmpget {
 6048:     my ($token,$server)=@_;
 6049:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 6050:     my $rep=&reply("tmpget:$token",$server);
 6051:     my %returnhash;
 6052:     foreach my $item (split(/\&/,$rep)) {
 6053: 	my ($key,$value)=split(/=/,$item);
 6054:         next if ($key =~ /^error: 2 /);
 6055: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 6056:     }
 6057:     return %returnhash;
 6058: }
 6059: 
 6060: # ------------------------------------------------------------ tmpdel interface
 6061: sub tmpdel {
 6062:     my ($token,$server)=@_;
 6063:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 6064:     return &reply("tmpdel:$token",$server);
 6065: }
 6066: 
 6067: # ------------------------------------------------------------ get_timebased_id 
 6068: 
 6069: sub get_timebased_id {
 6070:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 6071:         $maxtries) = @_;
 6072:     my ($newid,$error,$dellock);
 6073:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
 6074:         return ('','ok','invalid call to get suffix');
 6075:     }
 6076: 
 6077: # set defaults for any optional args for which values were not supplied
 6078:     if ($who eq '') {
 6079:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 6080:     }
 6081:     if (!$locktries) {
 6082:         $locktries = 3;
 6083:     }
 6084:     if (!$maxtries) {
 6085:         $maxtries = 10;
 6086:     }
 6087:     
 6088:     if (($cdom eq '') || ($cnum eq '')) {
 6089:         if ($env{'request.course.id'}) {
 6090:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6091:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6092:         }
 6093:         if (($cdom eq '') || ($cnum eq '')) {
 6094:             return ('','ok','call to get suffix not in course context');
 6095:         }
 6096:     }
 6097: 
 6098: # construct locking item
 6099:     my $lockhash = {
 6100:                       $prefix."\0".'locked_'.$keyid => $who,
 6101:                    };
 6102:     my $tries = 0;
 6103: 
 6104: # attempt to get lock on nohist_$namespace file
 6105:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 6106:     while (($gotlock ne 'ok') && $tries <$locktries) {
 6107:         $tries ++;
 6108:         sleep 1;
 6109:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 6110:     }
 6111: 
 6112: # attempt to get unique identifier, based on current timestamp
 6113:     if ($gotlock eq 'ok') {
 6114:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 6115:         my $id = time;
 6116:         $newid = $id;
 6117:         if ($idtype eq 'addcode') {
 6118:             $newid .= &sixnum_code();
 6119:         }
 6120:         my $idtries = 0;
 6121:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 6122:             if ($idtype eq 'concat') {
 6123:                 $newid = $id.$idtries;
 6124:             } elsif ($idtype eq 'addcode') {
 6125:                 $newid = $newid.&sixnum_code();
 6126:             } else {
 6127:                 $newid ++;
 6128:             }
 6129:             $idtries ++;
 6130:         }
 6131:         if (!exists($inuse{$prefix."\0".$newid})) {
 6132:             my %new_item =  (
 6133:                               $prefix."\0".$newid => $who,
 6134:                             );
 6135:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 6136:                                                  $cdom,$cnum);
 6137:             if ($putresult ne 'ok') {
 6138:                 undef($newid);
 6139:                 $error = 'error saving new item: '.$putresult;
 6140:             }
 6141:         } else {
 6142:              undef($newid);
 6143:              $error = ('error: no unique suffix available for the new item ');
 6144:         }
 6145: #  remove lock
 6146:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 6147:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 6148:     } else {
 6149:         $error = "error: could not obtain lockfile\n";
 6150:         $dellock = 'ok';
 6151:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
 6152:             $dellock = 'nolock';
 6153:         }
 6154:     }
 6155:     return ($newid,$dellock,$error);
 6156: }
 6157: 
 6158: sub sixnum_code {
 6159:     my $code;
 6160:     for (0..6) {
 6161:         $code .= int( rand(9) );
 6162:     }
 6163:     return $code;
 6164: }
 6165: 
 6166: # -------------------------------------------------- portfolio access checking
 6167: 
 6168: sub portfolio_access {
 6169:     my ($requrl,$clientip) = @_;
 6170:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 6171:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
 6172:     if ($result) {
 6173:         my %setters;
 6174:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 6175:             my ($startblock,$endblock) =
 6176:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 6177:             if ($startblock && $endblock) {
 6178:                 return 'B';
 6179:             }
 6180:         } else {
 6181:             my ($startblock,$endblock) =
 6182:                 &Apache::loncommon::blockcheck(\%setters,'port');
 6183:             if ($startblock && $endblock) {
 6184:                 return 'B';
 6185:             }
 6186:         }
 6187:     }
 6188:     if ($result eq 'ok') {
 6189:        return 'F';
 6190:     } elsif ($result =~ /^[^:]+:guest_/) {
 6191:        return 'A';
 6192:     }
 6193:     return '';
 6194: }
 6195: 
 6196: sub get_portfolio_access {
 6197:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
 6198: 
 6199:     if (!ref($access_hash)) {
 6200: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 6201: 	my %access_controls = &get_access_controls($current_perms,$group,
 6202: 						   $file_name);
 6203: 	$access_hash = $access_controls{$file_name};
 6204:     }
 6205: 
 6206:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
 6207:     my $now = time;
 6208:     if (ref($access_hash) eq 'HASH') {
 6209:         foreach my $key (keys(%{$access_hash})) {
 6210:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 6211:             if ($start > $now) {
 6212:                 next;
 6213:             }
 6214:             if ($end && $end<$now) {
 6215:                 next;
 6216:             }
 6217:             if ($scope eq 'public') {
 6218:                 $public = $key;
 6219:                 last;
 6220:             } elsif ($scope eq 'guest') {
 6221:                 $guest = $key;
 6222:             } elsif ($scope eq 'domains') {
 6223:                 push(@domains,$key);
 6224:             } elsif ($scope eq 'users') {
 6225:                 push(@users,$key);
 6226:             } elsif ($scope eq 'course') {
 6227:                 push(@courses,$key);
 6228:             } elsif ($scope eq 'group') {
 6229:                 push(@groups,$key);
 6230:             } elsif ($scope eq 'ip') {
 6231:                 push(@ips,$key);
 6232:             }
 6233:         }
 6234:         if ($public) {
 6235:             return 'ok';
 6236:         } elsif (@ips > 0) {
 6237:             my $allowed;
 6238:             foreach my $ipkey (@ips) {
 6239:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
 6240:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
 6241:                         $allowed = 1;
 6242:                         last; 
 6243:                     }
 6244:                 }
 6245:             }
 6246:             if ($allowed) {
 6247:                 return 'ok';
 6248:             }
 6249:         }
 6250:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 6251:             if ($guest) {
 6252:                 return $guest;
 6253:             }
 6254:         } else {
 6255:             if (@domains > 0) {
 6256:                 foreach my $domkey (@domains) {
 6257:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 6258:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 6259:                             return 'ok';
 6260:                         }
 6261:                     }
 6262:                 }
 6263:             }
 6264:             if (@users > 0) {
 6265:                 foreach my $userkey (@users) {
 6266:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 6267:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 6268:                             if (ref($item) eq 'HASH') {
 6269:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 6270:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 6271:                                     return 'ok';
 6272:                                 }
 6273:                             }
 6274:                         }
 6275:                     } 
 6276:                 }
 6277:             }
 6278:             my %roleshash;
 6279:             my @courses_and_groups = @courses;
 6280:             push(@courses_and_groups,@groups); 
 6281:             if (@courses_and_groups > 0) {
 6282:                 my (%allgroups,%allroles); 
 6283:                 my ($start,$end,$role,$sec,$group);
 6284:                 foreach my $envkey (%env) {
 6285:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 6286:                         my $cid = $2.'_'.$3; 
 6287:                         if ($1 eq 'gr') {
 6288:                             $group = $4;
 6289:                             $allgroups{$cid}{$group} = $env{$envkey};
 6290:                         } else {
 6291:                             if ($4 eq '') {
 6292:                                 $sec = 'none';
 6293:                             } else {
 6294:                                 $sec = $4;
 6295:                             }
 6296:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 6297:                         }
 6298:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 6299:                         my $cid = $2.'_'.$3;
 6300:                         if ($4 eq '') {
 6301:                             $sec = 'none';
 6302:                         } else {
 6303:                             $sec = $4;
 6304:                         }
 6305:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 6306:                     }
 6307:                 }
 6308:                 if (keys(%allroles) == 0) {
 6309:                     return;
 6310:                 }
 6311:                 foreach my $key (@courses_and_groups) {
 6312:                     my %content = %{$$access_hash{$key}};
 6313:                     my $cnum = $content{'number'};
 6314:                     my $cdom = $content{'domain'};
 6315:                     my $cid = $cdom.'_'.$cnum;
 6316:                     if (!exists($allroles{$cid})) {
 6317:                         next;
 6318:                     }    
 6319:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 6320:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 6321:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 6322:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 6323:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 6324:                         foreach my $role (keys(%{$allroles{$cid}})) {
 6325:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 6326:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 6327:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 6328:                                         if (grep/^all$/,@sections) {
 6329:                                             return 'ok';
 6330:                                         } else {
 6331:                                             if (grep/^$sec$/,@sections) {
 6332:                                                 return 'ok';
 6333:                                             }
 6334:                                         }
 6335:                                     }
 6336:                                 }
 6337:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 6338:                                     if (grep/^none$/,@groups) {
 6339:                                         return 'ok';
 6340:                                     }
 6341:                                 } else {
 6342:                                     if (grep/^all$/,@groups) {
 6343:                                         return 'ok';
 6344:                                     } 
 6345:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 6346:                                         if (grep/^$group$/,@groups) {
 6347:                                             return 'ok';
 6348:                                         }
 6349:                                     }
 6350:                                 } 
 6351:                             }
 6352:                         }
 6353:                     }
 6354:                 }
 6355:             }
 6356:             if ($guest) {
 6357:                 return $guest;
 6358:             }
 6359:         }
 6360:     }
 6361:     return;
 6362: }
 6363: 
 6364: sub course_group_datechecker {
 6365:     my ($dates,$now,$status) = @_;
 6366:     my ($start,$end) = split(/\./,$dates);
 6367:     if (!$start && !$end) {
 6368:         return 'ok';
 6369:     }
 6370:     if (grep/^active$/,@{$status}) {
 6371:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 6372:             return 'ok';
 6373:         }
 6374:     }
 6375:     if (grep/^previous$/,@{$status}) {
 6376:         if ($end > $now ) {
 6377:             return 'ok';
 6378:         }
 6379:     }
 6380:     if (grep/^future$/,@{$status}) {
 6381:         if ($start > $now) {
 6382:             return 'ok';
 6383:         }
 6384:     }
 6385:     return; 
 6386: }
 6387: 
 6388: sub parse_portfolio_url {
 6389:     my ($url) = @_;
 6390: 
 6391:     my ($type,$udom,$unum,$group,$file_name);
 6392:     
 6393:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 6394: 	$type = 1;
 6395:         $udom = $1;
 6396:         $unum = $2;
 6397:         $file_name = $3;
 6398:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 6399: 	$type = 2;
 6400:         $udom = $1;
 6401:         $unum = $2;
 6402:         $group = $3;
 6403:         $file_name = $3.'/'.$4;
 6404:     }
 6405:     if (wantarray) {
 6406: 	return ($type,$udom,$unum,$file_name,$group);
 6407:     }
 6408:     return $type;
 6409: }
 6410: 
 6411: sub is_portfolio_url {
 6412:     my ($url) = @_;
 6413:     return scalar(&parse_portfolio_url($url));
 6414: }
 6415: 
 6416: sub is_portfolio_file {
 6417:     my ($file) = @_;
 6418:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 6419:         return 1;
 6420:     }
 6421:     return;
 6422: }
 6423: 
 6424: sub usertools_access {
 6425:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 6426:     my ($access,%tools);
 6427:     if ($context eq '') {
 6428:         $context = 'tools';
 6429:     }
 6430:     if ($context eq 'requestcourses') {
 6431:         %tools = (
 6432:                       official   => 1,
 6433:                       unofficial => 1,
 6434:                       community  => 1,
 6435:                       textbook   => 1,
 6436:                  );
 6437:     } elsif ($context eq 'requestauthor') {
 6438:         %tools = (
 6439:                       requestauthor => 1,
 6440:                  );
 6441:     } else {
 6442:         %tools = (
 6443:                       aboutme   => 1,
 6444:                       blog      => 1,
 6445:                       webdav    => 1,
 6446:                       portfolio => 1,
 6447:                  );
 6448:     }
 6449:     return if (!defined($tools{$tool}));
 6450: 
 6451:     if (($udom eq '') || ($uname eq '')) {
 6452:         $udom = $env{'user.domain'};
 6453:         $uname = $env{'user.name'};
 6454:     }
 6455: 
 6456:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6457:         if ($action ne 'reload') {
 6458:             if ($context eq 'requestcourses') {
 6459:                 return $env{'environment.canrequest.'.$tool};
 6460:             } elsif ($context eq 'requestauthor') {
 6461:                 return $env{'environment.canrequest.author'};
 6462:             } else {
 6463:                 return $env{'environment.availabletools.'.$tool};
 6464:             }
 6465:         }
 6466:     }
 6467: 
 6468:     my ($toolstatus,$inststatus,$envkey);
 6469:     if ($context eq 'requestauthor') {
 6470:         $envkey = $context; 
 6471:     } else {
 6472:         $envkey = $context.'.'.$tool;
 6473:     }
 6474: 
 6475:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 6476:          ($action ne 'reload')) {
 6477:         $toolstatus = $env{'environment.'.$envkey};
 6478:         $inststatus = $env{'environment.inststatus'};
 6479:     } else {
 6480:         if (ref($userenvref) eq 'HASH') {
 6481:             $toolstatus = $userenvref->{$envkey};
 6482:             $inststatus = $userenvref->{'inststatus'};
 6483:         } else {
 6484:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 6485:             $toolstatus = $userenv{$envkey};
 6486:             $inststatus = $userenv{'inststatus'};
 6487:         }
 6488:     }
 6489: 
 6490:     if ($toolstatus ne '') {
 6491:         if ($toolstatus) {
 6492:             $access = 1;
 6493:         } else {
 6494:             $access = 0;
 6495:         }
 6496:         return $access;
 6497:     }
 6498: 
 6499:     my ($is_adv,%domdef);
 6500:     if (ref($is_advref) eq 'HASH') {
 6501:         $is_adv = $is_advref->{'is_adv'};
 6502:     } else {
 6503:         $is_adv = &is_advanced_user($udom,$uname);
 6504:     }
 6505:     if (ref($domdefref) eq 'HASH') {
 6506:         %domdef = %{$domdefref};
 6507:     } else {
 6508:         %domdef = &get_domain_defaults($udom);
 6509:     }
 6510:     if (ref($domdef{$tool}) eq 'HASH') {
 6511:         if ($is_adv) {
 6512:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 6513:                 if ($domdef{$tool}{'_LC_adv'}) { 
 6514:                     $access = 1;
 6515:                 } else {
 6516:                     $access = 0;
 6517:                 }
 6518:                 return $access;
 6519:             }
 6520:         }
 6521:         if ($inststatus ne '') {
 6522:             my ($hasaccess,$hasnoaccess);
 6523:             foreach my $affiliation (split(/:/,$inststatus)) {
 6524:                 if ($domdef{$tool}{$affiliation} ne '') { 
 6525:                     if ($domdef{$tool}{$affiliation}) {
 6526:                         $hasaccess = 1;
 6527:                     } else {
 6528:                         $hasnoaccess = 1;
 6529:                     }
 6530:                 }
 6531:             }
 6532:             if ($hasaccess || $hasnoaccess) {
 6533:                 if ($hasaccess) {
 6534:                     $access = 1;
 6535:                 } elsif ($hasnoaccess) {
 6536:                     $access = 0; 
 6537:                 }
 6538:                 return $access;
 6539:             }
 6540:         } else {
 6541:             if ($domdef{$tool}{'default'} ne '') {
 6542:                 if ($domdef{$tool}{'default'}) {
 6543:                     $access = 1;
 6544:                 } elsif ($domdef{$tool}{'default'} == 0) {
 6545:                     $access = 0;
 6546:                 }
 6547:                 return $access;
 6548:             }
 6549:         }
 6550:     } else {
 6551:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 6552:             $access = 1;
 6553:         } else {
 6554:             $access = 0;
 6555:         }
 6556:         return $access;
 6557:     }
 6558: }
 6559: 
 6560: sub is_course_owner {
 6561:     my ($cdom,$cnum,$udom,$uname) = @_;
 6562:     if (($udom eq '') || ($uname eq '')) {
 6563:         $udom = $env{'user.domain'};
 6564:         $uname = $env{'user.name'};
 6565:     }
 6566:     unless (($udom eq '') || ($uname eq '')) {
 6567:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 6568:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 6569:                 return 1;
 6570:             } else {
 6571:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 6572:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 6573:                     return 1;
 6574:                 }
 6575:             }
 6576:         }
 6577:     }
 6578:     return;
 6579: }
 6580: 
 6581: sub is_advanced_user {
 6582:     my ($udom,$uname) = @_;
 6583:     if ($udom ne '' && $uname ne '') {
 6584:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6585:             if (wantarray) {
 6586:                 return ($env{'user.adv'},$env{'user.author'});
 6587:             } else {
 6588:                 return $env{'user.adv'};
 6589:             }
 6590:         }
 6591:     }
 6592:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 6593:     my %allroles;
 6594:     my ($is_adv,$is_author);
 6595:     foreach my $role (keys(%roleshash)) {
 6596:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 6597:         my $area = '/'.$tdomain.'/'.$trest;
 6598:         if ($sec ne '') {
 6599:             $area .= '/'.$sec;
 6600:         }
 6601:         if (($area ne '') && ($trole ne '')) {
 6602:             my $spec=$trole.'.'.$area;
 6603:             if ($trole =~ /^cr\//) {
 6604:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6605:             } elsif ($trole ne 'gr') {
 6606:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6607:             }
 6608:             if ($trole eq 'au') {
 6609:                 $is_author = 1;
 6610:             }
 6611:         }
 6612:     }
 6613:     foreach my $role (keys(%allroles)) {
 6614:         last if ($is_adv);
 6615:         foreach my $item (split(/:/,$allroles{$role})) {
 6616:             if ($item ne '') {
 6617:                 my ($privilege,$restrictions)=split(/&/,$item);
 6618:                 if ($privilege eq 'adv') {
 6619:                     $is_adv = 1;
 6620:                     last;
 6621:                 }
 6622:             }
 6623:         }
 6624:     }
 6625:     if (wantarray) {
 6626:         return ($is_adv,$is_author);
 6627:     }
 6628:     return $is_adv;
 6629: }
 6630: 
 6631: sub check_can_request {
 6632:     my ($dom,$can_request,$request_domains) = @_;
 6633:     my $canreq = 0;
 6634:     my ($types,$typename) = &Apache::loncommon::course_types();
 6635:     my @options = ('approval','validate','autolimit');
 6636:     my $optregex = join('|',@options);
 6637:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 6638:         foreach my $type (@{$types}) {
 6639:             if (&usertools_access($env{'user.name'},
 6640:                                   $env{'user.domain'},
 6641:                                   $type,undef,'requestcourses')) {
 6642:                 $canreq ++;
 6643:                 if (ref($request_domains) eq 'HASH') {
 6644:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 6645:                 }
 6646:                 if ($dom eq $env{'user.domain'}) {
 6647:                     $can_request->{$type} = 1;
 6648:                 }
 6649:             }
 6650:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 6651:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 6652:                 if (@curr > 0) {
 6653:                     foreach my $item (@curr) {
 6654:                         if (ref($request_domains) eq 'HASH') {
 6655:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 6656:                             if ($otherdom ne '') {
 6657:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 6658:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 6659:                                         push(@{$request_domains->{$type}},$otherdom);
 6660:                                     }
 6661:                                 } else {
 6662:                                     push(@{$request_domains->{$type}},$otherdom);
 6663:                                 }
 6664:                             }
 6665:                         }
 6666:                     }
 6667:                     unless($dom eq $env{'user.domain'}) {
 6668:                         $canreq ++;
 6669:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 6670:                             $can_request->{$type} = 1;
 6671:                         }
 6672:                     }
 6673:                 }
 6674:             }
 6675:         }
 6676:     }
 6677:     return $canreq;
 6678: }
 6679: 
 6680: # ---------------------------------------------- Custom access rule evaluation
 6681: 
 6682: sub customaccess {
 6683:     my ($priv,$uri)=@_;
 6684:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 6685:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 6686:     $udom = &LONCAPA::clean_domain($udom);
 6687:     $ucrs = &LONCAPA::clean_username($ucrs);
 6688:     my $access=0;
 6689:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 6690: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 6691: 	if ($type eq 'user') {
 6692: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 6693: 		my ($tdom,$tuname)=split(m{/},$scope);
 6694: 		if ($tdom) {
 6695: 		    if ($tdom ne $env{'user.domain'}) { next; }
 6696: 		}
 6697: 		if ($tuname) {
 6698: 		    if ($tuname ne $env{'user.name'}) { next; }
 6699: 		}
 6700: 		$access=($effect eq 'allow');
 6701: 		last;
 6702: 	    }
 6703: 	} else {
 6704: 	    if ($role) {
 6705: 		if ($role ne $urole) { next; }
 6706: 	    }
 6707: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 6708: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 6709: 		if ($tdom) {
 6710: 		    if ($tdom ne $udom) { next; }
 6711: 		}
 6712: 		if ($tcrs) {
 6713: 		    if ($tcrs ne $ucrs) { next; }
 6714: 		}
 6715: 		if ($tsec) {
 6716: 		    if ($tsec ne $usec) { next; }
 6717: 		}
 6718: 		$access=($effect eq 'allow');
 6719: 		last;
 6720: 	    }
 6721: 	    if ($realm eq '' && $role eq '') {
 6722: 		$access=($effect eq 'allow');
 6723: 	    }
 6724: 	}
 6725:     }
 6726:     return $access;
 6727: }
 6728: 
 6729: # ------------------------------------------------- Check for a user privilege
 6730: 
 6731: sub allowed {
 6732:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
 6733:     my $ver_orguri=$uri;
 6734:     $uri=&deversion($uri);
 6735:     my $orguri=$uri;
 6736:     $uri=&declutter($uri);
 6737: 
 6738:     if ($priv eq 'evb') {
 6739: # Evade communication block restrictions for specified role in a course
 6740:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 6741:             return $1;
 6742:         } else {
 6743:             return;
 6744:         }
 6745:     }
 6746: 
 6747:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 6748: # Free bre access to adm and meta resources
 6749:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 6750: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 6751: 	&& ($priv eq 'bre')) {
 6752: 	return 'F';
 6753:     }
 6754: 
 6755: # Free bre access to user's own portfolio contents
 6756:     my ($space,$domain,$name,@dir)=split('/',$uri);
 6757:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 6758: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 6759:         my %setters;
 6760:         my ($startblock,$endblock) = 
 6761:             &Apache::loncommon::blockcheck(\%setters,'port');
 6762:         if ($startblock && $endblock) {
 6763:             return 'B';
 6764:         } else {
 6765:             return 'F';
 6766:         }
 6767:     }
 6768: 
 6769: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 6770:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 6771:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 6772:         if (exists($env{'request.course.id'})) {
 6773:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6774:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6775:             if (($domain eq $cdom) && ($name eq $cnum)) {
 6776:                 my $courseprivid=$env{'request.course.id'};
 6777:                 $courseprivid=~s/\_/\//;
 6778:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 6779:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 6780:                     return $1; 
 6781:                 } else {
 6782:                     if ($env{'request.course.sec'}) {
 6783:                         $courseprivid.='/'.$env{'request.course.sec'};
 6784:                     }
 6785:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 6786:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 6787:                         return $2;
 6788:                     }
 6789:                 }
 6790:             }
 6791:         }
 6792:     }
 6793: 
 6794: # Free bre to public access
 6795: 
 6796:     if ($priv eq 'bre') {
 6797:         my $copyright=&metadata($uri,'copyright');
 6798: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 6799:            return 'F'; 
 6800:         }
 6801:         if ($copyright eq 'priv') {
 6802:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6803: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 6804: 		return '';
 6805:             }
 6806:         }
 6807:         if ($copyright eq 'domain') {
 6808:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6809: 	    unless (($env{'user.domain'} eq $1) ||
 6810:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 6811: 		return '';
 6812:             }
 6813:         }
 6814:         if ($env{'request.role'}=~ /li\.\//) {
 6815:             # Library role, so allow browsing of resources in this domain.
 6816:             return 'F';
 6817:         }
 6818:         if ($copyright eq 'custom') {
 6819: 	    unless (&customaccess($priv,$uri)) { return ''; }
 6820:         }
 6821:     }
 6822:     # Domain coordinator is trying to create a course
 6823:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 6824:         # uri is the requested domain in this case.
 6825:         # comparison to 'request.role.domain' shows if the user has selected
 6826:         # a role of dc for the domain in question.
 6827:         return 'F' if ($uri eq $env{'request.role.domain'});
 6828:     }
 6829: 
 6830:     my $thisallowed='';
 6831:     my $statecond=0;
 6832:     my $courseprivid='';
 6833: 
 6834:     my $ownaccess;
 6835:     # Community Coordinator or Assistant Co-author browsing resource space.
 6836:     if (($priv eq 'bro') && ($env{'user.author'})) {
 6837:         if ($uri eq '') {
 6838:             $ownaccess = 1;
 6839:         } else {
 6840:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 6841:                 my $udom = $env{'user.domain'};
 6842:                 my $uname = $env{'user.name'};
 6843:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 6844:                     $ownaccess = 1;
 6845:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 6846:                     unless ($uri =~ m{\.\./}) {
 6847:                         $ownaccess = 1;
 6848:                     }
 6849:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 6850:                     my $now = time;
 6851:                     if ($uri =~ m{^([^/]+)/?$}) {
 6852:                         my $adom = $1;
 6853:                         foreach my $key (keys(%env)) {
 6854:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 6855:                                 my ($start,$end) = split('.',$env{$key});
 6856:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6857:                                     $ownaccess = 1;
 6858:                                     last;
 6859:                                 }
 6860:                             }
 6861:                         }
 6862:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 6863:                         my $adom = $1;
 6864:                         my $aname = $2;
 6865:                         foreach my $role ('ca','aa') { 
 6866:                             if ($env{"user.role.$role./$adom/$aname"}) {
 6867:                                 my ($start,$end) =
 6868:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 6869:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6870:                                     $ownaccess = 1;
 6871:                                     last;
 6872:                                 }
 6873:                             }
 6874:                         }
 6875:                     }
 6876:                 }
 6877:             }
 6878:         }
 6879:     }
 6880: 
 6881: # Course
 6882: 
 6883:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 6884:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6885:             $thisallowed.=$1;
 6886:         }
 6887:     }
 6888: 
 6889: # Domain
 6890: 
 6891:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 6892:        =~/\Q$priv\E\&([^\:]*)/) {
 6893:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6894:             $thisallowed.=$1;
 6895:         }
 6896:     }
 6897: 
 6898: # User who is not author or co-author might still be able to edit
 6899: # resource of an author in the domain (e.g., if Domain Coordinator).
 6900:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 6901:         (&allowed('mdc',$env{'request.course.id'}))) {
 6902:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 6903:             $thisallowed.=$1;
 6904:         }
 6905:     }
 6906: 
 6907: # Course: uri itself is a course
 6908:     my $courseuri=$uri;
 6909:     $courseuri=~s/\_(\d)/\/$1/;
 6910:     $courseuri=~s/^([^\/])/\/$1/;
 6911: 
 6912:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 6913:        =~/\Q$priv\E\&([^\:]*)/) {
 6914:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6915:             $thisallowed.=$1;
 6916:         }
 6917:     }
 6918: 
 6919: # URI is an uploaded document for this course, default permissions don't matter
 6920: # not allowing 'edit' access (editupload) to uploaded course docs
 6921:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 6922: 	$thisallowed='';
 6923:         my ($match)=&is_on_map($uri);
 6924:         if ($match) {
 6925:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 6926:                   =~/\Q$priv\E\&([^\:]*)/) {
 6927:                 my $value = $1;
 6928:                 if ($noblockcheck) {
 6929:                     $thisallowed.=$value;
 6930:                 } else {
 6931:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6932:                     if (@blockers > 0) {
 6933:                         $thisallowed = 'B';
 6934:                     } else {
 6935:                         $thisallowed.=$value;
 6936:                     }
 6937:                 }
 6938:             }
 6939:         } else {
 6940:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 6941:             if ($refuri) {
 6942:                 if ($refuri =~ m|^/adm/|) {
 6943:                     $thisallowed='F';
 6944:                 } else {
 6945:                     $refuri=&declutter($refuri);
 6946:                     my ($match) = &is_on_map($refuri);
 6947:                     if ($match) {
 6948:                         if ($noblockcheck) {
 6949:                             $thisallowed='F';
 6950:                         } else {
 6951:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6952:                             if (@blockers > 0) {
 6953:                                 $thisallowed = 'B';
 6954:                             } else {
 6955:                                 $thisallowed='F';
 6956:                             }
 6957:                         }
 6958:                     }
 6959:                 }
 6960:             }
 6961:         }
 6962:     }
 6963: 
 6964:     if ($priv eq 'bre'
 6965: 	&& $thisallowed ne 'F' 
 6966: 	&& $thisallowed ne '2'
 6967: 	&& &is_portfolio_url($uri)) {
 6968: 	$thisallowed = &portfolio_access($uri,$clientip);
 6969:     }
 6970: 
 6971: # Full access at system, domain or course-wide level? Exit.
 6972:     if ($thisallowed=~/F/) {
 6973: 	return 'F';
 6974:     }
 6975: 
 6976: # If this is generating or modifying users, exit with special codes
 6977: 
 6978:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 6979: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 6980: 	    my ($audom,$auname)=split('/',$uri);
 6981: # no author name given, so this just checks on the general right to make a co-author in this domain
 6982: 	    unless ($auname) { return $thisallowed; }
 6983: # an author name is given, so we are about to actually make a co-author for a certain account
 6984: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 6985: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 6986: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 6987: 	}
 6988: 	return $thisallowed;
 6989:     }
 6990: #
 6991: # Gathered so far: system, domain and course wide privileges
 6992: #
 6993: # Course: See if uri or referer is an individual resource that is part of 
 6994: # the course
 6995: 
 6996:     if ($env{'request.course.id'}) {
 6997: 
 6998:        $courseprivid=$env{'request.course.id'};
 6999:        if ($env{'request.course.sec'}) {
 7000:           $courseprivid.='/'.$env{'request.course.sec'};
 7001:        }
 7002:        $courseprivid=~s/\_/\//;
 7003:        my $checkreferer=1;
 7004:        my ($match,$cond)=&is_on_map($uri);
 7005:        if ($match) {
 7006:            $statecond=$cond;
 7007:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 7008:                =~/\Q$priv\E\&([^\:]*)/) {
 7009:                my $value = $1;
 7010:                if ($priv eq 'bre') {
 7011:                    if ($noblockcheck) {
 7012:                        $thisallowed.=$value;
 7013:                    } else {
 7014:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
 7015:                        if (@blockers > 0) {
 7016:                            $thisallowed = 'B';
 7017:                        } else {
 7018:                            $thisallowed.=$value;
 7019:                        }
 7020:                    }
 7021:                } else {
 7022:                    $thisallowed.=$value;
 7023:                }
 7024:                $checkreferer=0;
 7025:            }
 7026:        }
 7027:        
 7028:        if ($checkreferer) {
 7029: 	  my $refuri=$env{'httpref.'.$orguri};
 7030:             unless ($refuri) {
 7031:                 foreach my $key (keys(%env)) {
 7032: 		    if ($key=~/^httpref\..*\*/) {
 7033: 			my $pattern=$key;
 7034:                         $pattern=~s/^httpref\.\/res\///;
 7035:                         $pattern=~s/\*/\[\^\/\]\+/g;
 7036:                         $pattern=~s/\//\\\//g;
 7037:                         if ($orguri=~/$pattern/) {
 7038: 			    $refuri=$env{$key};
 7039:                         }
 7040:                     }
 7041:                 }
 7042:             }
 7043: 
 7044:          if ($refuri) { 
 7045: 	  $refuri=&declutter($refuri);
 7046:           my ($match,$cond)=&is_on_map($refuri);
 7047:             if ($match) {
 7048:               my $refstatecond=$cond;
 7049:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 7050:                   =~/\Q$priv\E\&([^\:]*)/) {
 7051:                   my $value = $1;
 7052:                   if ($priv eq 'bre') {
 7053:                       if ($noblockcheck) {
 7054:                           $thisallowed.=$value;
 7055:                       } else {
 7056:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 7057:                           if (@blockers > 0) {
 7058:                               $thisallowed = 'B';
 7059:                           } else {
 7060:                               $thisallowed.=$value;
 7061:                           }
 7062:                       }
 7063:                   } else {
 7064:                       $thisallowed.=$value;
 7065:                   }
 7066:                   $uri=$refuri;
 7067:                   $statecond=$refstatecond;
 7068:               }
 7069:           }
 7070:         }
 7071:        }
 7072:    }
 7073: 
 7074: #
 7075: # Gathered now: all privileges that could apply, and condition number
 7076: # 
 7077: #
 7078: # Full or no access?
 7079: #
 7080: 
 7081:     if ($thisallowed=~/F/) {
 7082: 	return 'F';
 7083:     }
 7084: 
 7085:     unless ($thisallowed) {
 7086:         return '';
 7087:     }
 7088: 
 7089: # Restrictions exist, deal with them
 7090: #
 7091: #   C:according to course preferences
 7092: #   R:according to resource settings
 7093: #   L:unless locked
 7094: #   X:according to user session state
 7095: #
 7096: 
 7097: # Possibly locked functionality, check all courses
 7098: # Locks might take effect only after 10 minutes cache expiration for other
 7099: # courses, and 2 minutes for current course
 7100: 
 7101:     my $envkey;
 7102:     if ($thisallowed=~/L/) {
 7103:         foreach $envkey (keys(%env)) {
 7104:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 7105:                my $courseid=$2;
 7106:                my $roleid=$1.'.'.$2;
 7107:                $courseid=~s/^\///;
 7108:                my $expiretime=600;
 7109:                if ($env{'request.role'} eq $roleid) {
 7110: 		  $expiretime=120;
 7111:                }
 7112: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 7113:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 7114:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 7115: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 7116:                }
 7117:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 7118:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 7119: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 7120:                        &log($env{'user.domain'},$env{'user.name'},
 7121:                             $env{'user.home'},
 7122:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 7123:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 7124:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 7125: 		       return '';
 7126:                    }
 7127:                }
 7128:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 7129:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 7130: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 7131:                        &log($env{'user.domain'},$env{'user.name'},
 7132:                             $env{'user.home'},
 7133:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 7134:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 7135:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 7136: 		       return '';
 7137:                    }
 7138:                }
 7139: 	   }
 7140:        }
 7141:     }
 7142:    
 7143: #
 7144: # Rest of the restrictions depend on selected course
 7145: #
 7146: 
 7147:     unless ($env{'request.course.id'}) {
 7148: 	if ($thisallowed eq 'A') {
 7149: 	    return 'A';
 7150:         } elsif ($thisallowed eq 'B') {
 7151:             return 'B';
 7152: 	} else {
 7153: 	    return '1';
 7154: 	}
 7155:     }
 7156: 
 7157: #
 7158: # Now user is definitely in a course
 7159: #
 7160: 
 7161: 
 7162: # Course preferences
 7163: 
 7164:    if ($thisallowed=~/C/) {
 7165:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 7166:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 7167:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 7168: 	   =~/\Q$rolecode\E/) {
 7169: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 7170: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 7171: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 7172: 			$env{'request.course.id'});
 7173: 	   }
 7174:            return '';
 7175:        }
 7176: 
 7177:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 7178: 	   =~/\Q$unamedom\E/) {
 7179: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 7180: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 7181: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 7182: 			$env{'request.course.id'});
 7183: 	   }
 7184:            return '';
 7185:        }
 7186:    }
 7187: 
 7188: # Resource preferences
 7189: 
 7190:    if ($thisallowed=~/R/) {
 7191:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 7192:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 7193: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 7194: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 7195: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 7196: 	   }
 7197: 	   return '';
 7198:        }
 7199:    }
 7200: 
 7201: # Restricted by state or randomout?
 7202: 
 7203:    if ($thisallowed=~/X/) {
 7204:       if ($env{'acc.randomout'}) {
 7205: 	 if (!$symb) { $symb=&symbread($uri,1); }
 7206:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 7207:             return ''; 
 7208:          }
 7209:       }
 7210:       if (&condval($statecond)) {
 7211: 	 return '2';
 7212:       } else {
 7213:          return '';
 7214:       }
 7215:    }
 7216: 
 7217:     if ($thisallowed eq 'A') {
 7218: 	return 'A';
 7219:     } elsif ($thisallowed eq 'B') {
 7220:         return 'B';
 7221:     }
 7222:    return 'F';
 7223: }
 7224: 
 7225: # ------------------------------------------- Check construction space access
 7226: 
 7227: sub constructaccess {
 7228:     my ($url,$setpriv)=@_;
 7229: 
 7230: # We do not allow editing of previous versions of files
 7231:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 7232: 
 7233: # Get username and domain from URL
 7234:     my ($ownername,$ownerdomain,$ownerhome);
 7235: 
 7236:     ($ownerdomain,$ownername) =
 7237:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)/});
 7238: 
 7239: # The URL does not really point to any authorspace, forget it
 7240:     unless (($ownername) && ($ownerdomain)) { return ''; }
 7241: 
 7242: # Now we need to see if the user has access to the authorspace of
 7243: # $ownername at $ownerdomain
 7244: 
 7245:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 7246: # Real author for this?
 7247:        $ownerhome = $env{'user.home'};
 7248:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 7249:           return ($ownername,$ownerdomain,$ownerhome);
 7250:        }
 7251:     } else {
 7252: # Co-author for this?
 7253:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 7254:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 7255:             $ownerhome = &homeserver($ownername,$ownerdomain);
 7256:             return ($ownername,$ownerdomain,$ownerhome);
 7257:         }
 7258:     }
 7259: 
 7260: # We don't have any access right now. If we are not possibly going to do anything about this,
 7261: # we might as well leave
 7262:    unless ($setpriv) { return ''; }
 7263: 
 7264: # Backdoor access?
 7265:     my $allowed=&allowed('eco',$ownerdomain);
 7266: # Nope
 7267:     unless ($allowed) { return ''; }
 7268: # Looks like we may have access, but could be locked by the owner of the construction space
 7269:     if ($allowed eq 'U') {
 7270:         my %blocked=&get('environment',['domcoord.author'],
 7271:                          $ownerdomain,$ownername);
 7272: # Is blocked by owner
 7273:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 7274:     }
 7275:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 7276: # Grant temporary access
 7277:         my $then=$env{'user.login.time'};
 7278:         my $update=$env{'user.update.time'};
 7279:         if (!$update) { $update = $then; }
 7280:         my $refresh=$env{'user.refresh.time'};
 7281:         if (!$refresh) { $refresh = $update; }
 7282:         my $now = time;
 7283:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 7284:                            $now,'ca','constructaccess');
 7285:         $ownerhome = &homeserver($ownername,$ownerdomain);
 7286:         return($ownername,$ownerdomain,$ownerhome);
 7287:     }
 7288: # No business here
 7289:     return '';
 7290: }
 7291: 
 7292: # ----------------------------------------------------------- Content Blocking
 7293: 
 7294: {
 7295: # Caches for faster Course Contents display where content blocking
 7296: # is in operation (i.e., interval param set) for timed quiz.
 7297: #
 7298: # User for whom data are being temporarily cached.
 7299: my $cacheduser='';
 7300: # Cached blockers for this user (a hash of blocking items). 
 7301: my %cachedblockers=();
 7302: # When the data were last cached.
 7303: my $cachedlast='';
 7304: 
 7305: sub load_all_blockers {
 7306:     my ($uname,$udom,$blocks)=@_;
 7307:     if (($uname ne '') && ($udom ne '')) { 
 7308:         if (($cacheduser eq $uname.':'.$udom) &&
 7309:             (abs($cachedlast-time)<5)) {
 7310:             return;
 7311:         }
 7312:     }
 7313:     $cachedlast=time;
 7314:     $cacheduser=$uname.':'.$udom;
 7315:     %cachedblockers = &get_commblock_resources($blocks);
 7316: }
 7317: 
 7318: sub get_comm_blocks {
 7319:     my ($cdom,$cnum) = @_;
 7320:     if ($cdom eq '' || $cnum eq '') {
 7321:         return unless ($env{'request.course.id'});
 7322:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7323:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7324:     }
 7325:     my %commblocks;
 7326:     my $hashid=$cdom.'_'.$cnum;
 7327:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 7328:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 7329:         %commblocks = %{$blocksref};
 7330:     } else {
 7331:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 7332:         my $cachetime = 600;
 7333:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 7334:     }
 7335:     return %commblocks;
 7336: }
 7337: 
 7338: sub get_commblock_resources {
 7339:     my ($blocks) = @_;
 7340:     my %blockers = ();
 7341:     return %blockers unless ($env{'request.course.id'});
 7342:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 7343:     my %commblocks;
 7344:     if (ref($blocks) eq 'HASH') {
 7345:         %commblocks = %{$blocks};
 7346:     } else {
 7347:         %commblocks = &get_comm_blocks();
 7348:     }
 7349:     return %blockers unless (keys(%commblocks) > 0); 
 7350:     my $navmap = Apache::lonnavmaps::navmap->new();
 7351:     return %blockers unless (ref($navmap));
 7352:     my $now = time;
 7353:     foreach my $block (keys(%commblocks)) {
 7354:         if ($block =~ /^(\d+)____(\d+)$/) {
 7355:             my ($start,$end) = ($1,$2);
 7356:             if ($start <= $now && $end >= $now) {
 7357:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 7358:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 7359:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 7360:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 7361:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
 7362:                             }
 7363:                         }
 7364:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 7365:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 7366:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 7367:                             }
 7368:                         }
 7369:                     }
 7370:                 }
 7371:             }
 7372:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 7373:             my $item = $1;
 7374:             my @to_test;
 7375:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 7376:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 7377:                     my @interval;
 7378:                     my $type = 'map';
 7379:                     if ($item eq 'course') {
 7380:                         $type = 'course';
 7381:                         @interval=&EXT("resource.0.interval");
 7382:                     } else {
 7383:                         if ($item =~ /___\d+___/) {
 7384:                             $type = 'resource';
 7385:                             @interval=&EXT("resource.0.interval",$item);
 7386:                             if (ref($navmap)) {                        
 7387:                                 my $res = $navmap->getBySymb($item); 
 7388:                                 push(@to_test,$res);
 7389:                             }
 7390:                         } else {
 7391:                             my $mapsymb = &symbread($item,1);
 7392:                             if ($mapsymb) {
 7393:                                 if (ref($navmap)) {
 7394:                                     my $mapres = $navmap->getBySymb($mapsymb);
 7395:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
 7396:                                     foreach my $res (@to_test) {
 7397:                                         my $symb = $res->symb();
 7398:                                         next if ($symb eq $mapsymb);
 7399:                                         if ($symb ne '') {
 7400:                                             @interval=&EXT("resource.0.interval",$symb);
 7401:                                             if ($interval[1] eq 'map') {
 7402:                                                 last;
 7403:                                             }
 7404:                                         }
 7405:                                     }
 7406:                                 }
 7407:                             }
 7408:                         }
 7409:                     }
 7410:                     if ($interval[0] =~ /^\d+/) {
 7411:                         my ($timelimit) = split(/_/,$interval[0]);
 7412:                         my $first_access;
 7413:                         if ($type eq 'resource') {
 7414:                             $first_access=&get_first_access($interval[1],$item);
 7415:                         } elsif ($type eq 'map') {
 7416:                             $first_access=&get_first_access($interval[1],undef,$item);
 7417:                         } else {
 7418:                             $first_access=&get_first_access($interval[1]);
 7419:                         }
 7420:                         if ($first_access) {
 7421:                             my $timesup = $first_access+$timelimit;
 7422:                             if ($timesup > $now) {
 7423:                                 my $activeblock;
 7424:                                 foreach my $res (@to_test) {
 7425:                                     if ($res->answerable()) {
 7426:                                         $activeblock = 1;
 7427:                                         last;
 7428:                                     }
 7429:                                 }
 7430:                                 if ($activeblock) {
 7431:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 7432:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
 7433:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
 7434:                                          }
 7435:                                     }
 7436:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 7437:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
 7438:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
 7439:                                         }
 7440:                                     }
 7441:                                 }
 7442:                             }
 7443:                         }
 7444:                     }
 7445:                 }
 7446:             }
 7447:         }
 7448:     }
 7449:     return %blockers;
 7450: }
 7451: 
 7452: sub has_comm_blocking {
 7453:     my ($priv,$symb,$uri,$blocks) = @_;
 7454:     my @blockers;
 7455:     return unless ($env{'request.course.id'});
 7456:     return unless ($priv eq 'bre');
 7457:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 7458:     return if ($env{'request.state'} eq 'construct');
 7459:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
 7460:     return unless (keys(%cachedblockers) > 0);
 7461:     my (%possibles,@symbs);
 7462:     if (!$symb) {
 7463:         $symb = &symbread($uri,1,1,1,\%possibles);
 7464:     }
 7465:     if ($symb) {
 7466:         @symbs = ($symb);
 7467:     } elsif (keys(%possibles)) { 
 7468:         @symbs = keys(%possibles);
 7469:     }
 7470:     my $noblock;
 7471:     foreach my $symb (@symbs) {
 7472:         last if ($noblock);
 7473:         my ($map,$resid,$resurl)=&decode_symb($symb);
 7474:         foreach my $block (keys(%cachedblockers)) {
 7475:             if ($block =~ /^firstaccess____(.+)$/) {
 7476:                 my $item = $1;
 7477:                 if (($item eq $map) || ($item eq $symb)) {
 7478:                     $noblock = 1;
 7479:                     last;
 7480:                 }
 7481:             }
 7482:             if (ref($cachedblockers{$block}) eq 'HASH') {
 7483:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
 7484:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
 7485:                         unless (grep(/^\Q$block\E$/,@blockers)) {
 7486:                             push(@blockers,$block);
 7487:                         }
 7488:                     }
 7489:                 }
 7490:             }
 7491:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
 7492:                 if ($cachedblockers{$block}{'maps'}{$map}) {
 7493:                     unless (grep(/^\Q$block\E$/,@blockers)) {
 7494:                         push(@blockers,$block);
 7495:                     }
 7496:                 }
 7497:             }
 7498:         }
 7499:     }
 7500:     return if ($noblock);
 7501:     return @blockers;
 7502: }
 7503: }
 7504: 
 7505: # -------------------------------- Deversion and split uri into path an filename   
 7506: 
 7507: #
 7508: #   Removes the version from a URI and
 7509: #   splits it in to its filename and path to the filename.
 7510: #   Seems like File::Basename could have done this more clearly.
 7511: #   Parameters:
 7512: #      $uri   - input URI
 7513: #   Returns:
 7514: #     Two element list consisting of 
 7515: #     $pathname  - the URI up to and excluding the trailing /
 7516: #     $filename  - The part of the URI following the last /
 7517: #  NOTE:
 7518: #    Another realization of this is simply:
 7519: #    use File::Basename;
 7520: #    ...
 7521: #    $uri = shift;
 7522: #    $filename = basename($uri);
 7523: #    $path     = dirname($uri);
 7524: #    return ($filename, $path);
 7525: #
 7526: #     The implementation below is probably faster however.
 7527: #
 7528: sub split_uri_for_cond {
 7529:     my $uri=&deversion(&declutter(shift));
 7530:     my @uriparts=split(/\//,$uri);
 7531:     my $filename=pop(@uriparts);
 7532:     my $pathname=join('/',@uriparts);
 7533:     return ($pathname,$filename);
 7534: }
 7535: # --------------------------------------------------- Is a resource on the map?
 7536: 
 7537: sub is_on_map {
 7538:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 7539:     #Trying to find the conditional for the file
 7540:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 7541: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 7542:     if ($match) {
 7543: 	return (1,$1);
 7544:     } else {
 7545: 	return (0,0);
 7546:     }
 7547: }
 7548: 
 7549: # --------------------------------------------------------- Get symb from alias
 7550: 
 7551: sub get_symb_from_alias {
 7552:     my $symb=shift;
 7553:     my ($map,$resid,$url)=&decode_symb($symb);
 7554: # Already is a symb
 7555:     if ($url) { return $symb; }
 7556: # Must be an alias
 7557:     my $aliassymb='';
 7558:     my %bighash;
 7559:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7560:                             &GDBM_READER(),0640)) {
 7561:         my $rid=$bighash{'mapalias_'.$symb};
 7562: 	if ($rid) {
 7563: 	    my ($mapid,$resid)=split(/\./,$rid);
 7564: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 7565: 				    $resid,$bighash{'src_'.$rid});
 7566: 	}
 7567:         untie %bighash;
 7568:     }
 7569:     return $aliassymb;
 7570: }
 7571: 
 7572: # ----------------------------------------------------------------- Define Role
 7573: 
 7574: sub definerole {
 7575:   if (allowed('mcr','/')) {
 7576:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 7577:     foreach my $role (split(':',$sysrole)) {
 7578: 	my ($crole,$cqual)=split(/\&/,$role);
 7579:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 7580:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 7581: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 7582:                return "refused:s:$crole&$cqual"; 
 7583:             }
 7584:         }
 7585:     }
 7586:     foreach my $role (split(':',$domrole)) {
 7587: 	my ($crole,$cqual)=split(/\&/,$role);
 7588:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 7589:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 7590: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 7591:                return "refused:d:$crole&$cqual"; 
 7592:             }
 7593:         }
 7594:     }
 7595:     foreach my $role (split(':',$courole)) {
 7596: 	my ($crole,$cqual)=split(/\&/,$role);
 7597:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 7598:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 7599: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 7600:                return "refused:c:$crole&$cqual"; 
 7601:             }
 7602:         }
 7603:     }
 7604:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 7605:                 "$env{'user.domain'}:$env{'user.name'}:".
 7606: 	        "rolesdef_$rolename=".
 7607:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 7608:     return reply($command,$env{'user.home'});
 7609:   } else {
 7610:     return 'refused';
 7611:   }
 7612: }
 7613: 
 7614: # ---------------- Make a metadata query against the network of library servers
 7615: 
 7616: sub metadata_query {
 7617:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 7618:     my %rhash;
 7619:     my %libserv = &all_library();
 7620:     my @server_list = (defined($server_array) ? @$server_array
 7621:                                               : keys(%libserv) );
 7622:     for my $server (@server_list) {
 7623:         my $domains = ''; 
 7624:         if (ref($domains_hash) eq 'HASH') {
 7625:             $domains = $domains_hash->{$server}; 
 7626:         }
 7627: 	unless ($custom or $customshow) {
 7628: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 7629: 	    $rhash{$server}=$reply;
 7630: 	}
 7631: 	else {
 7632: 	    my $reply=&reply("querysend:".&escape($query).':'.
 7633: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 7634: 			     $server);
 7635: 	    $rhash{$server}=$reply;
 7636: 	}
 7637:     }
 7638:     return \%rhash;
 7639: }
 7640: 
 7641: # ----------------------------------------- Send log queries and wait for reply
 7642: 
 7643: sub log_query {
 7644:     my ($uname,$udom,$query,%filters)=@_;
 7645:     my $uhome=&homeserver($uname,$udom);
 7646:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 7647:     my $uhost=&hostname($uhome);
 7648:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 7649:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 7650:                        $uhome);
 7651:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 7652:     return get_query_reply($queryid);
 7653: }
 7654: 
 7655: # -------------------------- Update MySQL table for portfolio file
 7656: 
 7657: sub update_portfolio_table {
 7658:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 7659:     if ($group ne '') {
 7660:         $file_name =~s /^\Q$group\E//;
 7661:     }
 7662:     my $homeserver = &homeserver($uname,$udom);
 7663:     my $queryid=
 7664:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 7665:                ':'.&escape($file_name).':'.$action,$homeserver);
 7666:     my $reply = &get_query_reply($queryid);
 7667:     return $reply;
 7668: }
 7669: 
 7670: # -------------------------- Update MySQL allusers table
 7671: 
 7672: sub update_allusers_table {
 7673:     my ($uname,$udom,$names) = @_;
 7674:     my $homeserver = &homeserver($uname,$udom);
 7675:     my $queryid=
 7676:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 7677:                'lastname='.&escape($names->{'lastname'}).'%%'.
 7678:                'firstname='.&escape($names->{'firstname'}).'%%'.
 7679:                'middlename='.&escape($names->{'middlename'}).'%%'.
 7680:                'generation='.&escape($names->{'generation'}).'%%'.
 7681:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 7682:                'id='.&escape($names->{'id'}),$homeserver);
 7683:     return;
 7684: }
 7685: 
 7686: # ------- Request retrieval of institutional classlists for course(s)
 7687: 
 7688: sub fetch_enrollment_query {
 7689:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 7690:     my $homeserver;
 7691:     my $maxtries = 1;
 7692:     if ($context eq 'automated') {
 7693:         $homeserver = $perlvar{'lonHostID'};
 7694:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 7695:     } else {
 7696:         $homeserver = &homeserver($cnum,$dom);
 7697:     }
 7698:     my $host=&hostname($homeserver);
 7699:     my $cmd = '';
 7700:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7701:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7702:     }
 7703:     $cmd =~ s/%%$//;
 7704:     $cmd = &escape($cmd);
 7705:     my $query = 'fetchenrollment';
 7706:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 7707:     unless ($queryid=~/^\Q$host\E\_/) { 
 7708:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 7709:         return 'error: '.$queryid;
 7710:     }
 7711:     my $reply = &get_query_reply($queryid);
 7712:     my $tries = 1;
 7713:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7714:         $reply = &get_query_reply($queryid);
 7715:         $tries ++;
 7716:     }
 7717:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7718:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7719:     } else {
 7720:         my @responses = split(/:/,$reply);
 7721:         if ($homeserver eq $perlvar{'lonHostID'}) {
 7722:             foreach my $line (@responses) {
 7723:                 my ($key,$value) = split(/=/,$line,2);
 7724:                 $$replyref{$key} = $value;
 7725:             }
 7726:         } else {
 7727:             my $pathname = LONCAPA::tempdir();
 7728:             foreach my $line (@responses) {
 7729:                 my ($key,$value) = split(/=/,$line);
 7730:                 $$replyref{$key} = $value;
 7731:                 if ($value > 0) {
 7732:                     foreach my $item (@{$$affiliatesref{$key}}) {
 7733:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 7734:                         my $destname = $pathname.'/'.$filename;
 7735:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 7736:                         if ($xml_classlist =~ /^error/) {
 7737:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 7738:                         } else {
 7739:                             if ( open(FILE,">$destname") ) {
 7740:                                 print FILE &unescape($xml_classlist);
 7741:                                 close(FILE);
 7742:                             } else {
 7743:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 7744:                             }
 7745:                         }
 7746:                     }
 7747:                 }
 7748:             }
 7749:         }
 7750:         return 'ok';
 7751:     }
 7752:     return 'error';
 7753: }
 7754: 
 7755: sub get_query_reply {
 7756:     my $queryid=shift;
 7757:     my $replyfile=LONCAPA::tempdir().$queryid;
 7758:     my $reply='';
 7759:     for (1..100) {
 7760: 	sleep(0.2);
 7761:         if (-e $replyfile.'.end') {
 7762: 	    if (open(my $fh,$replyfile)) {
 7763: 		$reply = join('',<$fh>);
 7764: 		close($fh);
 7765: 	   } else { return 'error: reply_file_error'; }
 7766:            return &unescape($reply);
 7767: 	}
 7768:     }
 7769:     return 'timeout:'.$queryid;
 7770: }
 7771: 
 7772: sub courselog_query {
 7773: #
 7774: # possible filters:
 7775: # url: url or symb
 7776: # username
 7777: # domain
 7778: # action: view, submit, grade
 7779: # start: timestamp
 7780: # end: timestamp
 7781: #
 7782:     my (%filters)=@_;
 7783:     unless ($env{'request.course.id'}) { return 'no_course'; }
 7784:     if ($filters{'url'}) {
 7785: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 7786:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 7787:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 7788:     }
 7789:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7790:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7791:     return &log_query($cname,$cdom,'courselog',%filters);
 7792: }
 7793: 
 7794: sub userlog_query {
 7795: #
 7796: # possible filters:
 7797: # action: log check role
 7798: # start: timestamp
 7799: # end: timestamp
 7800: #
 7801:     my ($uname,$udom,%filters)=@_;
 7802:     return &log_query($uname,$udom,'userlog',%filters);
 7803: }
 7804: 
 7805: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 7806: 
 7807: sub auto_run {
 7808:     my ($cnum,$cdom) = @_;
 7809:     my $response = 0;
 7810:     my $settings;
 7811:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 7812:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 7813:         $settings = $domconfig{'autoenroll'};
 7814:         if ($settings->{'run'} eq '1') {
 7815:             $response = 1;
 7816:         }
 7817:     } else {
 7818:         my $homeserver;
 7819:         if (&is_course($cdom,$cnum)) {
 7820:             $homeserver = &homeserver($cnum,$cdom);
 7821:         } else {
 7822:             $homeserver = &domain($cdom,'primary');
 7823:         }
 7824:         if ($homeserver ne 'no_host') {
 7825:             $response = &reply('autorun:'.$cdom,$homeserver);
 7826:         }
 7827:     }
 7828:     return $response;
 7829: }
 7830: 
 7831: sub auto_get_sections {
 7832:     my ($cnum,$cdom,$inst_coursecode) = @_;
 7833:     my $homeserver;
 7834:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 7835:         $homeserver = &homeserver($cnum,$cdom);
 7836:     }
 7837:     if (!defined($homeserver)) { 
 7838:         if ($cdom =~ /^$match_domain$/) {
 7839:             $homeserver = &domain($cdom,'primary');
 7840:         }
 7841:     }
 7842:     my @secs;
 7843:     if (defined($homeserver)) {
 7844:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 7845:         unless ($response eq 'refused') {
 7846:             @secs = split(/:/,$response);
 7847:         }
 7848:     }
 7849:     return @secs;
 7850: }
 7851: 
 7852: sub auto_new_course {
 7853:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 7854:     my $homeserver = &homeserver($cnum,$cdom);
 7855:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 7856:     return $response;
 7857: }
 7858: 
 7859: sub auto_validate_courseID {
 7860:     my ($cnum,$cdom,$inst_course_id) = @_;
 7861:     my $homeserver = &homeserver($cnum,$cdom);
 7862:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 7863:     return $response;
 7864: }
 7865: 
 7866: sub auto_validate_instcode {
 7867:     my ($cnum,$cdom,$instcode,$owner) = @_;
 7868:     my ($homeserver,$response);
 7869:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7870:         $homeserver = &homeserver($cnum,$cdom);
 7871:     }
 7872:     if (!defined($homeserver)) {
 7873:         if ($cdom =~ /^$match_domain$/) {
 7874:             $homeserver = &domain($cdom,'primary');
 7875:         }
 7876:     }
 7877:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 7878:                         &escape($instcode).':'.&escape($owner),$homeserver));
 7879:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 7880:     return ($outcome,$description,$defaultcredits);
 7881: }
 7882: 
 7883: sub auto_create_password {
 7884:     my ($cnum,$cdom,$authparam,$udom) = @_;
 7885:     my ($homeserver,$response);
 7886:     my $create_passwd = 0;
 7887:     my $authchk = '';
 7888:     if ($udom =~ /^$match_domain$/) {
 7889:         $homeserver = &domain($udom,'primary');
 7890:     }
 7891:     if ($homeserver eq '') {
 7892:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7893:             $homeserver = &homeserver($cnum,$cdom);
 7894:         }
 7895:     }
 7896:     if ($homeserver eq '') {
 7897:         $authchk = 'nodomain';
 7898:     } else {
 7899:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 7900:         if ($response eq 'refused') {
 7901:             $authchk = 'refused';
 7902:         } else {
 7903:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 7904:         }
 7905:     }
 7906:     return ($authparam,$create_passwd,$authchk);
 7907: }
 7908: 
 7909: sub auto_photo_permission {
 7910:     my ($cnum,$cdom,$students) = @_;
 7911:     my $homeserver = &homeserver($cnum,$cdom);
 7912:     my ($outcome,$perm_reqd,$conditions) = 
 7913: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 7914:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7915: 	return (undef,undef);
 7916:     }
 7917:     return ($outcome,$perm_reqd,$conditions);
 7918: }
 7919: 
 7920: sub auto_checkphotos {
 7921:     my ($uname,$udom,$pid) = @_;
 7922:     my $homeserver = &homeserver($uname,$udom);
 7923:     my ($result,$resulttype);
 7924:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 7925: 				   &escape($uname).':'.&escape($pid),
 7926: 				   $homeserver));
 7927:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7928: 	return (undef,undef);
 7929:     }
 7930:     if ($outcome) {
 7931:         ($result,$resulttype) = split(/:/,$outcome);
 7932:     } 
 7933:     return ($result,$resulttype);
 7934: }
 7935: 
 7936: sub auto_photochoice {
 7937:     my ($cnum,$cdom) = @_;
 7938:     my $homeserver = &homeserver($cnum,$cdom);
 7939:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 7940: 						       &escape($cdom),
 7941: 						       $homeserver)));
 7942:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7943: 	return (undef,undef);
 7944:     }
 7945:     return ($update,$comment);
 7946: }
 7947: 
 7948: sub auto_photoupdate {
 7949:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 7950:     my $homeserver = &homeserver($cnum,$dom);
 7951:     my $host=&hostname($homeserver);
 7952:     my $cmd = '';
 7953:     my $maxtries = 1;
 7954:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7955:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7956:     }
 7957:     $cmd =~ s/%%$//;
 7958:     $cmd = &escape($cmd);
 7959:     my $query = 'institutionalphotos';
 7960:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 7961:     unless ($queryid=~/^\Q$host\E\_/) {
 7962:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 7963:         return 'error: '.$queryid;
 7964:     }
 7965:     my $reply = &get_query_reply($queryid);
 7966:     my $tries = 1;
 7967:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7968:         $reply = &get_query_reply($queryid);
 7969:         $tries ++;
 7970:     }
 7971:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7972:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7973:     } else {
 7974:         my @responses = split(/:/,$reply);
 7975:         my $outcome = shift(@responses); 
 7976:         foreach my $item (@responses) {
 7977:             my ($key,$value) = split(/=/,$item);
 7978:             $$photo{$key} = $value;
 7979:         }
 7980:         return $outcome;
 7981:     }
 7982:     return 'error';
 7983: }
 7984: 
 7985: sub auto_instcode_format {
 7986:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 7987: 	$cat_order) = @_;
 7988:     my $courses = '';
 7989:     my @homeservers;
 7990:     if ($caller eq 'global') {
 7991: 	my %servers = &get_servers($codedom,'library');
 7992: 	foreach my $tryserver (keys(%servers)) {
 7993: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7994: 		push(@homeservers,$tryserver);
 7995: 	    }
 7996:         }
 7997:     } elsif ($caller eq 'requests') {
 7998:         if ($codedom =~ /^$match_domain$/) {
 7999:             my $chome = &domain($codedom,'primary');
 8000:             unless ($chome eq 'no_host') {
 8001:                 push(@homeservers,$chome);
 8002:             }
 8003:         }
 8004:     } else {
 8005:         push(@homeservers,&homeserver($caller,$codedom));
 8006:     }
 8007:     foreach my $code (keys(%{$instcodes})) {
 8008:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 8009:     }
 8010:     chop($courses);
 8011:     my $ok_response = 0;
 8012:     my $response;
 8013:     while (@homeservers > 0 && $ok_response == 0) {
 8014:         my $server = shift(@homeservers); 
 8015:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 8016:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 8017:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 8018: 		split(/:/,$response);
 8019:             %{$codes} = (%{$codes},&str2hash($codes_str));
 8020:             push(@{$codetitles},&str2array($codetitles_str));
 8021:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 8022:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 8023:             $ok_response = 1;
 8024:         }
 8025:     }
 8026:     if ($ok_response) {
 8027:         return 'ok';
 8028:     } else {
 8029:         return $response;
 8030:     }
 8031: }
 8032: 
 8033: sub auto_instcode_defaults {
 8034:     my ($domain,$returnhash,$code_order) = @_;
 8035:     my @homeservers;
 8036: 
 8037:     my %servers = &get_servers($domain,'library');
 8038:     foreach my $tryserver (keys(%servers)) {
 8039: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 8040: 	    push(@homeservers,$tryserver);
 8041: 	}
 8042:     }
 8043: 
 8044:     my $response;
 8045:     foreach my $server (@homeservers) {
 8046:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 8047:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 8048: 	
 8049: 	foreach my $pair (split(/\&/,$response)) {
 8050: 	    my ($name,$value)=split(/\=/,$pair);
 8051: 	    if ($name eq 'code_order') {
 8052: 		@{$code_order} = split(/\&/,&unescape($value));
 8053: 	    } else {
 8054: 		$returnhash->{&unescape($name)}=&unescape($value);
 8055: 	    }
 8056: 	}
 8057: 	return 'ok';
 8058:     }
 8059: 
 8060:     return $response;
 8061: }
 8062: 
 8063: sub auto_possible_instcodes {
 8064:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 8065:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 8066:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 8067:         return;
 8068:     }
 8069:     my (@homeservers,$uhome);
 8070:     if (defined(&domain($domain,'primary'))) {
 8071:         $uhome=&domain($domain,'primary');
 8072:         push(@homeservers,&domain($domain,'primary'));
 8073:     } else {
 8074:         my %servers = &get_servers($domain,'library');
 8075:         foreach my $tryserver (keys(%servers)) {
 8076:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 8077:                 push(@homeservers,$tryserver);
 8078:             }
 8079:         }
 8080:     }
 8081:     my $response;
 8082:     foreach my $server (@homeservers) {
 8083:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 8084:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 8085:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 8086:             split(':',$response);
 8087:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 8088:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 8089:         foreach my $item (split('&',$cat_title)) {   
 8090:             my ($name,$value)=split('=',$item);
 8091:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 8092:         }
 8093:         foreach my $item (split('&',$cat_order)) {
 8094:             my ($name,$value)=split('=',$item);
 8095:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 8096:         }
 8097:         return 'ok';
 8098:     }
 8099:     return $response;
 8100: }
 8101: 
 8102: sub auto_courserequest_checks {
 8103:     my ($dom) = @_;
 8104:     my ($homeserver,%validations);
 8105:     if ($dom =~ /^$match_domain$/) {
 8106:         $homeserver = &domain($dom,'primary');
 8107:     }
 8108:     unless ($homeserver eq 'no_host') {
 8109:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 8110:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 8111:             my @items = split(/&/,$response);
 8112:             foreach my $item (@items) {
 8113:                 my ($key,$value) = split('=',$item);
 8114:                 $validations{&unescape($key)} = &thaw_unescape($value);
 8115:             }
 8116:         }
 8117:     }
 8118:     return %validations; 
 8119: }
 8120: 
 8121: sub auto_courserequest_validation {
 8122:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
 8123:     my ($homeserver,$response);
 8124:     if ($dom =~ /^$match_domain$/) {
 8125:         $homeserver = &domain($dom,'primary');
 8126:     }
 8127:     unless ($homeserver eq 'no_host') {
 8128:         my $customdata;
 8129:         if (ref($custominfo) eq 'HASH') {
 8130:             $customdata = &freeze_escape($custominfo);
 8131:         }
 8132:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 8133:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 8134:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
 8135:                                     $customdata,$homeserver));
 8136:     }
 8137:     return $response;
 8138: }
 8139: 
 8140: sub auto_validate_class_sec {
 8141:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 8142:     my $homeserver = &homeserver($cnum,$cdom);
 8143:     my $ownerlist;
 8144:     if (ref($owners) eq 'ARRAY') {
 8145:         $ownerlist = join(',',@{$owners});
 8146:     } else {
 8147:         $ownerlist = $owners;
 8148:     }
 8149:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 8150:                         &escape($ownerlist).':'.$cdom,$homeserver);
 8151:     return $response;
 8152: }
 8153: 
 8154: sub auto_crsreq_update {
 8155:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
 8156:         $code,$accessstart,$accessend,$inbound) = @_;
 8157:     my ($homeserver,%crsreqresponse);
 8158:     if ($cdom =~ /^$match_domain$/) {
 8159:         $homeserver = &domain($cdom,'primary');
 8160:     }
 8161:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 8162:         my $info;
 8163:         if (ref($inbound) eq 'HASH') {
 8164:             $info = &freeze_escape($inbound);
 8165:         }
 8166:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
 8167:                             ':'.&escape($action).':'.&escape($ownername).':'.
 8168:                             &escape($ownerdomain).':'.&escape($fullname).':'.
 8169:                             &escape($title).':'.&escape($code).':'.
 8170:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
 8171:                             $homeserver);
 8172:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 8173:             my @items = split(/&/,$response);
 8174:             foreach my $item (@items) {
 8175:                 my ($key,$value) = split('=',$item);
 8176:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
 8177:             }
 8178:         }
 8179:     }
 8180:     return \%crsreqresponse;
 8181: }
 8182: 
 8183: sub check_instcode_cloning {
 8184:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
 8185:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 8186:         return;
 8187:     }
 8188:     my $canclone;
 8189:     if (@{$code_order} > 0) {
 8190:         my $instcoderegexp ='^';
 8191:         my @clonecodes = split(/\&/,$cloner);
 8192:         foreach my $item (@{$code_order}) {
 8193:             if (grep(/^\Q$item\E=/,@clonecodes)) {
 8194:                 foreach my $pair (@clonecodes) {
 8195:                     my ($key,$val) = split(/\=/,$pair,2);
 8196:                     $val = &unescape($val);
 8197:                     if ($key eq $item) {
 8198:                         $instcoderegexp .= '('.$val.')';
 8199:                         last;
 8200:                     }
 8201:                 }
 8202:             } else {
 8203:                 $instcoderegexp .= $codedefaults->{$item};
 8204:             }
 8205:         }
 8206:         $instcoderegexp .= '$';
 8207:         my (@from,@to);
 8208:         eval {
 8209:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
 8210:                (@to) = ($clonetocode =~ /$instcoderegexp/);
 8211:         };
 8212:         if ((@from > 0) && (@to > 0)) {
 8213:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 8214:             if (!@diffs) {
 8215:                 $canclone = 1;
 8216:             }
 8217:         }
 8218:     }
 8219:     return $canclone;
 8220: }
 8221: 
 8222: sub default_instcode_cloning {
 8223:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
 8224:     my (%codedefaults,@code_order,$canclone);
 8225:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
 8226:         %codedefaults = %{$codedefaultsref};
 8227:         @code_order = @{$codeorderref};
 8228:     } elsif ($clonedom) {
 8229:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
 8230:     }
 8231:     if (($domdefclone) && (@code_order)) {
 8232:         my @clonecodes = split(/\+/,$domdefclone);
 8233:         my $instcoderegexp ='^';
 8234:         foreach my $item (@code_order) {
 8235:             if (grep(/^\Q$item\E$/,@clonecodes)) {
 8236:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
 8237:             } else {
 8238:                 $instcoderegexp .= $codedefaults{$item};
 8239:             }
 8240:         }
 8241:         $instcoderegexp .= '$';
 8242:         my (@from,@to);
 8243:         eval {
 8244:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
 8245:             (@to) = ($clonetocode =~ /$instcoderegexp/);
 8246:         };
 8247:         if ((@from > 0) && (@to > 0)) {
 8248:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
 8249:             if (!@diffs) {
 8250:                 $canclone = 1;
 8251:             }
 8252:         }
 8253:     }
 8254:     return $canclone;
 8255: }
 8256: 
 8257: # ------------------------------------------------------- Course Group routines
 8258: 
 8259: sub get_coursegroups {
 8260:     my ($cdom,$cnum,$group,$namespace) = @_;
 8261:     return(&dump($namespace,$cdom,$cnum,$group));
 8262: }
 8263: 
 8264: sub modify_coursegroup {
 8265:     my ($cdom,$cnum,$groupsettings) = @_;
 8266:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 8267: }
 8268: 
 8269: sub toggle_coursegroup_status {
 8270:     my ($cdom,$cnum,$group,$action) = @_;
 8271:     my ($from_namespace,$to_namespace);
 8272:     if ($action eq 'delete') {
 8273:         $from_namespace = 'coursegroups';
 8274:         $to_namespace = 'deleted_groups';
 8275:     } else {
 8276:         $from_namespace = 'deleted_groups';
 8277:         $to_namespace = 'coursegroups';
 8278:     }
 8279:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 8280:     if (my $tmp = &error(%curr_group)) {
 8281:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 8282:         return ('read error',$tmp);
 8283:     } else {
 8284:         my %savedsettings = %curr_group; 
 8285:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 8286:         my $deloutcome;
 8287:         if ($result eq 'ok') {
 8288:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 8289:         } else {
 8290:             return ('write error',$result);
 8291:         }
 8292:         if ($deloutcome eq 'ok') {
 8293:             return 'ok';
 8294:         } else {
 8295:             return ('delete error',$deloutcome);
 8296:         }
 8297:     }
 8298: }
 8299: 
 8300: sub modify_group_roles {
 8301:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 8302:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 8303:     my $role = 'gr/'.&escape($userprivs);
 8304:     my ($uname,$udom) = split(/:/,$user);
 8305:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 8306:     if ($result eq 'ok') {
 8307:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 8308:     }
 8309:     return $result;
 8310: }
 8311: 
 8312: sub modify_coursegroup_membership {
 8313:     my ($cdom,$cnum,$membership) = @_;
 8314:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 8315:     return $result;
 8316: }
 8317: 
 8318: sub get_active_groups {
 8319:     my ($udom,$uname,$cdom,$cnum) = @_;
 8320:     my $now = time;
 8321:     my %groups = ();
 8322:     foreach my $key (keys(%env)) {
 8323:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 8324:             my ($start,$end) = split(/\./,$env{$key});
 8325:             if (($end!=0) && ($end<$now)) { next; }
 8326:             if (($start!=0) && ($start>$now)) { next; }
 8327:             if ($1 eq $cdom && $2 eq $cnum) {
 8328:                 $groups{$3} = $env{$key} ;
 8329:             }
 8330:         }
 8331:     }
 8332:     return %groups;
 8333: }
 8334: 
 8335: sub get_group_membership {
 8336:     my ($cdom,$cnum,$group) = @_;
 8337:     return(&dump('groupmembership',$cdom,$cnum,$group));
 8338: }
 8339: 
 8340: sub get_users_groups {
 8341:     my ($udom,$uname,$courseid) = @_;
 8342:     my @usersgroups;
 8343:     my $cachetime=1800;
 8344: 
 8345:     my $hashid="$udom:$uname:$courseid";
 8346:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 8347:     if (defined($cached)) {
 8348:         @usersgroups = split(/:/,$grouplist);
 8349:     } else {  
 8350:         $grouplist = '';
 8351:         my $courseurl = &courseid_to_courseurl($courseid);
 8352:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 8353:         my $access_end = $env{'course.'.$courseid.
 8354:                               '.default_enrollment_end_date'};
 8355:         my $now = time;
 8356:         foreach my $key (keys(%roleshash)) {
 8357:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 8358:                 my $group = $1;
 8359:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 8360:                     my $start = $2;
 8361:                     my $end = $1;
 8362:                     if ($start == -1) { next; } # deleted from group
 8363:                     if (($start!=0) && ($start>$now)) { next; }
 8364:                     if (($end!=0) && ($end<$now)) {
 8365:                         if ($access_end && $access_end < $now) {
 8366:                             if ($access_end - $end < 86400) {
 8367:                                 push(@usersgroups,$group);
 8368:                             }
 8369:                         }
 8370:                         next;
 8371:                     }
 8372:                     push(@usersgroups,$group);
 8373:                 }
 8374:             }
 8375:         }
 8376:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 8377:         $grouplist = join(':',@usersgroups);
 8378:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 8379:     }
 8380:     return @usersgroups;
 8381: }
 8382: 
 8383: sub devalidate_getgroups_cache {
 8384:     my ($udom,$uname,$cdom,$cnum)=@_;
 8385:     my $courseid = $cdom.'_'.$cnum;
 8386: 
 8387:     my $hashid="$udom:$uname:$courseid";
 8388:     &devalidate_cache_new('getgroups',$hashid);
 8389: }
 8390: 
 8391: # ------------------------------------------------------------------ Plain Text
 8392: 
 8393: sub plaintext {
 8394:     my ($short,$type,$cid,$forcedefault) = @_;
 8395:     if ($short =~ m{^cr/}) {
 8396: 	return (split('/',$short))[-1];
 8397:     }
 8398:     if (!defined($cid)) {
 8399:         $cid = $env{'request.course.id'};
 8400:     }
 8401:     my %rolenames = (
 8402:                       Course    => 'std',
 8403:                       Community => 'alt1',
 8404:                     );
 8405:     if ($cid ne '') {
 8406:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 8407:             unless ($forcedefault) {
 8408:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 8409:                 &Apache::lonlocal::mt_escape(\$roletext);
 8410:                 return &Apache::lonlocal::mt($roletext);
 8411:             }
 8412:         }
 8413:     }
 8414:     if ((defined($type)) && (defined($rolenames{$type})) &&
 8415:         (defined($rolenames{$type})) && 
 8416:         (defined($prp{$short}{$rolenames{$type}}))) {
 8417:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 8418:     } elsif ($cid ne '') {
 8419:         my $crstype = $env{'course.'.$cid.'.type'};
 8420:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 8421:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 8422:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 8423:         }
 8424:     }
 8425:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 8426: }
 8427: 
 8428: # ----------------------------------------------------------------- Assign Role
 8429: 
 8430: sub assignrole {
 8431:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 8432:         $context)=@_;
 8433:     my $mrole;
 8434:     if ($role =~ /^cr\//) {
 8435:         my $cwosec=$url;
 8436:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 8437: 	unless (&allowed('ccr',$cwosec)) {
 8438:            my $refused = 1;
 8439:            if ($context eq 'requestcourses') {
 8440:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 8441:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 8442:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 8443:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 8444:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8445:                            if ($crsenv{'internal.courseowner'} eq
 8446:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 8447:                                $refused = '';
 8448:                            }
 8449:                        }
 8450:                    }
 8451:                }
 8452:            }
 8453:            if ($refused) {
 8454:                &logthis('Refused custom assignrole: '.
 8455:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 8456:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 8457:                return 'refused';
 8458:            }
 8459:         }
 8460:         $mrole='cr';
 8461:     } elsif ($role =~ /^gr\//) {
 8462:         my $cwogrp=$url;
 8463:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 8464:         unless (&allowed('mdg',$cwogrp)) {
 8465:             &logthis('Refused group assignrole: '.
 8466:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 8467:                     $env{'user.name'}.' at '.$env{'user.domain'});
 8468:             return 'refused';
 8469:         }
 8470:         $mrole='gr';
 8471:     } else {
 8472:         my $cwosec=$url;
 8473:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 8474:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 8475:             my $refused;
 8476:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 8477:                 if (!(&allowed('c'.$role,$url))) {
 8478:                     $refused = 1;
 8479:                 }
 8480:             } else {
 8481:                 $refused = 1;
 8482:             }
 8483:             if ($refused) {
 8484:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 8485:                 if (!$selfenroll && $context eq 'course') {
 8486:                     my %crsenv;
 8487:                     if ($role eq 'cc' || $role eq 'co') {
 8488:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8489:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 8490:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 8491:                                 if ($crsenv{'internal.courseowner'} eq 
 8492:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 8493:                                     $refused = '';
 8494:                                 }
 8495:                             }
 8496:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 8497:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 8498:                                 if ($crsenv{'internal.courseowner'} eq 
 8499:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 8500:                                     $refused = '';
 8501:                                 }
 8502:                             }
 8503:                         }
 8504:                     }
 8505:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 8506:                     $refused = '';
 8507:                 } elsif ($context eq 'requestcourses') {
 8508:                     my @possroles = ('st','ta','ep','in','cc','co');
 8509:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 8510:                         my $wrongcc;
 8511:                         if ($cnum =~ /^$match_community$/) {
 8512:                             $wrongcc = 1 if ($role eq 'cc');
 8513:                         } else {
 8514:                             $wrongcc = 1 if ($role eq 'co');
 8515:                         }
 8516:                         unless ($wrongcc) {
 8517:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8518:                             if ($crsenv{'internal.courseowner'} eq 
 8519:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 8520:                                 $refused = '';
 8521:                             }
 8522:                         }
 8523:                     }
 8524:                 } elsif ($context eq 'requestauthor') {
 8525:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
 8526:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 8527:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 8528:                             $refused = '';
 8529:                         } else {
 8530:                             my %domdefaults = &get_domain_defaults($udom);
 8531:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 8532:                                 my $checkbystatus;
 8533:                                 if ($env{'user.adv'}) { 
 8534:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 8535:                                     if ($disposition eq 'automatic') {
 8536:                                         $refused = '';
 8537:                                     } elsif ($disposition eq '') {
 8538:                                         $checkbystatus = 1;
 8539:                                     } 
 8540:                                 } else {
 8541:                                     $checkbystatus = 1;
 8542:                                 }
 8543:                                 if ($checkbystatus) {
 8544:                                     if ($env{'environment.inststatus'}) {
 8545:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 8546:                                         foreach my $type (@inststatuses) {
 8547:                                             if (($type ne '') &&
 8548:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 8549:                                                 $refused = '';
 8550:                                             }
 8551:                                         }
 8552:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 8553:                                         $refused = '';
 8554:                                     }
 8555:                                 }
 8556:                             }
 8557:                         }
 8558:                     }
 8559:                 }
 8560:                 if ($refused) {
 8561:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 8562:                              ' '.$role.' '.$end.' '.$start.' by '.
 8563: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 8564:                     return 'refused';
 8565:                 }
 8566:             }
 8567:         } elsif ($role eq 'au') {
 8568:             if ($url ne '/'.$udom.'/') {
 8569:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 8570:                          ' to assign author role for '.$uname.':'.$udom.
 8571:                          ' in domain: '.$url.' refused (wrong domain).');
 8572:                 return 'refused';
 8573:             }
 8574:         }
 8575:         $mrole=$role;
 8576:     }
 8577:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 8578:                 "$udom:$uname:$url".'_'."$mrole=$role";
 8579:     if ($end) { $command.='_'.$end; }
 8580:     if ($start) {
 8581: 	if ($end) { 
 8582:            $command.='_'.$start; 
 8583:         } else {
 8584:            $command.='_0_'.$start;
 8585:         }
 8586:     }
 8587:     my $origstart = $start;
 8588:     my $origend = $end;
 8589:     my $delflag;
 8590: # actually delete
 8591:     if ($deleteflag) {
 8592: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 8593: # modify command to delete the role
 8594:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 8595:                 "$udom:$uname:$url".'_'."$mrole";
 8596: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 8597: # set start and finish to negative values for userrolelog
 8598:            $start=-1;
 8599:            $end=-1;
 8600:            $delflag = 1;
 8601:         }
 8602:     }
 8603: # send command
 8604:     my $answer=&reply($command,&homeserver($uname,$udom));
 8605: # log new user role if status is ok
 8606:     if ($answer eq 'ok') {
 8607: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 8608:         if (($role eq 'cc') || ($role eq 'in') ||
 8609:             ($role eq 'ep') || ($role eq 'ad') ||
 8610:             ($role eq 'ta') || ($role eq 'st') ||
 8611:             ($role=~/^cr/) || ($role eq 'gr') ||
 8612:             ($role eq 'co')) {
 8613: # for course roles, perform group memberships changes triggered by role change.
 8614:             unless ($role =~ /^gr/) {
 8615:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 8616:                                                  $origstart,$selfenroll,$context);
 8617:             }
 8618:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8619:                            $selfenroll,$context);
 8620:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
 8621:                  ($role eq 'au') || ($role eq 'dc')) {
 8622:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8623:                            $context);
 8624:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
 8625:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8626:                              $context); 
 8627:         }
 8628:         if ($role eq 'cc') {
 8629:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 8630:         }
 8631:     }
 8632:     return $answer;
 8633: }
 8634: 
 8635: sub autoupdate_coowners {
 8636:     my ($url,$end,$start,$uname,$udom) = @_;
 8637:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 8638:     if (($cdom ne '') && ($cnum ne '')) {
 8639:         my $now = time;
 8640:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 8641:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 8642:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 8643:             my $instcode = $coursehash{'internal.coursecode'};
 8644:             if ($instcode ne '') {
 8645:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 8646:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 8647:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 8648:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 8649:                         if ($result eq 'valid') {
 8650:                             if ($coursehash{'internal.co-owners'}) {
 8651:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 8652:                                     push(@newcoowners,$coowner);
 8653:                                 }
 8654:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 8655:                                     push(@newcoowners,$uname.':'.$udom);
 8656:                                 }
 8657:                                 @newcoowners = sort(@newcoowners);
 8658:                             } else {
 8659:                                 push(@newcoowners,$uname.':'.$udom);
 8660:                             }
 8661:                         } else {
 8662:                             if ($coursehash{'internal.co-owners'}) {
 8663:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 8664:                                     unless ($coowner eq $uname.':'.$udom) {
 8665:                                         push(@newcoowners,$coowner);
 8666:                                     }
 8667:                                 }
 8668:                                 unless (@newcoowners > 0) {
 8669:                                     $delcoowners = 1;
 8670:                                     $coowners = '';
 8671:                                 }
 8672:                             }
 8673:                         }
 8674:                         if (@newcoowners || $delcoowners) {
 8675:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 8676:                                             $delcoowners,@newcoowners);
 8677:                         }
 8678:                     }
 8679:                 }
 8680:             }
 8681:         }
 8682:     }
 8683: }
 8684: 
 8685: sub store_coowners {
 8686:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 8687:     my $cid = $cdom.'_'.$cnum;
 8688:     my ($coowners,$delresult,$putresult);
 8689:     if (@newcoowners) {
 8690:         $coowners = join(',',@newcoowners);
 8691:         my %coownershash = (
 8692:                             'internal.co-owners' => $coowners,
 8693:                            );
 8694:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 8695:         if ($putresult eq 'ok') {
 8696:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 8697:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 8698:             }
 8699:         }
 8700:     }
 8701:     if ($delcoowners) {
 8702:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 8703:         if ($delresult eq 'ok') {
 8704:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 8705:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 8706:             }
 8707:         }
 8708:     }
 8709:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 8710:         my %crsinfo =
 8711:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 8712:         if (ref($crsinfo{$cid}) eq 'HASH') {
 8713:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 8714:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 8715:         }
 8716:     }
 8717: }
 8718: 
 8719: # -------------------------------------------------- Modify user authentication
 8720: # Overrides without validation
 8721: 
 8722: sub modifyuserauth {
 8723:     my ($udom,$uname,$umode,$upass)=@_;
 8724:     my $uhome=&homeserver($uname,$udom);
 8725:     unless (&allowed('mau',$udom)) { return 'refused'; }
 8726:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 8727:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 8728:              ' in domain '.$env{'request.role.domain'});  
 8729:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 8730: 		     &escape($upass),$uhome);
 8731:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 8732:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 8733:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 8734:     &log($udom,,$uname,$uhome,
 8735:         'Authentication changed by '.$env{'user.domain'}.', '.
 8736:                                      $env{'user.name'}.', '.$umode.
 8737:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 8738:     unless ($reply eq 'ok') {
 8739:         &logthis('Authentication mode error: '.$reply);
 8740: 	return 'error: '.$reply;
 8741:     }   
 8742:     return 'ok';
 8743: }
 8744: 
 8745: # --------------------------------------------------------------- Modify a user
 8746: 
 8747: sub modifyuser {
 8748:     my ($udom,    $uname, $uid,
 8749:         $umode,   $upass, $first,
 8750:         $middle,  $last,  $gene,
 8751:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 8752:     $udom= &LONCAPA::clean_domain($udom);
 8753:     $uname=&LONCAPA::clean_username($uname);
 8754:     my $showcandelete = 'none';
 8755:     if (ref($candelete) eq 'ARRAY') {
 8756:         if (@{$candelete} > 0) {
 8757:             $showcandelete = join(', ',@{$candelete});
 8758:         }
 8759:     }
 8760:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 8761:              $umode.', '.$first.', '.$middle.', '.
 8762: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 8763:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 8764:                                      ' desiredhome not specified'). 
 8765:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 8766:              ' in domain '.$env{'request.role.domain'});
 8767:     my $uhome=&homeserver($uname,$udom,'true');
 8768:     my $newuser;
 8769:     if ($uhome eq 'no_host') {
 8770:         $newuser = 1;
 8771:     }
 8772: # ----------------------------------------------------------------- Create User
 8773:     if (($uhome eq 'no_host') && 
 8774: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 8775:         my $unhome='';
 8776:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 8777:             $unhome = $desiredhome;
 8778: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 8779: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 8780:         } else { # load balancing routine for determining $unhome
 8781:             my $loadm=10000000;
 8782: 	    my %servers = &get_servers($udom,'library');
 8783: 	    foreach my $tryserver (keys(%servers)) {
 8784: 		my $answer=reply('load',$tryserver);
 8785: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 8786: 		    $loadm=$answer;
 8787: 		    $unhome=$tryserver;
 8788: 		}
 8789: 	    }
 8790:         }
 8791:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 8792: 	    return 'error: unable to find a home server for '.$uname.
 8793:                    ' in domain '.$udom;
 8794:         }
 8795:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 8796:                          &escape($upass),$unhome);
 8797: 	unless ($reply eq 'ok') {
 8798:             return 'error: '.$reply;
 8799:         }   
 8800:         $uhome=&homeserver($uname,$udom,'true');
 8801:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 8802: 	    return 'error: unable verify users home machine.';
 8803:         }
 8804:     }   # End of creation of new user
 8805: # ---------------------------------------------------------------------- Add ID
 8806:     if ($uid) {
 8807:        $uid=~tr/A-Z/a-z/;
 8808:        my %uidhash=&idrget($udom,$uname);
 8809:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 8810:          && (!$forceid)) {
 8811: 	  unless ($uid eq $uidhash{$uname}) {
 8812: 	      return 'error: user id "'.$uid.'" does not match '.
 8813:                   'current user id "'.$uidhash{$uname}.'".';
 8814:           }
 8815:        } else {
 8816: 	  &idput($udom,($uname => $uid));
 8817:        }
 8818:     }
 8819: # -------------------------------------------------------------- Add names, etc
 8820:     my @tmp=&get('environment',
 8821: 		   ['firstname','middlename','lastname','generation','id',
 8822:                     'permanentemail','inststatus'],
 8823: 		   $udom,$uname);
 8824:     my (%names,%oldnames);
 8825:     if ($tmp[0] =~ m/^error:.*/) { 
 8826:         %names=(); 
 8827:     } else {
 8828:         %names = @tmp;
 8829:         %oldnames = %names;
 8830:     }
 8831: #
 8832: # If name, email and/or uid are blank (e.g., because an uploaded file
 8833: # of users did not contain them), do not overwrite existing values
 8834: # unless field is in $candelete array ref.  
 8835: #
 8836: 
 8837:     my @fields = ('firstname','middlename','lastname','generation',
 8838:                   'permanentemail','id');
 8839:     my %newvalues;
 8840:     if (ref($candelete) eq 'ARRAY') {
 8841:         foreach my $field (@fields) {
 8842:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 8843:                 if ($field eq 'firstname') {
 8844:                     $names{$field} = $first;
 8845:                 } elsif ($field eq 'middlename') {
 8846:                     $names{$field} = $middle;
 8847:                 } elsif ($field eq 'lastname') {
 8848:                     $names{$field} = $last;
 8849:                 } elsif ($field eq 'generation') { 
 8850:                     $names{$field} = $gene;
 8851:                 } elsif ($field eq 'permanentemail') {
 8852:                     $names{$field} = $email;
 8853:                 } elsif ($field eq 'id') {
 8854:                     $names{$field}  = $uid;
 8855:                 }
 8856:             }
 8857:         }
 8858:     }
 8859:     if ($first)  { $names{'firstname'}  = $first; }
 8860:     if (defined($middle)) { $names{'middlename'} = $middle; }
 8861:     if ($last)   { $names{'lastname'}   = $last; }
 8862:     if (defined($gene))   { $names{'generation'} = $gene; }
 8863:     if ($email) {
 8864:        $email=~s/[^\w\@\.\-\,]//gs;
 8865:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 8866:     }
 8867:     if ($uid) { $names{'id'}  = $uid; }
 8868:     if (defined($inststatus)) {
 8869:         $names{'inststatus'} = '';
 8870:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 8871:         if (ref($usertypes) eq 'HASH') {
 8872:             my @okstatuses; 
 8873:             foreach my $item (split(/:/,$inststatus)) {
 8874:                 if (defined($usertypes->{$item})) {
 8875:                     push(@okstatuses,$item);  
 8876:                 }
 8877:             }
 8878:             if (@okstatuses) {
 8879:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 8880:             }
 8881:         }
 8882:     }
 8883:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 8884:                  $umode.', '.$first.', '.$middle.', '.
 8885:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 8886:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 8887:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 8888:     } else {
 8889:         $logmsg .= ' during self creation';
 8890:     }
 8891:     my $changed;
 8892:     if ($newuser) {
 8893:         $changed = 1;
 8894:     } else {
 8895:         foreach my $field (@fields) {
 8896:             if ($names{$field} ne $oldnames{$field}) {
 8897:                 $changed = 1;
 8898:                 last;
 8899:             }
 8900:         }
 8901:     }
 8902:     unless ($changed) {
 8903:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 8904:         &logthis($logmsg);
 8905:         return 'ok';
 8906:     }
 8907:     my $reply = &put('environment', \%names, $udom,$uname);
 8908:     if ($reply ne 'ok') { 
 8909:         return 'error: '.$reply;
 8910:     }
 8911:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
 8912:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
 8913:     }
 8914:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 8915:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 8916:     $logmsg = 'Success modifying user '.$logmsg;
 8917:     &logthis($logmsg);
 8918:     return 'ok';
 8919: }
 8920: 
 8921: # -------------------------------------------------------------- Modify student
 8922: 
 8923: sub modifystudent {
 8924:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 8925:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 8926:         $selfenroll,$context,$inststatus,$credits)=@_;
 8927:     if (!$cid) {
 8928: 	unless ($cid=$env{'request.course.id'}) {
 8929: 	    return 'not_in_class';
 8930: 	}
 8931:     }
 8932: # --------------------------------------------------------------- Make the user
 8933:     my $reply=&modifyuser
 8934: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 8935:          $desiredhome,$email,$inststatus);
 8936:     unless ($reply eq 'ok') { return $reply; }
 8937:     # This will cause &modify_student_enrollment to get the uid from the
 8938:     # student's environment
 8939:     $uid = undef if (!$forceid);
 8940:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 8941:                                         $gene,$usec,$end,$start,$type,$locktype,
 8942:                                         $cid,$selfenroll,$context,$credits);
 8943:     return $reply;
 8944: }
 8945: 
 8946: sub modify_student_enrollment {
 8947:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
 8948:         $locktype,$cid,$selfenroll,$context,$credits) = @_;
 8949:     my ($cdom,$cnum,$chome);
 8950:     if (!$cid) {
 8951: 	unless ($cid=$env{'request.course.id'}) {
 8952: 	    return 'not_in_class';
 8953: 	}
 8954: 	$cdom=$env{'course.'.$cid.'.domain'};
 8955: 	$cnum=$env{'course.'.$cid.'.num'};
 8956:     } else {
 8957: 	($cdom,$cnum)=split(/_/,$cid);
 8958:     }
 8959:     $chome=$env{'course.'.$cid.'.home'};
 8960:     if (!$chome) {
 8961: 	$chome=&homeserver($cnum,$cdom);
 8962:     }
 8963:     if (!$chome) { return 'unknown_course'; }
 8964:     # Make sure the user exists
 8965:     my $uhome=&homeserver($uname,$udom);
 8966:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8967: 	return 'error: no such user';
 8968:     }
 8969:     # Get student data if we were not given enough information
 8970:     if (!defined($first)  || $first  eq '' || 
 8971:         !defined($last)   || $last   eq '' || 
 8972:         !defined($uid)    || $uid    eq '' || 
 8973:         !defined($middle) || $middle eq '' || 
 8974:         !defined($gene)   || $gene   eq '') {
 8975:         # They did not supply us with enough data to enroll the student, so
 8976:         # we need to pick up more information.
 8977:         my %tmp = &get('environment',
 8978:                        ['firstname','middlename','lastname', 'generation','id']
 8979:                        ,$udom,$uname);
 8980: 
 8981:         #foreach my $key (keys(%tmp)) {
 8982:         #    &logthis("key $key = ".$tmp{$key});
 8983:         #}
 8984:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 8985:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 8986:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 8987:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 8988:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 8989:     }
 8990:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 8991:     my $user = "$uname:$udom";
 8992:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
 8993:     my $reply=cput('classlist',
 8994: 		   {$user => 
 8995: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
 8996: 		   $cdom,$cnum);
 8997:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
 8998:         &devalidate_getsection_cache($udom,$uname,$cid);
 8999:     } else { 
 9000: 	return 'error: '.$reply;
 9001:     }
 9002:     # Add student role to user
 9003:     my $uurl='/'.$cid;
 9004:     $uurl=~s/\_/\//g;
 9005:     if ($usec) {
 9006: 	$uurl.='/'.$usec;
 9007:     }
 9008:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
 9009:                              $selfenroll,$context);
 9010:     if ($result ne 'ok') {
 9011:         if ($old_entry{$user} ne '') {
 9012:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
 9013:         } else {
 9014:             $reply = &del('classlist',[$user],$cdom,$cnum);
 9015:         }
 9016:     }
 9017:     return $result; 
 9018: }
 9019: 
 9020: sub format_name {
 9021:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 9022:     my $name;
 9023:     if ($first ne 'lastname') {
 9024: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 9025:     } else {
 9026: 	if ($lastname=~/\S/) {
 9027: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 9028: 	    $name=~s/\s+,/,/;
 9029: 	} else {
 9030: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 9031: 	}
 9032:     }
 9033:     $name=~s/^\s+//;
 9034:     $name=~s/\s+$//;
 9035:     $name=~s/\s+/ /g;
 9036:     return $name;
 9037: }
 9038: 
 9039: # ------------------------------------------------- Write to course preferences
 9040: 
 9041: sub writecoursepref {
 9042:     my ($courseid,%prefs)=@_;
 9043:     $courseid=~s/^\///;
 9044:     $courseid=~s/\_/\//g;
 9045:     my ($cdomain,$cnum)=split(/\//,$courseid);
 9046:     my $chome=homeserver($cnum,$cdomain);
 9047:     if (($chome eq '') || ($chome eq 'no_host')) { 
 9048: 	return 'error: no such course';
 9049:     }
 9050:     my $cstring='';
 9051:     foreach my $pref (keys(%prefs)) {
 9052: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 9053:     }
 9054:     $cstring=~s/\&$//;
 9055:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 9056: }
 9057: 
 9058: # ---------------------------------------------------------- Make/modify course
 9059: 
 9060: sub createcourse {
 9061:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 9062:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 9063:     $url=&declutter($url);
 9064:     my $cid='';
 9065:     if ($context eq 'requestcourses') {
 9066:         my $can_create = 0;
 9067:         my ($ownername,$ownerdom) = split(':',$course_owner);
 9068:         if ($udom eq $ownerdom) {
 9069:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 9070:                                   $context)) {
 9071:                 $can_create = 1;
 9072:             }
 9073:         } else {
 9074:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 9075:                                            $category);
 9076:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 9077:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 9078:                 if (@curr > 0) {
 9079:                     my @options = qw(approval validate autolimit);
 9080:                     my $optregex = join('|',@options);
 9081:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 9082:                         $can_create = 1;
 9083:                     }
 9084:                 }
 9085:             }
 9086:         }
 9087:         if ($can_create) {
 9088:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 9089:                 unless (&allowed('ccc',$udom)) {
 9090:                     return 'refused'; 
 9091:                 }
 9092:             }
 9093:         } else {
 9094:             return 'refused';
 9095:         }
 9096:     } elsif (!&allowed('ccc',$udom)) {
 9097:         return 'refused';
 9098:     }
 9099: # --------------------------------------------------------------- Get Unique ID
 9100:     my $uname;
 9101:     if ($cnum =~ /^$match_courseid$/) {
 9102:         my $chome=&homeserver($cnum,$udom,'true');
 9103:         if (($chome eq '') || ($chome eq 'no_host')) {
 9104:             $uname = $cnum;
 9105:         } else {
 9106:             $uname = &generate_coursenum($udom,$crstype);
 9107:         }
 9108:     } else {
 9109:         $uname = &generate_coursenum($udom,$crstype);
 9110:     }
 9111:     return $uname if ($uname =~ /^error/);
 9112: # -------------------------------------------------- Check supplied server name
 9113:     if (!defined($course_server)) {
 9114:         if (defined(&domain($udom,'primary'))) {
 9115:             $course_server = &domain($udom,'primary');
 9116:         } else {
 9117:             $course_server = $env{'user.home'}; 
 9118:         }
 9119:     }
 9120:     my %host_servers =
 9121:         &Apache::lonnet::get_servers($udom,'library');
 9122:     unless ($host_servers{$course_server}) {
 9123:         return 'error: invalid home server for course: '.$course_server;
 9124:     }
 9125: # ------------------------------------------------------------- Make the course
 9126:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 9127:                       $course_server);
 9128:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 9129:     my $uhome=&homeserver($uname,$udom,'true');
 9130:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 9131: 	return 'error: no such course';
 9132:     }
 9133: # ----------------------------------------------------------------- Course made
 9134: # log existence
 9135:     my $now = time;
 9136:     my $newcourse = {
 9137:                     $udom.'_'.$uname => {
 9138:                                      description => $description,
 9139:                                      inst_code   => $inst_code,
 9140:                                      owner       => $course_owner,
 9141:                                      type        => $crstype,
 9142:                                      creator     => $env{'user.name'}.':'.
 9143:                                                     $env{'user.domain'},
 9144:                                      created     => $now,
 9145:                                      context     => $context,
 9146:                                                 },
 9147:                     };
 9148:     &courseidput($udom,$newcourse,$uhome,'notime');
 9149: # set toplevel url
 9150:     my $topurl=$url;
 9151:     unless ($nonstandard) {
 9152: # ------------------------------------------ For standard courses, make top url
 9153:         my $mapurl=&clutter($url);
 9154:         if ($mapurl eq '/res/') { $mapurl=''; }
 9155:         $env{'form.initmap'}=(<<ENDINITMAP);
 9156: <map>
 9157: <resource id="1" type="start"></resource>
 9158: <resource id="2" src="$mapurl"></resource>
 9159: <resource id="3" type="finish"></resource>
 9160: <link index="1" from="1" to="2"></link>
 9161: <link index="2" from="2" to="3"></link>
 9162: </map>
 9163: ENDINITMAP
 9164:         $topurl=&declutter(
 9165:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 9166:                           );
 9167:     }
 9168: # ----------------------------------------------------------- Write preferences
 9169:     &writecoursepref($udom.'_'.$uname,
 9170:                      ('description'              => $description,
 9171:                       'url'                      => $topurl,
 9172:                       'internal.creator'         => $env{'user.name'}.':'.
 9173:                                                     $env{'user.domain'},
 9174:                       'internal.created'         => $now,
 9175:                       'internal.creationcontext' => $context)
 9176:                     );
 9177:     return '/'.$udom.'/'.$uname;
 9178: }
 9179: 
 9180: # ------------------------------------------------------------------- Create ID
 9181: sub generate_coursenum {
 9182:     my ($udom,$crstype) = @_;
 9183:     my $domdesc = &domain($udom);
 9184:     return 'error: invalid domain' if ($domdesc eq '');
 9185:     my $first;
 9186:     if ($crstype eq 'Community') {
 9187:         $first = '0';
 9188:     } else {
 9189:         $first = int(1+rand(9)); 
 9190:     } 
 9191:     my $uname=$first.
 9192:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 9193:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
 9194:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 9195: # ----------------------------------------------- Make sure that does not exist
 9196:     my $uhome=&homeserver($uname,$udom,'true');
 9197:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
 9198:         if ($crstype eq 'Community') {
 9199:             $first = '0';
 9200:         } else {
 9201:             $first = int(1+rand(9));
 9202:         }
 9203:         $uname=$first.
 9204:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 9205:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
 9206:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 9207:         $uhome=&homeserver($uname,$udom,'true');
 9208:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
 9209:             return 'error: unable to generate unique course-ID';
 9210:         }
 9211:     }
 9212:     return $uname;
 9213: }
 9214: 
 9215: sub is_course {
 9216:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
 9217:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
 9218: 
 9219:     return unless $cdom and $cnum;
 9220: 
 9221:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
 9222:         '.');
 9223: 
 9224:     return unless(exists($courses{$cdom.'_'.$cnum}));
 9225:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
 9226: }
 9227: 
 9228: sub store_userdata {
 9229:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
 9230:     my $result;
 9231:     if ($datakey ne '') {
 9232:         if (ref($storehash) eq 'HASH') {
 9233:             if ($udom eq '' || $uname eq '') {
 9234:                 $udom = $env{'user.domain'};
 9235:                 $uname = $env{'user.name'};
 9236:             }
 9237:             my $uhome=&homeserver($uname,$udom);
 9238:             if (($uhome eq '') || ($uhome eq 'no_host')) {
 9239:                 $result = 'error: no_host';
 9240:             } else {
 9241:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
 9242:                 $storehash->{'host'} = $perlvar{'lonHostID'};
 9243: 
 9244:                 my $namevalue='';
 9245:                 foreach my $key (keys(%{$storehash})) {
 9246:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 9247:                 }
 9248:                 $namevalue=~s/\&$//;
 9249:                 unless ($namespace eq 'courserequests') {
 9250:                     $datakey = &escape($datakey);
 9251:                 }
 9252:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
 9253:                                   $namevalue,$uhome);
 9254:             }
 9255:         } else {
 9256:             $result = 'error: data to store was not a hash reference'; 
 9257:         }
 9258:     } else {
 9259:         $result= 'error: invalid requestkey'; 
 9260:     }
 9261:     return $result;
 9262: }
 9263: 
 9264: # ---------------------------------------------------------- Assign Custom Role
 9265: 
 9266: sub assigncustomrole {
 9267:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 9268:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 9269:                        $end,$start,$deleteflag,$selfenroll,$context);
 9270: }
 9271: 
 9272: # ----------------------------------------------------------------- Revoke Role
 9273: 
 9274: sub revokerole {
 9275:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 9276:     my $now=time;
 9277:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 9278: }
 9279: 
 9280: # ---------------------------------------------------------- Revoke Custom Role
 9281: 
 9282: sub revokecustomrole {
 9283:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 9284:     my $now=time;
 9285:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 9286:            $deleteflag,$selfenroll,$context);
 9287: }
 9288: 
 9289: # ------------------------------------------------------------ Disk usage
 9290: sub diskusage {
 9291:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 9292:     $directorypath =~ s/\/$//;
 9293:     my $listing=&reply('du2:'.&escape($directorypath).':'
 9294:                        .&escape($getpropath).':'.&escape($uname).':'
 9295:                        .&escape($udom),homeserver($uname,$udom));
 9296:     if ($listing eq 'unknown_cmd') {
 9297:         if ($getpropath) {
 9298:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 9299:         }
 9300:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 9301:     }
 9302:     return $listing;
 9303: }
 9304: 
 9305: sub is_locked {
 9306:     my ($file_name, $domain, $user, $which) = @_;
 9307:     my @check;
 9308:     my $is_locked;
 9309:     push (@check,$file_name);
 9310:     my %locked = &get('file_permissions',\@check,
 9311: 		      $env{'user.domain'},$env{'user.name'});
 9312:     my ($tmp)=keys(%locked);
 9313:     if ($tmp=~/^error:/) { undef(%locked); }
 9314:     
 9315:     if (ref($locked{$file_name}) eq 'ARRAY') {
 9316:         $is_locked = 'false';
 9317:         foreach my $entry (@{$locked{$file_name}}) {
 9318:            if (ref($entry) eq 'ARRAY') {
 9319:                $is_locked = 'true';
 9320:                if (ref($which) eq 'ARRAY') {
 9321:                    push(@{$which},$entry);
 9322:                } else {
 9323:                    last;
 9324:                }
 9325:            }
 9326:        }
 9327:     } else {
 9328:         $is_locked = 'false';
 9329:     }
 9330:     return $is_locked;
 9331: }
 9332: 
 9333: sub declutter_portfile {
 9334:     my ($file) = @_;
 9335:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 9336:     return $file;
 9337: }
 9338: 
 9339: # ------------------------------------------------------------- Mark as Read Only
 9340: 
 9341: sub mark_as_readonly {
 9342:     my ($domain,$user,$files,$what) = @_;
 9343:     my %current_permissions = &dump('file_permissions',$domain,$user);
 9344:     my ($tmp)=keys(%current_permissions);
 9345:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9346:     foreach my $file (@{$files}) {
 9347: 	$file = &declutter_portfile($file);
 9348:         push(@{$current_permissions{$file}},$what);
 9349:     }
 9350:     &put('file_permissions',\%current_permissions,$domain,$user);
 9351:     return;
 9352: }
 9353: 
 9354: # ------------------------------------------------------------Save Selected Files
 9355: 
 9356: sub save_selected_files {
 9357:     my ($user, $path, @files) = @_;
 9358:     my $filename = $user."savedfiles";
 9359:     my @other_files = &files_not_in_path($user, $path);
 9360:     open (OUT, '>'.$tmpdir.$filename);
 9361:     foreach my $file (@files) {
 9362:         print (OUT $env{'form.currentpath'}.$file."\n");
 9363:     }
 9364:     foreach my $file (@other_files) {
 9365:         print (OUT $file."\n");
 9366:     }
 9367:     close (OUT);
 9368:     return 'ok';
 9369: }
 9370: 
 9371: sub clear_selected_files {
 9372:     my ($user) = @_;
 9373:     my $filename = $user."savedfiles";
 9374:     open (OUT, '>'.LONCAPA::tempdir().$filename);
 9375:     print (OUT undef);
 9376:     close (OUT);
 9377:     return ("ok");    
 9378: }
 9379: 
 9380: sub files_in_path {
 9381:     my ($user, $path) = @_;
 9382:     my $filename = $user."savedfiles";
 9383:     my %return_files;
 9384:     open (IN, '<'.LONCAPA::tempdir().$filename);
 9385:     while (my $line_in = <IN>) {
 9386:         chomp ($line_in);
 9387:         my @paths_and_file = split (m!/!, $line_in);
 9388:         my $file_part = pop (@paths_and_file);
 9389:         my $path_part = join ('/', @paths_and_file);
 9390:         $path_part.='/';
 9391:         my $path_and_file = $path_part.$file_part;
 9392:         if ($path_part eq $path) {
 9393:             $return_files{$file_part}= 'selected';
 9394:         }
 9395:     }
 9396:     close (IN);
 9397:     return (\%return_files);
 9398: }
 9399: 
 9400: # called in portfolio select mode, to show files selected NOT in current directory
 9401: sub files_not_in_path {
 9402:     my ($user, $path) = @_;
 9403:     my $filename = $user."savedfiles";
 9404:     my @return_files;
 9405:     my $path_part;
 9406:     open(IN, '<'.LONCAPA::.$filename);
 9407:     while (my $line = <IN>) {
 9408:         #ok, I know it's clunky, but I want it to work
 9409:         my @paths_and_file = split(m|/|, $line);
 9410:         my $file_part = pop(@paths_and_file);
 9411:         chomp($file_part);
 9412:         my $path_part = join('/', @paths_and_file);
 9413:         $path_part .= '/';
 9414:         my $path_and_file = $path_part.$file_part;
 9415:         if ($path_part ne $path) {
 9416:             push(@return_files, ($path_and_file));
 9417:         }
 9418:     }
 9419:     close(OUT);
 9420:     return (@return_files);
 9421: }
 9422: 
 9423: #------------------------------Submitted/Handedback Portfolio Files Versioning
 9424:  
 9425: sub portfiles_versioning {
 9426:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
 9427:     my $portfolio_root = '/userfiles/portfolio';
 9428:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
 9429:     foreach my $file (@{$portfiles}) {
 9430:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
 9431:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
 9432:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
 9433:         my $getpropath = 1;
 9434:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
 9435:                                              $stu_name,$getpropath);
 9436:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
 9437:         my $new_answer = 
 9438:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
 9439:         if ($new_answer ne 'problem getting file') {
 9440:             push(@{$versioned_portfiles}, $directory.$new_answer);
 9441:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
 9442:                               [$symb,$env{'request.course.id'},'graded']);
 9443:         }
 9444:     }
 9445: }
 9446: 
 9447: sub get_next_version {
 9448:     my ($answer_name, $answer_ext, $dir_list) = @_;
 9449:     my $version;
 9450:     if (ref($dir_list) eq 'ARRAY') {
 9451:         foreach my $row (@{$dir_list}) {
 9452:             my ($file) = split(/\&/,$row,2);
 9453:             my ($file_name,$file_version,$file_ext) =
 9454:                 &file_name_version_ext($file);
 9455:             if (($file_name eq $answer_name) &&
 9456:                 ($file_ext eq $answer_ext)) {
 9457:                      # gets here if filename and extension match,
 9458:                      # regardless of version
 9459:                 if ($file_version ne '') {
 9460:                     # a versioned file is found  so save it for later
 9461:                     if ($file_version > $version) {
 9462:                         $version = $file_version;
 9463:                     }
 9464:                 }
 9465:             }
 9466:         }
 9467:     }
 9468:     $version ++;
 9469:     return($version);
 9470: }
 9471: 
 9472: sub version_selected_portfile {
 9473:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
 9474:     my ($answer_name,$answer_ver,$answer_ext) =
 9475:         &file_name_version_ext($file_name);
 9476:     my $new_answer;
 9477:     $env{'form.copy'} =
 9478:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
 9479:     if($env{'form.copy'} eq '-1') {
 9480:         $new_answer = 'problem getting file';
 9481:     } else {
 9482:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
 9483:         my $copy_result = 
 9484:             &finishuserfileupload($stu_name,$domain,'copy',
 9485:                                   '/portfolio'.$directory.$new_answer);
 9486:     }
 9487:     undef($env{'form.copy'});
 9488:     return ($new_answer);
 9489: }
 9490: 
 9491: sub file_name_version_ext {
 9492:     my ($file)=@_;
 9493:     my @file_parts = split(/\./, $file);
 9494:     my ($name,$version,$ext);
 9495:     if (@file_parts > 1) {
 9496:         $ext=pop(@file_parts);
 9497:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
 9498:             $version=pop(@file_parts);
 9499:         }
 9500:         $name=join('.',@file_parts);
 9501:     } else {
 9502:         $name=join('.',@file_parts);
 9503:     }
 9504:     return($name,$version,$ext);
 9505: }
 9506: 
 9507: #----------------------------------------------Get portfolio file permissions
 9508: 
 9509: sub get_portfile_permissions {
 9510:     my ($domain,$user) = @_;
 9511:     my %current_permissions = &dump('file_permissions',$domain,$user);
 9512:     my ($tmp)=keys(%current_permissions);
 9513:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9514:     return \%current_permissions;
 9515: }
 9516: 
 9517: #---------------------------------------------Get portfolio file access controls
 9518: 
 9519: sub get_access_controls {
 9520:     my ($current_permissions,$group,$file) = @_;
 9521:     my %access;
 9522:     my $real_file = $file;
 9523:     $file =~ s/\.meta$//;
 9524:     if (defined($file)) {
 9525:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 9526:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 9527:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 9528:             }
 9529:         }
 9530:     } else {
 9531:         foreach my $key (keys(%{$current_permissions})) {
 9532:             if ($key =~ /\0accesscontrol$/) {
 9533:                 if (defined($group)) {
 9534:                     if ($key !~ m-^\Q$group\E/-) {
 9535:                         next;
 9536:                     }
 9537:                 }
 9538:                 my ($fullpath) = split(/\0/,$key);
 9539:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 9540:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 9541:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 9542:                     }
 9543:                 }
 9544:             }
 9545:         }
 9546:     }
 9547:     return %access;
 9548: }
 9549: 
 9550: sub modify_access_controls {
 9551:     my ($file_name,$changes,$domain,$user)=@_;
 9552:     my ($outcome,$deloutcome);
 9553:     my %store_permissions;
 9554:     my %new_values;
 9555:     my %new_control;
 9556:     my %translation;
 9557:     my @deletions = ();
 9558:     my $now = time;
 9559:     if (exists($$changes{'activate'})) {
 9560:         if (ref($$changes{'activate'}) eq 'HASH') {
 9561:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 9562:             my $numnew = scalar(@newitems);
 9563:             for (my $i=0; $i<$numnew; $i++) {
 9564:                 my $newkey = $newitems[$i];
 9565:                 my $newid = &Apache::loncommon::get_cgi_id();
 9566:                 if ($newkey =~ /^\d+:/) { 
 9567:                     $newkey =~ s/^(\d+)/$newid/;
 9568:                     $translation{$1} = $newid;
 9569:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 9570:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 9571:                     $translation{$1} = $newid;
 9572:                 }
 9573:                 $new_values{$file_name."\0".$newkey} = 
 9574:                                           $$changes{'activate'}{$newitems[$i]};
 9575:                 $new_control{$newkey} = $now;
 9576:             }
 9577:         }
 9578:     }
 9579:     my %todelete;
 9580:     my %changed_items;
 9581:     foreach my $action ('delete','update') {
 9582:         if (exists($$changes{$action})) {
 9583:             if (ref($$changes{$action}) eq 'HASH') {
 9584:                 foreach my $key (keys(%{$$changes{$action}})) {
 9585:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 9586:                     if ($action eq 'delete') { 
 9587:                         $todelete{$itemnum} = 1;
 9588:                     } else {
 9589:                         $changed_items{$itemnum} = $key;
 9590:                     }
 9591:                 }
 9592:             }
 9593:         }
 9594:     }
 9595:     # get lock on access controls for file.
 9596:     my $lockhash = {
 9597:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 9598:                                                        ':'.$env{'user.domain'},
 9599:                    }; 
 9600:     my $tries = 0;
 9601:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 9602:    
 9603:     while (($gotlock ne 'ok') && $tries < 10) {
 9604:         $tries ++;
 9605:         sleep(0.1);
 9606:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 9607:     }
 9608:     if ($gotlock eq 'ok') {
 9609:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 9610:         my ($tmp)=keys(%curr_permissions);
 9611:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 9612:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 9613:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 9614:             if (ref($curr_controls) eq 'HASH') {
 9615:                 foreach my $control_item (keys(%{$curr_controls})) {
 9616:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 9617:                     if (defined($todelete{$itemnum})) {
 9618:                         push(@deletions,$file_name."\0".$control_item);
 9619:                     } else {
 9620:                         if (defined($changed_items{$itemnum})) {
 9621:                             $new_control{$changed_items{$itemnum}} = $now;
 9622:                             push(@deletions,$file_name."\0".$control_item);
 9623:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 9624:                         } else {
 9625:                             $new_control{$control_item} = $$curr_controls{$control_item};
 9626:                         }
 9627:                     }
 9628:                 }
 9629:             }
 9630:         }
 9631:         my ($group);
 9632:         if (&is_course($domain,$user)) {
 9633:             ($group,my $file) = split(/\//,$file_name,2);
 9634:         }
 9635:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 9636:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 9637:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 9638:         #  remove lock
 9639:         my @del_lock = ($file_name."\0".'locked_access_records');
 9640:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 9641:         my $sqlresult =
 9642:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 9643:                                     $group);
 9644:     } else {
 9645:         $outcome = "error: could not obtain lockfile\n";  
 9646:     }
 9647:     return ($outcome,$deloutcome,\%new_values,\%translation);
 9648: }
 9649: 
 9650: sub make_public_indefinitely {
 9651:     my (@requrl) = @_;
 9652:     return &automated_portfile_access('public',\@requrl);
 9653: }
 9654: 
 9655: sub automated_portfile_access {
 9656:     my ($accesstype,$addsref,$delsref,$info) = @_;
 9657:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
 9658:         return 'invalid';
 9659:     }
 9660:     my %urls;
 9661:     if (ref($addsref) eq 'ARRAY') {
 9662:         foreach my $requrl (@{$addsref}) {
 9663:             if (&is_portfolio_url($requrl)) {
 9664:                 unless (exists($urls{$requrl})) {
 9665:                     $urls{$requrl} = 'add';
 9666:                 }
 9667:             }
 9668:         }
 9669:     }
 9670:     if (ref($delsref) eq 'ARRAY') {
 9671:         foreach my $requrl (@{$delsref}) { 
 9672:             if (&is_portfolio_url($requrl)) {
 9673:                 unless (exists($urls{$requrl})) {
 9674:                     $urls{$requrl} = 'delete'; 
 9675:                 }
 9676:             }
 9677:         }
 9678:     }
 9679:     unless (keys(%urls)) {
 9680:         return 'invalid';
 9681:     }
 9682:     my $ip;
 9683:     if ($accesstype eq 'ip') {
 9684:         if (ref($info) eq 'HASH') {
 9685:             if ($info->{'ip'} ne '') {
 9686:                 $ip = $info->{'ip'};
 9687:             }
 9688:         }
 9689:         if ($ip eq '') {
 9690:             return 'invalid';
 9691:         }
 9692:     }
 9693:     my $errors;
 9694:     my $now = time;
 9695:     my %current_perms;
 9696:     foreach my $requrl (sort(keys(%urls))) {
 9697:         my $action;
 9698:         if ($urls{$requrl} eq 'add') {
 9699:             $action = 'activate';
 9700:         } else {
 9701:             $action = 'none';
 9702:         }
 9703:         my $aclnum = 0;
 9704:         my (undef,$udom,$unum,$file_name,$group) =
 9705:             &parse_portfolio_url($requrl);
 9706:         unless (exists($current_perms{$unum.':'.$udom})) {
 9707:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
 9708:         }
 9709:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
 9710:                                                    $group,$file_name);
 9711:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 9712:             my ($num,$scope,$end,$start) = 
 9713:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 9714:             if ($scope eq $accesstype) {
 9715:                 if (($start <= $now) && ($end == 0)) {
 9716:                     if ($accesstype eq 'ip') {
 9717:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
 9718:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
 9719:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
 9720:                                     if ($urls{$requrl} eq 'add') {
 9721:                                         $action = 'none';
 9722:                                         last;
 9723:                                     } else {
 9724:                                         $action = 'delete';
 9725:                                         $aclnum = $num;
 9726:                                         last;
 9727:                                     }
 9728:                                 }
 9729:                             }
 9730:                         }
 9731:                     } elsif ($accesstype eq 'public') {
 9732:                         if ($urls{$requrl} eq 'add') {
 9733:                             $action = 'none';
 9734:                             last;
 9735:                         } else {
 9736:                             $action = 'delete';
 9737:                             $aclnum = $num;
 9738:                             last;
 9739:                         }
 9740:                     }
 9741:                 } elsif ($accesstype eq 'public') {
 9742:                     $action = 'update';
 9743:                     $aclnum = $num;
 9744:                     last;
 9745:                 }
 9746:             }
 9747:         }
 9748:         if ($action eq 'none') {
 9749:             next;
 9750:         } else {
 9751:             my %changes;
 9752:             my $newend = 0;
 9753:             my $newstart = $now;
 9754:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
 9755:             $changes{$action}{$newkey} = {
 9756:                 type => $accesstype,
 9757:                 time => {
 9758:                     start => $newstart,
 9759:                     end   => $newend,
 9760:                 },
 9761:             };
 9762:             if ($accesstype eq 'ip') {
 9763:                 $changes{$action}{$newkey}{'ip'} = [$ip];
 9764:             }
 9765:             my ($outcome,$deloutcome,$new_values,$translation) =
 9766:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 9767:             unless ($outcome eq 'ok') {
 9768:                 $errors .= $outcome.' ';
 9769:             }
 9770:         }
 9771:     }
 9772:     if ($errors) {
 9773:         $errors =~ s/\s$//;
 9774:         return $errors;
 9775:     } else {
 9776:         return 'ok';
 9777:     }
 9778: }
 9779: 
 9780: #------------------------------------------------------Get Marked as Read Only
 9781: 
 9782: sub get_marked_as_readonly {
 9783:     my ($domain,$user,$what,$group) = @_;
 9784:     my $current_permissions = &get_portfile_permissions($domain,$user);
 9785:     my @readonly_files;
 9786:     my $cmp1=$what;
 9787:     if (ref($what)) { $cmp1=join('',@{$what}) };
 9788:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 9789:         if (defined($group)) {
 9790:             if ($file_name !~ m-^\Q$group\E/-) {
 9791:                 next;
 9792:             }
 9793:         }
 9794:         if (ref($value) eq "ARRAY"){
 9795:             foreach my $stored_what (@{$value}) {
 9796:                 my $cmp2=$stored_what;
 9797:                 if (ref($stored_what) eq 'ARRAY') {
 9798:                     $cmp2=join('',@{$stored_what});
 9799:                 }
 9800:                 if ($cmp1 eq $cmp2) {
 9801:                     push(@readonly_files, $file_name);
 9802:                     last;
 9803:                 } elsif (!defined($what)) {
 9804:                     push(@readonly_files, $file_name);
 9805:                     last;
 9806:                 }
 9807:             }
 9808:         }
 9809:     }
 9810:     return @readonly_files;
 9811: }
 9812: #-----------------------------------------------------------Get Marked as Read Only Hash
 9813: 
 9814: sub get_marked_as_readonly_hash {
 9815:     my ($current_permissions,$group,$what) = @_;
 9816:     my %readonly_files;
 9817:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 9818:         if (defined($group)) {
 9819:             if ($file_name !~ m-^\Q$group\E/-) {
 9820:                 next;
 9821:             }
 9822:         }
 9823:         if (ref($value) eq "ARRAY"){
 9824:             foreach my $stored_what (@{$value}) {
 9825:                 if (ref($stored_what) eq 'ARRAY') {
 9826:                     foreach my $lock_descriptor(@{$stored_what}) {
 9827:                         if ($lock_descriptor eq 'graded') {
 9828:                             $readonly_files{$file_name} = 'graded';
 9829:                         } elsif ($lock_descriptor eq 'handback') {
 9830:                             $readonly_files{$file_name} = 'handback';
 9831:                         } else {
 9832:                             if (!exists($readonly_files{$file_name})) {
 9833:                                 $readonly_files{$file_name} = 'locked';
 9834:                             }
 9835:                         }
 9836:                     }
 9837:                 } 
 9838:             }
 9839:         } 
 9840:     }
 9841:     return %readonly_files;
 9842: }
 9843: # ------------------------------------------------------------ Unmark as Read Only
 9844: 
 9845: sub unmark_as_readonly {
 9846:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 9847:     # for portfolio submissions, $what contains [$symb,$crsid] 
 9848:     my ($domain,$user,$what,$file_name,$group) = @_;
 9849:     $file_name = &declutter_portfile($file_name);
 9850:     my $symb_crs = $what;
 9851:     if (ref($what)) { $symb_crs=join('',@$what); }
 9852:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 9853:     my ($tmp)=keys(%current_permissions);
 9854:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9855:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 9856:     foreach my $file (@readonly_files) {
 9857: 	my $clean_file = &declutter_portfile($file);
 9858: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 9859: 	my $current_locks = $current_permissions{$file};
 9860:         my @new_locks;
 9861:         my @del_keys;
 9862:         if (ref($current_locks) eq "ARRAY"){
 9863:             foreach my $locker (@{$current_locks}) {
 9864:                 my $compare=$locker;
 9865:                 if (ref($locker) eq 'ARRAY') {
 9866:                     $compare=join('',@{$locker});
 9867:                     if ($compare ne $symb_crs) {
 9868:                         push(@new_locks, $locker);
 9869:                     }
 9870:                 }
 9871:             }
 9872:             if (scalar(@new_locks) > 0) {
 9873:                 $current_permissions{$file} = \@new_locks;
 9874:             } else {
 9875:                 push(@del_keys, $file);
 9876:                 &del('file_permissions',\@del_keys, $domain, $user);
 9877:                 delete($current_permissions{$file});
 9878:             }
 9879:         }
 9880:     }
 9881:     &put('file_permissions',\%current_permissions,$domain,$user);
 9882:     return;
 9883: }
 9884: 
 9885: # ------------------------------------------------------------ Directory lister
 9886: 
 9887: sub dirlist {
 9888:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 9889:     $uri=~s/^\///;
 9890:     $uri=~s/\/$//;
 9891:     my ($udom, $uname);
 9892:     if ($getuserdir) {
 9893:         $udom = $userdomain;
 9894:         $uname = $username;
 9895:     } else {
 9896:         (undef,$udom,$uname)=split(/\//,$uri);
 9897:         if(defined($userdomain)) {
 9898:             $udom = $userdomain;
 9899:         }
 9900:         if(defined($username)) {
 9901:             $uname = $username;
 9902:         }
 9903:     }
 9904:     my ($dirRoot,$listing,@listing_results);
 9905: 
 9906:     $dirRoot = $perlvar{'lonDocRoot'};
 9907:     if (defined($getpropath)) {
 9908:         $dirRoot = &propath($udom,$uname);
 9909:         $dirRoot =~ s/\/$//;
 9910:     } elsif (defined($getuserdir)) {
 9911:         my $subdir=$uname.'__';
 9912:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 9913:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 9914:                    ."/$udom/$subdir/$uname";
 9915:     } elsif (defined($alternateRoot)) {
 9916:         $dirRoot = $alternateRoot;
 9917:     }
 9918: 
 9919:     if($udom) {
 9920:         if($uname) {
 9921:             my $uhome = &homeserver($uname,$udom);
 9922:             if ($uhome eq 'no_host') {
 9923:                 return ([],'no_host');
 9924:             }
 9925:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 9926:                               .$getuserdir.':'.&escape($dirRoot)
 9927:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
 9928:             if ($listing eq 'unknown_cmd') {
 9929:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
 9930:             } else {
 9931:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 9932:             }
 9933:             if ($listing eq 'unknown_cmd') {
 9934:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
 9935:                 @listing_results = split(/:/,$listing);
 9936:             } else {
 9937:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 9938:             }
 9939:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
 9940:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
 9941:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 9942:                 return ([],$listing);
 9943:             } else {
 9944:                 return (\@listing_results);
 9945:             }
 9946:         } elsif(!$alternateRoot) {
 9947:             my (%allusers,%listerror);
 9948: 	    my %servers = &get_servers($udom,'library');
 9949:  	    foreach my $tryserver (keys(%servers)) {
 9950:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 9951:                                   &escape($udom),$tryserver);
 9952:                 if ($listing eq 'unknown_cmd') {
 9953: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 9954: 				      $udom, $tryserver);
 9955:                 } else {
 9956:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 9957:                 }
 9958: 		if ($listing eq 'unknown_cmd') {
 9959: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 9960: 				      $udom, $tryserver);
 9961: 		    @listing_results = split(/:/,$listing);
 9962: 		} else {
 9963: 		    @listing_results =
 9964: 			map { &unescape($_); } split(/:/,$listing);
 9965: 		}
 9966:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
 9967:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
 9968:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 9969:                     $listerror{$tryserver} = $listing;
 9970:                 } else {
 9971: 		    foreach my $line (@listing_results) {
 9972: 			my ($entry) = split(/&/,$line,2);
 9973: 			$allusers{$entry} = 1;
 9974: 		    }
 9975: 		}
 9976:             }
 9977:             my @alluserslist=();
 9978:             foreach my $user (sort(keys(%allusers))) {
 9979:                 push(@alluserslist,$user.'&user');
 9980:             }
 9981:             return (\@alluserslist);
 9982:         } else {
 9983:             return ([],'missing username');
 9984:         }
 9985:     } elsif(!defined($getpropath)) {
 9986:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
 9987:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
 9988:         return (\@all_domains);
 9989:     } else {
 9990:         return ([],'missing domain');
 9991:     }
 9992: }
 9993: 
 9994: # --------------------------------------------- GetFileTimestamp
 9995: # This function utilizes dirlist and returns the date stamp for
 9996: # when it was last modified.  It will also return an error of -1
 9997: # if an error occurs
 9998: 
 9999: sub GetFileTimestamp {
10000:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
10001:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
10002:     $studentName   = &LONCAPA::clean_username($studentName);
10003:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
10004:                                     undef,$getuserdir);
10005:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10006:         return -1;
10007:     }
10008:     if (ref($fileref) eq 'ARRAY') {
10009:         my @stats = split('&',$fileref->[0]);
10010:         # @stats contains first the filename, then the stat output
10011:         return $stats[10]; # so this is 10 instead of 9.
10012:     } else {
10013:         return -1;
10014:     }
10015: }
10016: 
10017: sub stat_file {
10018:     my ($uri) = @_;
10019:     $uri = &clutter_with_no_wrapper($uri);
10020: 
10021:     my ($udom,$uname,$file);
10022:     if ($uri =~ m-^/(uploaded|editupload)/-) {
10023: 	($udom,$uname,$file) =
10024: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
10025: 	$file = 'userfiles/'.$file;
10026:     }
10027:     if ($uri =~ m-^/res/-) {
10028: 	($udom,$uname) = 
10029: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
10030: 	$file = $uri;
10031:     }
10032: 
10033:     if (!$udom || !$uname || !$file) {
10034: 	# unable to handle the uri
10035: 	return ();
10036:     }
10037:     my $getpropath;
10038:     if ($file =~ /^userfiles\//) {
10039:         $getpropath = 1;
10040:     }
10041:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
10042:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
10043:         return ();
10044:     } else {
10045:         if (ref($listref) eq 'ARRAY') {
10046:             my @stats = split('&',$listref->[0]);
10047: 	    shift(@stats); #filename is first
10048: 	    return @stats;
10049:         }
10050:     }
10051:     return ();
10052: }
10053: 
10054: # -------------------------------------------------------- Value of a Condition
10055: 
10056: # gets the value of a specific preevaluated condition
10057: #    stored in the string  $env{user.state.<cid>}
10058: # or looks up a condition reference in the bighash and if if hasn't
10059: # already been evaluated recurses into docondval to get the value of
10060: # the condition, then memoizing it to 
10061: #   $env{user.state.<cid>.<condition>}
10062: sub directcondval {
10063:     my $number=shift;
10064:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
10065: 	&Apache::lonuserstate::evalstate();
10066:     }
10067:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
10068: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
10069:     } elsif ($number =~ /^_/) {
10070: 	my $sub_condition;
10071: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10072: 		&GDBM_READER(),0640)) {
10073: 	    $sub_condition=$bighash{'conditions'.$number};
10074: 	    untie(%bighash);
10075: 	}
10076: 	my $value = &docondval($sub_condition);
10077: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
10078: 	return $value;
10079:     }
10080:     if ($env{'user.state.'.$env{'request.course.id'}}) {
10081:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
10082:     } else {
10083:        return 2;
10084:     }
10085: }
10086: 
10087: # get the collection of conditions for this resource
10088: sub condval {
10089:     my $condidx=shift;
10090:     my $allpathcond='';
10091:     foreach my $cond (split(/\|/,$condidx)) {
10092: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
10093: 	    $allpathcond.=
10094: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
10095: 	}
10096:     }
10097:     $allpathcond=~s/\|$//;
10098:     return &docondval($allpathcond);
10099: }
10100: 
10101: #evaluates an expression of conditions
10102: sub docondval {
10103:     my ($allpathcond) = @_;
10104:     my $result=0;
10105:     if ($env{'request.course.id'}
10106: 	&& defined($allpathcond)) {
10107: 	my $operand='|';
10108: 	my @stack;
10109: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
10110: 	    if ($chunk eq '(') {
10111: 		push @stack,($operand,$result);
10112: 	    } elsif ($chunk eq ')') {
10113: 		my $before=pop @stack;
10114: 		if (pop @stack eq '&') {
10115: 		    $result=$result>$before?$before:$result;
10116: 		} else {
10117: 		    $result=$result>$before?$result:$before;
10118: 		}
10119: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
10120: 		$operand=$chunk;
10121: 	    } else {
10122: 		my $new=directcondval($chunk);
10123: 		if ($operand eq '&') {
10124: 		    $result=$result>$new?$new:$result;
10125: 		} else {
10126: 		    $result=$result>$new?$result:$new;
10127: 		}
10128: 	    }
10129: 	}
10130:     }
10131:     return $result;
10132: }
10133: 
10134: # ---------------------------------------------------- Devalidate courseresdata
10135: 
10136: sub devalidatecourseresdata {
10137:     my ($coursenum,$coursedomain)=@_;
10138:     my $hashid=$coursenum.':'.$coursedomain;
10139:     &devalidate_cache_new('courseres',$hashid);
10140: }
10141: 
10142: 
10143: # --------------------------------------------------- Course Resourcedata Query
10144: #
10145: #  Parameters:
10146: #      $coursenum    - Number of the course.
10147: #      $coursedomain - Domain at which the course was created.
10148: #  Returns:
10149: #     A hash of the course parameters along (I think) with timestamps
10150: #     and version info.
10151: 
10152: sub get_courseresdata {
10153:     my ($coursenum,$coursedomain)=@_;
10154:     my $coursehom=&homeserver($coursenum,$coursedomain);
10155:     my $hashid=$coursenum.':'.$coursedomain;
10156:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
10157:     my %dumpreply;
10158:     unless (defined($cached)) {
10159: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
10160: 	$result=\%dumpreply;
10161: 	my ($tmp) = keys(%dumpreply);
10162: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10163: 	    &do_cache_new('courseres',$hashid,$result,600);
10164: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
10165: 	    return $tmp;
10166: 	} elsif ($tmp =~ /^(error)/) {
10167: 	    $result=undef;
10168: 	    &do_cache_new('courseres',$hashid,$result,600);
10169: 	}
10170:     }
10171:     return $result;
10172: }
10173: 
10174: sub devalidateuserresdata {
10175:     my ($uname,$udom)=@_;
10176:     my $hashid="$udom:$uname";
10177:     &devalidate_cache_new('userres',$hashid);
10178: }
10179: 
10180: sub get_userresdata {
10181:     my ($uname,$udom)=@_;
10182:     #most student don\'t have any data set, check if there is some data
10183:     if (&EXT_cache_status($udom,$uname)) { return undef; }
10184: 
10185:     my $hashid="$udom:$uname";
10186:     my ($result,$cached)=&is_cached_new('userres',$hashid);
10187:     if (!defined($cached)) {
10188: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
10189: 	$result=\%resourcedata;
10190: 	&do_cache_new('userres',$hashid,$result,600);
10191:     }
10192:     my ($tmp)=keys(%$result);
10193:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
10194: 	return $result;
10195:     }
10196:     #error 2 occurs when the .db doesn't exist
10197:     if ($tmp!~/error: 2 /) {
10198:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
10199: 	    &logthis("<font color=\"blue\">WARNING:".
10200: 		     " Trying to get resource data for ".
10201: 		     $uname." at ".$udom.": ".
10202: 		     $tmp."</font>");
10203:         }
10204:     } elsif ($tmp=~/error: 2 /) {
10205: 	#&EXT_cache_set($udom,$uname);
10206: 	&do_cache_new('userres',$hashid,undef,600);
10207: 	undef($tmp); # not really an error so don't send it back
10208:     }
10209:     return $tmp;
10210: }
10211: #----------------------------------------------- resdata - return resource data
10212: #  Purpose:
10213: #    Return resource data for either users or for a course.
10214: #  Parameters:
10215: #     $name      - Course/user name.
10216: #     $domain    - Name of the domain the user/course is registered on.
10217: #     $type      - Type of thing $name is (must be 'course' or 'user'
10218: #     @which     - Array of names of resources desired.
10219: #  Returns:
10220: #     The value of the first reasource in @which that is found in the
10221: #     resource hash.
10222: #  Exceptional Conditions:
10223: #     If the $type passed in is not valid (not the string 'course' or 
10224: #     'user', an undefined  reference is returned.
10225: #     If none of the resources are found, an undef is returned
10226: sub resdata {
10227:     my ($name,$domain,$type,@which)=@_;
10228:     my $result;
10229:     if ($type eq 'course') {
10230: 	$result=&get_courseresdata($name,$domain);
10231:     } elsif ($type eq 'user') {
10232: 	$result=&get_userresdata($name,$domain);
10233:     }
10234:     if (!ref($result)) { return $result; }    
10235:     foreach my $item (@which) {
10236: 	if (defined($result->{$item->[0]})) {
10237: 	    return [$result->{$item->[0]},$item->[1]];
10238: 	}
10239:     }
10240:     return undef;
10241: }
10242: 
10243: sub get_domain_ltitools {
10244:     my ($cdom) = @_;
10245:     my %ltitools;
10246:     my ($result,$cached)=&is_cached_new('ltitools',$cdom);
10247:     if (defined($cached)) {
10248:         if (ref($result) eq 'HASH') {
10249:             %ltitools = %{$result};
10250:         }
10251:     } else {
10252:         my %domconfig = &get_dom('configuration',['ltitools'],$cdom);
10253:         if (ref($domconfig{'ltitools'}) eq 'HASH') {
10254:             %ltitools = %{$domconfig{'ltitools'}};
10255:         }
10256:         my $cachetime = 24*60*60;
10257:         &do_cache_new('ltitools',$cdom,\%ltitools,$cachetime);
10258:     }
10259:     return %ltitools;
10260: }
10261: 
10262: sub get_numsuppfiles {
10263:     my ($cnum,$cdom,$ignorecache)=@_;
10264:     my $hashid=$cnum.':'.$cdom;
10265:     my ($suppcount,$cached);
10266:     unless ($ignorecache) {
10267:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
10268:     }
10269:     unless (defined($cached)) {
10270:         my $chome=&homeserver($cnum,$cdom);
10271:         unless ($chome eq 'no_host') {
10272:             ($suppcount,my $errors) = (0,0);
10273:             my $suppmap = 'supplemental.sequence';
10274:             ($suppcount,$errors) = 
10275:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
10276:         }
10277:         &do_cache_new('suppcount',$hashid,$suppcount,600);
10278:     }
10279:     return $suppcount;
10280: }
10281: 
10282: #
10283: # EXT resource caching routines
10284: #
10285: 
10286: sub clear_EXT_cache_status {
10287:     &delenv('cache.EXT.');
10288: }
10289: 
10290: sub EXT_cache_status {
10291:     my ($target_domain,$target_user) = @_;
10292:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
10293:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
10294:         # We know already the user has no data
10295:         return 1;
10296:     } else {
10297:         return 0;
10298:     }
10299: }
10300: 
10301: sub EXT_cache_set {
10302:     my ($target_domain,$target_user) = @_;
10303:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
10304:     #&appenv({$cachename => time});
10305: }
10306: 
10307: # --------------------------------------------------------- Value of a Variable
10308: sub EXT {
10309: 
10310:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
10311:     unless ($varname) { return ''; }
10312:     #get real user name/domain, courseid and symb
10313:     my $courseid;
10314:     my $publicuser;
10315:     if ($symbparm) {
10316: 	$symbparm=&get_symb_from_alias($symbparm);
10317:     }
10318:     if (!($uname && $udom)) {
10319:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
10320:       if (!$symbparm) {	$symbparm=$cursymb; }
10321:     } else {
10322: 	$courseid=$env{'request.course.id'};
10323:     }
10324:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
10325:     my $rest;
10326:     if (defined($therest[0])) {
10327:        $rest=join('.',@therest);
10328:     } else {
10329:        $rest='';
10330:     }
10331: 
10332:     my $qualifierrest=$qualifier;
10333:     if ($rest) { $qualifierrest.='.'.$rest; }
10334:     my $spacequalifierrest=$space;
10335:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
10336:     if ($realm eq 'user') {
10337: # --------------------------------------------------------------- user.resource
10338: 	if ($space eq 'resource') {
10339: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
10340: 		  || defined($Apache::lonhomework::parsing_a_task))
10341: 		 &&
10342: 		 ($symbparm eq &symbread()) ) {	
10343: 		# if we are in the middle of processing the resource the
10344: 		# get the value we are planning on committing
10345:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
10346:                     return $Apache::lonhomework::results{$qualifierrest};
10347:                 } else {
10348:                     return $Apache::lonhomework::history{$qualifierrest};
10349:                 }
10350: 	    } else {
10351: 		my %restored;
10352: 		if ($publicuser || $env{'request.state'} eq 'construct') {
10353: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
10354: 		} else {
10355: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
10356: 		}
10357: 		return $restored{$qualifierrest};
10358: 	    }
10359: # ----------------------------------------------------------------- user.access
10360:         } elsif ($space eq 'access') {
10361: 	    # FIXME - not supporting calls for a specific user
10362:             return &allowed($qualifier,$rest);
10363: # ------------------------------------------ user.preferences, user.environment
10364:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
10365: 	    if (($uname eq $env{'user.name'}) &&
10366: 		($udom eq $env{'user.domain'})) {
10367: 		return $env{join('.',('environment',$qualifierrest))};
10368: 	    } else {
10369: 		my %returnhash;
10370: 		if (!$publicuser) {
10371: 		    %returnhash=&userenvironment($udom,$uname,
10372: 						 $qualifierrest);
10373: 		}
10374: 		return $returnhash{$qualifierrest};
10375: 	    }
10376: # ----------------------------------------------------------------- user.course
10377:         } elsif ($space eq 'course') {
10378: 	    # FIXME - not supporting calls for a specific user
10379:             return $env{join('.',('request.course',$qualifier))};
10380: # ------------------------------------------------------------------- user.role
10381:         } elsif ($space eq 'role') {
10382: 	    # FIXME - not supporting calls for a specific user
10383:             my ($role,$where)=split(/\./,$env{'request.role'});
10384:             if ($qualifier eq 'value') {
10385: 		return $role;
10386:             } elsif ($qualifier eq 'extent') {
10387:                 return $where;
10388:             }
10389: # ----------------------------------------------------------------- user.domain
10390:         } elsif ($space eq 'domain') {
10391:             return $udom;
10392: # ------------------------------------------------------------------- user.name
10393:         } elsif ($space eq 'name') {
10394:             return $uname;
10395: # ---------------------------------------------------- Any other user namespace
10396:         } else {
10397: 	    my %reply;
10398: 	    if (!$publicuser) {
10399: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
10400: 	    }
10401: 	    return $reply{$qualifierrest};
10402:         }
10403:     } elsif ($realm eq 'query') {
10404: # ---------------------------------------------- pull stuff out of query string
10405:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
10406: 						[$spacequalifierrest]);
10407: 	return $env{'form.'.$spacequalifierrest}; 
10408:    } elsif ($realm eq 'request') {
10409: # ------------------------------------------------------------- request.browser
10410:         if ($space eq 'browser') {
10411:             return $env{'browser.'.$qualifier};
10412: # ------------------------------------------------------------ request.filename
10413:         } else {
10414:             return $env{'request.'.$spacequalifierrest};
10415:         }
10416:     } elsif ($realm eq 'course') {
10417: # ---------------------------------------------------------- course.description
10418:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
10419:     } elsif ($realm eq 'resource') {
10420: 
10421: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
10422: 	    if (!$symbparm) { $symbparm=&symbread(); }
10423: 	}
10424: 
10425:         if ($qualifier eq '') {
10426: 	    if ($space eq 'title') {
10427: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
10428: 	        return &gettitle($symbparm);
10429: 	    }
10430: 	
10431: 	    if ($space eq 'map') {
10432: 	        my ($map) = &decode_symb($symbparm);
10433: 	        return &symbread($map);
10434: 	    }
10435:             if ($space eq 'maptitle') {
10436:                 my ($map) = &decode_symb($symbparm);
10437:                 return &gettitle($map);
10438:             }
10439: 	    if ($space eq 'filename') {
10440: 	        if ($symbparm) {
10441: 		    return &clutter((&decode_symb($symbparm))[2]);
10442: 	        }
10443: 	        return &hreflocation('',$env{'request.filename'});
10444: 	    }
10445: 
10446:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
10447:                 if ($space eq 'visibleparts') {
10448:                     my $navmap = Apache::lonnavmaps::navmap->new();
10449:                     my $item;
10450:                     if (ref($navmap)) {
10451:                         my $res = $navmap->getBySymb($symbparm);
10452:                         my $parts = $res->parts();
10453:                         if (ref($parts) eq 'ARRAY') {
10454:                             $item = join(',',@{$parts});
10455:                         }
10456:                         undef($navmap);
10457:                     }
10458:                     return $item;
10459:                 }
10460:             }
10461:         }
10462: 
10463: 	my ($section, $group, @groups);
10464: 	my ($courselevelm,$courselevel);
10465:         if (($courseid eq '') && ($cid)) {
10466:             $courseid = $cid;
10467:         }
10468: 	if (($symbparm && $courseid) && 
10469: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
10470: 
10471: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
10472: 
10473: # ----------------------------------------------------- Cascading lookup scheme
10474: 	    my $symbp=$symbparm;
10475: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
10476: 
10477: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
10478: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
10479: 
10480: 	    if (($env{'user.name'} eq $uname) &&
10481: 		($env{'user.domain'} eq $udom)) {
10482: 		$section=$env{'request.course.sec'};
10483:                 @groups = split(/:/,$env{'request.course.groups'});  
10484:                 @groups=&sort_course_groups($courseid,@groups); 
10485: 	    } else {
10486: 		if (! defined($usection)) {
10487: 		    $section=&getsection($udom,$uname,$courseid);
10488: 		} else {
10489: 		    $section = $usection;
10490: 		}
10491:                 @groups = &get_users_groups($udom,$uname,$courseid);
10492: 	    }
10493: 
10494: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
10495: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
10496: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
10497: 
10498: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
10499: 	    my $courselevelr=$courseid.'.'.$symbparm;
10500: 	    $courselevelm=$courseid.'.'.$mapparm;
10501: 
10502: # ----------------------------------------------------------- first, check user
10503: 
10504: 	    my $userreply=&resdata($uname,$udom,'user',
10505: 				       ([$courselevelr,'resource'],
10506: 					[$courselevelm,'map'     ],
10507: 					[$courselevel, 'course'  ]));
10508: 	    if (defined($userreply)) { return &get_reply($userreply); }
10509: 
10510: # ------------------------------------------------ second, check some of course
10511:             my $coursereply;
10512:             if (@groups > 0) {
10513:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
10514:                                        $mapparm,$spacequalifierrest);
10515:                 if (defined($coursereply)) { return &get_reply($coursereply); }
10516:             }
10517: 
10518: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10519: 				  $env{'course.'.$courseid.'.domain'},
10520: 				  'course',
10521: 				  ([$seclevelr,   'resource'],
10522: 				   [$seclevelm,   'map'     ],
10523: 				   [$seclevel,    'course'  ],
10524: 				   [$courselevelr,'resource']));
10525: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
10526: 
10527: # ------------------------------------------------------ third, check map parms
10528: 	    my %parmhash=();
10529: 	    my $thisparm='';
10530: 	    if (tie(%parmhash,'GDBM_File',
10531: 		    $env{'request.course.fn'}.'_parms.db',
10532: 		    &GDBM_READER(),0640)) {
10533: 		$thisparm=$parmhash{$symbparm};
10534: 		untie(%parmhash);
10535: 	    }
10536: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
10537: 	}
10538: # ------------------------------------------ fourth, look in resource metadata
10539: 
10540: 	$spacequalifierrest=~s/\./\_/;
10541: 	my $filename;
10542: 	if (!$symbparm) { $symbparm=&symbread(); }
10543: 	if ($symbparm) {
10544: 	    $filename=(&decode_symb($symbparm))[2];
10545: 	} else {
10546: 	    $filename=$env{'request.filename'};
10547: 	}
10548: 	my $metadata=&metadata($filename,$spacequalifierrest);
10549: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
10550: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
10551: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
10552: 
10553: # ---------------------------------------------- fourth, look in rest of course
10554: 	if ($symbparm && defined($courseid) && 
10555: 	    $courseid eq $env{'request.course.id'}) {
10556: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10557: 				     $env{'course.'.$courseid.'.domain'},
10558: 				     'course',
10559: 				     ([$courselevelm,'map'   ],
10560: 				      [$courselevel, 'course']));
10561: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
10562: 	}
10563: # ------------------------------------------------------------------ Cascade up
10564: 	unless ($space eq '0') {
10565: 	    my @parts=split(/_/,$space);
10566: 	    my $id=pop(@parts);
10567: 	    my $part=join('_',@parts);
10568: 	    if ($part eq '') { $part='0'; }
10569: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
10570: 				 $symbparm,$udom,$uname,$section,1);
10571: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
10572: 	}
10573: 	if ($recurse) { return undef; }
10574: 	my $pack_def=&packages_tab_default($filename,$varname);
10575: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
10576: # ---------------------------------------------------- Any other user namespace
10577:     } elsif ($realm eq 'environment') {
10578: # ----------------------------------------------------------------- environment
10579: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
10580: 	    return $env{'environment.'.$spacequalifierrest};
10581: 	} else {
10582: 	    if ($uname eq 'anonymous' && $udom eq '') {
10583: 		return '';
10584: 	    }
10585: 	    my %returnhash=&userenvironment($udom,$uname,
10586: 					    $spacequalifierrest);
10587: 	    return $returnhash{$spacequalifierrest};
10588: 	}
10589:     } elsif ($realm eq 'system') {
10590: # ----------------------------------------------------------------- system.time
10591: 	if ($space eq 'time') {
10592: 	    return time;
10593:         }
10594:     } elsif ($realm eq 'server') {
10595: # ----------------------------------------------------------------- system.time
10596: 	if ($space eq 'name') {
10597: 	    return $ENV{'SERVER_NAME'};
10598:         }
10599:     }
10600:     return '';
10601: }
10602: 
10603: sub get_reply {
10604:     my ($reply_value) = @_;
10605:     if (ref($reply_value) eq 'ARRAY') {
10606:         if (wantarray) {
10607: 	    return @$reply_value;
10608:         }
10609:         return $reply_value->[0];
10610:     } else {
10611:         return $reply_value;
10612:     }
10613: }
10614: 
10615: sub check_group_parms {
10616:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10617:     my @groupitems = ();
10618:     my $resultitem;
10619:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
10620:     foreach my $group (@{$groups}) {
10621:         foreach my $level (@levels) {
10622:              my $item = $courseid.'.['.$group.'].'.$level->[0];
10623:              push(@groupitems,[$item,$level->[1]]);
10624:         }
10625:     }
10626:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10627:                             $env{'course.'.$courseid.'.domain'},
10628:                                      'course',@groupitems);
10629:     return $coursereply;
10630: }
10631: 
10632: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
10633:     my ($courseid,@groups) = @_;
10634:     @groups = sort(@groups);
10635:     return @groups;
10636: }
10637: 
10638: sub packages_tab_default {
10639:     my ($uri,$varname)=@_;
10640:     my (undef,$part,$name)=split(/\./,$varname);
10641: 
10642:     my (@extension,@specifics,$do_default);
10643:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
10644: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
10645: 	if ($pack_type eq 'default') {
10646: 	    $do_default=1;
10647: 	} elsif ($pack_type eq 'extension') {
10648: 	    push(@extension,[$package,$pack_type,$pack_part]);
10649: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
10650: 	    # only look at packages defaults for packages that this id is
10651: 	    push(@specifics,[$package,$pack_type,$pack_part]);
10652: 	}
10653:     }
10654:     # first look for a package that matches the requested part id
10655:     foreach my $package (@specifics) {
10656: 	my (undef,$pack_type,$pack_part)=@{$package};
10657: 	next if ($pack_part ne $part);
10658: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10659: 	    return $packagetab{"$pack_type&$name&default"};
10660: 	}
10661:     }
10662:     # look for any possible matching non extension_ package
10663:     foreach my $package (@specifics) {
10664: 	my (undef,$pack_type,$pack_part)=@{$package};
10665: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10666: 	    return $packagetab{"$pack_type&$name&default"};
10667: 	}
10668: 	if ($pack_type eq 'part') { $pack_part='0'; }
10669: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10670: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
10671: 	}
10672:     }
10673:     # look for any posible extension_ match
10674:     foreach my $package (@extension) {
10675: 	my ($package,$pack_type)=@{$package};
10676: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10677: 	    return $packagetab{"$pack_type&$name&default"};
10678: 	}
10679: 	if (defined($packagetab{$package."&$name&default"})) {
10680: 	    return $packagetab{$package."&$name&default"};
10681: 	}
10682:     }
10683:     # look for a global default setting
10684:     if ($do_default && defined($packagetab{"default&$name&default"})) {
10685: 	return $packagetab{"default&$name&default"};
10686:     }
10687:     return undef;
10688: }
10689: 
10690: sub add_prefix_and_part {
10691:     my ($prefix,$part)=@_;
10692:     my $keyroot;
10693:     if (defined($prefix) && $prefix !~ /^__/) {
10694: 	# prefix that has a part already
10695: 	$keyroot=$prefix;
10696:     } elsif (defined($prefix)) {
10697: 	# prefix that is missing a part
10698: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10699:     } else {
10700: 	# no prefix at all
10701: 	if (defined($part)) { $keyroot='_'.$part; }
10702:     }
10703:     return $keyroot;
10704: }
10705: 
10706: # ---------------------------------------------------------------- Get metadata
10707: 
10708: my %metaentry;
10709: my %importedpartids;
10710: sub metadata {
10711:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
10712:     $uri=&declutter($uri);
10713:     # if it is a non metadata possible uri return quickly
10714:     if (($uri eq '') || 
10715: 	(($uri =~ m|^/*adm/|) && 
10716: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|exttools?)$})) ||
10717:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
10718: 	return undef;
10719:     }
10720:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
10721: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
10722: 	return undef;
10723:     }
10724:     my $filename=$uri;
10725:     $uri=~s/\.meta$//;
10726: #
10727: # Is the metadata already cached?
10728: # Look at timestamp of caching
10729: # Everything is cached by the main uri, libraries are never directly cached
10730: #
10731:     if (!defined($liburi)) {
10732: 	my ($result,$cached)=&is_cached_new('meta',$uri);
10733: 	if (defined($cached)) { return $result->{':'.$what}; }
10734:     }
10735:     {
10736: # Imported parts would go here
10737:         my %importedids=();
10738:         my @origfileimportpartids=();
10739:         my $importedparts=0;
10740: #
10741: # Is this a recursive call for a library?
10742: #
10743: #	if (! exists($metacache{$uri})) {
10744: #	    $metacache{$uri}={};
10745: #	}
10746: 	my $cachetime = 60*60;
10747:         if ($liburi) {
10748: 	    $liburi=&declutter($liburi);
10749:             $filename=$liburi;
10750:         } else {
10751: 	    &devalidate_cache_new('meta',$uri);
10752: 	    undef(%metaentry);
10753: 	}
10754:         my %metathesekeys=();
10755:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
10756: 	my $metastring;
10757: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
10758: 	    my $which = &hreflocation('','/'.($liburi || $uri));
10759: 	    $metastring = 
10760: 		&Apache::lonnet::ssi_body($which,
10761: 					  ('grade_target' => 'meta'));
10762: 	    $cachetime = 1; # only want this cached in the child not long term
10763: 	} elsif (($uri !~ m -^(editupload)/-) && 
10764:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
10765: 	    my $file=&filelocation('',&clutter($filename));
10766: 	    #push(@{$metaentry{$uri.'.file'}},$file);
10767: 	    $metastring=&getfile($file);
10768: 	}
10769:         my $parser=HTML::LCParser->new(\$metastring);
10770:         my $token;
10771:         undef %metathesekeys;
10772:         while ($token=$parser->get_token) {
10773: 	    if ($token->[0] eq 'S') {
10774: 		if (defined($token->[2]->{'package'})) {
10775: #
10776: # This is a package - get package info
10777: #
10778: 		    my $package=$token->[2]->{'package'};
10779: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10780: 		    if (defined($token->[2]->{'id'})) { 
10781: 			$keyroot.='_'.$token->[2]->{'id'}; 
10782: 		    }
10783: 		    if ($metaentry{':packages'}) {
10784: 			$metaentry{':packages'}.=','.$package.$keyroot;
10785: 		    } else {
10786: 			$metaentry{':packages'}=$package.$keyroot;
10787: 		    }
10788: 		    foreach my $pack_entry (keys(%packagetab)) {
10789: 			my $part=$keyroot;
10790: 			$part=~s/^\_//;
10791: 			if ($pack_entry=~/^\Q$package\E\&/ || 
10792: 			    $pack_entry=~/^\Q$package\E_0\&/) {
10793: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
10794: 			    # ignore package.tab specified default values
10795:                             # here &package_tab_default() will fetch those
10796: 			    if ($subp eq 'default') { next; }
10797: 			    my $value=$packagetab{$pack_entry};
10798: 			    my $unikey;
10799: 			    if ($pack =~ /_0$/) {
10800: 				$unikey='parameter_0_'.$name;
10801: 				$part=0;
10802: 			    } else {
10803: 				$unikey='parameter'.$keyroot.'_'.$name;
10804: 			    }
10805: 			    if ($subp eq 'display') {
10806: 				$value.=' [Part: '.$part.']';
10807: 			    }
10808: 			    $metaentry{':'.$unikey.'.part'}=$part;
10809: 			    $metathesekeys{$unikey}=1;
10810: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10811: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
10812: 			    }
10813: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
10814: 				$metaentry{':'.$unikey}=
10815: 				    $metaentry{':'.$unikey.'.default'};
10816: 			    }
10817: 			}
10818: 		    }
10819: 		} else {
10820: #
10821: # This is not a package - some other kind of start tag
10822: #
10823: 		    my $entry=$token->[1];
10824: 		    my $unikey='';
10825: 
10826: 		    if ($entry eq 'import') {
10827: #
10828: # Importing a library here
10829: #
10830:                         my $location=$parser->get_text('/import');
10831:                         my $dir=$filename;
10832:                         $dir=~s|[^/]*$||;
10833:                         $location=&filelocation($dir,$location);
10834:                        
10835:                         my $importmode=$token->[2]->{'importmode'};
10836:                         if ($importmode eq 'problem') {
10837: # Import as problem/response
10838:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10839:                         } elsif ($importmode eq 'part') {
10840: # Import as part(s)
10841:                            $importedparts=1;
10842: # We need to get the original file and the imported file to get the part order correct
10843: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10844: # Load and inspect original file
10845:                            if ($#origfileimportpartids<0) {
10846:                               undef(%importedpartids);
10847:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10848:                               my $origfile=&getfile($origfilelocation);
10849:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10850:                            }
10851: 
10852: # Load and inspect imported file
10853:                            my $impfile=&getfile($location);
10854:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10855:                            if ($#impfilepartids>=0) {
10856: # This problem had parts
10857:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
10858:                            } else {
10859: # Importing by turning a single problem into a problem part
10860: # It gets the import-tags ID as part-ID
10861:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
10862:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
10863:                            }
10864:                         } else {
10865: # Normal import
10866:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10867:                            if (defined($token->[2]->{'id'})) {
10868:                               $unikey.='_'.$token->[2]->{'id'};
10869:                            }
10870:                         }
10871: 
10872: 			if ($depthcount<20) {
10873: 			    my $metadata = 
10874: 				&metadata($uri,'keys', $location,$unikey,
10875: 					  $depthcount+1);
10876: 			    foreach my $meta (split(',',$metadata)) {
10877: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
10878: 				$metathesekeys{$meta}=1;
10879: 			    }
10880: 			
10881:                         }
10882: 		    } else {
10883: #
10884: # Not importing, some other kind of non-package, non-library start tag
10885: # 
10886:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10887:                         if (defined($token->[2]->{'id'})) {
10888:                             $unikey.='_'.$token->[2]->{'id'};
10889:                         }
10890: 			if (defined($token->[2]->{'name'})) { 
10891: 			    $unikey.='_'.$token->[2]->{'name'}; 
10892: 			}
10893: 			$metathesekeys{$unikey}=1;
10894: 			foreach my $param (@{$token->[3]}) {
10895: 			    $metaentry{':'.$unikey.'.'.$param} =
10896: 				$token->[2]->{$param};
10897: 			}
10898: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
10899: 			my $default=$metaentry{':'.$unikey.'.default'};
10900: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10901: 		 # only ws inside the tag, and not in default, so use default
10902: 		 # as value
10903: 			    $metaentry{':'.$unikey}=$default;
10904: 			} elsif ( $internaltext =~ /\S/ ) {
10905: 		  # something interesting inside the tag
10906: 			    $metaentry{':'.$unikey}=$internaltext;
10907: 			} else {
10908: 		  # no interesting values, don't set a default
10909: 			}
10910: # end of not-a-package not-a-library import
10911: 		    }
10912: # end of not-a-package start tag
10913: 		}
10914: # the next is the end of "start tag"
10915: 	    }
10916: 	}
10917: 	my ($extension) = ($uri =~ /\.(\w+)$/);
10918: 	$extension = lc($extension);
10919: 	if ($extension eq 'htm') { $extension='html'; }
10920: 
10921: 	foreach my $key (keys(%packagetab)) {
10922: 	    #no specific packages #how's our extension
10923: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
10924: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
10925: 					 \%metathesekeys);
10926: 	}
10927: 
10928: 	if (!exists($metaentry{':packages'})
10929: 	    || $packagetab{"import_defaults&extension_$extension"}) {
10930: 	    foreach my $key (keys(%packagetab)) {
10931: 		#no specific packages well let's get default then
10932: 		if ($key!~/^default&/) { next; }
10933: 		&metadata_create_package_def($uri,$key,'default',
10934: 					     \%metathesekeys);
10935: 	    }
10936: 	}
10937: # are there custom rights to evaluate
10938: 	if ($metaentry{':copyright'} eq 'custom') {
10939: 
10940:     #
10941:     # Importing a rights file here
10942:     #
10943: 	    unless ($depthcount) {
10944: 		my $location=$metaentry{':customdistributionfile'};
10945: 		my $dir=$filename;
10946: 		$dir=~s|[^/]*$||;
10947: 		$location=&filelocation($dir,$location);
10948: 		my $rights_metadata =
10949: 		    &metadata($uri,'keys',$location,'_rights',
10950: 			      $depthcount+1);
10951: 		foreach my $rights (split(',',$rights_metadata)) {
10952: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10953: 		    $metathesekeys{$rights}=1;
10954: 		}
10955: 	    }
10956: 	}
10957: 	# uniqifiy package listing
10958: 	my %seen;
10959: 	my @uniq_packages =
10960: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10961: 	$metaentry{':packages'} = join(',',@uniq_packages);
10962: 
10963:         if ($importedparts) {
10964: # We had imported parts and need to rebuild partorder
10965:            $metaentry{':partorder'}='';
10966:            $metathesekeys{'partorder'}=1;
10967:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10968:                if ($origfileimportpartids[$index] eq 'part') {
10969: # original part, part of the problem
10970:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10971:                } else {
10972: # we have imported parts at this position
10973:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10974:                }
10975:            }
10976:            $metaentry{':partorder'}=~s/^\,//;
10977:         }
10978: 
10979: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
10980: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
10981: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
10982: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
10983: # this is the end of "was not already recently cached
10984:     }
10985:     return $metaentry{':'.$what};
10986: }
10987: 
10988: sub metadata_create_package_def {
10989:     my ($uri,$key,$package,$metathesekeys)=@_;
10990:     my ($pack,$name,$subp)=split(/\&/,$key);
10991:     if ($subp eq 'default') { next; }
10992:     
10993:     if (defined($metaentry{':packages'})) {
10994: 	$metaentry{':packages'}.=','.$package;
10995:     } else {
10996: 	$metaentry{':packages'}=$package;
10997:     }
10998:     my $value=$packagetab{$key};
10999:     my $unikey;
11000:     $unikey='parameter_0_'.$name;
11001:     $metaentry{':'.$unikey.'.part'}=0;
11002:     $$metathesekeys{$unikey}=1;
11003:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11004: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
11005:     }
11006:     if (defined($metaentry{':'.$unikey.'.default'})) {
11007: 	$metaentry{':'.$unikey}=
11008: 	    $metaentry{':'.$unikey.'.default'};
11009:     }
11010: }
11011: 
11012: sub metadata_generate_part0 {
11013:     my ($metadata,$metacache,$uri) = @_;
11014:     my %allnames;
11015:     foreach my $metakey (keys(%$metadata)) {
11016: 	if ($metakey=~/^parameter\_(.*)/) {
11017: 	  my $part=$$metacache{':'.$metakey.'.part'};
11018: 	  my $name=$$metacache{':'.$metakey.'.name'};
11019: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
11020: 	    $allnames{$name}=$part;
11021: 	  }
11022: 	}
11023:     }
11024:     foreach my $name (keys(%allnames)) {
11025:       $$metadata{"parameter_0_$name"}=1;
11026:       my $key=":parameter_0_$name";
11027:       $$metacache{"$key.part"}='0';
11028:       $$metacache{"$key.name"}=$name;
11029:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
11030: 					   $allnames{$name}.'_'.$name.
11031: 					   '.type'};
11032:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
11033: 			     '.display'};
11034:       my $expr='[Part: '.$allnames{$name}.']';
11035:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
11036:       $$metacache{"$key.display"}=$olddis;
11037:     }
11038: }
11039: 
11040: # ------------------------------------------------------ Devalidate title cache
11041: 
11042: sub devalidate_title_cache {
11043:     my ($url)=@_;
11044:     if (!$env{'request.course.id'}) { return; }
11045:     my $symb=&symbread($url);
11046:     if (!$symb) { return; }
11047:     my $key=$env{'request.course.id'}."\0".$symb;
11048:     &devalidate_cache_new('title',$key);
11049: }
11050: 
11051: # ------------------------------------------------- Get the title of a course
11052: 
11053: sub current_course_title {
11054:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
11055: }
11056: # ------------------------------------------------- Get the title of a resource
11057: 
11058: sub gettitle {
11059:     my $urlsymb=shift;
11060:     my $symb=&symbread($urlsymb);
11061:     if ($symb) {
11062: 	my $key=$env{'request.course.id'}."\0".$symb;
11063: 	my ($result,$cached)=&is_cached_new('title',$key);
11064: 	if (defined($cached)) { 
11065: 	    return $result;
11066: 	}
11067: 	my ($map,$resid,$url)=&decode_symb($symb);
11068: 	my $title='';
11069: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
11070: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
11071: 	} else {
11072: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11073: 		    &GDBM_READER(),0640)) {
11074: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
11075: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
11076: 		untie(%bighash);
11077: 	    }
11078: 	}
11079: 	$title=~s/\&colon\;/\:/gs;
11080: 	if ($title) {
11081: # Remember both $symb and $title for dynamic metadata
11082:             $accesshash{$symb.'___crstitle'}=$title;
11083:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
11084: # Cache this title and then return it
11085: 	    return &do_cache_new('title',$key,$title,600);
11086: 	}
11087: 	$urlsymb=$url;
11088:     }
11089:     my $title=&metadata($urlsymb,'title');
11090:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
11091:     return $title;
11092: }
11093: 
11094: sub get_slot {
11095:     my ($which,$cnum,$cdom)=@_;
11096:     if (!$cnum || !$cdom) {
11097: 	(undef,my $courseid)=&whichuser();
11098: 	$cdom=$env{'course.'.$courseid.'.domain'};
11099: 	$cnum=$env{'course.'.$courseid.'.num'};
11100:     }
11101:     my $key=join("\0",'slots',$cdom,$cnum,$which);
11102:     my %slotinfo;
11103:     if (exists($remembered{$key})) {
11104: 	$slotinfo{$which} = $remembered{$key};
11105:     } else {
11106: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
11107: 	&Apache::lonhomework::showhash(%slotinfo);
11108: 	my ($tmp)=keys(%slotinfo);
11109: 	if ($tmp=~/^error:/) { return (); }
11110: 	$remembered{$key} = $slotinfo{$which};
11111:     }
11112:     if (ref($slotinfo{$which}) eq 'HASH') {
11113: 	return %{$slotinfo{$which}};
11114:     }
11115:     return $slotinfo{$which};
11116: }
11117: 
11118: sub get_reservable_slots {
11119:     my ($cnum,$cdom,$uname,$udom) = @_;
11120:     my $now = time;
11121:     my $reservable_info;
11122:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
11123:     if (exists($remembered{$key})) {
11124:         $reservable_info = $remembered{$key};
11125:     } else {
11126:         my %resv;
11127:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
11128:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
11129:         $reservable_info = \%resv;
11130:         $remembered{$key} = $reservable_info;
11131:     }
11132:     return $reservable_info;
11133: }
11134: 
11135: sub get_course_slots {
11136:     my ($cnum,$cdom) = @_;
11137:     my $hashid=$cnum.':'.$cdom;
11138:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
11139:     if (defined($cached)) {
11140:         if (ref($result) eq 'HASH') {
11141:             return %{$result};
11142:         }
11143:     } else {
11144:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
11145:         my ($tmp) = keys(%slots);
11146:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
11147:             &do_cache_new('allslots',$hashid,\%slots,600);
11148:             return %slots;
11149:         }
11150:     }
11151:     return;
11152: }
11153: 
11154: sub devalidate_slots_cache {
11155:     my ($cnum,$cdom)=@_;
11156:     my $hashid=$cnum.':'.$cdom;
11157:     &devalidate_cache_new('allslots',$hashid);
11158: }
11159: 
11160: sub get_coursechange {
11161:     my ($cdom,$cnum) = @_;
11162:     if ($cdom eq '' || $cnum eq '') {
11163:         return unless ($env{'request.course.id'});
11164:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
11165:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
11166:     }
11167:     my $hashid=$cdom.'_'.$cnum;
11168:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
11169:     if ((defined($cached)) && ($change ne '')) {
11170:         return $change;
11171:     } else {
11172:         my %crshash;
11173:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
11174:         if ($crshash{'internal.contentchange'} eq '') {
11175:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
11176:             if ($change eq '') {
11177:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
11178:                 $change = $crshash{'internal.created'};
11179:             }
11180:         } else {
11181:             $change = $crshash{'internal.contentchange'};
11182:         }
11183:         my $cachetime = 600;
11184:         &do_cache_new('crschange',$hashid,$change,$cachetime);
11185:     }
11186:     return $change;
11187: }
11188: 
11189: sub devalidate_coursechange_cache {
11190:     my ($cnum,$cdom)=@_;
11191:     my $hashid=$cnum.':'.$cdom;
11192:     &devalidate_cache_new('crschange',$hashid);
11193: }
11194: 
11195: # ------------------------------------------------- Update symbolic store links
11196: 
11197: sub symblist {
11198:     my ($mapname,%newhash)=@_;
11199:     $mapname=&deversion(&declutter($mapname));
11200:     my %hash;
11201:     if (($env{'request.course.fn'}) && (%newhash)) {
11202:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
11203:                       &GDBM_WRCREAT(),0640)) {
11204: 	    foreach my $url (keys(%newhash)) {
11205: 		next if ($url eq 'last_known'
11206: 			 && $env{'form.no_update_last_known'});
11207: 		$hash{declutter($url)}=&encode_symb($mapname,
11208: 						    $newhash{$url}->[1],
11209: 						    $newhash{$url}->[0]);
11210:             }
11211:             if (untie(%hash)) {
11212: 		return 'ok';
11213:             }
11214:         }
11215:     }
11216:     return 'error';
11217: }
11218: 
11219: # --------------------------------------------------------------- Verify a symb
11220: 
11221: sub symbverify {
11222:     my ($symb,$thisurl,$encstate)=@_;
11223:     my $thisfn=$thisurl;
11224:     $thisfn=&declutter($thisfn);
11225: # direct jump to resource in page or to a sequence - will construct own symbs
11226:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
11227: # check URL part
11228:     my ($map,$resid,$url)=&decode_symb($symb);
11229: 
11230:     unless ($url eq $thisfn) { return 0; }
11231: 
11232:     $symb=&symbclean($symb);
11233:     $thisurl=&deversion($thisurl);
11234:     $thisfn=&deversion($thisfn);
11235: 
11236:     my %bighash;
11237:     my $okay=0;
11238: 
11239:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11240:                             &GDBM_READER(),0640)) {
11241:         my $noclutter;
11242:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
11243:             $thisurl =~ s/\?.+$//;
11244:             if ($map =~ m{^uploaded/.+\.page$}) {
11245:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
11246:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
11247:                 $noclutter = 1;
11248:             }
11249:         }
11250:         my $ids;
11251:         if ($noclutter) {
11252:             $ids=$bighash{'ids_'.$thisurl};
11253:         } else {
11254:             $ids=$bighash{'ids_'.&clutter($thisurl)};
11255:         }
11256:         unless ($ids) {
11257:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
11258:             $ids=$bighash{$idkey};
11259:         }
11260:         if ($ids) {
11261: # ------------------------------------------------------------------- Has ID(s)
11262:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
11263:                 $symb =~ s/\?.+$//;
11264:             }
11265: 	    foreach my $id (split(/\,/,$ids)) {
11266: 	       my ($mapid,$resid)=split(/\./,$id);
11267:                if (
11268:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
11269:    eq $symb) {
11270:                    if (ref($encstate)) {
11271:                        $$encstate = $bighash{'encrypted_'.$id};
11272:                    }
11273: 		   if (($env{'request.role.adv'}) ||
11274: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
11275:                        ($thisurl eq '/adm/navmaps')) {
11276: 		       $okay=1;
11277:                        last;
11278: 		   }
11279: 	       }
11280: 	   }
11281:         }
11282: 	untie(%bighash);
11283:     }
11284:     return $okay;
11285: }
11286: 
11287: # --------------------------------------------------------------- Clean-up symb
11288: 
11289: sub symbclean {
11290:     my $symb=shift;
11291:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
11292: # remove version from map
11293:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
11294: 
11295: # remove version from URL
11296:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
11297: 
11298: # remove wrapper
11299: 
11300:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
11301:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
11302:     return $symb;
11303: }
11304: 
11305: # ---------------------------------------------- Split symb to find map and url
11306: 
11307: sub encode_symb {
11308:     my ($map,$resid,$url)=@_;
11309:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
11310: }
11311: 
11312: sub decode_symb {
11313:     my $symb=shift;
11314:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
11315:     my ($map,$resid,$url)=split(/___/,$symb);
11316:     return (&fixversion($map),$resid,&fixversion($url));
11317: }
11318: 
11319: sub fixversion {
11320:     my $fn=shift;
11321:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
11322:     my %bighash;
11323:     my $uri=&clutter($fn);
11324:     my $key=$env{'request.course.id'}.'_'.$uri;
11325: # is this cached?
11326:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
11327:     if (defined($cached)) { return $result; }
11328: # unfortunately not cached, or expired
11329:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11330: 	    &GDBM_READER(),0640)) {
11331:  	if ($bighash{'version_'.$uri}) {
11332:  	    my $version=$bighash{'version_'.$uri};
11333:  	    unless (($version eq 'mostrecent') || 
11334: 		    ($version==&getversion($uri))) {
11335:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
11336:  	    }
11337:  	}
11338:  	untie %bighash;
11339:     }
11340:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
11341: }
11342: 
11343: sub deversion {
11344:     my $url=shift;
11345:     $url=~s/\.\d+\.(\w+)$/\.$1/;
11346:     return $url;
11347: }
11348: 
11349: # ------------------------------------------------------ Return symb list entry
11350: 
11351: sub symbread {
11352:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
11353:     my $cache_str='request.symbread.cached.'.$thisfn;
11354:     if (defined($env{$cache_str})) {
11355:         if ($ignorecachednull) {
11356:             return $env{$cache_str} unless ($env{$cache_str} eq '');
11357:         } else {
11358:             return $env{$cache_str};
11359:         }
11360:     }
11361: # no filename provided? try from environment
11362:     unless ($thisfn) {
11363:         if ($env{'request.symb'}) {
11364: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
11365: 	}
11366: 	$thisfn=$env{'request.filename'};
11367:     }
11368:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
11369: # is that filename actually a symb? Verify, clean, and return
11370:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
11371: 	if (&symbverify($thisfn,$1)) {
11372: 	    return $env{$cache_str}=&symbclean($thisfn);
11373: 	}
11374:     }
11375:     $thisfn=declutter($thisfn);
11376:     my %hash;
11377:     my %bighash;
11378:     my $syval='';
11379:     if (($env{'request.course.fn'}) && ($thisfn)) {
11380:         my $targetfn = $thisfn;
11381:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
11382:             $targetfn = 'adm/wrapper/'.$thisfn;
11383:         }
11384: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
11385: 	    $targetfn=$1;
11386: 	}
11387:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
11388:                       &GDBM_READER(),0640)) {
11389: 	    $syval=$hash{$targetfn};
11390:             untie(%hash);
11391:         }
11392: # ---------------------------------------------------------- There was an entry
11393:         if ($syval) {
11394: 	    #unless ($syval=~/\_\d+$/) {
11395: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
11396: 		    #&appenv({'request.ambiguous' => $thisfn});
11397: 		    #return $env{$cache_str}='';
11398: 		#}    
11399: 		#$syval.=$1;
11400: 	    #}
11401:         } else {
11402: # ------------------------------------------------------- Was not in symb table
11403:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11404:                             &GDBM_READER(),0640)) {
11405: # ---------------------------------------------- Get ID(s) for current resource
11406:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
11407:               unless ($ids) { 
11408:                  $ids=$bighash{'ids_/'.$thisfn};
11409:               }
11410:               unless ($ids) {
11411: # alias?
11412: 		  $ids=$bighash{'mapalias_'.$thisfn};
11413:               }
11414:               if ($ids) {
11415: # ------------------------------------------------------------------- Has ID(s)
11416:                  my @possibilities=split(/\,/,$ids);
11417:                  if ($#possibilities==0) {
11418: # ----------------------------------------------- There is only one possibility
11419: 		     my ($mapid,$resid)=split(/\./,$ids);
11420: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
11421: 						    $resid,$thisfn);
11422:                      if (ref($possibles) eq 'HASH') {
11423:                          $possibles->{$syval} = 1;    
11424:                      }
11425:                      if ($checkforblock) {
11426:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
11427:                          if (@blockers) {
11428:                              $syval = '';
11429:                              return;
11430:                          }
11431:                      }
11432:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
11433: # ------------------------------------------ There is more than one possibility
11434:                      my $realpossible=0;
11435:                      foreach my $id (@possibilities) {
11436: 			 my $file=$bighash{'src_'.$id};
11437:                          my $canaccess;
11438:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
11439:                              $canaccess = 1;
11440:                          } else { 
11441:                              $canaccess = &allowed('bre',$file);
11442:                          }
11443:                          if ($canaccess) {
11444:          		     my ($mapid,$resid)=split(/\./,$id);
11445:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
11446:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
11447: 						             $resid,$thisfn);
11448:                                  if (ref($possibles) eq 'HASH') {
11449:                                      $possibles->{$syval} = 1;
11450:                                  }
11451:                                  if ($checkforblock) {
11452:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
11453:                                      unless (@blockers > 0) {
11454:                                          $syval = $poss_syval;
11455:                                          $realpossible++;
11456:                                      }
11457:                                  } else {
11458:                                      $syval = $poss_syval;
11459:                                      $realpossible++;
11460:                                  }
11461:                              }
11462: 			 }
11463:                      }
11464: 		     if ($realpossible!=1) { $syval=''; }
11465:                  } else {
11466:                      $syval='';
11467:                  }
11468: 	      }
11469:               untie(%bighash);
11470:            }
11471:         }
11472:         if ($syval) {
11473: 	    return $env{$cache_str}=$syval;
11474:         }
11475:     }
11476:     &appenv({'request.ambiguous' => $thisfn});
11477:     return $env{$cache_str}='';
11478: }
11479: 
11480: # ---------------------------------------------------------- Return random seed
11481: 
11482: sub numval {
11483:     my $txt=shift;
11484:     $txt=~tr/A-J/0-9/;
11485:     $txt=~tr/a-j/0-9/;
11486:     $txt=~tr/K-T/0-9/;
11487:     $txt=~tr/k-t/0-9/;
11488:     $txt=~tr/U-Z/0-5/;
11489:     $txt=~tr/u-z/0-5/;
11490:     $txt=~s/\D//g;
11491:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
11492:     return int($txt);
11493: }
11494: 
11495: sub numval2 {
11496:     my $txt=shift;
11497:     $txt=~tr/A-J/0-9/;
11498:     $txt=~tr/a-j/0-9/;
11499:     $txt=~tr/K-T/0-9/;
11500:     $txt=~tr/k-t/0-9/;
11501:     $txt=~tr/U-Z/0-5/;
11502:     $txt=~tr/u-z/0-5/;
11503:     $txt=~s/\D//g;
11504:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11505:     my $total;
11506:     foreach my $val (@txts) { $total+=$val; }
11507:     if ($_64bit) { if ($total > 2**32) { return -1; } }
11508:     return int($total);
11509: }
11510: 
11511: sub numval3 {
11512:     use integer;
11513:     my $txt=shift;
11514:     $txt=~tr/A-J/0-9/;
11515:     $txt=~tr/a-j/0-9/;
11516:     $txt=~tr/K-T/0-9/;
11517:     $txt=~tr/k-t/0-9/;
11518:     $txt=~tr/U-Z/0-5/;
11519:     $txt=~tr/u-z/0-5/;
11520:     $txt=~s/\D//g;
11521:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11522:     my $total;
11523:     foreach my $val (@txts) { $total+=$val; }
11524:     if ($_64bit) { $total=(($total<<32)>>32); }
11525:     return $total;
11526: }
11527: 
11528: sub digest {
11529:     my ($data)=@_;
11530:     my $digest=&Digest::MD5::md5($data);
11531:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
11532:     my ($e,$f);
11533:     {
11534:         use integer;
11535:         $e=($a+$b);
11536:         $f=($c+$d);
11537:         if ($_64bit) {
11538:             $e=(($e<<32)>>32);
11539:             $f=(($f<<32)>>32);
11540:         }
11541:     }
11542:     if (wantarray) {
11543: 	return ($e,$f);
11544:     } else {
11545: 	my $g;
11546: 	{
11547: 	    use integer;
11548: 	    $g=($e+$f);
11549: 	    if ($_64bit) {
11550: 		$g=(($g<<32)>>32);
11551: 	    }
11552: 	}
11553: 	return $g;
11554:     }
11555: }
11556: 
11557: sub latest_rnd_algorithm_id {
11558:     return '64bit5';
11559: }
11560: 
11561: sub get_rand_alg {
11562:     my ($courseid)=@_;
11563:     if (!$courseid) { $courseid=(&whichuser())[1]; }
11564:     if ($courseid) {
11565: 	return $env{"course.$courseid.rndseed"};
11566:     }
11567:     return &latest_rnd_algorithm_id();
11568: }
11569: 
11570: sub validCODE {
11571:     my ($CODE)=@_;
11572:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
11573:     return 0;
11574: }
11575: 
11576: sub getCODE {
11577:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
11578:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
11579: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
11580: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
11581: 	return $Apache::lonhomework::history{'resource.CODE'};
11582:     }
11583:     return undef;
11584: }
11585: #
11586: #  Determines the random seed for a specific context:
11587: #
11588: # parameters:
11589: #   symb      - in course context the symb for the seed.
11590: #   course_id - The course id of the form domain_coursenum.
11591: #   domain    - Domain for the user.
11592: #   course    - Course for the user.
11593: #   cenv      - environment of the course.
11594: #
11595: # NOTE:
11596: #   All parameters are picked out of the environment if missing
11597: #   or not defined.
11598: #   If a symb cannot be determined the current time is used instead.
11599: #
11600: #  For a given well defined symb, courside, domain, username,
11601: #  and course environment, the seed is reproducible.
11602: #
11603: sub rndseed {
11604:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
11605:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
11606:     if (!defined($symb)) {
11607: 	unless ($symb=$wsymb) { return time; }
11608:     }
11609:     if (!defined $courseid) { 
11610: 	$courseid=$wcourseid; 
11611:     }
11612:     if (!defined $domain) { $domain=$wdomain; }
11613:     if (!defined $username) { $username=$wusername }
11614: 
11615:     my $which;
11616:     if (defined($cenv->{'rndseed'})) {
11617: 	$which = $cenv->{'rndseed'};
11618:     } else {
11619: 	$which =&get_rand_alg($courseid);
11620:     }
11621:     if (defined(&getCODE())) {
11622: 
11623: 	if ($which eq '64bit5') {
11624: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
11625: 	} elsif ($which eq '64bit4') {
11626: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
11627: 	} else {
11628: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
11629: 	}
11630:     } elsif ($which eq '64bit5') {
11631: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
11632:     } elsif ($which eq '64bit4') {
11633: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
11634:     } elsif ($which eq '64bit3') {
11635: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
11636:     } elsif ($which eq '64bit2') {
11637: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
11638:     } elsif ($which eq '64bit') {
11639: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
11640:     }
11641:     return &rndseed_32bit($symb,$courseid,$domain,$username);
11642: }
11643: 
11644: sub rndseed_32bit {
11645:     my ($symb,$courseid,$domain,$username)=@_;
11646:     {
11647: 	use integer;
11648: 	my $symbchck=unpack("%32C*",$symb) << 27;
11649: 	my $symbseed=numval($symb) << 22;
11650: 	my $namechck=unpack("%32C*",$username) << 17;
11651: 	my $nameseed=numval($username) << 12;
11652: 	my $domainseed=unpack("%32C*",$domain) << 7;
11653: 	my $courseseed=unpack("%32C*",$courseid);
11654: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
11655: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11656: 	#&logthis("rndseed :$num:$symb");
11657: 	if ($_64bit) { $num=(($num<<32)>>32); }
11658: 	return $num;
11659:     }
11660: }
11661: 
11662: sub rndseed_64bit {
11663:     my ($symb,$courseid,$domain,$username)=@_;
11664:     {
11665: 	use integer;
11666: 	my $symbchck=unpack("%32S*",$symb) << 21;
11667: 	my $symbseed=numval($symb) << 10;
11668: 	my $namechck=unpack("%32S*",$username);
11669: 	
11670: 	my $nameseed=numval($username) << 21;
11671: 	my $domainseed=unpack("%32S*",$domain) << 10;
11672: 	my $courseseed=unpack("%32S*",$courseid);
11673: 	
11674: 	my $num1=$symbchck+$symbseed+$namechck;
11675: 	my $num2=$nameseed+$domainseed+$courseseed;
11676: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11677: 	#&logthis("rndseed :$num:$symb");
11678: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11679: 	return "$num1,$num2";
11680:     }
11681: }
11682: 
11683: sub rndseed_64bit2 {
11684:     my ($symb,$courseid,$domain,$username)=@_;
11685:     {
11686: 	use integer;
11687: 	# strings need to be an even # of cahracters long, it it is odd the
11688:         # last characters gets thrown away
11689: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11690: 	my $symbseed=numval($symb) << 10;
11691: 	my $namechck=unpack("%32S*",$username.' ');
11692: 	
11693: 	my $nameseed=numval($username) << 21;
11694: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11695: 	my $courseseed=unpack("%32S*",$courseid.' ');
11696: 	
11697: 	my $num1=$symbchck+$symbseed+$namechck;
11698: 	my $num2=$nameseed+$domainseed+$courseseed;
11699: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11700: 	#&logthis("rndseed :$num:$symb");
11701: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11702: 	return "$num1,$num2";
11703:     }
11704: }
11705: 
11706: sub rndseed_64bit3 {
11707:     my ($symb,$courseid,$domain,$username)=@_;
11708:     {
11709: 	use integer;
11710: 	# strings need to be an even # of cahracters long, it it is odd the
11711:         # last characters gets thrown away
11712: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11713: 	my $symbseed=numval2($symb) << 10;
11714: 	my $namechck=unpack("%32S*",$username.' ');
11715: 	
11716: 	my $nameseed=numval2($username) << 21;
11717: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11718: 	my $courseseed=unpack("%32S*",$courseid.' ');
11719: 	
11720: 	my $num1=$symbchck+$symbseed+$namechck;
11721: 	my $num2=$nameseed+$domainseed+$courseseed;
11722: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11723: 	#&logthis("rndseed :$num1:$num2:$_64bit");
11724: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11725: 	
11726: 	return "$num1:$num2";
11727:     }
11728: }
11729: 
11730: sub rndseed_64bit4 {
11731:     my ($symb,$courseid,$domain,$username)=@_;
11732:     {
11733: 	use integer;
11734: 	# strings need to be an even # of cahracters long, it it is odd the
11735:         # last characters gets thrown away
11736: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11737: 	my $symbseed=numval3($symb) << 10;
11738: 	my $namechck=unpack("%32S*",$username.' ');
11739: 	
11740: 	my $nameseed=numval3($username) << 21;
11741: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11742: 	my $courseseed=unpack("%32S*",$courseid.' ');
11743: 	
11744: 	my $num1=$symbchck+$symbseed+$namechck;
11745: 	my $num2=$nameseed+$domainseed+$courseseed;
11746: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11747: 	#&logthis("rndseed :$num1:$num2:$_64bit");
11748: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11749: 	
11750: 	return "$num1:$num2";
11751:     }
11752: }
11753: 
11754: sub rndseed_64bit5 {
11755:     my ($symb,$courseid,$domain,$username)=@_;
11756:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11757:     return "$num1:$num2";
11758: }
11759: 
11760: sub rndseed_CODE_64bit {
11761:     my ($symb,$courseid,$domain,$username)=@_;
11762:     {
11763: 	use integer;
11764: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
11765: 	my $symbseed=numval2($symb);
11766: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11767: 	my $CODEseed=numval(&getCODE());
11768: 	my $courseseed=unpack("%32S*",$courseid.' ');
11769: 	my $num1=$symbseed+$CODEchck;
11770: 	my $num2=$CODEseed+$courseseed+$symbchck;
11771: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11772: 	#&logthis("rndseed :$num1:$num2:$symb");
11773: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
11774: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
11775: 	return "$num1:$num2";
11776:     }
11777: }
11778: 
11779: sub rndseed_CODE_64bit4 {
11780:     my ($symb,$courseid,$domain,$username)=@_;
11781:     {
11782: 	use integer;
11783: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
11784: 	my $symbseed=numval3($symb);
11785: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11786: 	my $CODEseed=numval3(&getCODE());
11787: 	my $courseseed=unpack("%32S*",$courseid.' ');
11788: 	my $num1=$symbseed+$CODEchck;
11789: 	my $num2=$CODEseed+$courseseed+$symbchck;
11790: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11791: 	#&logthis("rndseed :$num1:$num2:$symb");
11792: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
11793: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
11794: 	return "$num1:$num2";
11795:     }
11796: }
11797: 
11798: sub rndseed_CODE_64bit5 {
11799:     my ($symb,$courseid,$domain,$username)=@_;
11800:     my $code = &getCODE();
11801:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
11802:     return "$num1:$num2";
11803: }
11804: 
11805: sub setup_random_from_rndseed {
11806:     my ($rndseed)=@_;
11807:     if ($rndseed =~/([,:])/) {
11808:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
11809:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
11810:             &Math::Random::random_set_seed_from_phrase($rndseed);
11811:         } else {
11812:             &Math::Random::random_set_seed($num1,$num2);
11813:         }
11814:     } else {
11815: 	&Math::Random::random_set_seed_from_phrase($rndseed);
11816:     }
11817: }
11818: 
11819: sub latest_receipt_algorithm_id {
11820:     return 'receipt3';
11821: }
11822: 
11823: sub recunique {
11824:     my $fucourseid=shift;
11825:     my $unique;
11826:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11827: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11828: 	$unique=$env{"course.$fucourseid.internal.encseed"};
11829:     } else {
11830: 	$unique=$perlvar{'lonReceipt'};
11831:     }
11832:     return unpack("%32C*",$unique);
11833: }
11834: 
11835: sub recprefix {
11836:     my $fucourseid=shift;
11837:     my $prefix;
11838:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11839: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11840: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
11841:     } else {
11842: 	$prefix=$perlvar{'lonHostID'};
11843:     }
11844:     return unpack("%32C*",$prefix);
11845: }
11846: 
11847: sub ireceipt {
11848:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
11849: 
11850:     my $return =&recprefix($fucourseid).'-';
11851: 
11852:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11853: 	$env{'request.state'} eq 'construct') {
11854: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11855: 	return $return;
11856:     }
11857: 
11858:     my $cuname=unpack("%32C*",$funame);
11859:     my $cudom=unpack("%32C*",$fudom);
11860:     my $cucourseid=unpack("%32C*",$fucourseid);
11861:     my $cusymb=unpack("%32C*",$fusymb);
11862:     my $cunique=&recunique($fucourseid);
11863:     my $cpart=unpack("%32S*",$part);
11864:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11865: 
11866: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
11867: 			       
11868: 	$return.= ($cunique%$cuname+
11869: 		   $cunique%$cudom+
11870: 		   $cusymb%$cuname+
11871: 		   $cusymb%$cudom+
11872: 		   $cucourseid%$cuname+
11873: 		   $cucourseid%$cudom+
11874: 		   $cpart%$cuname+
11875: 		   $cpart%$cudom);
11876:     } else {
11877: 	$return.= ($cunique%$cuname+
11878: 		   $cunique%$cudom+
11879: 		   $cusymb%$cuname+
11880: 		   $cusymb%$cudom+
11881: 		   $cucourseid%$cuname+
11882: 		   $cucourseid%$cudom);
11883:     }
11884:     return $return;
11885: }
11886: 
11887: sub receipt {
11888:     my ($part)=@_;
11889:     my ($symb,$courseid,$domain,$name) = &whichuser();
11890:     return &ireceipt($name,$domain,$courseid,$symb,$part);
11891: }
11892: 
11893: sub whichuser {
11894:     my ($passedsymb)=@_;
11895:     my ($symb,$courseid,$domain,$name,$publicuser);
11896:     if (defined($env{'form.grade_symb'})) {
11897: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11898: 	my $allowed=&allowed('vgr',$tmp_courseid);
11899: 	if (!$allowed &&
11900: 	    exists($env{'request.course.sec'}) &&
11901: 	    $env{'request.course.sec'} !~ /^\s*$/) {
11902: 	    $allowed=&allowed('vgr',$tmp_courseid.
11903: 			      '/'.$env{'request.course.sec'});
11904: 	}
11905: 	if ($allowed) {
11906: 	    ($symb)=&get_env_multiple('form.grade_symb');
11907: 	    $courseid=$tmp_courseid;
11908: 	    ($domain)=&get_env_multiple('form.grade_domain');
11909: 	    ($name)=&get_env_multiple('form.grade_username');
11910: 	    return ($symb,$courseid,$domain,$name,$publicuser);
11911: 	}
11912:     }
11913:     if (!$passedsymb) {
11914: 	$symb=&symbread();
11915:     } else {
11916: 	$symb=$passedsymb;
11917:     }
11918:     $courseid=$env{'request.course.id'};
11919:     $domain=$env{'user.domain'};
11920:     $name=$env{'user.name'};
11921:     if ($name eq 'public' && $domain eq 'public') {
11922: 	if (!defined($env{'form.username'})) {
11923: 	    $env{'form.username'}.=time.rand(10000000);
11924: 	}
11925: 	$name.=$env{'form.username'};
11926:     }
11927:     return ($symb,$courseid,$domain,$name,$publicuser);
11928: 
11929: }
11930: 
11931: # ------------------------------------------------------------ Serves up a file
11932: # returns either the contents of the file or 
11933: # -1 if the file doesn't exist
11934: #
11935: # if the target is a file that was uploaded via DOCS, 
11936: # a check will be made to see if a current copy exists on the local server,
11937: # if it does this will be served, otherwise a copy will be retrieved from
11938: # the home server for the course and stored in /home/httpd/html/userfiles on
11939: # the local server.   
11940: 
11941: sub getfile {
11942:     my ($file) = @_;
11943:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
11944:     &repcopy($file);
11945:     return &readfile($file);
11946: }
11947: 
11948: sub repcopy_userfile {
11949:     my ($file)=@_;
11950:     my $londocroot = $perlvar{'lonDocRoot'};
11951:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
11952:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
11953:     my ($cdom,$cnum,$filename) = 
11954: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
11955:     my $uri="/uploaded/$cdom/$cnum/$filename";
11956:     if (-e "$file") {
11957: # we already have a local copy, check it out
11958: 	my @fileinfo = stat($file);
11959: 	my $rtncode;
11960: 	my $info;
11961: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
11962: 	if ($lwpresp ne 'ok') {
11963: # there is no such file anymore, even though we had a local copy
11964: 	    if ($rtncode eq '404') {
11965: 		unlink($file);
11966: 	    }
11967: 	    return -1;
11968: 	}
11969: 	if ($info < $fileinfo[9]) {
11970: # nice, the file we have is up-to-date, just say okay
11971: 	    return 'ok';
11972: 	} else {
11973: # the file is outdated, get rid of it
11974: 	    unlink($file);
11975: 	}
11976:     }
11977: # one way or the other, at this point, we don't have the file
11978: # construct the correct path for the file
11979:     my @parts = ($cdom,$cnum); 
11980:     if ($filename =~ m|^(.+)/[^/]+$|) {
11981: 	push @parts, split(/\//,$1);
11982:     }
11983:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11984:     foreach my $part (@parts) {
11985: 	$path .= '/'.$part;
11986: 	if (!-e $path) {
11987: 	    mkdir($path,0770);
11988: 	}
11989:     }
11990: # now the path exists for sure
11991: # get a user agent
11992:     my $ua=new LWP::UserAgent;
11993:     my $transferfile=$file.'.in.transfer';
11994: # FIXME: this should flock
11995:     if (-e $transferfile) { return 'ok'; }
11996:     my $request;
11997:     $uri=~s/^\///;
11998:     my $homeserver = &homeserver($cnum,$cdom);
11999:     my $protocol = $protocol{$homeserver};
12000:     $protocol = 'http' if ($protocol ne 'https');
12001:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
12002:     my $response=$ua->request($request,$transferfile);
12003: # did it work?
12004:     if ($response->is_error()) {
12005: 	unlink($transferfile);
12006: 	&logthis("Userfile repcopy failed for $uri");
12007: 	return -1;
12008:     }
12009: # worked, rename the transfer file
12010:     rename($transferfile,$file);
12011:     return 'ok';
12012: }
12013: 
12014: sub tokenwrapper {
12015:     my $uri=shift;
12016:     $uri=~s|^https?\://([^/]+)||;
12017:     $uri=~s|^/||;
12018:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
12019:     my $token=$1;
12020:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
12021:     if ($udom && $uname && $file) {
12022: 	$file=~s|(\?\.*)*$||;
12023:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
12024:         my $homeserver = &homeserver($uname,$udom);
12025:         my $protocol = $protocol{$homeserver};
12026:         $protocol = 'http' if ($protocol ne 'https');
12027:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
12028:                (($uri=~/\?/)?'&':'?').'token='.$token.
12029:                                '&tokenissued='.$perlvar{'lonHostID'};
12030:     } else {
12031:         return '/adm/notfound.html';
12032:     }
12033: }
12034: 
12035: # call with reqtype HEAD: get last modification time
12036: # call with reqtype GET: get the file contents
12037: # Do not call this with reqtype GET for large files! It loads everything into memory
12038: #
12039: sub getuploaded {
12040:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
12041:     $uri=~s/^\///;
12042:     my $homeserver = &homeserver($cnum,$cdom);
12043:     my $protocol = $protocol{$homeserver};
12044:     $protocol = 'http' if ($protocol ne 'https');
12045:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
12046:     my $ua=new LWP::UserAgent;
12047:     my $request=new HTTP::Request($reqtype,$uri);
12048:     my $response=$ua->request($request);
12049:     $$rtncode = $response->code;
12050:     if (! $response->is_success()) {
12051: 	return 'failed';
12052:     }      
12053:     if ($reqtype eq 'HEAD') {
12054: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
12055:     } elsif ($reqtype eq 'GET') {
12056: 	$$info = $response->content;
12057:     }
12058:     return 'ok';
12059: }
12060: 
12061: sub readfile {
12062:     my $file = shift;
12063:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
12064:     my $fh;
12065:     open($fh,"<$file");
12066:     my $a='';
12067:     while (my $line = <$fh>) { $a .= $line; }
12068:     return $a;
12069: }
12070: 
12071: sub filelocation {
12072:     my ($dir,$file) = @_;
12073:     my $location;
12074:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
12075: 
12076:     if ($file =~ m-^/adm/-) {
12077: 	$file=~s-^/adm/wrapper/-/-;
12078: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
12079:     }
12080: 
12081:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
12082:         $location = $file;
12083:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
12084:         my ($udom,$uname,$filename)=
12085:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
12086:         my $home=&homeserver($uname,$udom);
12087:         my $is_me=0;
12088:         my @ids=&current_machine_ids();
12089:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
12090:         if ($is_me) {
12091:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
12092:         } else {
12093:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
12094:   	      $udom.'/'.$uname.'/'.$filename;
12095:         }
12096:     } elsif ($file =~ m-^/adm/-) {
12097: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
12098:     } else {
12099:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
12100:         $file=~s:^/(res|priv)/:/:;
12101:         my $space=$1;
12102:         if ( !( $file =~ m:^/:) ) {
12103:             $location = $dir. '/'.$file;
12104:         } else {
12105:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
12106:         }
12107:     }
12108:     $location=~s://+:/:g; # remove duplicate /
12109:     while ($location=~m{/\.\./}) {
12110: 	if ($location =~ m{/[^/]+/\.\./}) {
12111: 	    $location=~ s{/[^/]+/\.\./}{/}g;
12112: 	} else {
12113: 	    $location=~ s{/\.\./}{/}g;
12114: 	}
12115:     } #remove dir/..
12116:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
12117:     return $location;
12118: }
12119: 
12120: sub hreflocation {
12121:     my ($dir,$file)=@_;
12122:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
12123: 	$file=filelocation($dir,$file);
12124:     } elsif ($file=~m-^/adm/-) {
12125: 	$file=~s-^/adm/wrapper/-/-;
12126: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
12127:     }
12128:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
12129: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
12130:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
12131: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
12132: 	        {/uploaded/$1/$2/}x;
12133:     }
12134:     if ($file=~ m{^/userfiles/}) {
12135: 	$file =~ s{^/userfiles/}{/uploaded/};
12136:     }
12137:     return $file;
12138: }
12139: 
12140: 
12141: 
12142: 
12143: 
12144: sub current_machine_domains {
12145:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
12146: }
12147: 
12148: sub machine_domains {
12149:     my ($hostname) = @_;
12150:     my @domains;
12151:     my %hostname = &all_hostnames();
12152:     while( my($id, $name) = each(%hostname)) {
12153: #	&logthis("-$id-$name-$hostname-");
12154: 	if ($hostname eq $name) {
12155: 	    push(@domains,&host_domain($id));
12156: 	}
12157:     }
12158:     return @domains;
12159: }
12160: 
12161: sub current_machine_ids {
12162:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
12163: }
12164: 
12165: sub machine_ids {
12166:     my ($hostname) = @_;
12167:     $hostname ||= &hostname($perlvar{'lonHostID'});
12168:     my @ids;
12169:     my %name_to_host = &all_names();
12170:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
12171: 	return @{ $name_to_host{$hostname} };
12172:     }
12173:     return;
12174: }
12175: 
12176: sub additional_machine_domains {
12177:     my @domains;
12178:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
12179:     while( my $line = <$fh>) {
12180:         $line =~ s/\s//g;
12181:         push(@domains,$line);
12182:     }
12183:     return @domains;
12184: }
12185: 
12186: sub default_login_domain {
12187:     my $domain = $perlvar{'lonDefDomain'};
12188:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
12189:     foreach my $posdom (&current_machine_domains(),
12190:                         &additional_machine_domains()) {
12191:         if (lc($posdom) eq lc($testdomain)) {
12192:             $domain=$posdom;
12193:             last;
12194:         }
12195:     }
12196:     return $domain;
12197: }
12198: 
12199: # ------------------------------------------------------------- Declutters URLs
12200: 
12201: sub declutter {
12202:     my $thisfn=shift;
12203:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
12204:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
12205:         $thisfn=~s{^/home/httpd/html}{};
12206:     }
12207:     $thisfn=~s/^\///;
12208:     $thisfn=~s|^adm/wrapper/||;
12209:     $thisfn=~s|^adm/coursedocs/showdoc/||;
12210:     $thisfn=~s/^res\///;
12211:     $thisfn=~s/^priv\///;
12212:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
12213:         $thisfn=~s/\?.+$//;
12214:     }
12215:     return $thisfn;
12216: }
12217: 
12218: # ------------------------------------------------------------- Clutter up URLs
12219: 
12220: sub clutter {
12221:     my $thisfn='/'.&declutter(shift);
12222:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
12223: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
12224:        $thisfn='/res'.$thisfn; 
12225:     }
12226:     if ($thisfn !~m|^/adm|) {
12227: 	if ($thisfn =~ m|^/ext/|) {
12228: 	    $thisfn='/adm/wrapper'.$thisfn;
12229: 	} else {
12230: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
12231: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
12232: 	    if ($embstyle eq 'ssi'
12233: 		|| ($embstyle eq 'hdn')
12234: 		|| ($embstyle eq 'rat')
12235: 		|| ($embstyle eq 'prv')
12236: 		|| ($embstyle eq 'ign')) {
12237: 		#do nothing with these
12238: 	    } elsif (($embstyle eq 'img') 
12239: 		|| ($embstyle eq 'emb')
12240: 		|| ($embstyle eq 'wrp')) {
12241: 		$thisfn='/adm/wrapper'.$thisfn;
12242: 	    } elsif ($embstyle eq 'unk'
12243: 		     && $thisfn!~/\.(sequence|page)$/) {
12244: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
12245: 	    } else {
12246: #		&logthis("Got a blank emb style");
12247: 	    }
12248: 	}
12249:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/exttools?$}) {
12250:         $thisfn='/adm/wrapper'.$thisfn;
12251:     }
12252:     return $thisfn;
12253: }
12254: 
12255: sub clutter_with_no_wrapper {
12256:     my $uri = &clutter(shift);
12257:     if ($uri =~ m-^/adm/-) {
12258: 	$uri =~ s-^/adm/wrapper/-/-;
12259: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
12260:     }
12261:     return $uri;
12262: }
12263: 
12264: sub freeze_escape {
12265:     my ($value)=@_;
12266:     if (ref($value)) {
12267: 	$value=&nfreeze($value);
12268: 	return '__FROZEN__'.&escape($value);
12269:     }
12270:     return &escape($value);
12271: }
12272: 
12273: 
12274: sub thaw_unescape {
12275:     my ($value)=@_;
12276:     if ($value =~ /^__FROZEN__/) {
12277: 	substr($value,0,10,undef);
12278: 	$value=&unescape($value);
12279: 	return &thaw($value);
12280:     }
12281:     return &unescape($value);
12282: }
12283: 
12284: sub correct_line_ends {
12285:     my ($result)=@_;
12286:     $$result =~s/\r\n/\n/mg;
12287:     $$result =~s/\r/\n/mg;
12288: }
12289: # ================================================================ Main Program
12290: 
12291: sub goodbye {
12292:    &logthis("Starting Shut down");
12293: #not converted to using infrastruture and probably shouldn't be
12294:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
12295: #converted
12296: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
12297:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
12298: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
12299: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
12300: #1.1 only
12301: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
12302: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
12303: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
12304: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
12305:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
12306:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
12307:    &logthis(sprintf("%-20s is %s",'hits',$hits));
12308:    &flushcourselogs();
12309:    &logthis("Shutting down");
12310: }
12311: 
12312: sub get_dns {
12313:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
12314:     if (!$ignore_cache) {
12315: 	my ($content,$cached)=
12316: 	    &Apache::lonnet::is_cached_new('dns',$url);
12317: 	if ($cached) {
12318: 	    &$func($content,$hashref);
12319: 	    return;
12320: 	}
12321:     }
12322: 
12323:     my %alldns;
12324:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12325:     foreach my $dns (<$config>) {
12326: 	next if ($dns !~ /^\^(\S*)/x);
12327:         my $line = $1;
12328:         my ($host,$protocol) = split(/:/,$line);
12329:         if ($protocol ne 'https') {
12330:             $protocol = 'http';
12331:         }
12332: 	$alldns{$host} = $protocol;
12333:     }
12334:     while (%alldns) {
12335: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
12336: 	my $ua=new LWP::UserAgent;
12337:         $ua->timeout(30);
12338: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
12339: 	my $response=$ua->request($request);
12340:         delete($alldns{$dns});
12341: 	next if ($response->is_error());
12342: 	my @content = split("\n",$response->content);
12343: 	unless ($nocache) {
12344: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
12345: 	}
12346: 	&$func(\@content,$hashref);
12347: 	return;
12348:     }
12349:     close($config);
12350:     my $which = (split('/',$url))[3];
12351:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
12352:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
12353:     my @content = <$config>;
12354:     &$func(\@content,$hashref);
12355:     return;
12356: }
12357: 
12358: # ------------------------------------------------------Get DNS checksums file
12359: sub parse_dns_checksums_tab {
12360:     my ($lines,$hashref) = @_;
12361:     my $lonhost = $perlvar{'lonHostID'};
12362:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
12363:     my $loncaparev = &get_server_loncaparev($machine_dom);
12364:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
12365:     my $webconfdir = '/etc/httpd/conf';
12366:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
12367:         $webconfdir = '/etc/apache2';
12368:     } elsif ($distro =~ /^sles(\d+)$/) {
12369:         if ($1 >= 10) {
12370:             $webconfdir = '/etc/apache2';
12371:         }
12372:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
12373:         if ($1 >= 10.0) {
12374:             $webconfdir = '/etc/apache2';
12375:         }
12376:     }
12377:     my ($release,$timestamp) = split(/\-/,$loncaparev);
12378:     my (%chksum,%revnum);
12379:     if (ref($lines) eq 'ARRAY') {
12380:         chomp(@{$lines});
12381:         my $version = shift(@{$lines});
12382:         if ($version eq $release) {  
12383:             foreach my $line (@{$lines}) {
12384:                 my ($file,$version,$shasum) = split(/,/,$line);
12385:                 if ($file =~ m{^/etc/httpd/conf}) {
12386:                     if ($webconfdir eq '/etc/apache2') {
12387:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
12388:                     }
12389:                 }
12390:                 $chksum{$file} = $shasum;
12391:                 $revnum{$file} = $version;
12392:             }
12393:             if (ref($hashref) eq 'HASH') {
12394:                 %{$hashref} = (
12395:                                 sums     => \%chksum,
12396:                                 versions => \%revnum,
12397:                               );
12398:             }
12399:         }
12400:     }
12401:     return;
12402: }
12403: 
12404: sub fetch_dns_checksums {
12405:     my %checksums;
12406:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
12407:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
12408:     my ($release,$timestamp) = split(/\-/,$loncaparev);
12409:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
12410:              \%checksums);
12411:     return \%checksums;
12412: }
12413: 
12414: # ------------------------------------------------------------ Read domain file
12415: {
12416:     my $loaded;
12417:     my %domain;
12418: 
12419:     sub parse_domain_tab {
12420: 	my ($lines) = @_;
12421: 	foreach my $line (@$lines) {
12422: 	    next if ($line =~ /^(\#|\s*$ )/x);
12423: 
12424: 	    chomp($line);
12425: 	    my ($name,@elements) = split(/:/,$line,9);
12426: 	    my %this_domain;
12427: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
12428: 			       'lang_def', 'city', 'longi', 'lati',
12429: 			       'primary') {
12430: 		$this_domain{$field} = shift(@elements);
12431: 	    }
12432: 	    $domain{$name} = \%this_domain;
12433: 	}
12434:     }
12435: 
12436:     sub reset_domain_info {
12437: 	undef($loaded);
12438: 	undef(%domain);
12439:     }
12440: 
12441:     sub load_domain_tab {
12442: 	my ($ignore_cache,$nocache) = @_;
12443: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
12444: 	my $fh;
12445: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
12446: 	    my @lines = <$fh>;
12447: 	    &parse_domain_tab(\@lines);
12448: 	}
12449: 	close($fh);
12450: 	$loaded = 1;
12451:     }
12452: 
12453:     sub domain {
12454: 	&load_domain_tab() if (!$loaded);
12455: 
12456: 	my ($name,$what) = @_;
12457: 	return if ( !exists($domain{$name}) );
12458: 
12459: 	if (!$what) {
12460: 	    return $domain{$name}{'description'};
12461: 	}
12462: 	return $domain{$name}{$what};
12463:     }
12464: 
12465:     sub domain_info {
12466:         &load_domain_tab() if (!$loaded);
12467:         return %domain;
12468:     }
12469: 
12470: }
12471: 
12472: 
12473: # ------------------------------------------------------------- Read hosts file
12474: {
12475:     my %hostname;
12476:     my %hostdom;
12477:     my %libserv;
12478:     my $loaded;
12479:     my %name_to_host;
12480:     my %internetdom;
12481:     my %LC_dns_serv;
12482: 
12483:     sub parse_hosts_tab {
12484: 	my ($file) = @_;
12485: 	foreach my $configline (@$file) {
12486: 	    next if ($configline =~ /^(\#|\s*$ )/x);
12487:             chomp($configline);
12488: 	    if ($configline =~ /^\^/) {
12489:                 if ($configline =~ /^\^([\w.\-]+)/) {
12490:                     $LC_dns_serv{$1} = 1;
12491:                 }
12492:                 next;
12493:             }
12494: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
12495: 	    $name=~s/\s//g;
12496: 	    if ($id && $domain && $role && $name) {
12497: 		$hostname{$id}=$name;
12498: 		push(@{$name_to_host{$name}}, $id);
12499: 		$hostdom{$id}=$domain;
12500: 		if ($role eq 'library') { $libserv{$id}=$name; }
12501:                 if (defined($protocol)) {
12502:                     if ($protocol eq 'https') {
12503:                         $protocol{$id} = $protocol;
12504:                     } else {
12505:                         $protocol{$id} = 'http'; 
12506:                     }
12507:                 } else {
12508:                     $protocol{$id} = 'http';
12509:                 }
12510:                 if (defined($intdom)) {
12511:                     $internetdom{$id} = $intdom;
12512:                 }
12513: 	    }
12514: 	}
12515:     }
12516:     
12517:     sub reset_hosts_info {
12518: 	&purge_remembered();
12519: 	&reset_domain_info();
12520: 	&reset_hosts_ip_info();
12521: 	undef(%name_to_host);
12522: 	undef(%hostname);
12523: 	undef(%hostdom);
12524: 	undef(%libserv);
12525: 	undef($loaded);
12526:     }
12527: 
12528:     sub load_hosts_tab {
12529: 	my ($ignore_cache,$nocache) = @_;
12530: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
12531: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12532: 	my @config = <$config>;
12533: 	&parse_hosts_tab(\@config);
12534: 	close($config);
12535: 	$loaded=1;
12536:     }
12537: 
12538:     sub hostname {
12539: 	&load_hosts_tab() if (!$loaded);
12540: 
12541: 	my ($lonid) = @_;
12542: 	return $hostname{$lonid};
12543:     }
12544: 
12545:     sub all_hostnames {
12546: 	&load_hosts_tab() if (!$loaded);
12547: 
12548: 	return %hostname;
12549:     }
12550: 
12551:     sub all_names {
12552:         my ($ignore_cache,$nocache) = @_;
12553: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
12554: 
12555: 	return %name_to_host;
12556:     }
12557: 
12558:     sub all_host_domain {
12559:         &load_hosts_tab() if (!$loaded);
12560:         return %hostdom;
12561:     }
12562: 
12563:     sub is_library {
12564: 	&load_hosts_tab() if (!$loaded);
12565: 
12566: 	return exists($libserv{$_[0]});
12567:     }
12568: 
12569:     sub all_library {
12570: 	&load_hosts_tab() if (!$loaded);
12571: 
12572: 	return %libserv;
12573:     }
12574: 
12575:     sub unique_library {
12576: 	#2x reverse removes all hostnames that appear more than once
12577:         my %unique = reverse &all_library();
12578:         return reverse %unique;
12579:     }
12580: 
12581:     sub get_servers {
12582: 	&load_hosts_tab() if (!$loaded);
12583: 
12584: 	my ($domain,$type) = @_;
12585: 	my %possible_hosts = ($type eq 'library') ? %libserv
12586: 	                                          : %hostname;
12587: 	my %result;
12588: 	if (ref($domain) eq 'ARRAY') {
12589: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
12590: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
12591: 		    $result{$host} = $hostname;
12592: 		}
12593: 	    }
12594: 	} else {
12595: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
12596: 		if ($hostdom{$host} eq $domain) {
12597: 		    $result{$host} = $hostname;
12598: 		}
12599: 	    }
12600: 	}
12601: 	return %result;
12602:     }
12603: 
12604:     sub get_unique_servers {
12605:         my %unique = reverse &get_servers(@_);
12606: 	return reverse %unique;
12607:     }
12608: 
12609:     sub host_domain {
12610: 	&load_hosts_tab() if (!$loaded);
12611: 
12612: 	my ($lonid) = @_;
12613: 	return $hostdom{$lonid};
12614:     }
12615: 
12616:     sub all_domains {
12617: 	&load_hosts_tab() if (!$loaded);
12618: 
12619: 	my %seen;
12620: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
12621: 	return @uniq;
12622:     }
12623: 
12624:     sub internet_dom {
12625:         &load_hosts_tab() if (!$loaded);
12626: 
12627:         my ($lonid) = @_;
12628:         return $internetdom{$lonid};
12629:     }
12630: 
12631:     sub is_LC_dns {
12632:         &load_hosts_tab() if (!$loaded);
12633: 
12634:         my ($hostname) = @_;
12635:         return exists($LC_dns_serv{$hostname});
12636:     }
12637: 
12638: }
12639: 
12640: { 
12641:     my %iphost;
12642:     my %name_to_ip;
12643:     my %lonid_to_ip;
12644: 
12645:     sub get_hosts_from_ip {
12646: 	my ($ip) = @_;
12647: 	my %iphosts = &get_iphost();
12648: 	if (ref($iphosts{$ip})) {
12649: 	    return @{$iphosts{$ip}};
12650: 	}
12651: 	return;
12652:     }
12653:     
12654:     sub reset_hosts_ip_info {
12655: 	undef(%iphost);
12656: 	undef(%name_to_ip);
12657: 	undef(%lonid_to_ip);
12658:     }
12659: 
12660:     sub get_host_ip {
12661: 	my ($lonid) = @_;
12662: 	if (exists($lonid_to_ip{$lonid})) {
12663: 	    return $lonid_to_ip{$lonid};
12664: 	}
12665: 	my $name=&hostname($lonid);
12666:    	my $ip = gethostbyname($name);
12667: 	return if (!$ip || length($ip) ne 4);
12668: 	$ip=inet_ntoa($ip);
12669: 	$name_to_ip{$name}   = $ip;
12670: 	$lonid_to_ip{$lonid} = $ip;
12671: 	return $ip;
12672:     }
12673:     
12674:     sub get_iphost {
12675: 	my ($ignore_cache,$nocache) = @_;
12676: 
12677: 	if (!$ignore_cache) {
12678: 	    if (%iphost) {
12679: 		return %iphost;
12680: 	    }
12681: 	    my ($ip_info,$cached)=
12682: 		&Apache::lonnet::is_cached_new('iphost','iphost');
12683: 	    if ($cached) {
12684: 		%iphost      = %{$ip_info->[0]};
12685: 		%name_to_ip  = %{$ip_info->[1]};
12686: 		%lonid_to_ip = %{$ip_info->[2]};
12687: 		return %iphost;
12688: 	    }
12689: 	}
12690: 
12691: 	# get yesterday's info for fallback
12692: 	my %old_name_to_ip;
12693: 	my ($ip_info,$cached)=
12694: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
12695: 	if ($cached) {
12696: 	    %old_name_to_ip = %{$ip_info->[1]};
12697: 	}
12698: 
12699: 	my %name_to_host = &all_names($ignore_cache,$nocache);
12700: 	foreach my $name (keys(%name_to_host)) {
12701: 	    my $ip;
12702: 	    if (!exists($name_to_ip{$name})) {
12703: 		$ip = gethostbyname($name);
12704: 		if (!$ip || length($ip) ne 4) {
12705: 		    if (defined($old_name_to_ip{$name})) {
12706: 			$ip = $old_name_to_ip{$name};
12707: 			&logthis("Can't find $name defaulting to old $ip");
12708: 		    } else {
12709: 			&logthis("Name $name no IP found");
12710: 			next;
12711: 		    }
12712: 		} else {
12713: 		    $ip=inet_ntoa($ip);
12714: 		}
12715: 		$name_to_ip{$name} = $ip;
12716: 	    } else {
12717: 		$ip = $name_to_ip{$name};
12718: 	    }
12719: 	    foreach my $id (@{ $name_to_host{$name} }) {
12720: 		$lonid_to_ip{$id} = $ip;
12721: 	    }
12722: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
12723: 	}
12724:         unless ($nocache) {
12725: 	    &do_cache_new('iphost','iphost',
12726: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
12727: 		          48*60*60);
12728:         }
12729: 
12730: 	return %iphost;
12731:     }
12732: 
12733:     #
12734:     #  Given a DNS returns the loncapa host name for that DNS 
12735:     # 
12736:     sub host_from_dns {
12737:         my ($dns) = @_;
12738:         my @hosts;
12739:         my $ip;
12740: 
12741:         if (exists($name_to_ip{$dns})) {
12742:             $ip = $name_to_ip{$dns};
12743:         }
12744:         if (!$ip) {
12745:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12746:             if (length($ip) == 4) { 
12747: 	        $ip   = &IO::Socket::inet_ntoa($ip);
12748:             }
12749:         }
12750:         if ($ip) {
12751: 	    @hosts = get_hosts_from_ip($ip);
12752: 	    return $hosts[0];
12753:         }
12754:         return undef;
12755:     }
12756: 
12757:     sub get_internet_names {
12758:         my ($lonid) = @_;
12759:         return if ($lonid eq '');
12760:         my ($idnref,$cached)=
12761:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
12762:         if ($cached) {
12763:             return $idnref;
12764:         }
12765:         my $ip = &get_host_ip($lonid);
12766:         my @hosts = &get_hosts_from_ip($ip);
12767:         my %iphost = &get_iphost();
12768:         my (@idns,%seen);
12769:         foreach my $id (@hosts) {
12770:             my $dom = &host_domain($id);
12771:             my $prim_id = &domain($dom,'primary');
12772:             my $prim_ip = &get_host_ip($prim_id);
12773:             next if ($seen{$prim_ip});
12774:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12775:                 foreach my $id (@{$iphost{$prim_ip}}) {
12776:                     my $intdom = &internet_dom($id);
12777:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
12778:                         push(@idns,$intdom);
12779:                     }
12780:                 }
12781:             }
12782:             $seen{$prim_ip} = 1;
12783:         }
12784:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
12785:     }
12786: 
12787: }
12788: 
12789: sub all_loncaparevs {
12790:     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);
12791: }
12792: 
12793: # ---------------------------------------------------------- Read loncaparev table
12794: {
12795:     sub load_loncaparevs { 
12796:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12797:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12798:                 while (my $configline=<$config>) {
12799:                     chomp($configline);
12800:                     my ($hostid,$loncaparev)=split(/:/,$configline);
12801:                     $loncaparevs{$hostid}=$loncaparev;
12802:                 }
12803:                 close($config);
12804:             }
12805:         }
12806:     }
12807: }
12808: 
12809: # ---------------------------------------------------------- Read serverhostID table
12810: {
12811:     sub load_serverhomeIDs {
12812:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12813:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12814:                 while (my $configline=<$config>) {
12815:                     chomp($configline);
12816:                     my ($name,$id)=split(/:/,$configline);
12817:                     $serverhomeIDs{$name}=$id;
12818:                 }
12819:                 close($config);
12820:             }
12821:         }
12822:     }
12823: }
12824: 
12825: 
12826: BEGIN {
12827: 
12828: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12829:     unless ($readit) {
12830: {
12831:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12832:     %perlvar = (%perlvar,%{$configvars});
12833: }
12834: 
12835: 
12836: # ------------------------------------------------------ Read spare server file
12837: {
12838:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
12839: 
12840:     while (my $configline=<$config>) {
12841:        chomp($configline);
12842:        if ($configline) {
12843: 	   my ($host,$type) = split(':',$configline,2);
12844: 	   if (!defined($type) || $type eq '') { $type = 'default' };
12845: 	   push(@{ $spareid{$type} }, $host);
12846:        }
12847:     }
12848:     close($config);
12849: }
12850: # ------------------------------------------------------------ Read permissions
12851: {
12852:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
12853: 
12854:     while (my $configline=<$config>) {
12855: 	chomp($configline);
12856: 	if ($configline) {
12857: 	    my ($role,$perm)=split(/ /,$configline);
12858: 	    if ($perm ne '') { $pr{$role}=$perm; }
12859: 	}
12860:     }
12861:     close($config);
12862: }
12863: 
12864: # -------------------------------------------- Read plain texts for permissions
12865: {
12866:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
12867: 
12868:     while (my $configline=<$config>) {
12869: 	chomp($configline);
12870: 	if ($configline) {
12871: 	    my ($short,@plain)=split(/:/,$configline);
12872:             %{$prp{$short}} = ();
12873: 	    if (@plain > 0) {
12874:                 $prp{$short}{'std'} = $plain[0];
12875:                 for (my $i=1; $i<@plain; $i++) {
12876:                     $prp{$short}{'alt'.$i} = $plain[$i];  
12877:                 }
12878:             }
12879: 	}
12880:     }
12881:     close($config);
12882: }
12883: 
12884: # ---------------------------------------------------------- Read package table
12885: {
12886:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
12887: 
12888:     while (my $configline=<$config>) {
12889: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
12890: 	chomp($configline);
12891: 	my ($short,$plain)=split(/:/,$configline);
12892: 	my ($pack,$name)=split(/\&/,$short);
12893: 	if ($plain ne '') {
12894: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
12895: 	    $packagetab{$short}=$plain; 
12896: 	}
12897:     }
12898:     close($config);
12899: }
12900: 
12901: # ---------------------------------------------------------- Read loncaparev table
12902: 
12903: &load_loncaparevs();
12904: 
12905: # ---------------------------------------------------------- Read serverhostID table
12906: 
12907: &load_serverhomeIDs();
12908: 
12909: # ---------------------------------------------------------- Read releaseslist XML
12910: {
12911:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12912:     if (-e $file) {
12913:         my $parser = HTML::LCParser->new($file);
12914:         while (my $token = $parser->get_token()) {
12915:             if ($token->[0] eq 'S') {
12916:                 my $item = $token->[1];
12917:                 my $name = $token->[2]{'name'};
12918:                 my $value = $token->[2]{'value'};
12919:                 my $valuematch = $token->[2]{'valuematch'};
12920:                 if ($item ne '' && $name ne '' && ($value ne '' || $valuematch ne '')) {
12921:                     my $release = $parser->get_text();
12922:                     $release =~ s/(^\s*|\s*$ )//gx;
12923:                     $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch} = $release;
12924:                 }
12925:             }
12926:         }
12927:     }
12928: }
12929: 
12930: # ---------------------------------------------------------- Read managers table
12931: {
12932:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12933:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12934:             while (my $configline=<$config>) {
12935:                 chomp($configline);
12936:                 next if ($configline =~ /^\#/);
12937:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12938:                     $managerstab{$configline} = 1;
12939:                 }
12940:             }
12941:             close($config);
12942:         }
12943:     }
12944: }
12945: 
12946: # ------------- set up temporary directory
12947: {
12948:     $tmpdir = LONCAPA::tempdir();
12949: 
12950: }
12951: 
12952: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
12953: 				'compress_threshold'=> 20_000,
12954:  			        });
12955: 
12956: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
12957: $dumpcount=0;
12958: $locknum=0;
12959: 
12960: &logtouch();
12961: &logthis('<font color="yellow">INFO: Read configuration</font>');
12962: $readit=1;
12963:     {
12964: 	use integer;
12965: 	my $test=(2**32)+1;
12966: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
12967: 	&logthis(" Detected 64bit platform ($_64bit)");
12968:     }
12969: }
12970: }
12971: 
12972: 1;
12973: __END__
12974: 
12975: =pod
12976: 
12977: =head1 NAME
12978: 
12979: Apache::lonnet - Subroutines to ask questions about things in the network.
12980: 
12981: =head1 SYNOPSIS
12982: 
12983: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
12984: 
12985:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12986: 
12987: Common parameters:
12988: 
12989: =over 4
12990: 
12991: =item *
12992: 
12993: $uname : an internal username (if $cname expecting a course Id specifically)
12994: 
12995: =item *
12996: 
12997: $udom : a domain (if $cdom expecting a course's domain specifically)
12998: 
12999: =item *
13000: 
13001: $symb : a resource instance identifier
13002: 
13003: =item *
13004: 
13005: $namespace : the name of a .db file that contains the data needed or
13006: being set.
13007: 
13008: =back
13009: 
13010: =head1 OVERVIEW
13011: 
13012: lonnet provides subroutines which interact with the
13013: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
13014: about classes, users, and resources.
13015: 
13016: For many of these objects you can also use this to store data about
13017: them or modify them in various ways.
13018: 
13019: =head2 Symbs
13020: 
13021: To identify a specific instance of a resource, LON-CAPA uses symbols
13022: or "symbs"X<symb>. These identifiers are built from the URL of the
13023: map, the resource number of the resource in the map, and the URL of
13024: the resource itself. The latter is somewhat redundant, but might help
13025: if maps change.
13026: 
13027: An example is
13028: 
13029:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
13030: 
13031: The respective map entry is
13032: 
13033:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
13034:   title="Problem 2">
13035:  </resource>
13036: 
13037: Symbs are used by the random number generator, as well as to store and
13038: restore data specific to a certain instance of for example a problem.
13039: 
13040: =head2 Storing And Retrieving Data
13041: 
13042: X<store()>X<cstore()>X<restore()>Three of the most important functions
13043: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
13044: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
13045: is is the non-critical message twin of cstore. These functions are for
13046: handlers to store a perl hash to a user's permanent data space in an
13047: easy manner, and to retrieve it again on another call. It is expected
13048: that a handler would use this once at the beginning to retrieve data,
13049: and then again once at the end to send only the new data back.
13050: 
13051: The data is stored in the user's data directory on the user's
13052: homeserver under the ID of the course.
13053: 
13054: The hash that is returned by restore will have all of the previous
13055: value for all of the elements of the hash.
13056: 
13057: Example:
13058: 
13059:  #creating a hash
13060:  my %hash;
13061:  $hash{'foo'}='bar';
13062: 
13063:  #storing it
13064:  &Apache::lonnet::cstore(\%hash);
13065: 
13066:  #changing a value
13067:  $hash{'foo'}='notbar';
13068: 
13069:  #adding a new value
13070:  $hash{'bar'}='foo';
13071:  &Apache::lonnet::cstore(\%hash);
13072: 
13073:  #retrieving the hash
13074:  my %history=&Apache::lonnet::restore();
13075: 
13076:  #print the hash
13077:  foreach my $key (sort(keys(%history))) {
13078:    print("\%history{$key} = $history{$key}");
13079:  }
13080: 
13081: Will print out:
13082: 
13083:  %history{1:foo} = bar
13084:  %history{1:keys} = foo:timestamp
13085:  %history{1:timestamp} = 990455579
13086:  %history{2:bar} = foo
13087:  %history{2:foo} = notbar
13088:  %history{2:keys} = foo:bar:timestamp
13089:  %history{2:timestamp} = 990455580
13090:  %history{bar} = foo
13091:  %history{foo} = notbar
13092:  %history{timestamp} = 990455580
13093:  %history{version} = 2
13094: 
13095: Note that the special hash entries C<keys>, C<version> and
13096: C<timestamp> were added to the hash. C<version> will be equal to the
13097: total number of versions of the data that have been stored. The
13098: C<timestamp> attribute will be the UNIX time the hash was
13099: stored. C<keys> is available in every historical section to list which
13100: keys were added or changed at a specific historical revision of a
13101: hash.
13102: 
13103: B<Warning>: do not store the hash that restore returns directly. This
13104: will cause a mess since it will restore the historical keys as if the
13105: were new keys. I.E. 1:foo will become 1:1:foo etc.
13106: 
13107: Calling convention:
13108: 
13109:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
13110:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
13111: 
13112: For more detailed information, see lonnet specific documentation.
13113: 
13114: =head1 RETURN MESSAGES
13115: 
13116: =over 4
13117: 
13118: =item * B<con_lost>: unable to contact remote host
13119: 
13120: =item * B<con_delayed>: unable to contact remote host, message will be delivered
13121: when the connection is brought back up
13122: 
13123: =item * B<con_failed>: unable to contact remote host and unable to save message
13124: for later delivery
13125: 
13126: =item * B<error:>: an error a occurred, a description of the error follows the :
13127: 
13128: =item * B<no_such_host>: unable to fund a host associated with the user/domain
13129: that was requested
13130: 
13131: =back
13132: 
13133: =head1 PUBLIC SUBROUTINES
13134: 
13135: =head2 Session Environment Functions
13136: 
13137: =over 4
13138: 
13139: =item * 
13140: X<appenv()>
13141: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
13142: the user envirnoment file, and will be restored for each access this
13143: user makes during this session, also modifies the %env for the current
13144: process. Optional rolesarrayref - if defined contains a reference to an array
13145: of roles which are exempt from the restriction on modifying user.role entries 
13146: in the user's environment.db and in %env.    
13147: 
13148: =item *
13149: X<delenv()>
13150: B<delenv($delthis,$regexp)>: removes all items from the session
13151: environment file that begin with $delthis. If the 
13152: optional second arg - $regexp - is true, $delthis is treated as a 
13153: regular expression, otherwise \Q$delthis\E is used. 
13154: The values are also deleted from the current processes %env.
13155: 
13156: =item * get_env_multiple($name) 
13157: 
13158: gets $name from the %env hash, it seemlessly handles the cases where multiple
13159: values may be defined and end up as an array ref.
13160: 
13161: returns an array of values
13162: 
13163: =back
13164: 
13165: =head2 User Information
13166: 
13167: =over 4
13168: 
13169: =item *
13170: X<queryauthenticate()>
13171: B<queryauthenticate($uname,$udom)>: try to determine user's current 
13172: authentication scheme
13173: 
13174: =item *
13175: X<authenticate()>
13176: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
13177: authenticate user from domain's lib servers (first use the current
13178: one). C<$upass> should be the users password.
13179: $checkdefauth is optional (value is 1 if a check should be made to
13180:    authenticate user using default authentication method, and allow
13181:    account creation if username does not have account in the domain).
13182: $clientcancheckhost is optional (value is 1 if checking whether the
13183:    server can host will occur on the client side in lonauth.pm).   
13184: 
13185: =item *
13186: X<homeserver()>
13187: B<homeserver($uname,$udom)>: find the server which has
13188: the user's directory and files (there must be only one), this caches
13189: the answer, and also caches if there is a borken connection.
13190: 
13191: =item *
13192: X<idget()>
13193: B<idget($udom,@ids)>: find the usernames behind a list of IDs
13194: (IDs are a unique resource in a domain, there must be only 1 ID per
13195: username, and only 1 username per ID in a specific domain) (returns
13196: hash: id=>name,id=>name)
13197: 
13198: =item *
13199: X<idrget()>
13200: B<idrget($udom,@unames)>: find the IDs behind a list of
13201: usernames (returns hash: name=>id,name=>id)
13202: 
13203: =item *
13204: X<idput()>
13205: B<idput($udom,%ids)>: store away a list of names and associated IDs
13206: 
13207: =item *
13208: X<rolesinit()>
13209: B<rolesinit($udom,$username)>: get user privileges.
13210: returns user role, first access and timer interval hashes
13211: 
13212: =item *
13213: X<privileged()>
13214: B<privileged($username,$domain)>: returns a true if user has a
13215: privileged and active role (i.e. su or dc), false otherwise.
13216: 
13217: =item *
13218: X<getsection()>
13219: B<getsection($udom,$uname,$cname)>: finds the section of student in the
13220: course $cname, return section name/number or '' for "not in course"
13221: and '-1' for "no section"
13222: 
13223: =item *
13224: X<userenvironment()>
13225: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
13226: passed in @what from the requested user's environment, returns a hash
13227: 
13228: =item * 
13229: X<userlog_query()>
13230: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
13231: activity.log file. %filters defines filters applied when parsing the
13232: log file. These can be start or end timestamps, or the type of action
13233: - log to look for Login or Logout events, check for Checkin or
13234: Checkout, role for role selection. The response is in the form
13235: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
13236: escaped strings of the action recorded in the activity.log file.
13237: 
13238: =back
13239: 
13240: =head2 User Roles
13241: 
13242: =over 4
13243: 
13244: =item *
13245: 
13246: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
13247: returns codes for allowed actions.
13248: 
13249: The first argument is required, all others are optional.
13250: 
13251: $priv is the privilege being checked.
13252: $uri contains additional information about what is being checked for access (e.g.,
13253: URL, course ID etc.). 
13254: $symb is the unique resource instance identifier in a course; if needed,
13255: but not provided, it will be retrieved via a call to &symbread(). 
13256: $role is the role for which a priv is being checked (only used if priv is evb). 
13257: $clientip is the user's IP address (only used when checking for access to portfolio 
13258: files).
13259: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
13260: prevents recursive calls to &allowed.
13261: 
13262:  F: full access
13263:  U,I,K: authentication modes (cxx only)
13264:  '': forbidden
13265:  1: user needs to choose course
13266:  2: browse allowed
13267:  A: passphrase authentication needed
13268:  B: access temporarily blocked because of a blocking event in a course.
13269: 
13270: =item *
13271: 
13272: constructaccess($url,$setpriv) : check for access to construction space URL
13273: 
13274: See if the owner domain and name in the URL match those in the
13275: expected environment.  If so, return three element list
13276: ($ownername,$ownerdomain,$ownerhome).
13277: 
13278: Otherwise return the null string.
13279: 
13280: If second argument 'setpriv' is true, it assigns the privileges,
13281: and returns the same three element list, unless the owner has
13282: blocked "ad hoc" Domain Coordinator access to the Author Space,
13283: in which case the null string is returned.
13284: 
13285: =item *
13286: 
13287: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
13288: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
13289: and course level
13290: 
13291: =item *
13292: 
13293: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
13294: (rolesplain.tab); plain text explanation of a user role term.
13295: $type is Course (default) or Community.
13296: If $forcedefault evaluates to true, text returned will be default 
13297: text for $type. Otherwise, if this is a course, the text returned 
13298: will be a custom name for the role (if defined in the course's 
13299: environment).  If no custom name is defined the default is returned.
13300:    
13301: =item *
13302: 
13303: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
13304: All arguments are optional. Returns a hash of a roles, either for
13305: co-author/assistant author roles for a user's Construction Space
13306: (default), or if $context is 'userroles', roles for the user himself,
13307: In the hash, keys are set to colon-separated $uname,$udom,$role, and
13308: (optionally) if $withsec is true, a fourth colon-separated item - $section.
13309: For each key, value is set to colon-separated start and end times for
13310: the role.  If no username and domain are specified, will default to
13311: current user/domain. Types, roles, and roledoms are references to arrays
13312: of role statuses (active, future or previous), roles 
13313: (e.g., cc,in, st etc.) and domains of the roles which can be used
13314: to restrict the list of roles reported. If no array ref is 
13315: provided for types, will default to return only active roles.
13316: 
13317: =item *
13318: 
13319: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
13320: user: $uname:$udom has a role in the course: $cdom_$cnum. 
13321: 
13322: Additional optional arguments are: $type (if role checking is to be restricted 
13323: to certain user status types -- previous (expired roles), active (currently
13324: available roles) or future (roles available in the future), and
13325: $hideprivileged -- if true will not report course roles for users who
13326: have active Domain Coordinator role in course's domain or in additional
13327: domains (specified in 'Domains to check for privileged users' in course
13328: environment -- set via:  Course Settings -> Classlists and staff listing).
13329: 
13330: =item *
13331: 
13332: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
13333: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
13334: $possdomains and $possroles are optional array refs -- to domains to check and
13335: roles to check.  If $possdomains is not specified, a dump will be done of the
13336: users' roles.db to check for a dc or su role in any domain. This can be
13337: time consuming if &privileged is called repeatedly (e.g., when displaying a
13338: classlist), so in such cases, supplying a $possdomains array is preferred, as
13339: this then allows &privileged_by_domain() to be used, which caches the identity
13340: of privileged users, eliminating the need for repeated calls to &dump().
13341: 
13342: =item *
13343: 
13344: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
13345: where the outer hash keys are domains specified in the $possdomains array ref,
13346: next inner hash keys are privileged roles specified in the $roles array ref,
13347: and the innermost hash contains key = value pairs for username:domain = end:start
13348: for active or future "privileged" users with that role in that domain. To avoid
13349: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
13350: innerhash are cached using priv_$role and $dom as the identifiers.
13351: 
13352: =back
13353: 
13354: =head2 User Modification
13355: 
13356: =over 4
13357: 
13358: =item *
13359: 
13360: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
13361: user for the level given by URL.  Optional start and end dates (leave empty
13362: string or zero for "no date")
13363: 
13364: =item *
13365: 
13366: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
13367: change a users, password, possible return values are: ok,
13368: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
13369: refused
13370: 
13371: =item *
13372: 
13373: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
13374: 
13375: =item *
13376: 
13377: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
13378:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
13379: 
13380: will update user information (firstname,middlename,lastname,generation,
13381: permanentemail), and if forceid is true, student/employee ID also.
13382: A user's institutional affiliation(s) can also be updated.
13383: User information fields will not be overwritten with empty entries 
13384: unless the field is included in the $candelete array reference.
13385: This array is included when a single user is modified via "Manage Users",
13386: or when Autoupdate.pl is run by cron in a domain.
13387: 
13388: =item *
13389: 
13390: modifystudent
13391: 
13392: modify a student's enrollment and identification information.
13393: The course id is resolved based on the current user's environment.  
13394: This means the invoking user must be a course coordinator or otherwise
13395: associated with a course.
13396: 
13397: This call is essentially a wrapper for lonnet::modifyuser and
13398: lonnet::modify_student_enrollment
13399: 
13400: Inputs: 
13401: 
13402: =over 4
13403: 
13404: =item B<$udom> Student's loncapa domain
13405: 
13406: =item B<$uname> Student's loncapa login name
13407: 
13408: =item B<$uid> Student/Employee ID
13409: 
13410: =item B<$umode> Student's authentication mode
13411: 
13412: =item B<$upass> Student's password
13413: 
13414: =item B<$first> Student's first name
13415: 
13416: =item B<$middle> Student's middle name
13417: 
13418: =item B<$last> Student's last name
13419: 
13420: =item B<$gene> Student's generation
13421: 
13422: =item B<$usec> Student's section in course
13423: 
13424: =item B<$end> Unix time of the roles expiration
13425: 
13426: =item B<$start> Unix time of the roles start date
13427: 
13428: =item B<$forceid> If defined, allow $uid to be changed
13429: 
13430: =item B<$desiredhome> server to use as home server for student
13431: 
13432: =item B<$email> Student's permanent e-mail address
13433: 
13434: =item B<$type> Type of enrollment (auto or manual)
13435: 
13436: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
13437: 
13438: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
13439: 
13440: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
13441: 
13442: =item B<$context> role change context (shown in User Management Logs display in a course)
13443: 
13444: =item B<$inststatus> institutional status of user - : separated string of escaped status types
13445: 
13446: =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.
13447: 
13448: =back
13449: 
13450: =item *
13451: 
13452: modify_student_enrollment
13453: 
13454: Change a student's enrollment status in a class.  The environment variable
13455: 'role.request.course' must be defined for this function to proceed.
13456: 
13457: Inputs:
13458: 
13459: =over 4
13460: 
13461: =item $udom, student's domain
13462: 
13463: =item $uname, student's name
13464: 
13465: =item $uid, student's user id
13466: 
13467: =item $first, student's first name
13468: 
13469: =item $middle
13470: 
13471: =item $last
13472: 
13473: =item $gene
13474: 
13475: =item $usec
13476: 
13477: =item $end
13478: 
13479: =item $start
13480: 
13481: =item $type
13482: 
13483: =item $locktype
13484: 
13485: =item $cid
13486: 
13487: =item $selfenroll
13488: 
13489: =item $context
13490: 
13491: =item $credits, number of credits student will earn from this class
13492: 
13493: =back
13494: 
13495: 
13496: =item *
13497: 
13498: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
13499: custom role; give a custom role to a user for the level given by URL.  Specify
13500: name and domain of role author, and role name
13501: 
13502: =item *
13503: 
13504: revokerole($udom,$uname,$url,$role) : revoke a role for url
13505: 
13506: =item *
13507: 
13508: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
13509: 
13510: =back
13511: 
13512: =head2 Course Infomation
13513: 
13514: =over 4
13515: 
13516: =item *
13517: 
13518: coursedescription($courseid,$options) : returns a hash of information about the
13519: specified course id, including all environment settings for the
13520: course, the description of the course will be in the hash under the
13521: key 'description'
13522: 
13523: $options is an optional parameter that if supplied is a hash reference that controls
13524: what how this function works.  It has the following key/values:
13525: 
13526: =over 4
13527: 
13528: =item freshen_cache
13529: 
13530: If defined, and the environment cache for the course is valid, it is 
13531: returned in the returned hash.
13532: 
13533: =item one_time
13534: 
13535: If defined, the last cache time is set to _now_
13536: 
13537: =item user
13538: 
13539: If defined, the supplied username is used instead of the current user.
13540: 
13541: 
13542: =back
13543: 
13544: =item *
13545: 
13546: resdata($name,$domain,$type,@which) : request for current parameter
13547: setting for a specific $type, where $type is either 'course' or 'user',
13548: @what should be a list of parameters to ask about. This routine caches
13549: answers for 10 minutes.
13550: 
13551: =item *
13552: 
13553: get_courseresdata($courseid, $domain) : dump the entire course resource
13554: data base, returning a hash that is keyed by the resource name and has
13555: values that are the resource value.  I believe that the timestamps and
13556: versions are also returned.
13557: 
13558: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
13559: supplemental content area. This routine caches the number of files for 
13560: 10 minutes.
13561: 
13562: =back
13563: 
13564: =head2 Course Modification
13565: 
13566: =over 4
13567: 
13568: =item *
13569: 
13570: writecoursepref($courseid,%prefs) : write preferences (environment
13571: database) for a course
13572: 
13573: =item *
13574: 
13575: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
13576: 
13577: =item *
13578: 
13579: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
13580: 
13581: =item *
13582: 
13583: is_course($courseid), is_course($cdom, $cnum)
13584: 
13585: Accepts either a combined $courseid (in the form of domain_courseid) or the
13586: two component version $cdom, $cnum. It checks if the specified course exists.
13587: 
13588: Returns:
13589:     undef if the course doesn't exist, otherwise
13590:     in scalar context the combined courseid.
13591:     in list context the two components of the course identifier, domain and 
13592:     courseid.    
13593: 
13594: =back
13595: 
13596: =head2 Resource Subroutines
13597: 
13598: =over 4
13599: 
13600: =item *
13601: 
13602: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
13603: 
13604: =item *
13605: 
13606: repcopy($filename) : subscribes to the requested file, and attempts to
13607: replicate from the owning library server, Might return
13608: 'unavailable', 'not_found', 'forbidden', 'ok', or
13609: 'bad_request', also attempts to grab the metadata for the
13610: resource. Expects the local filesystem pathname
13611: (/home/httpd/html/res/....)
13612: 
13613: =back
13614: 
13615: =head2 Resource Information
13616: 
13617: =over 4
13618: 
13619: =item *
13620: 
13621: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
13622: and returns the value of a variety of different possible values,
13623: $varname should be a request string, and the other parameters can be
13624: used to specify who and what one is asking about. Ordinarily, $cid 
13625: does not need to be specified, as it is retrived from 
13626: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
13627: within lonuserstate::loadmap() when initializing a course, before
13628: $env{'request.course.id'} has been set, so it needs to be provided
13629: in that one case.
13630: 
13631: Possible values for $varname are environment.lastname (or other item
13632: from the envirnment hash), user.name (or someother aspect about the
13633: user), resource.0.maxtries (or some other part and parameter of a
13634: resource)
13635: 
13636: =item *
13637: 
13638: directcondval($number) : get current value of a condition; reads from a state
13639: string
13640: 
13641: =item *
13642: 
13643: condval($condidx) : value of condition index based on state
13644: 
13645: =item *
13646: 
13647: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
13648: resource's metadata, $what should be either a specific key, or either
13649: 'keys' (to get a list of possible keys) or 'packages' to get a list of
13650: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
13651: 
13652: this function automatically caches all requests
13653: 
13654: =item *
13655: 
13656: metadata_query($query,$custom,$customshow) : make a metadata query against the
13657: network of library servers; returns file handle of where SQL and regex results
13658: will be stored for query
13659: 
13660: =item *
13661: 
13662: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
13663: return symbolic list entry (all arguments optional). 
13664: 
13665: Args: filename is the filename (including path) for the file for which a symb 
13666: is required; donotrecurse, if true will prevent calls to allowed() being made 
13667: to check access status if more than one resource was found in the bighash 
13668: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
13669: a randompick); ignorecachednull, if true will prevent a symb of '' being 
13670: returned if $env{$cache_str} is defined as ''; checkforblock if true will
13671: cause possible symbs to be checked to determine if they are subject to content
13672: blocking, if so they will not be included as possible symbs; possibles is a
13673: ref to a hash, which, as a side effect, will be populated with all possible 
13674: symbs (content blocking not tested).
13675:  
13676: returns the data handle
13677: 
13678: =item *
13679: 
13680: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
13681: and is a possible symb for the URL in $thisfn, and if is an encrypted
13682: resource that the user accessed using /enc/ returns a 1 on success, 0
13683: on failure, user must be in a course, as it assumes the existence of
13684: the course initial hash, and uses $env('request.course.id'}.  The third
13685: arg is an optional reference to a scalar.  If this arg is passed in the 
13686: call to symbverify, it will be set to 1 if the symb has been set to be 
13687: encrypted; otherwise it will be null.  
13688: 
13689: =item *
13690: 
13691: symbclean($symb) : removes versions numbers from a symb, returns the
13692: cleaned symb
13693: 
13694: =item *
13695: 
13696: is_on_map($uri) : checks if the $uri is somewhere on the current
13697: course map, user must be in a course for it to work.
13698: 
13699: =item *
13700: 
13701: numval($salt) : return random seed value (addend for rndseed)
13702: 
13703: =item *
13704: 
13705: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13706: a random seed, all arguments are optional, if they aren't sent it uses the
13707: environment to derive them. Note: if symb isn't sent and it can't get one
13708: from &symbread it will use the current time as its return value
13709: 
13710: =item *
13711: 
13712: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13713: unfakeable, receipt
13714: 
13715: =item *
13716: 
13717: receipt() : API to ireceipt working off of env values; given out to users
13718: 
13719: =item *
13720: 
13721: countacc($url) : count the number of accesses to a given URL
13722: 
13723: =item *
13724: 
13725: 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
13726: 
13727: =item *
13728: 
13729: 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)
13730: 
13731: =item *
13732: 
13733: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
13734: 
13735: =item *
13736: 
13737: devalidate($symb) : devalidate temporary spreadsheet calculations,
13738: forcing spreadsheet to reevaluate the resource scores next time.
13739: 
13740: =item * 
13741: 
13742: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13743: when viewing in course context.
13744: 
13745:  input: six args -- filename (decluttered), course number, course domain,
13746:                     url, symb (if registered) and group (if this is a 
13747:                     group item -- e.g., bulletin board, group page etc.).
13748: 
13749:  output: array of five scalars --
13750:          $cfile -- url for file editing if editable on current server
13751:          $home -- homeserver of resource (i.e., for author if published,
13752:                                           or course if uploaded.).
13753:          $switchserver --  1 if server switch will be needed.
13754:          $forceedit -- 1 if icon/link should be to go to edit mode 
13755:          $forceview -- 1 if icon/link should be to go to view mode
13756: 
13757: =item *
13758: 
13759: is_course_upload($file,$cnum,$cdom)
13760: 
13761: Used in course context to determine if current file was uploaded to 
13762: the course (i.e., would be found in /userfiles/docs on the course's 
13763: homeserver.
13764: 
13765:   input: 3 args -- filename (decluttered), course number and course domain.
13766:   output: boolean -- 1 if file was uploaded.
13767: 
13768: =back
13769: 
13770: =head2 Storing/Retreiving Data
13771: 
13772: =over 4
13773: 
13774: =item *
13775: 
13776: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
13777: permanently for this url; hashref needs to be given and should be a \%hashname;
13778: the remaining args aren't required and if they aren't passed or are '' they will
13779: be derived from the env (with the exception of $laststore, which is an 
13780: optional arg used when a user's submission is stored in grading).
13781: $laststore is $version=$timestamp, where $version is the most recent version
13782: number retrieved for the corresponding $symb in the $namespace db file, and
13783: $timestamp is the timestamp for that transaction (UNIX time).
13784: $laststore is currently only passed when cstore() is called by 
13785: structuretags::finalize_storage().
13786: 
13787: =item *
13788: 
13789: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
13790: but uses critical subroutine
13791: 
13792: =item *
13793: 
13794: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13795: all args are optional
13796: 
13797: =item *
13798: 
13799: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
13800: dumps the complete (or key matching regexp) namespace into a hash
13801: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13802: normally &store()ed into
13803: 
13804: $range should be either an integer '100' (give me the first 100
13805:                                            matching records)
13806:               or be  two integers sperated by a - with no spaces
13807:                  '30-50' (give me the 30th through the 50th matching
13808:                           records)
13809: 
13810: 
13811: =item *
13812: 
13813: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
13814: replaces a &store() version of data with a replacement set of data
13815: for a particular resource in a namespace passed in the $storehash hash 
13816: reference. If $tolog is true, the transaction is logged in the courselog
13817: with an action=PUTSTORE.
13818: 
13819: =item *
13820: 
13821: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13822: works very similar to store/cstore, but all data is stored in a
13823: temporary location and can be reset using tmpreset, $storehash should
13824: be a hash reference, returns nothing on success
13825: 
13826: =item *
13827: 
13828: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13829: similar to restore, but all data is stored in a temporary location and
13830: can be reset using tmpreset. Returns a hash of values on success,
13831: error string otherwise.
13832: 
13833: =item *
13834: 
13835: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13836: deltes all keys for $symb form the temporary storage hash.
13837: 
13838: =item *
13839: 
13840: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13841: reference filled in from namesp ($udom and $uname are optional)
13842: 
13843: =item *
13844: 
13845: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13846: namesp ($udom and $uname are optional)
13847: 
13848: =item *
13849: 
13850: dump($namespace,$udom,$uname,$regexp,$range) : 
13851: dumps the complete (or key matching regexp) namespace into a hash
13852: ($udom, $uname, $regexp, $range are optional)
13853: 
13854: $range should be either an integer '100' (give me the first 100
13855:                                            matching records)
13856:               or be  two integers sperated by a - with no spaces
13857:                  '30-50' (give me the 30th through the 50th matching
13858:                           records)
13859: =item *
13860: 
13861: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13862: $store can be a scalar, an array reference, or if the amount to be 
13863: incremented is > 1, a hash reference.
13864: 
13865: ($udom and $uname are optional)
13866: 
13867: =item *
13868: 
13869: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13870: ($udom and $uname are optional)
13871: 
13872: =item *
13873: 
13874: cput($namespace,$storehash,$udom,$uname) : critical put
13875: ($udom and $uname are optional)
13876: 
13877: =item *
13878: 
13879: newput($namespace,$storehash,$udom,$uname) :
13880: 
13881: Attempts to store the items in the $storehash, but only if they don't
13882: currently exist, if this succeeds you can be certain that you have 
13883: successfully created a new key value pair in the $namespace db.
13884: 
13885: 
13886: Args:
13887:  $namespace: name of database to store values to
13888:  $storehash: hashref to store to the db
13889:  $udom: (optional) domain of user containing the db
13890:  $uname: (optional) name of user caontaining the db
13891: 
13892: Returns:
13893:  'ok' -> succeeded in storing all keys of $storehash
13894:  'key_exists: <key>' -> failed to anything out of $storehash, as at
13895:                         least <key> already existed in the db (other
13896:                         requested keys may also already exist)
13897:  'error: <msg>' -> unable to tie the DB or other error occurred
13898:  'con_lost' -> unable to contact request server
13899:  'refused' -> action was not allowed by remote machine
13900: 
13901: 
13902: =item *
13903: 
13904: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13905: reference filled in from namesp (encrypts the return communication)
13906: ($udom and $uname are optional)
13907: 
13908: =item *
13909: 
13910: log($udom,$name,$home,$message) : write to permanent log for user; use
13911: critical subroutine
13912: 
13913: =item *
13914: 
13915: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13916: array reference filled in from namespace found in domain level on either
13917: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
13918: 
13919: =item *
13920: 
13921: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
13922: domain level either on specified domain server ($uhome) or primary domain 
13923: server ($udom and $uhome are optional)
13924: 
13925: =item * 
13926: 
13927: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
13928: for: authentication, language, quotas, timezone, date locale, and portal URL in
13929: the target domain.
13930: 
13931: May also include additional key => value pairs for the following groups:
13932: 
13933: =over
13934: 
13935: =item
13936: disk quotas (MB allocated by default to portfolios and authoring spaces).
13937: 
13938: =over
13939: 
13940: =item defaultquota, authorquota
13941: 
13942: =back
13943: 
13944: =item
13945: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
13946: portfolio for users).
13947: 
13948: =over
13949: 
13950: =item
13951: aboutme, blog, webdav, portfolio
13952: 
13953: =back
13954: 
13955: =item
13956: requestcourses: ability to request courses, and how requests are processed.
13957: 
13958: =over
13959: 
13960: =item
13961: official, unofficial, community, textbook
13962: 
13963: =back
13964: 
13965: =item
13966: inststatus: types of institutional affiliation, and order in which they are displayed.
13967: 
13968: =over
13969: 
13970: =item
13971: inststatustypes, inststatusorder, inststatusguest
13972: 
13973: =back
13974: 
13975: =item
13976: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
13977: for course's uploaded content.
13978: 
13979: =over
13980: 
13981: =item
13982: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
13983: communityquota, textbookquota
13984: 
13985: =back
13986: 
13987: =item
13988: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
13989: on your servers.
13990: 
13991: =over
13992: 
13993: =item 
13994: remotesessions, hostedsessions
13995: 
13996: =back
13997: 
13998: =back
13999: 
14000: In cases where a domain coordinator has never used the "Set Domain Configuration"
14001: utility to create a configuration.db file on a domain's primary library server 
14002: only the following domain defaults: auth_def, auth_arg_def, lang_def
14003: -- corresponding values are authentication type (internal, krb4, krb5,
14004: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
14005: will be available. Values are retrieved from cache (if current), unless the
14006: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
14007: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
14008: 
14009: Typical usage:
14010: 
14011: %domdefaults = &get_domain_defaults($target_domain);
14012: 
14013: =back
14014: 
14015: =head2 Network Status Functions
14016: 
14017: =over 4
14018: 
14019: =item *
14020: 
14021: dirlist() : return directory list based on URI (first arg).
14022: 
14023: Inputs: 1 required, 5 optional.
14024: 
14025: =over
14026: 
14027: =item 
14028: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
14029: 
14030: =item
14031: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
14032: 
14033: =item
14034: $username -  username of user/course to be listed. Extracted from $uri if absent. 
14035: 
14036: =item
14037: $getpropath - boolean: 1 if prepend path using &propath(). 
14038: 
14039: =item
14040: $getuserdir - boolean: 1 if prepend path for "userfiles".
14041: 
14042: =item 
14043: $alternateRoot - path to prepend in place of path from $uri.
14044: 
14045: =back
14046: 
14047: Returns: Array of up to two items.
14048: 
14049: =over
14050: 
14051: a reference to an array of files/subdirectories
14052: 
14053: =over
14054: 
14055: Each element in the array of files/subdirectories is a & separated list of
14056: item name and the result of running stat on the item.  If dirlist was requested
14057: for a file instead of a directory, the item name will be ''. For a directory 
14058: listing, if the item is a metadata file, the element will end &N&M 
14059: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
14060: default copyright set (1).  
14061: 
14062: =back
14063: 
14064: a scalar containing error condition (if encountered).
14065: 
14066: =over
14067: 
14068: =item 
14069: no_host (no homeserver identified for $username:$domain).
14070: 
14071: =item 
14072: no_such_host (server contacted for listing not identified as valid host).
14073: 
14074: =item 
14075: con_lost (connection to remote server failed).
14076: 
14077: =item 
14078: refused (invalid $username:$domain received on lond side).
14079: 
14080: =item 
14081: no_such_dir (directory at specified path on lond side does not exist). 
14082: 
14083: =item 
14084: empty (directory at specified path on lond side is empty).
14085: 
14086: =over
14087: 
14088: This is currently not encountered because the &ls3, &ls2, 
14089: &ls (_handler) routines on the lond side do not filter out
14090: . and .. from a directory listing. 
14091: 
14092: =back
14093: 
14094: =back
14095: 
14096: =back
14097: 
14098: =item *
14099: 
14100: spareserver() : find server with least workload from spare.tab
14101: 
14102: 
14103: =item *
14104: 
14105: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
14106: if there is no corresponding loncapa host.
14107: 
14108: =back
14109: 
14110: 
14111: =head2 Apache Request
14112: 
14113: =over 4
14114: 
14115: =item *
14116: 
14117: ssi($url,%hash) : server side include, does a complete request cycle on url to
14118: localhost, posts hash
14119: 
14120: =back
14121: 
14122: =head2 Data to String to Data
14123: 
14124: =over 4
14125: 
14126: =item *
14127: 
14128: hash2str(%hash) : convert a hash into a string complete with escaping and '='
14129: and '&' separators, supports elements that are arrayrefs and hashrefs
14130: 
14131: =item *
14132: 
14133: hashref2str($hashref) : convert a hashref into a string complete with
14134: escaping and '=' and '&' separators, supports elements that are
14135: arrayrefs and hashrefs
14136: 
14137: =item *
14138: 
14139: arrayref2str($arrayref) : convert an arrayref into a string complete
14140: with escaping and '&' separators, supports elements that are arrayrefs
14141: and hashrefs
14142: 
14143: =item *
14144: 
14145: str2hash($string) : convert string to hash using unescaping and
14146: splitting on '=' and '&', supports elements that are arrayrefs and
14147: hashrefs
14148: 
14149: =item *
14150: 
14151: str2array($string) : convert string to hash using unescaping and
14152: splitting on '&', supports elements that are arrayrefs and hashrefs
14153: 
14154: =back
14155: 
14156: =head2 Logging Routines
14157: 
14158: 
14159: These routines allow one to make log messages in the lonnet.log and
14160: lonnet.perm logfiles.
14161: 
14162: =over 4
14163: 
14164: =item *
14165: 
14166: logtouch() : make sure the logfile, lonnet.log, exists
14167: 
14168: =item *
14169: 
14170: logthis() : append message to the normal lonnet.log file, it gets
14171: preiodically rolled over and deleted.
14172: 
14173: =item *
14174: 
14175: logperm() : append a permanent message to lonnet.perm.log, this log
14176: file never gets deleted by any automated portion of the system, only
14177: messages of critical importance should go in here.
14178: 
14179: 
14180: =back
14181: 
14182: =head2 General File Helper Routines
14183: 
14184: =over 4
14185: 
14186: =item *
14187: 
14188: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
14189: (a) files in /uploaded
14190:   (i) If a local copy of the file exists - 
14191:       compares modification date of local copy with last-modified date for 
14192:       definitive version stored on home server for course. If local copy is 
14193:       stale, requests a new version from the home server and stores it. 
14194:       If the original has been removed from the home server, then local copy 
14195:       is unlinked.
14196:   (ii) If local copy does not exist -
14197:       requests the file from the home server and stores it. 
14198:   
14199:   If $caller is 'uploadrep':  
14200:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
14201:     for request for files originally uploaded via DOCS. 
14202:      - returns 'ok' if fresh local copy now available, -1 otherwise.
14203:   
14204:   Otherwise:
14205:      This indicates a call from the content generation phase of the request.
14206:      -  returns the entire contents of the file or -1.
14207:      
14208: (b) files in /res
14209:    - returns the entire contents of a file or -1; 
14210:    it properly subscribes to and replicates the file if neccessary.
14211: 
14212: 
14213: =item *
14214: 
14215: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
14216:                   reference
14217: 
14218: returns either a stat() list of data about the file or an empty list
14219: if the file doesn't exist or couldn't find out about it (connection
14220: problems or user unknown)
14221: 
14222: =item *
14223: 
14224: filelocation($dir,$file) : returns file system location of a file
14225: based on URI; meant to be "fairly clean" absolute reference, $dir is a
14226: directory that relative $file lookups are to looked in ($dir of /a/dir
14227: and a file of ../bob will become /a/bob)
14228: 
14229: =item *
14230: 
14231: hreflocation($dir,$file) : returns file system location or a URL; same as
14232: filelocation except for hrefs
14233: 
14234: =item *
14235: 
14236: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
14237: also removes beginning /home/httpd/html unless /priv/ follows it.
14238: 
14239: =back
14240: 
14241: =head2 Usererfile file routines (/uploaded*)
14242: 
14243: =over 4
14244: 
14245: =item *
14246: 
14247: userfileupload(): main rotine for putting a file in a user or course's
14248:                   filespace, arguments are,
14249: 
14250:  formname - required - this is the name of the element in $env where the
14251:            filename, and the contents of the file to create/modifed exist
14252:            the filename is in $env{'form.'.$formname.'.filename'} and the
14253:            contents of the file is located in $env{'form.'.$formname}
14254:  context - if coursedoc, store the file in the course of the active role
14255:              of the current user; 
14256:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
14257:            if 'canceloverwrite': delete file in tmp/overwrites directory
14258:  subdir - required - subdirectory to put the file in under ../userfiles/
14259:          if undefined, it will be placed in "unknown"
14260: 
14261:  (This routine calls clean_filename() to remove any dangerous
14262:  characters from the filename, and then calls finuserfileupload() to
14263:  complete the transaction)
14264: 
14265:  returns either the url of the uploaded file (/uploaded/....) if successful
14266:  and /adm/notfound.html if unsuccessful
14267: 
14268: =item *
14269: 
14270: clean_filename(): routine for cleaing a filename up for storage in
14271:                  userfile space, argument is:
14272: 
14273:  filename - proposed filename
14274: 
14275: returns: the new clean filename
14276: 
14277: =item *
14278: 
14279: finishuserfileupload(): routine that creates and sends the file to
14280: userspace, probably shouldn't be called directly
14281: 
14282:   docuname: username or courseid of destination for the file
14283:   docudom: domain of user/course of destination for the file
14284:   formname: same as for userfileupload()
14285:   fname: filename (including subdirectories) for the file
14286:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
14287:   allfiles: reference to hash used to store objects found by parser
14288:   codebase: reference to hash used for codebases of java objects found by parser
14289:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
14290:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
14291:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
14292:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
14293:   context: if 'overwrite', will move the uploaded file from its temporary location to
14294:             userfiles to facilitate overwriting a previously uploaded file with same name.
14295:   mimetype: reference to scalar to accommodate mime type determined
14296:             from File::MMagic if $parser = parse.
14297: 
14298:  returns either the url of the uploaded file (/uploaded/....) if successful
14299:  and /adm/notfound.html if unsuccessful (or an error message if context 
14300:  was 'overwrite').
14301:  
14302: 
14303: =item *
14304: 
14305: renameuserfile(): renames an existing userfile to a new name
14306: 
14307:   Args:
14308:    docuname: username or courseid of destination for the file
14309:    docudom: domain of user/course of destination for the file
14310:    old: current file name (including any subdirs under userfiles)
14311:    new: desired file name (including any subdirs under userfiles)
14312: 
14313: =item *
14314: 
14315: mkdiruserfile(): creates a directory is a userfiles dir
14316: 
14317:   Args:
14318:    docuname: username or courseid of destination for the file
14319:    docudom: domain of user/course of destination for the file
14320:    dir: dir to create (including any subdirs under userfiles)
14321: 
14322: =item *
14323: 
14324: removeuserfile(): removes a file that exists in userfiles
14325: 
14326:   Args:
14327:    docuname: username or courseid of destination for the file
14328:    docudom: domain of user/course of destination for the file
14329:    fname: filname to delete (including any subdirs under userfiles)
14330: 
14331: =item *
14332: 
14333: removeuploadedurl(): convience function for removeuserfile()
14334: 
14335:   Args:
14336:    url:  a full /uploaded/... url to delete
14337: 
14338: =item * 
14339: 
14340: get_portfile_permissions():
14341:   Args:
14342:     domain: domain of user or course contain the portfolio files
14343:     user: name of user or num of course contain the portfolio files
14344:   Returns:
14345:     hashref of a dump of the proper file_permissions.db
14346:    
14347: 
14348: =item * 
14349: 
14350: get_access_controls():
14351: 
14352: Args:
14353:   current_permissions: the hash ref returned from get_portfile_permissions()
14354:   group: (optional) the group you want the files associated with
14355:   file: (optional) the file you want access info on
14356: 
14357: Returns:
14358:     a hash (keys are file names) of hashes containing
14359:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
14360:         values are XML containing access control settings (see below) 
14361: 
14362: Internal notes:
14363: 
14364:  access controls are stored in file_permissions.db as key=value pairs.
14365:     key -> path to file/file_name\0uniqueID:scope_end_start
14366:         where scope -> public,guest,course,group,domains or users.
14367:               end -> UNIX time for end of access (0 -> no end date)
14368:               start -> UNIX time for start of access
14369: 
14370:     value -> XML description of access control
14371:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
14372:             <start></start>
14373:             <end></end>
14374: 
14375:             <password></password>  for scope type = guest
14376: 
14377:             <domain></domain>     for scope type = course or group
14378:             <number></number>
14379:             <roles id="">
14380:              <role></role>
14381:              <access></access>
14382:              <section></section>
14383:              <group></group>
14384:             </roles>
14385: 
14386:             <dom></dom>         for scope type = domains
14387: 
14388:             <users>             for scope type = users
14389:              <user>
14390:               <uname></uname>
14391:               <udom></udom>
14392:              </user>
14393:             </users>
14394:            </scope> 
14395:               
14396:  Access data is also aggregated for each file in an additional key=value pair:
14397:  key -> path to file/file_name\0accesscontrol 
14398:  value -> reference to hash
14399:           hash contains key = value pairs
14400:           where key = uniqueID:scope_end_start
14401:                 value = UNIX time record was last updated
14402: 
14403:           Used to improve speed of look-ups of access controls for each file.  
14404:  
14405:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
14406: 
14407: =item *
14408: 
14409: modify_access_controls():
14410: 
14411: Modifies access controls for a portfolio file
14412: Args
14413: 1. file name
14414: 2. reference to hash of required changes,
14415: 3. domain
14416: 4. username
14417:   where domain,username are the domain of the portfolio owner 
14418:   (either a user or a course) 
14419: 
14420: Returns:
14421: 1. result of additions or updates ('ok' or 'error', with error message). 
14422: 2. result of deletions ('ok' or 'error', with error message).
14423: 3. reference to hash of any new or updated access controls.
14424: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
14425:    key = integer (inbound ID)
14426:    value = uniqueID
14427: 
14428: =item *
14429: 
14430: get_timebased_id():
14431: 
14432: Attempts to get a unique timestamp-based suffix for use with items added to a 
14433: course via the Course Editor (e.g., folders, composite pages, 
14434: group bulletin boards).
14435: 
14436: Args: (first three required; six others optional)
14437: 
14438: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
14439:    docssequence, or name of group
14440: 
14441: 2. keyid (alphanumeric): name of temporary locking key in hash,
14442:    e.g., num, boardids
14443: 
14444: 3. namespace: name of gdbm file used to store suffixes already assigned;  
14445:    file will be named nohist_namespace.db
14446: 
14447: 4. cdom: domain of course; default is current course domain from %env
14448: 
14449: 5. cnum: course number; default is current course number from %env
14450: 
14451: 6. idtype: set to concat if an additional digit is to be appended to the 
14452:    unix timestamp to form the suffix, if the plain timestamp is already
14453:    in use.  Default is to not do this, but simply increment the unix 
14454:    timestamp by 1 until a unique key is obtained.
14455: 
14456: 7. who: holder of locking key; defaults to user:domain for user.
14457: 
14458: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
14459:    retrying); default is 3.
14460: 
14461: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
14462: 
14463: Returns:
14464: 
14465: 1. suffix obtained (numeric)
14466: 
14467: 2. result of deleting locking key (ok if deleted, or lock never obtained)
14468: 
14469: 3. error: contains (localized) error message if an error occurred.
14470: 
14471: 
14472: =back
14473: 
14474: =head2 HTTP Helper Routines
14475: 
14476: =over 4
14477: 
14478: =item *
14479: 
14480: escape() : unpack non-word characters into CGI-compatible hex codes
14481: 
14482: =item *
14483: 
14484: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
14485: 
14486: =back
14487: 
14488: =head1 PRIVATE SUBROUTINES
14489: 
14490: =head2 Underlying communication routines (Shouldn't call)
14491: 
14492: =over 4
14493: 
14494: =item *
14495: 
14496: subreply() : tries to pass a message to lonc, returns con_lost if incapable
14497: 
14498: =item *
14499: 
14500: reply() : uses subreply to send a message to remote machine, logs all failures
14501: 
14502: =item *
14503: 
14504: critical() : passes a critical message to another server; if cannot
14505: get through then place message in connection buffer directory and
14506: returns con_delayed, if incapable of saving message, returns
14507: con_failed
14508: 
14509: =item *
14510: 
14511: reconlonc() : tries to reconnect lonc client processes.
14512: 
14513: =back
14514: 
14515: =head2 Resource Access Logging
14516: 
14517: =over 4
14518: 
14519: =item *
14520: 
14521: flushcourselogs() : flush (save) buffer logs and access logs
14522: 
14523: =item *
14524: 
14525: courselog($what) : save message for course in hash
14526: 
14527: =item *
14528: 
14529: courseacclog($what) : save message for course using &courselog().  Perform
14530: special processing for specific resource types (problems, exams, quizzes, etc).
14531: 
14532: =item *
14533: 
14534: goodbye() : flush course logs and log shutting down; it is called in srm.conf
14535: as a PerlChildExitHandler
14536: 
14537: =back
14538: 
14539: =head2 Other
14540: 
14541: =over 4
14542: 
14543: =item *
14544: 
14545: symblist($mapname,%newhash) : update symbolic storage links
14546: 
14547: =back
14548: 
14549: =cut
14550: 

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