File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1172.2.62: download - view: text, annotated - select for diffs
Wed Apr 1 23:43:55 2015 UTC (9 years, 2 months ago) by raeburn
Branches: version_2_11_X
- For 2.11
  Backport 1.1279.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1172.2.62 2015/04/01 23:43:55 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: =pod
   31: 
   32: =head1 NAME
   33: 
   34: Apache::lonnet.pm
   35: 
   36: =head1 SYNOPSIS
   37: 
   38: This file is an interface to the lonc processes of
   39: the LON-CAPA network as well as set of elaborated functions for handling information
   40: necessary for navigating through a given cluster of LON-CAPA machines within a
   41: domain. There are over 40 specialized functions in this module which handle the
   42: reading and transmission of metadata, user information (ids, names, environments, roles,
   43: logs), file information (storage, reading, directories, extensions, replication, embedded
   44: styles and descriptors), educational resources (course descriptions, section names and
   45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
   46: and from more descriptive phrases or explanations.
   47: 
   48: This is part of the LearningOnline Network with CAPA project
   49: described at http://www.lon-capa.org.
   50: 
   51: =head1 Package Variables
   52: 
   53: These are largely undocumented, so if you decipher one please note it here.
   54: 
   55: =over 4
   56: 
   57: =item $processmarker
   58: 
   59: Contains the time this process was started and this servers host id.
   60: 
   61: =item $dumpcount
   62: 
   63: Counts the number of times a message log flush has been attempted (regardless
   64: of success) by this process.  Used as part of the filename when messages are
   65: delayed.
   66: 
   67: =back
   68: 
   69: =cut
   70: 
   71: package Apache::lonnet;
   72: 
   73: use strict;
   74: use LWP::UserAgent();
   75: use HTTP::Date;
   76: use Image::Magick;
   77: 
   78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
   79:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
   80:             %managerstab);
   81: 
   82: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   83:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   84:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   85:     %courseownerbuf, %coursetypebuf,$locknum);
   86: 
   87: use IO::Socket;
   88: use GDBM_File;
   89: use HTML::LCParser;
   90: use Fcntl qw(:flock);
   91: use Storable qw(thaw nfreeze);
   92: use Time::HiRes qw( gettimeofday tv_interval );
   93: use Cache::Memcached;
   94: use Digest::MD5;
   95: use Math::Random;
   96: use File::MMagic;
   97: use LONCAPA qw(:DEFAULT :match);
   98: use LONCAPA::Configuration;
   99: use LONCAPA::lonmetadata;
  100: use LONCAPA::Lond;
  101: 
  102: use File::Copy;
  103: 
  104: my $readit;
  105: my $max_connection_retries = 10;     # Or some such value.
  106: 
  107: require Exporter;
  108: 
  109: our @ISA = qw (Exporter);
  110: our @EXPORT = qw(%env);
  111: 
  112: # ------------------------------------ Logging (parameters, docs, slots, roles)
  113: {
  114:     my $logid;
  115:     sub write_log {
  116: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  117:         if ($context eq 'course') {
  118:             if (($cnum eq '') || ($cdom eq '')) {
  119:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  120:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  121:             }
  122:         }
  123: 	$logid ++;
  124:         my $now = time();
  125: 	my $id=$now.'00000'.$$.'00000'.$logid;
  126:         my $logentry = {
  127:                          $id => {
  128:                                   'exe_uname' => $env{'user.name'},
  129:                                   'exe_udom'  => $env{'user.domain'},
  130:                                   'exe_time'  => $now,
  131:                                   'exe_ip'    => $ENV{'REMOTE_ADDR'},
  132:                                   'delflag'   => $delflag,
  133:                                   'logentry'  => $storehash,
  134:                                   'uname'     => $uname,
  135:                                   'udom'      => $udom,
  136:                                 }
  137:                        };
  138:         return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
  139:     }
  140: }
  141: 
  142: sub logtouch {
  143:     my $execdir=$perlvar{'lonDaemons'};
  144:     unless (-e "$execdir/logs/lonnet.log") {	
  145: 	open(my $fh,">>$execdir/logs/lonnet.log");
  146: 	close $fh;
  147:     }
  148:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  149:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  150: }
  151: 
  152: sub logthis {
  153:     my $message=shift;
  154:     my $execdir=$perlvar{'lonDaemons'};
  155:     my $now=time;
  156:     my $local=localtime($now);
  157:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  158: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  159: 	print $fh $logstring;
  160: 	close($fh);
  161:     }
  162:     return 1;
  163: }
  164: 
  165: sub logperm {
  166:     my $message=shift;
  167:     my $execdir=$perlvar{'lonDaemons'};
  168:     my $now=time;
  169:     my $local=localtime($now);
  170:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  171: 	print $fh "$now:$message:$local\n";
  172: 	close($fh);
  173:     }
  174:     return 1;
  175: }
  176: 
  177: sub create_connection {
  178:     my ($hostname,$lonid) = @_;
  179:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  180: 				     Type    => SOCK_STREAM,
  181: 				     Timeout => 10);
  182:     return 0 if (!$client);
  183:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  184:     my $result = <$client>;
  185:     chomp($result);
  186:     return 1 if ($result eq 'done');
  187:     return 0;
  188: }
  189: 
  190: sub get_server_timezone {
  191:     my ($cnum,$cdom) = @_;
  192:     my $home=&homeserver($cnum,$cdom);
  193:     if ($home ne 'no_host') {
  194:         my $cachetime = 24*3600;
  195:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  196:         if (defined($cached)) {
  197:             return $timezone;
  198:         } else {
  199:             my $timezone = &reply('servertimezone',$home);
  200:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  201:         }
  202:     }
  203: }
  204: 
  205: sub get_server_distarch {
  206:     my ($lonhost,$ignore_cache) = @_;
  207:     if (defined($lonhost)) {
  208:         if (!defined(&hostname($lonhost))) {
  209:             return;
  210:         }
  211:         my $cachetime = 12*3600;
  212:         if (!$ignore_cache) {
  213:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  214:             if (defined($cached)) {
  215:                 return $distarch;
  216:             }
  217:         }
  218:         my $rep = &reply('serverdistarch',$lonhost);
  219:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  220:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  221:                 $rep eq '') {
  222:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  223:         }
  224:     }
  225:     return;
  226: }
  227: 
  228: sub get_server_loncaparev {
  229:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  230:     if (defined($lonhost)) {
  231:         if (!defined(&hostname($lonhost))) {
  232:             undef($lonhost);
  233:         }
  234:     }
  235:     if (!defined($lonhost)) {
  236:         if (defined(&domain($dom,'primary'))) {
  237:             $lonhost=&domain($dom,'primary');
  238:             if ($lonhost eq 'no_host') {
  239:                 undef($lonhost);
  240:             }
  241:         }
  242:     }
  243:     if (defined($lonhost)) {
  244:         my $cachetime = 12*3600;
  245:         if (!$ignore_cache) {
  246:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  247:             if (defined($cached)) {
  248:                 return $loncaparev;
  249:             }
  250:         }
  251:         my ($answer,$loncaparev);
  252:         my @ids=&current_machine_ids();
  253:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  254:             $answer = $perlvar{'lonVersion'};
  255:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  256:                 $loncaparev = $1;
  257:             }
  258:         } else {
  259:             $answer = &reply('serverloncaparev',$lonhost);
  260:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  261:                 if ($caller eq 'loncron') {
  262:                     my $ua=new LWP::UserAgent;
  263:                     $ua->timeout(4);
  264:                     my $protocol = $protocol{$lonhost};
  265:                     $protocol = 'http' if ($protocol ne 'https');
  266:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
  267:                     my $request=new HTTP::Request('GET',$url);
  268:                     my $response=$ua->request($request);
  269:                     unless ($response->is_error()) {
  270:                         my $content = $response->content;
  271:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  272:                             $loncaparev = $1;
  273:                         }
  274:                     }
  275:                 } else {
  276:                     $loncaparev = $loncaparevs{$lonhost};
  277:                 }
  278:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  279:                 $loncaparev = $1;
  280:             }
  281:         }
  282:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  283:     }
  284: }
  285: 
  286: sub get_server_homeID {
  287:     my ($hostname,$ignore_cache,$caller) = @_;
  288:     unless ($ignore_cache) {
  289:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  290:         if (defined($cached)) {
  291:             return $serverhomeID;
  292:         }
  293:     }
  294:     my $cachetime = 12*3600;
  295:     my $serverhomeID;
  296:     if ($caller eq 'loncron') { 
  297:         my @machine_ids = &machine_ids($hostname);
  298:         foreach my $id (@machine_ids) {
  299:             my $response = &reply('serverhomeID',$id);
  300:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  301:                 $serverhomeID = $response;
  302:                 last;
  303:             }
  304:         }
  305:         if ($serverhomeID eq '') {
  306:             $serverhomeID = $machine_ids[-1];
  307:         }
  308:     } else {
  309:         $serverhomeID = $serverhomeIDs{$hostname};
  310:     }
  311:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  312: }
  313: 
  314: sub get_remote_globals {
  315:     my ($lonhost,$whathash,$ignore_cache) = @_;
  316:     my ($result,%returnhash,%whatneeded);
  317:     if (ref($whathash) eq 'HASH') {
  318:         foreach my $what (sort(keys(%{$whathash}))) {
  319:             my $hashid = $lonhost.'-'.$what;
  320:             my ($response,$cached);
  321:             unless ($ignore_cache) {
  322:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  323:             }
  324:             if (defined($cached)) {
  325:                 $returnhash{$what} = $response;
  326:             } else {
  327:                 $whatneeded{$what} = 1;
  328:             }
  329:         }
  330:         if (keys(%whatneeded) == 0) {
  331:             $result = 'ok';
  332:         } else {
  333:             my $requested = &freeze_escape(\%whatneeded);
  334:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  335:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  336:                 ($rep eq 'unknown_cmd')) {
  337:                 $result = $rep;
  338:             } else {
  339:                 $result = 'ok';
  340:                 my @pairs=split(/\&/,$rep);
  341:                 foreach my $item (@pairs) {
  342:                     my ($key,$value)=split(/=/,$item,2);
  343:                     my $what = &unescape($key);
  344:                     my $hashid = $lonhost.'-'.$what;
  345:                     $returnhash{$what}=&thaw_unescape($value);
  346:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  347:                 }
  348:             }
  349:         }
  350:     }
  351:     return ($result,\%returnhash);
  352: }
  353: 
  354: sub remote_devalidate_cache {
  355:     my ($lonhost,$cachekeys) = @_;
  356:     my $items;
  357:     return unless (ref($cachekeys) eq 'ARRAY');
  358:     my $cachestr = join('&',@{$cachekeys});
  359:     return &reply('devalidatecache:'.&escape($cachestr),$lonhost);
  360: }
  361: 
  362: # -------------------------------------------------- Non-critical communication
  363: sub subreply {
  364:     my ($cmd,$server)=@_;
  365:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  366:     #
  367:     #  With loncnew process trimming, there's a timing hole between lonc server
  368:     #  process exit and the master server picking up the listen on the AF_UNIX
  369:     #  socket.  In that time interval, a lock file will exist:
  370: 
  371:     my $lockfile=$peerfile.".lock";
  372:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  373: 	sleep(1);
  374:     }
  375:     # At this point, either a loncnew parent is listening or an old lonc
  376:     # or loncnew child is listening so we can connect or everything's dead.
  377:     #
  378:     #   We'll give the connection a few tries before abandoning it.  If
  379:     #   connection is not possible, we'll con_lost back to the client.
  380:     #   
  381:     my $client;
  382:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  383: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  384: 				      Type    => SOCK_STREAM,
  385: 				      Timeout => 10);
  386: 	if ($client) {
  387: 	    last;		# Connected!
  388: 	} else {
  389: 	    &create_connection(&hostname($server),$server);
  390: 	}
  391:         sleep(1);		# Try again later if failed connection.
  392:     }
  393:     my $answer;
  394:     if ($client) {
  395: 	print $client "sethost:$server:$cmd\n";
  396: 	$answer=<$client>;
  397: 	if (!$answer) { $answer="con_lost"; }
  398: 	chomp($answer);
  399:     } else {
  400: 	$answer = 'con_lost';	# Failed connection.
  401:     }
  402:     return $answer;
  403: }
  404: 
  405: sub reply {
  406:     my ($cmd,$server)=@_;
  407:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  408:     my $answer=subreply($cmd,$server);
  409:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  410:        &logthis("<font color=\"blue\">WARNING:".
  411:                 " $cmd to $server returned $answer</font>");
  412:     }
  413:     return $answer;
  414: }
  415: 
  416: # ----------------------------------------------------------- Send USR1 to lonc
  417: 
  418: sub reconlonc {
  419:     my ($lonid) = @_;
  420:     my $hostname = &hostname($lonid);
  421:     if ($lonid) {
  422: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  423: 	if ($hostname && -e $peerfile) {
  424: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  425: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  426: 					     Type    => SOCK_STREAM,
  427: 					     Timeout => 10);
  428: 	    if ($client) {
  429: 		print $client ("reset_retries\n");
  430: 		my $answer=<$client>;
  431: 		#reset just this one.
  432: 	    }
  433: 	}
  434: 	return;
  435:     }
  436: 
  437:     &logthis("Trying to reconnect lonc");
  438:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  439:     if (open(my $fh,"<$loncfile")) {
  440: 	my $loncpid=<$fh>;
  441:         chomp($loncpid);
  442:         if (kill 0 => $loncpid) {
  443: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  444:             kill USR1 => $loncpid;
  445:             sleep 1;
  446:          } else {
  447: 	    &logthis(
  448:                "<font color=\"blue\">WARNING:".
  449:                " lonc at pid $loncpid not responding, giving up</font>");
  450:         }
  451:     } else {
  452: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  453:     }
  454: }
  455: 
  456: # ------------------------------------------------------ Critical communication
  457: 
  458: sub critical {
  459:     my ($cmd,$server)=@_;
  460:     unless (&hostname($server)) {
  461:         &logthis("<font color=\"blue\">WARNING:".
  462:                " Critical message to unknown server ($server)</font>");
  463:         return 'no_such_host';
  464:     }
  465:     my $answer=reply($cmd,$server);
  466:     if ($answer eq 'con_lost') {
  467: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  468: 	my $answer=reply($cmd,$server);
  469:         if ($answer eq 'con_lost') {
  470:             my $now=time;
  471:             my $middlename=$cmd;
  472:             $middlename=substr($middlename,0,16);
  473:             $middlename=~s/\W//g;
  474:             my $dfilename=
  475:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  476:             $dumpcount++;
  477:             {
  478: 		my $dfh;
  479: 		if (open($dfh,">$dfilename")) {
  480: 		    print $dfh "$cmd\n"; 
  481: 		    close($dfh);
  482: 		}
  483:             }
  484:             sleep 2;
  485:             my $wcmd='';
  486:             {
  487: 		my $dfh;
  488: 		if (open($dfh,"<$dfilename")) {
  489: 		    $wcmd=<$dfh>; 
  490: 		    close($dfh);
  491: 		}
  492:             }
  493:             chomp($wcmd);
  494:             if ($wcmd eq $cmd) {
  495: 		&logthis("<font color=\"blue\">WARNING: ".
  496:                          "Connection buffer $dfilename: $cmd</font>");
  497:                 &logperm("D:$server:$cmd");
  498: 	        return 'con_delayed';
  499:             } else {
  500:                 &logthis("<font color=\"red\">CRITICAL:"
  501:                         ." Critical connection failed: $server $cmd</font>");
  502:                 &logperm("F:$server:$cmd");
  503:                 return 'con_failed';
  504:             }
  505:         }
  506:     }
  507:     return $answer;
  508: }
  509: 
  510: # ------------------------------------------- check if return value is an error
  511: 
  512: sub error {
  513:     my ($result) = @_;
  514:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  515: 	if ($2 == 2) { return undef; }
  516: 	return $1;
  517:     }
  518:     return undef;
  519: }
  520: 
  521: sub convert_and_load_session_env {
  522:     my ($lonidsdir,$handle)=@_;
  523:     my @profile;
  524:     {
  525: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  526: 	if (!$opened) {
  527: 	    return 0;
  528: 	}
  529: 	flock($idf,LOCK_SH);
  530: 	@profile=<$idf>;
  531: 	close($idf);
  532:     }
  533:     my %temp_env;
  534:     foreach my $line (@profile) {
  535: 	if ($line !~ m/=/) {
  536: 	    return 0;
  537: 	}
  538: 	chomp($line);
  539: 	my ($envname,$envvalue)=split(/=/,$line,2);
  540: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  541:     }
  542:     unlink("$lonidsdir/$handle.id");
  543:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  544: 	    0640)) {
  545: 	%disk_env = %temp_env;
  546: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  547: 	untie(%disk_env);
  548:     }
  549:     return 1;
  550: }
  551: 
  552: # ------------------------------------------- Transfer profile into environment
  553: my $env_loaded;
  554: sub transfer_profile_to_env {
  555:     my ($lonidsdir,$handle,$force_transfer) = @_;
  556:     if (!$force_transfer && $env_loaded) { return; } 
  557: 
  558:     if (!defined($lonidsdir)) {
  559: 	$lonidsdir = $perlvar{'lonIDsDir'};
  560:     }
  561:     if (!defined($handle)) {
  562:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  563:     }
  564: 
  565:     my $convert;
  566:     {
  567:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  568: 	if (!$opened) {
  569: 	    return;
  570: 	}
  571: 	flock($idf,LOCK_SH);
  572: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  573: 		&GDBM_READER(),0640)) {
  574: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  575: 	    untie(%disk_env);
  576: 	} else {
  577: 	    $convert = 1;
  578: 	}
  579:     }
  580:     if ($convert) {
  581: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  582: 	    &logthis("Failed to load session, or convert session.");
  583: 	}
  584:     }
  585: 
  586:     my %remove;
  587:     while ( my $envname = each(%env) ) {
  588:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  589:             if ($time < time-300) {
  590:                 $remove{$key}++;
  591:             }
  592:         }
  593:     }
  594: 
  595:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  596:     $env_loaded=1;
  597:     foreach my $expired_key (keys(%remove)) {
  598:         &delenv($expired_key);
  599:     }
  600: }
  601: 
  602: # ---------------------------------------------------- Check for valid session 
  603: sub check_for_valid_session {
  604:     my ($r,$name,$userhashref) = @_;
  605:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  606:     if ($name eq '') {
  607:         $name = 'lonID';
  608:     }
  609:     my $lonid=$cookies{$name};
  610:     return undef if (!$lonid);
  611: 
  612:     my $handle=&LONCAPA::clean_handle($lonid->value);
  613:     my $lonidsdir;
  614:     if ($name eq 'lonDAV') {
  615:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  616:     } else {
  617:         $lonidsdir=$r->dir_config('lonIDsDir');
  618:     }
  619:     return undef if (!-e "$lonidsdir/$handle.id");
  620: 
  621:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  622:     return undef if (!$opened);
  623: 
  624:     flock($idf,LOCK_SH);
  625:     my %disk_env;
  626:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  627: 	    &GDBM_READER(),0640)) {
  628: 	return undef;	
  629:     }
  630: 
  631:     if (!defined($disk_env{'user.name'})
  632: 	|| !defined($disk_env{'user.domain'})) {
  633: 	return undef;
  634:     }
  635: 
  636:     if (ref($userhashref) eq 'HASH') {
  637:         $userhashref->{'name'} = $disk_env{'user.name'};
  638:         $userhashref->{'domain'} = $disk_env{'user.domain'};
  639:     }
  640: 
  641:     return $handle;
  642: }
  643: 
  644: sub timed_flock {
  645:     my ($file,$lock_type) = @_;
  646:     my $failed=0;
  647:     eval {
  648: 	local $SIG{__DIE__}='DEFAULT';
  649: 	local $SIG{ALRM}=sub {
  650: 	    $failed=1;
  651: 	    die("failed lock");
  652: 	};
  653: 	alarm(13);
  654: 	flock($file,$lock_type);
  655: 	alarm(0);
  656:     };
  657:     if ($failed) {
  658: 	return undef;
  659:     } else {
  660: 	return 1;
  661:     }
  662: }
  663: 
  664: # ---------------------------------------------------------- Append Environment
  665: 
  666: sub appenv {
  667:     my ($newenv,$roles) = @_;
  668:     if (ref($newenv) eq 'HASH') {
  669:         foreach my $key (keys(%{$newenv})) {
  670:             my $refused = 0;
  671: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  672:                 $refused = 1;
  673:                 if (ref($roles) eq 'ARRAY') {
  674:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
  675:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  676:                         $refused = 0;
  677:                     }
  678:                 }
  679:             }
  680:             if ($refused) {
  681:                 &logthis("<font color=\"blue\">WARNING: ".
  682:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  683:                          .'</font>');
  684: 	        delete($newenv->{$key});
  685:             } else {
  686:                 $env{$key}=$newenv->{$key};
  687:             }
  688:         }
  689:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  690:         if ($opened
  691: 	    && &timed_flock($env_file,LOCK_EX)
  692: 	    &&
  693: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  694: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  695: 	    while (my ($key,$value) = each(%{$newenv})) {
  696: 	        $disk_env{$key} = $value;
  697: 	    }
  698: 	    untie(%disk_env);
  699:         }
  700:     }
  701:     return 'ok';
  702: }
  703: # ----------------------------------------------------- Delete from Environment
  704: 
  705: sub delenv {
  706:     my ($delthis,$regexp,$roles) = @_;
  707:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  708:         my $refused = 1;
  709:         if (ref($roles) eq 'ARRAY') {
  710:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  711:             if (grep(/^\Q$role\E$/,@{$roles})) {
  712:                 $refused = 0;
  713:             }
  714:         }
  715:         if ($refused) {
  716:             &logthis("<font color=\"blue\">WARNING: ".
  717:                      "Attempt to delete from environment ".$delthis);
  718:             return 'error';
  719:         }
  720:     }
  721:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  722:     if ($opened
  723: 	&& &timed_flock($env_file,LOCK_EX)
  724: 	&&
  725: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  726: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  727: 	foreach my $key (keys(%disk_env)) {
  728: 	    if ($regexp) {
  729:                 if ($key=~/^$delthis/) {
  730:                     delete($env{$key});
  731:                     delete($disk_env{$key});
  732:                 } 
  733:             } else {
  734:                 if ($key=~/^\Q$delthis\E/) {
  735: 		    delete($env{$key});
  736: 		    delete($disk_env{$key});
  737: 	        }
  738:             }
  739: 	}
  740: 	untie(%disk_env);
  741:     }
  742:     return 'ok';
  743: }
  744: 
  745: sub get_env_multiple {
  746:     my ($name) = @_;
  747:     my @values;
  748:     if (defined($env{$name})) {
  749:         # exists is it an array
  750:         if (ref($env{$name})) {
  751:             @values=@{ $env{$name} };
  752:         } else {
  753:             $values[0]=$env{$name};
  754:         }
  755:     }
  756:     return(@values);
  757: }
  758: 
  759: # ------------------------------------------------------------------- Locking
  760: 
  761: sub set_lock {
  762:     my ($text)=@_;
  763:     $locknum++;
  764:     my $id=$$.'-'.$locknum;
  765:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  766:              'session.lock.'.$id => $text});
  767:     return $id;
  768: }
  769: 
  770: sub get_locks {
  771:     my $num=0;
  772:     my %texts=();
  773:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  774:        if ($lock=~/\w/) {
  775:           $num++;
  776:           $texts{$lock}=$env{'session.lock.'.$lock};
  777:        }
  778:    }
  779:    return ($num,%texts);
  780: }
  781: 
  782: sub remove_lock {
  783:     my ($id)=@_;
  784:     my $newlocks='';
  785:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  786:        if (($lock=~/\w/) && ($lock ne $id)) {
  787:           $newlocks.=','.$lock;
  788:        }
  789:     }
  790:     &appenv({'session.locks' => $newlocks});
  791:     &delenv('session.lock.'.$id);
  792: }
  793: 
  794: sub remove_all_locks {
  795:     my $activelocks=$env{'session.locks'};
  796:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  797:        if ($lock=~/\w/) {
  798:           &remove_lock($lock);
  799:        }
  800:     }
  801: }
  802: 
  803: 
  804: # ------------------------------------------ Find out current server userload
  805: sub userload {
  806:     my $numusers=0;
  807:     {
  808: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  809: 	my $filename;
  810: 	my $curtime=time;
  811: 	while ($filename=readdir(LONIDS)) {
  812: 	    next if ($filename eq '.' || $filename eq '..');
  813: 	    next if ($filename =~ /publicuser_\d+\.id/);
  814: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  815: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  816: 	}
  817: 	closedir(LONIDS);
  818:     }
  819:     my $userloadpercent=0;
  820:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  821:     if ($maxuserload) {
  822: 	$userloadpercent=100*$numusers/$maxuserload;
  823:     }
  824:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  825:     return $userloadpercent;
  826: }
  827: 
  828: # ------------------------------ Find server with least workload from spare.tab
  829: 
  830: sub spareserver {
  831:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  832:     my $spare_server;
  833:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  834:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  835:                                                      :  $userloadpercent;
  836:     my ($uint_dom,$remotesessions);
  837:     if (($udom ne '') && (&domain($udom) ne '')) {
  838:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  839:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  840:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  841:         $remotesessions = $udomdefaults{'remotesessions'};
  842:     }
  843:     my $spareshash = &this_host_spares($udom);
  844:     if (ref($spareshash) eq 'HASH') {
  845:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  846:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  847:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  848:                                              $try_server));
  849: 	        ($spare_server, $lowest_load) =
  850: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  851:             }
  852:         }
  853: 
  854:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
  855: 
  856:         if (!$found_server) {
  857:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
  858: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
  859:                     next unless (&spare_can_host($udom,$uint_dom,
  860:                                                  $remotesessions,$try_server));
  861: 	            ($spare_server, $lowest_load) =
  862: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
  863:                 }
  864: 	    }
  865:         }
  866:     }
  867: 
  868:     if (!$want_server_name) {
  869:         my $protocol = 'http';
  870:         if ($protocol{$spare_server} eq 'https') {
  871:             $protocol = $protocol{$spare_server};
  872:         }
  873:         if (defined($spare_server)) {
  874:             my $hostname = &hostname($spare_server);
  875:             if (defined($hostname)) {
  876: 	        $spare_server = $protocol.'://'.$hostname;
  877:             }
  878:         }
  879:     }
  880:     return $spare_server;
  881: }
  882: 
  883: sub compare_server_load {
  884:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
  885: 
  886:     if ($required) {
  887:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
  888:         my $remoterev = &get_server_loncaparev(undef,$try_server);
  889:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
  890:         if (($major eq '' && $minor eq '') ||
  891:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
  892:             return ($spare_server,$lowest_load);
  893:         }
  894:     }
  895: 
  896:     my $loadans     = &reply('load',    $try_server);
  897:     my $userloadans = &reply('userload',$try_server);
  898: 
  899:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  900: 	return ($spare_server, $lowest_load); #didn't get a number from the server
  901:     }
  902: 
  903:     my $load;
  904:     if ($loadans =~ /\d/) {
  905: 	if ($userloadans =~ /\d/) {
  906: 	    #both are numbers, pick the bigger one
  907: 	    $load = ($loadans > $userloadans) ? $loadans 
  908: 		                              : $userloadans;
  909: 	} else {
  910: 	    $load = $loadans;
  911: 	}
  912:     } else {
  913: 	$load = $userloadans;
  914:     }
  915: 
  916:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  917: 	$spare_server = $try_server;
  918: 	$lowest_load  = $load;
  919:     }
  920:     return ($spare_server,$lowest_load);
  921: }
  922: 
  923: # --------------------------- ask offload servers if user already has a session
  924: sub find_existing_session {
  925:     my ($udom,$uname) = @_;
  926:     my $spareshash = &this_host_spares($udom);
  927:     if (ref($spareshash) eq 'HASH') {
  928:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  929:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  930:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  931:             }
  932:         }
  933:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
  934:             foreach my $try_server (@{ $spareshash->{'default'} }) {
  935:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  936:             }
  937:         }
  938:     }
  939:     return;
  940: }
  941: 
  942: # -------------------------------- ask if server already has a session for user
  943: sub has_user_session {
  944:     my ($lonid,$udom,$uname) = @_;
  945:     my $result = &reply(join(':','userhassession',
  946: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  947:     return 1 if ($result eq 'ok');
  948: 
  949:     return 0;
  950: }
  951: 
  952: # --------- determine least loaded server in a user's domain which allows login
  953: 
  954: sub choose_server {
  955:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
  956:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
  957:     my %servers = &get_servers($udom);
  958:     my $lowest_load = 30000;
  959:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
  960:     if ($skiploadbal) {
  961:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
  962:         unless (defined($cached)) {
  963:             my $cachetime = 60*60*24;
  964:             my %domconfig =
  965:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
  966:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
  967:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
  968:                                            $cachetime);
  969:             }
  970:         }
  971:     }
  972:     foreach my $lonhost (keys(%servers)) {
  973:         my $loginvia;
  974:         if ($skiploadbal) {
  975:             if (ref($balancers) eq 'HASH') {
  976:                 next if (exists($balancers->{$lonhost}));
  977:             }
  978:         }
  979:         if ($checkloginvia) {
  980:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
  981:             if ($loginvia) {
  982:                 my ($server,$path) = split(/:/,$loginvia);
  983:                 ($login_host, $lowest_load) =
  984:                     &compare_server_load($server, $login_host, $lowest_load, $required);
  985:                 if ($login_host eq $server) {
  986:                     $portal_path = $path;
  987:                     $isredirect = 1;
  988:                 }
  989:             } else {
  990:                 ($login_host, $lowest_load) =
  991:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
  992:                 if ($login_host eq $lonhost) {
  993:                     $portal_path = '';
  994:                     $isredirect = ''; 
  995:                 }
  996:             }
  997:         } else {
  998:             ($login_host, $lowest_load) =
  999:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
 1000:         }
 1001:     }
 1002:     if ($login_host ne '') {
 1003:         $hostname = &hostname($login_host);
 1004:     }
 1005:     return ($login_host,$hostname,$portal_path,$isredirect);
 1006: }
 1007: 
 1008: # --------------------------------------------- Try to change a user's password
 1009: 
 1010: sub changepass {
 1011:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
 1012:     $currentpass = &escape($currentpass);
 1013:     $newpass     = &escape($newpass);
 1014:     my $lonhost = $perlvar{'lonHostID'};
 1015:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
 1016: 		       $server);
 1017:     if (! $answer) {
 1018: 	&logthis("No reply on password change request to $server ".
 1019: 		 "by $uname in domain $udom.");
 1020:     } elsif ($answer =~ "^ok") {
 1021:         &logthis("$uname in $udom successfully changed their password ".
 1022: 		 "on $server.");
 1023:     } elsif ($answer =~ "^pwchange_failure") {
 1024: 	&logthis("$uname in $udom was unable to change their password ".
 1025: 		 "on $server.  The action was blocked by either lcpasswd ".
 1026: 		 "or pwchange");
 1027:     } elsif ($answer =~ "^non_authorized") {
 1028:         &logthis("$uname in $udom did not get their password correct when ".
 1029: 		 "attempting to change it on $server.");
 1030:     } elsif ($answer =~ "^auth_mode_error") {
 1031:         &logthis("$uname in $udom attempted to change their password despite ".
 1032: 		 "not being locally or internally authenticated on $server.");
 1033:     } elsif ($answer =~ "^unknown_user") {
 1034:         &logthis("$uname in $udom attempted to change their password ".
 1035: 		 "on $server but were unable to because $server is not ".
 1036: 		 "their home server.");
 1037:     } elsif ($answer =~ "^refused") {
 1038: 	&logthis("$server refused to change $uname in $udom password because ".
 1039: 		 "it was sent an unencrypted request to change the password.");
 1040:     } elsif ($answer =~ "invalid_client") {
 1041:         &logthis("$server refused to change $uname in $udom password because ".
 1042:                  "it was a reset by e-mail originating from an invalid server.");
 1043:     }
 1044:     return $answer;
 1045: }
 1046: 
 1047: # ----------------------- Try to determine user's current authentication scheme
 1048: 
 1049: sub queryauthenticate {
 1050:     my ($uname,$udom)=@_;
 1051:     my $uhome=&homeserver($uname,$udom);
 1052:     if (!$uhome) {
 1053: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1054: 	return 'no_host';
 1055:     }
 1056:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1057:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1058: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1059:     }
 1060:     return $answer;
 1061: }
 1062: 
 1063: # --------- Try to authenticate user from domain's lib servers (first this one)
 1064: 
 1065: sub authenticate {
 1066:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1067:     $upass=&escape($upass);
 1068:     $uname= &LONCAPA::clean_username($uname);
 1069:     my $uhome=&homeserver($uname,$udom,1);
 1070:     my $newhome;
 1071:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1072: # Maybe the machine was offline and only re-appeared again recently?
 1073:         &reconlonc();
 1074: # One more
 1075: 	$uhome=&homeserver($uname,$udom,1);
 1076:         if (($uhome eq 'no_host') && $checkdefauth) {
 1077:             if (defined(&domain($udom,'primary'))) {
 1078:                 $newhome=&domain($udom,'primary');
 1079:             }
 1080:             if ($newhome ne '') {
 1081:                 $uhome = $newhome;
 1082:             }
 1083:         }
 1084: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1085: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1086: 	    return 'no_host';
 1087:         }
 1088:     }
 1089:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1090:     if ($answer eq 'authorized') {
 1091:         if ($newhome) {
 1092:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1093:             return 'no_account_on_host'; 
 1094:         } else {
 1095:             &logthis("User $uname at $udom authorized by $uhome");
 1096:             return $uhome;
 1097:         }
 1098:     }
 1099:     if ($answer eq 'non_authorized') {
 1100: 	&logthis("User $uname at $udom rejected by $uhome");
 1101: 	return 'no_host'; 
 1102:     }
 1103:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1104:     return 'no_host';
 1105: }
 1106: 
 1107: sub can_host_session {
 1108:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1109:     my $canhost = 1;
 1110:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1111:     if (ref($remotesessions) eq 'HASH') {
 1112:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1113:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1114:                 $canhost = 0;
 1115:             } else {
 1116:                 $canhost = 1;
 1117:             }
 1118:         }
 1119:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1120:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1121:                 $canhost = 1;
 1122:             } else {
 1123:                 $canhost = 0;
 1124:             }
 1125:         }
 1126:         if ($canhost) {
 1127:             if ($remotesessions->{'version'} ne '') {
 1128:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1129:                 if ($reqmajor ne '' && $reqminor ne '') {
 1130:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1131:                         my $major = $1;
 1132:                         my $minor = $2;
 1133:                         if (($major < $reqmajor ) ||
 1134:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1135:                             $canhost = 0;
 1136:                         }
 1137:                     } else {
 1138:                         $canhost = 0;
 1139:                     }
 1140:                 }
 1141:             }
 1142:         }
 1143:     }
 1144:     if ($canhost) {
 1145:         if (ref($hostedsessions) eq 'HASH') {
 1146:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1147:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1148:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1149:                 if (($uint_dom ne '') && 
 1150:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1151:                     $canhost = 0;
 1152:                 } else {
 1153:                     $canhost = 1;
 1154:                 }
 1155:             }
 1156:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1157:                 if (($uint_dom ne '') && 
 1158:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1159:                     $canhost = 1;
 1160:                 } else {
 1161:                     $canhost = 0;
 1162:                 }
 1163:             }
 1164:         }
 1165:     }
 1166:     return $canhost;
 1167: }
 1168: 
 1169: sub spare_can_host {
 1170:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1171:     my $canhost=1;
 1172:     my $try_server_hostname = &hostname($try_server);
 1173:     my $serverhomeID = &get_server_homeID($try_server_hostname);
 1174:     my $serverhomedom = &host_domain($serverhomeID);
 1175:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
 1176:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
 1177:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
 1178:             $canhost = 0;
 1179:         }
 1180:     }
 1181:     if (($canhost) && ($uint_dom)) {
 1182:         my @intdoms;
 1183:         my $internet_names = &get_internet_names($try_server);
 1184:         if (ref($internet_names) eq 'ARRAY') {
 1185:             @intdoms = @{$internet_names};
 1186:         }
 1187:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1188:             my $remoterev = &get_server_loncaparev(undef,$try_server);
 1189:             $canhost = &can_host_session($udom,$try_server,$remoterev,
 1190:                                          $remotesessions,
 1191:                                          $defdomdefaults{'hostedsessions'});
 1192:         }
 1193:     }
 1194:     return $canhost;
 1195: }
 1196: 
 1197: sub this_host_spares {
 1198:     my ($dom) = @_;
 1199:     my ($dom_in_use,$lonhost_in_use,$result);
 1200:     my @hosts = &current_machine_ids();
 1201:     foreach my $lonhost (@hosts) {
 1202:         if (&host_domain($lonhost) eq $dom) {
 1203:             $dom_in_use = $dom;
 1204:             $lonhost_in_use = $lonhost;
 1205:             last;
 1206:         }
 1207:     }
 1208:     if ($dom_in_use ne '') {
 1209:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1210:     }
 1211:     if (ref($result) ne 'HASH') {
 1212:         $lonhost_in_use = $perlvar{'lonHostID'};
 1213:         $dom_in_use = &host_domain($lonhost_in_use);
 1214:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1215:         if (ref($result) ne 'HASH') {
 1216:             $result = \%spareid;
 1217:         }
 1218:     }
 1219:     return $result;
 1220: }
 1221: 
 1222: sub spares_for_offload  {
 1223:     my ($dom_in_use,$lonhost_in_use) = @_;
 1224:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1225:     if (defined($cached)) {
 1226:         return $result;
 1227:     } else {
 1228:         my $cachetime = 60*60*24;
 1229:         my %domconfig =
 1230:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1231:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1232:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1233:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1234:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1235:                 }
 1236:             }
 1237:         }
 1238:     }
 1239:     return;
 1240: }
 1241: 
 1242: sub get_lonbalancer_config {
 1243:     my ($servers) = @_;
 1244:     my ($currbalancer,$currtargets);
 1245:     if (ref($servers) eq 'HASH') {
 1246:         foreach my $server (keys(%{$servers})) {
 1247:             my %what = (
 1248:                          spareid => 1,
 1249:                          perlvar => 1,
 1250:                        );
 1251:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1252:             if ($result eq 'ok') {
 1253:                 if (ref($returnhash) eq 'HASH') {
 1254:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1255:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1256:                             $currbalancer = $server;
 1257:                             $currtargets = {};
 1258:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1259:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1260:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1261:                                 }
 1262:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1263:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1264:                                 }
 1265:                             }
 1266:                             last;
 1267:                         }
 1268:                     }
 1269:                 }
 1270:             }
 1271:         }
 1272:     }
 1273:     return ($currbalancer,$currtargets);
 1274: }
 1275: 
 1276: sub check_loadbalancing {
 1277:     my ($uname,$udom) = @_;
 1278:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
 1279:         $rule_in_effect,$offloadto,$otherserver);
 1280:     my $lonhost = $perlvar{'lonHostID'};
 1281:     my @hosts = &current_machine_ids();
 1282:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1283:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1284:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1285:     my $serverhomedom = &host_domain($lonhost);
 1286: 
 1287:     my $cachetime = 60*60*24;
 1288: 
 1289:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1290:         $dom_in_use = $udom;
 1291:         $homeintdom = 1;
 1292:     } else {
 1293:         $dom_in_use = $serverhomedom;
 1294:     }
 1295:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1296:     unless (defined($cached)) {
 1297:         my %domconfig =
 1298:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1299:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1300:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1301:         }
 1302:     }
 1303:     if (ref($result) eq 'HASH') {
 1304:         ($is_balancer,$currtargets,$currrules) =
 1305:             &check_balancer_result($result,@hosts);
 1306:         if ($is_balancer) {
 1307:             if (ref($currrules) eq 'HASH') {
 1308:                 if ($homeintdom) {
 1309:                     if ($uname ne '') {
 1310:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1311:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1312:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1313:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1314:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1315:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1316:                             }
 1317:                         }
 1318:                         if ($rule_in_effect eq '') {
 1319:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1320:                             if ($userenv{'inststatus'} ne '') {
 1321:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1322:                                 my ($othertitle,$usertypes,$types) =
 1323:                                     &Apache::loncommon::sorted_inst_types($udom);
 1324:                                 if (ref($types) eq 'ARRAY') {
 1325:                                     foreach my $type (@{$types}) {
 1326:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1327:                                             if (exists($currrules->{$type})) {
 1328:                                                 $rule_in_effect = $currrules->{$type};
 1329:                                             }
 1330:                                         }
 1331:                                     }
 1332:                                 }
 1333:                             } else {
 1334:                                 if (exists($currrules->{'default'})) {
 1335:                                     $rule_in_effect = $currrules->{'default'};
 1336:                                 }
 1337:                             }
 1338:                         }
 1339:                     } else {
 1340:                         if (exists($currrules->{'default'})) {
 1341:                             $rule_in_effect = $currrules->{'default'};
 1342:                         }
 1343:                     }
 1344:                 } else {
 1345:                     if ($currrules->{'_LC_external'} ne '') {
 1346:                         $rule_in_effect = $currrules->{'_LC_external'};
 1347:                     }
 1348:                 }
 1349:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1350:                                                        $uname,$udom);
 1351:             }
 1352:         }
 1353:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1354:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1355:         unless (defined($cached)) {
 1356:             my %domconfig =
 1357:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1358:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1359:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1360:             }
 1361:         }
 1362:         if (ref($result) eq 'HASH') {
 1363:             ($is_balancer,$currtargets,$currrules) =
 1364:                 &check_balancer_result($result,@hosts);
 1365:             if ($is_balancer) {
 1366:                 if (ref($currrules) eq 'HASH') {
 1367:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1368:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1369:                     }
 1370:                 }
 1371:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1372:                                                        $uname,$udom);
 1373:             }
 1374:         } else {
 1375:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1376:                 $is_balancer = 1;
 1377:                 $offloadto = &this_host_spares($dom_in_use);
 1378:             }
 1379:         }
 1380:     } else {
 1381:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1382:             $is_balancer = 1;
 1383:             $offloadto = &this_host_spares($dom_in_use);
 1384:         }
 1385:     }
 1386:     if ($is_balancer) {
 1387:         my $lowest_load = 30000;
 1388:         if (ref($offloadto) eq 'HASH') {
 1389:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1390:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1391:                     ($otherserver,$lowest_load) =
 1392:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1393:                 }
 1394:             }
 1395:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1396: 
 1397:             if (!$found_server) {
 1398:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1399:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1400:                         ($otherserver,$lowest_load) =
 1401:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1402:                     }
 1403:                 }
 1404:             }
 1405:         } elsif (ref($offloadto) eq 'ARRAY') {
 1406:             if (@{$offloadto} == 1) {
 1407:                 $otherserver = $offloadto->[0];
 1408:             } elsif (@{$offloadto} > 1) {
 1409:                 foreach my $try_server (@{$offloadto}) {
 1410:                     ($otherserver,$lowest_load) =
 1411:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1412:                 }
 1413:             }
 1414:         }
 1415:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1416:             $is_balancer = 0;
 1417:             if ($uname ne '' && $udom ne '') {
 1418:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1419: 
 1420:                     &appenv({'user.loadbalexempt'     => $lonhost,
 1421:                              'user.loadbalcheck.time' => time});
 1422:                 }
 1423:             }
 1424:         }
 1425:     }
 1426:     return ($is_balancer,$otherserver);
 1427: }
 1428: 
 1429: sub check_balancer_result {
 1430:     my ($result,@hosts) = @_;
 1431:     my ($is_balancer,$currtargets,$currrules);
 1432:     if (ref($result) eq 'HASH') {
 1433:         if ($result->{'lonhost'} ne '') {
 1434:             my $currbalancer = $result->{'lonhost'};
 1435:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1436:                 $is_balancer = 1;
 1437:                 $currtargets = $result->{'targets'};
 1438:                 $currrules = $result->{'rules'};
 1439:             }
 1440:         } else {
 1441:             foreach my $key (keys(%{$result})) {
 1442:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
 1443:                     (ref($result->{$key}) eq 'HASH')) {
 1444:                     $is_balancer = 1;
 1445:                     $currrules = $result->{$key}{'rules'};
 1446:                     $currtargets = $result->{$key}{'targets'};
 1447:                     last;
 1448:                 }
 1449:             }
 1450:         }
 1451:     }
 1452:     return ($is_balancer,$currtargets,$currrules);
 1453: }
 1454: 
 1455: sub get_loadbalancer_targets {
 1456:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1457:     my $offloadto;
 1458:     if ($rule_in_effect eq 'none') {
 1459:         return [$perlvar{'lonHostID'}];
 1460:     } elsif ($rule_in_effect eq '') {
 1461:         $offloadto = $currtargets;
 1462:     } else {
 1463:         if ($rule_in_effect eq 'homeserver') {
 1464:             my $homeserver = &homeserver($uname,$udom);
 1465:             if ($homeserver ne 'no_host') {
 1466:                 $offloadto = [$homeserver];
 1467:             }
 1468:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1469:             my %domconfig =
 1470:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1471:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1472:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1473:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1474:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1475:                     }
 1476:                 }
 1477:             } else {
 1478:                 my %servers = &internet_dom_servers($udom);
 1479:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1480:                 if (&hostname($remotebalancer) ne '') {
 1481:                     $offloadto = [$remotebalancer];
 1482:                 }
 1483:             }
 1484:         } elsif (&hostname($rule_in_effect) ne '') {
 1485:             $offloadto = [$rule_in_effect];
 1486:         }
 1487:     }
 1488:     return $offloadto;
 1489: }
 1490: 
 1491: sub internet_dom_servers {
 1492:     my ($dom) = @_;
 1493:     my (%uniqservers,%servers);
 1494:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1495:     my @machinedoms = &machine_domains($primaryserver);
 1496:     foreach my $mdom (@machinedoms) {
 1497:         my %currservers = %servers;
 1498:         my %server = &get_servers($mdom);
 1499:         %servers = (%currservers,%server);
 1500:     }
 1501:     my %by_hostname;
 1502:     foreach my $id (keys(%servers)) {
 1503:         push(@{$by_hostname{$servers{$id}}},$id);
 1504:     }
 1505:     foreach my $hostname (sort(keys(%by_hostname))) {
 1506:         if (@{$by_hostname{$hostname}} > 1) {
 1507:             my $match = 0;
 1508:             foreach my $id (@{$by_hostname{$hostname}}) {
 1509:                 if (&host_domain($id) eq $dom) {
 1510:                     $uniqservers{$id} = $hostname;
 1511:                     $match = 1;
 1512:                 }
 1513:             }
 1514:             unless ($match) {
 1515:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1516:             }
 1517:         } else {
 1518:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1519:         }
 1520:     }
 1521:     return %uniqservers;
 1522: }
 1523: 
 1524: # ---------------------- Find the homebase for a user from domain's lib servers
 1525: 
 1526: my %homecache;
 1527: sub homeserver {
 1528:     my ($uname,$udom,$ignoreBadCache)=@_;
 1529:     my $index="$uname:$udom";
 1530: 
 1531:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1532: 
 1533:     my %servers = &get_servers($udom,'library');
 1534:     foreach my $tryserver (keys(%servers)) {
 1535:         next if ($ignoreBadCache ne 'true' && 
 1536: 		 exists($badServerCache{$tryserver}));
 1537: 
 1538: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1539: 	if ($answer eq 'found') {
 1540: 	    delete($badServerCache{$tryserver}); 
 1541: 	    return $homecache{$index}=$tryserver;
 1542: 	} elsif ($answer eq 'no_host') {
 1543: 	    $badServerCache{$tryserver}=1;
 1544: 	}
 1545:     }    
 1546:     return 'no_host';
 1547: }
 1548: 
 1549: # ------------------------------------- Find the usernames behind a list of IDs
 1550: 
 1551: sub idget {
 1552:     my ($udom,@ids)=@_;
 1553:     my %returnhash=();
 1554:     
 1555:     my %servers = &get_servers($udom,'library');
 1556:     foreach my $tryserver (keys(%servers)) {
 1557: 	my $idlist=join('&',@ids);
 1558: 	$idlist=~tr/A-Z/a-z/; 
 1559: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1560: 	my @answer=();
 1561: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1562: 	    @answer=split(/\&/,$reply);
 1563: 	}                    ;
 1564: 	my $i;
 1565: 	for ($i=0;$i<=$#ids;$i++) {
 1566: 	    if ($answer[$i]) {
 1567: 		$returnhash{$ids[$i]}=$answer[$i];
 1568: 	    } 
 1569: 	}
 1570:     } 
 1571:     return %returnhash;
 1572: }
 1573: 
 1574: # ------------------------------------- Find the IDs behind a list of usernames
 1575: 
 1576: sub idrget {
 1577:     my ($udom,@unames)=@_;
 1578:     my %returnhash=();
 1579:     foreach my $uname (@unames) {
 1580:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1581:     }
 1582:     return %returnhash;
 1583: }
 1584: 
 1585: # ------------------------------- Store away a list of names and associated IDs
 1586: 
 1587: sub idput {
 1588:     my ($udom,%ids)=@_;
 1589:     my %servers=();
 1590:     foreach my $uname (keys(%ids)) {
 1591: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1592:         my $uhom=&homeserver($uname,$udom);
 1593:         if ($uhom ne 'no_host') {
 1594:             my $id=&escape($ids{$uname});
 1595:             $id=~tr/A-Z/a-z/;
 1596:             my $esc_unam=&escape($uname);
 1597: 	    if ($servers{$uhom}) {
 1598: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
 1599:             } else {
 1600:                 $servers{$uhom}=$id.'='.$esc_unam;
 1601:             }
 1602:         }
 1603:     }
 1604:     foreach my $server (keys(%servers)) {
 1605:         &critical('idput:'.$udom.':'.$servers{$server},$server);
 1606:     }
 1607: }
 1608: 
 1609: # ---------------------------------------- Delete unwanted IDs from ids.db file
 1610: 
 1611: sub iddel {
 1612:     my ($udom,$idshashref,$uhome)=@_;
 1613:     my %result=();
 1614:     unless (ref($idshashref) eq 'HASH') {
 1615:         return %result;
 1616:     }
 1617:     my %servers=();
 1618:     while (my ($id,$uname) = each(%{$idshashref})) {
 1619:         my $uhom;
 1620:         if ($uhome) {
 1621:             $uhom = $uhome;
 1622:         } else {
 1623:             $uhom=&homeserver($uname,$udom);
 1624:         }
 1625:         if ($uhom ne 'no_host') {
 1626:             if ($servers{$uhom}) {
 1627:                 $servers{$uhom}.='&'.&escape($id);
 1628:             } else {
 1629:                 $servers{$uhom}=&escape($id);
 1630:             }
 1631:         }
 1632:     }
 1633:     foreach my $server (keys(%servers)) {
 1634:         $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
 1635:     }
 1636:     return %result;
 1637: }
 1638: 
 1639: # ------------------------------dump from db file owned by domainconfig user
 1640: sub dump_dom {
 1641:     my ($namespace, $udom, $regexp) = @_;
 1642: 
 1643:     $udom ||= $env{'user.domain'};
 1644: 
 1645:     return () unless $udom;
 1646: 
 1647:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 1648: }
 1649: 
 1650: # ------------------------------------------ get items from domain db files   
 1651: 
 1652: sub get_dom {
 1653:     my ($namespace,$storearr,$udom,$uhome)=@_;
 1654:     return if ($udom eq 'public');
 1655:     my $items='';
 1656:     foreach my $item (@$storearr) {
 1657:         $items.=&escape($item).'&';
 1658:     }
 1659:     $items=~s/\&$//;
 1660:     if (!$udom) {
 1661:         $udom=$env{'user.domain'};
 1662:         return if ($udom eq 'public');
 1663:         if (defined(&domain($udom,'primary'))) {
 1664:             $uhome=&domain($udom,'primary');
 1665:         } else {
 1666:             undef($uhome);
 1667:         }
 1668:     } else {
 1669:         if (!$uhome) {
 1670:             if (defined(&domain($udom,'primary'))) {
 1671:                 $uhome=&domain($udom,'primary');
 1672:             }
 1673:         }
 1674:     }
 1675:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1676:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 1677:         my %returnhash;
 1678:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 1679:             return %returnhash;
 1680:         }
 1681:         my @pairs=split(/\&/,$rep);
 1682:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1683:             return @pairs;
 1684:         }
 1685:         my $i=0;
 1686:         foreach my $item (@$storearr) {
 1687:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 1688:             $i++;
 1689:         }
 1690:         return %returnhash;
 1691:     } else {
 1692:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1693:     }
 1694: }
 1695: 
 1696: # -------------------------------------------- put items in domain db files 
 1697: 
 1698: sub put_dom {
 1699:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1700:     if (!$udom) {
 1701:         $udom=$env{'user.domain'};
 1702:         if (defined(&domain($udom,'primary'))) {
 1703:             $uhome=&domain($udom,'primary');
 1704:         } else {
 1705:             undef($uhome);
 1706:         }
 1707:     } else {
 1708:         if (!$uhome) {
 1709:             if (defined(&domain($udom,'primary'))) {
 1710:                 $uhome=&domain($udom,'primary');
 1711:             }
 1712:         }
 1713:     } 
 1714:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1715:         my $items='';
 1716:         foreach my $item (keys(%$storehash)) {
 1717:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 1718:         }
 1719:         $items=~s/\&$//;
 1720:         return &reply("putdom:$udom:$namespace:$items",$uhome);
 1721:     } else {
 1722:         &logthis("put_dom failed - no homeserver and/or domain");
 1723:     }
 1724: }
 1725: 
 1726: # --------------------- newput for items in db file owned by domainconfig user
 1727: sub newput_dom {
 1728:     my ($namespace,$storehash,$udom) = @_;
 1729:     my $result;
 1730:     if (!$udom) {
 1731:         $udom=$env{'user.domain'};
 1732:     }
 1733:     if ($udom) {
 1734:         my $uname = &get_domainconfiguser($udom);
 1735:         $result = &newput($namespace,$storehash,$udom,$uname);
 1736:     }
 1737:     return $result;
 1738: }
 1739: 
 1740: # --------------------- delete for items in db file owned by domainconfig user
 1741: sub del_dom {
 1742:     my ($namespace,$storearr,$udom)=@_;
 1743:     if (ref($storearr) eq 'ARRAY') {
 1744:         if (!$udom) {
 1745:             $udom=$env{'user.domain'};
 1746:         }
 1747:         if ($udom) {
 1748:             my $uname = &get_domainconfiguser($udom); 
 1749:             return &del($namespace,$storearr,$udom,$uname);
 1750:         }
 1751:     }
 1752: }
 1753: 
 1754: # ----------------------------------construct domainconfig user for a domain 
 1755: sub get_domainconfiguser {
 1756:     my ($udom) = @_;
 1757:     return $udom.'-domainconfig';
 1758: }
 1759: 
 1760: sub retrieve_inst_usertypes {
 1761:     my ($udom) = @_;
 1762:     my (%returnhash,@order);
 1763:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 1764:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 1765:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 1766:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
 1767:     } else {
 1768:         if (defined(&domain($udom,'primary'))) {
 1769:             my $uhome=&domain($udom,'primary');
 1770:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 1771:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 1772:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
 1773:                 return (\%returnhash,\@order);
 1774:             }
 1775:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 1776:             my @pairs=split(/\&/,$hashitems);
 1777:             foreach my $item (@pairs) {
 1778:                 my ($key,$value)=split(/=/,$item,2);
 1779:                 $key = &unescape($key);
 1780:                 next if ($key =~ /^error: 2 /);
 1781:                 $returnhash{$key}=&thaw_unescape($value);
 1782:             }
 1783:             my @esc_order = split(/\&/,$orderitems);
 1784:             foreach my $item (@esc_order) {
 1785:                 push(@order,&unescape($item));
 1786:             }
 1787:         } else {
 1788:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
 1789:         }
 1790:         return (\%returnhash,\@order);
 1791:     }
 1792: }
 1793: 
 1794: sub is_domainimage {
 1795:     my ($url) = @_;
 1796:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1797:         if (&domain($1) ne '') {
 1798:             return '1';
 1799:         }
 1800:     }
 1801:     return;
 1802: }
 1803: 
 1804: sub inst_directory_query {
 1805:     my ($srch) = @_;
 1806:     my $udom = $srch->{'srchdomain'};
 1807:     my %results;
 1808:     my $homeserver = &domain($udom,'primary');
 1809:     my $outcome;
 1810:     if ($homeserver ne '') {
 1811: 	my $queryid=&reply("querysend:instdirsearch:".
 1812: 			   &escape($srch->{'srchby'}).':'.
 1813: 			   &escape($srch->{'srchterm'}).':'.
 1814: 			   &escape($srch->{'srchtype'}),$homeserver);
 1815: 	my $host=&hostname($homeserver);
 1816: 	if ($queryid !~/^\Q$host\E\_/) {
 1817: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1818: 	    return;
 1819: 	}
 1820: 	my $response = &get_query_reply($queryid);
 1821: 	my $maxtries = 5;
 1822: 	my $tries = 1;
 1823: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1824: 	    $response = &get_query_reply($queryid);
 1825: 	    $tries ++;
 1826: 	}
 1827: 
 1828:         if (!&error($response) && $response ne 'refused') {
 1829:             if ($response eq 'unavailable') {
 1830:                 $outcome = $response;
 1831:             } else {
 1832:                 $outcome = 'ok';
 1833:                 my @matches = split(/\n/,$response);
 1834:                 foreach my $match (@matches) {
 1835:                     my ($key,$value) = split(/=/,$match);
 1836:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1837:                 }
 1838:             }
 1839:         }
 1840:     }
 1841:     return ($outcome,%results);
 1842: }
 1843: 
 1844: sub usersearch {
 1845:     my ($srch) = @_;
 1846:     my $dom = $srch->{'srchdomain'};
 1847:     my %results;
 1848:     my %libserv = &all_library();
 1849:     my $query = 'usersearch';
 1850:     foreach my $tryserver (keys(%libserv)) {
 1851:         if (&host_domain($tryserver) eq $dom) {
 1852:             my $host=&hostname($tryserver);
 1853:             my $queryid=
 1854:                 &reply("querysend:".&escape($query).':'.
 1855:                        &escape($srch->{'srchby'}).':'.
 1856:                        &escape($srch->{'srchtype'}).':'.
 1857:                        &escape($srch->{'srchterm'}),$tryserver);
 1858:             if ($queryid !~/^\Q$host\E\_/) {
 1859:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1860:                 next;
 1861:             }
 1862:             my $reply = &get_query_reply($queryid);
 1863:             my $maxtries = 1;
 1864:             my $tries = 1;
 1865:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1866:                 $reply = &get_query_reply($queryid);
 1867:                 $tries ++;
 1868:             }
 1869:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1870:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1871:             } else {
 1872:                 my @matches;
 1873:                 if ($reply =~ /\n/) {
 1874:                     @matches = split(/\n/,$reply);
 1875:                 } else {
 1876:                     @matches = split(/\&/,$reply);
 1877:                 }
 1878:                 foreach my $match (@matches) {
 1879:                     my ($uname,$udom,%userhash);
 1880:                     foreach my $entry (split(/:/,$match)) {
 1881:                         my ($key,$value) =
 1882:                             map {&unescape($_);} split(/=/,$entry);
 1883:                         $userhash{$key} = $value;
 1884:                         if ($key eq 'username') {
 1885:                             $uname = $value;
 1886:                         } elsif ($key eq 'domain') {
 1887:                             $udom = $value;
 1888:                         }
 1889:                     }
 1890:                     $results{$uname.':'.$udom} = \%userhash;
 1891:                 }
 1892:             }
 1893:         }
 1894:     }
 1895:     return %results;
 1896: }
 1897: 
 1898: sub get_instuser {
 1899:     my ($udom,$uname,$id) = @_;
 1900:     my $homeserver = &domain($udom,'primary');
 1901:     my ($outcome,%results);
 1902:     if ($homeserver ne '') {
 1903:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1904:                            &escape($id).':'.&escape($udom),$homeserver);
 1905:         my $host=&hostname($homeserver);
 1906:         if ($queryid !~/^\Q$host\E\_/) {
 1907:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1908:             return;
 1909:         }
 1910:         my $response = &get_query_reply($queryid);
 1911:         my $maxtries = 5;
 1912:         my $tries = 1;
 1913:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1914:             $response = &get_query_reply($queryid);
 1915:             $tries ++;
 1916:         }
 1917:         if (!&error($response) && $response ne 'refused') {
 1918:             if ($response eq 'unavailable') {
 1919:                 $outcome = $response;
 1920:             } else {
 1921:                 $outcome = 'ok';
 1922:                 my @matches = split(/\n/,$response);
 1923:                 foreach my $match (@matches) {
 1924:                     my ($key,$value) = split(/=/,$match);
 1925:                     $results{&unescape($key)} = &thaw_unescape($value);
 1926:                 }
 1927:             }
 1928:         }
 1929:     }
 1930:     my %userinfo;
 1931:     if (ref($results{$uname}) eq 'HASH') {
 1932:         %userinfo = %{$results{$uname}};
 1933:     } 
 1934:     return ($outcome,%userinfo);
 1935: }
 1936: 
 1937: sub inst_rulecheck {
 1938:     my ($udom,$uname,$id,$item,$rules) = @_;
 1939:     my %returnhash;
 1940:     if ($udom ne '') {
 1941:         if (ref($rules) eq 'ARRAY') {
 1942:             @{$rules} = map {&escape($_);} (@{$rules});
 1943:             my $rulestr = join(':',@{$rules});
 1944:             my $homeserver=&domain($udom,'primary');
 1945:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1946:                 my $response;
 1947:                 if ($item eq 'username') {                
 1948:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1949:                                               ':'.&escape($uname).':'.$rulestr,
 1950:                                               $homeserver));
 1951:                 } elsif ($item eq 'id') {
 1952:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1953:                                               ':'.&escape($id).':'.$rulestr,
 1954:                                               $homeserver));
 1955:                 } elsif ($item eq 'selfcreate') {
 1956:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1957:                                                &escape($udom).':'.&escape($uname).
 1958:                                               ':'.$rulestr,$homeserver));
 1959:                 }
 1960:                 if ($response ne 'refused') {
 1961:                     my @pairs=split(/\&/,$response);
 1962:                     foreach my $item (@pairs) {
 1963:                         my ($key,$value)=split(/=/,$item,2);
 1964:                         $key = &unescape($key);
 1965:                         next if ($key =~ /^error: 2 /);
 1966:                         $returnhash{$key}=&thaw_unescape($value);
 1967:                     }
 1968:                 }
 1969:             }
 1970:         }
 1971:     }
 1972:     return %returnhash;
 1973: }
 1974: 
 1975: sub inst_userrules {
 1976:     my ($udom,$check) = @_;
 1977:     my (%ruleshash,@ruleorder);
 1978:     if ($udom ne '') {
 1979:         my $homeserver=&domain($udom,'primary');
 1980:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1981:             my $response;
 1982:             if ($check eq 'id') {
 1983:                 $response=&reply('instidrules:'.&escape($udom),
 1984:                                  $homeserver);
 1985:             } elsif ($check eq 'email') {
 1986:                 $response=&reply('instemailrules:'.&escape($udom),
 1987:                                  $homeserver);
 1988:             } else {
 1989:                 $response=&reply('instuserrules:'.&escape($udom),
 1990:                                  $homeserver);
 1991:             }
 1992:             if (($response ne 'refused') && ($response ne 'error') && 
 1993:                 ($response ne 'unknown_cmd') && 
 1994:                 ($response ne 'no_such_host')) {
 1995:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1996:                 my @pairs=split(/\&/,$hashitems);
 1997:                 foreach my $item (@pairs) {
 1998:                     my ($key,$value)=split(/=/,$item,2);
 1999:                     $key = &unescape($key);
 2000:                     next if ($key =~ /^error: 2 /);
 2001:                     $ruleshash{$key}=&thaw_unescape($value);
 2002:                 }
 2003:                 my @esc_order = split(/\&/,$orderitems);
 2004:                 foreach my $item (@esc_order) {
 2005:                     push(@ruleorder,&unescape($item));
 2006:                 }
 2007:             }
 2008:         }
 2009:     }
 2010:     return (\%ruleshash,\@ruleorder);
 2011: }
 2012: 
 2013: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 2014: 
 2015: sub get_domain_defaults {
 2016:     my ($domain,$ignore_cache) = @_;
 2017:     return if (($domain eq '') || ($domain eq 'public'));
 2018:     my $cachetime = 60*60*24;
 2019:     unless ($ignore_cache) {
 2020:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 2021:         if (defined($cached)) {
 2022:             if (ref($result) eq 'HASH') {
 2023:                 return %{$result};
 2024:             }
 2025:         }
 2026:     }
 2027:     my %domdefaults;
 2028:     my %domconfig =
 2029:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 2030:                                   'requestcourses','inststatus',
 2031:                                   'coursedefaults','usersessions',
 2032:                                   'requestauthor','selfenrollment',
 2033:                                   'coursecategories'],$domain);
 2034:     my @coursetypes = ('official','unofficial','community','textbook');
 2035:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 2036:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 2037:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 2038:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 2039:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 2040:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 2041:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 2042:     } else {
 2043:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 2044:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 2045:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 2046:     }
 2047:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 2048:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 2049:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 2050:         } else {
 2051:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 2052:         }
 2053:         my @usertools = ('aboutme','blog','webdav','portfolio');
 2054:         foreach my $item (@usertools) {
 2055:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 2056:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 2057:             }
 2058:         }
 2059:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
 2060:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
 2061:         }
 2062:     }
 2063:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 2064:         foreach my $item ('official','unofficial','community','textbook') {
 2065:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 2066:         }
 2067:     }
 2068:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 2069:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 2070:     }
 2071:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 2072:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
 2073:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 2074:         }
 2075:     }
 2076:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 2077:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
 2078:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
 2079:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
 2080:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
 2081:         }
 2082:         foreach my $type (@coursetypes) {
 2083:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
 2084:                 unless ($type eq 'community') {
 2085:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
 2086:                 }
 2087:             }
 2088:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
 2089:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
 2090:             }
 2091:             if ($domdefaults{'postsubmit'} eq 'on') {
 2092:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
 2093:                     $domdefaults{$type.'postsubtimeout'} =
 2094:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
 2095:                 }
 2096:             }
 2097:         }
 2098:     }
 2099:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 2100:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 2101:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 2102:         }
 2103:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 2104:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 2105:         }
 2106:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
 2107:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
 2108:         }
 2109:     }
 2110:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
 2111:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
 2112:             my @settings = ('types','registered','enroll_dates','access_dates','section',
 2113:                             'approval','limit');
 2114:             foreach my $type (@coursetypes) {
 2115:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
 2116:                     my @mgrdc = ();
 2117:                     foreach my $item (@settings) {
 2118:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
 2119:                             push(@mgrdc,$item);
 2120:                         }
 2121:                     }
 2122:                     if (@mgrdc) {
 2123:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
 2124:                     }
 2125:                 }
 2126:             }
 2127:         }
 2128:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
 2129:             foreach my $type (@coursetypes) {
 2130:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
 2131:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
 2132:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
 2133:                     }
 2134:                 }
 2135:             }
 2136:         }
 2137:     }
 2138:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
 2139:         $domdefaults{'catauth'} = 'std';
 2140:         $domdefaults{'catunauth'} = 'std';
 2141:         if ($domconfig{'coursecategories'}{'auth'}) {
 2142:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
 2143:         }
 2144:         if ($domconfig{'coursecategories'}{'unauth'}) {
 2145:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
 2146:         }
 2147:     }
 2148:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
 2149:     return %domdefaults;
 2150: }
 2151: 
 2152: # --------------------------------------------------- Assign a key to a student
 2153: 
 2154: sub assign_access_key {
 2155: #
 2156: # a valid key looks like uname:udom#comments
 2157: # comments are being appended
 2158: #
 2159:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2160:     $kdom=
 2161:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2162:     $knum=
 2163:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2164:     $cdom=
 2165:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2166:     $cnum=
 2167:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2168:     $udom=$env{'user.name'} unless (defined($udom));
 2169:     $uname=$env{'user.domain'} unless (defined($uname));
 2170:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2171:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2172:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2173:                                                   # assigned to this person
 2174:                                                   # - this should not happen,
 2175:                                                   # unless something went wrong
 2176:                                                   # the first time around
 2177: # ready to assign
 2178:         $logentry=$1.'; '.$logentry;
 2179:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2180:                                                  $kdom,$knum) eq 'ok') {
 2181: # key now belongs to user
 2182: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2183:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2184:                 &appenv({'environment.'.$envkey => $ckey});
 2185:                 return 'ok';
 2186:             } else {
 2187:                 return 
 2188:   'error: Count not permanently assign key, will need to be re-entered later.';
 2189: 	    }
 2190:         } else {
 2191:             return 'error: Could not assign key, try again later.';
 2192:         }
 2193:     } elsif (!$existing{$ckey}) {
 2194: # the key does not exist
 2195: 	return 'error: The key does not exist';
 2196:     } else {
 2197: # the key is somebody else's
 2198: 	return 'error: The key is already in use';
 2199:     }
 2200: }
 2201: 
 2202: # ------------------------------------------ put an additional comment on a key
 2203: 
 2204: sub comment_access_key {
 2205: #
 2206: # a valid key looks like uname:udom#comments
 2207: # comments are being appended
 2208: #
 2209:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2210:     $cdom=
 2211:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2212:     $cnum=
 2213:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2214:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2215:     if ($existing{$ckey}) {
 2216:         $existing{$ckey}.='; '.$logentry;
 2217: # ready to assign
 2218:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2219:                                                  $cdom,$cnum) eq 'ok') {
 2220: 	    return 'ok';
 2221:         } else {
 2222: 	    return 'error: Count not store comment.';
 2223:         }
 2224:     } else {
 2225: # the key does not exist
 2226: 	return 'error: The key does not exist';
 2227:     }
 2228: }
 2229: 
 2230: # ------------------------------------------------------ Generate a set of keys
 2231: 
 2232: sub generate_access_keys {
 2233:     my ($number,$cdom,$cnum,$logentry)=@_;
 2234:     $cdom=
 2235:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2236:     $cnum=
 2237:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2238:     unless (&allowed('mky',$cdom)) { return 0; }
 2239:     unless (($cdom) && ($cnum)) { return 0; }
 2240:     if ($number>10000) { return 0; }
 2241:     sleep(2); # make sure don't get same seed twice
 2242:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2243:     my $total=0;
 2244:     for (my $i=1;$i<=$number;$i++) {
 2245:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2246:                   sprintf("%lx",int(100000*rand)).'-'.
 2247:                   sprintf("%lx",int(100000*rand));
 2248:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2249:        $newkey=~s/0/h/g; # and also 0 and O
 2250:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2251:        if ($existing{$newkey}) {
 2252:            $i--;
 2253:        } else {
 2254: 	  if (&put('accesskeys',
 2255:               { $newkey => '# generated '.localtime().
 2256:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2257:                            '; '.$logentry },
 2258: 		   $cdom,$cnum) eq 'ok') {
 2259:               $total++;
 2260: 	  }
 2261:        }
 2262:     }
 2263:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2264:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2265:     return $total;
 2266: }
 2267: 
 2268: # ------------------------------------------------------- Validate an accesskey
 2269: 
 2270: sub validate_access_key {
 2271:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2272:     $cdom=
 2273:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2274:     $cnum=
 2275:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2276:     $udom=$env{'user.domain'} unless (defined($udom));
 2277:     $uname=$env{'user.name'} unless (defined($uname));
 2278:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2279:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2280: }
 2281: 
 2282: # ------------------------------------- Find the section of student in a course
 2283: sub devalidate_getsection_cache {
 2284:     my ($udom,$unam,$courseid)=@_;
 2285:     my $hashid="$udom:$unam:$courseid";
 2286:     &devalidate_cache_new('getsection',$hashid);
 2287: }
 2288: 
 2289: sub courseid_to_courseurl {
 2290:     my ($courseid) = @_;
 2291:     #already url style courseid
 2292:     return $courseid if ($courseid =~ m{^/});
 2293: 
 2294:     if (exists($env{'course.'.$courseid.'.num'})) {
 2295: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2296: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2297: 	return "/$cdom/$cnum";
 2298:     }
 2299: 
 2300:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2301:     if (exists($courseinfo{'num'})) {
 2302: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2303:     }
 2304: 
 2305:     return undef;
 2306: }
 2307: 
 2308: sub getsection {
 2309:     my ($udom,$unam,$courseid)=@_;
 2310:     my $cachetime=1800;
 2311: 
 2312:     my $hashid="$udom:$unam:$courseid";
 2313:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2314:     if (defined($cached)) { return $result; }
 2315: 
 2316:     my %Pending; 
 2317:     my %Expired;
 2318:     #
 2319:     # Each role can either have not started yet (pending), be active, 
 2320:     #    or have expired.
 2321:     #
 2322:     # If there is an active role, we are done.
 2323:     #
 2324:     # If there is more than one role which has not started yet, 
 2325:     #     choose the one which will start sooner
 2326:     # If there is one role which has not started yet, return it.
 2327:     #
 2328:     # If there is more than one expired role, choose the one which ended last.
 2329:     # If there is a role which has expired, return it.
 2330:     #
 2331:     $courseid = &courseid_to_courseurl($courseid);
 2332:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 2333:     foreach my $key (keys(%roleshash)) {
 2334:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2335:         my $section=$1;
 2336:         if ($key eq $courseid.'_st') { $section=''; }
 2337:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2338:         my $now=time;
 2339:         if (defined($end) && $end && ($now > $end)) {
 2340:             $Expired{$end}=$section;
 2341:             next;
 2342:         }
 2343:         if (defined($start) && $start && ($now < $start)) {
 2344:             $Pending{$start}=$section;
 2345:             next;
 2346:         }
 2347:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2348:     }
 2349:     #
 2350:     # Presumedly there will be few matching roles from the above
 2351:     # loop and the sorting time will be negligible.
 2352:     if (scalar(keys(%Pending))) {
 2353:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2354:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2355:     } 
 2356:     if (scalar(keys(%Expired))) {
 2357:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2358:         my $time = pop(@sorted);
 2359:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2360:     }
 2361:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2362: }
 2363: 
 2364: sub save_cache {
 2365:     &purge_remembered();
 2366:     #&Apache::loncommon::validate_page();
 2367:     undef(%env);
 2368:     undef($env_loaded);
 2369: }
 2370: 
 2371: my $to_remember=-1;
 2372: my %remembered;
 2373: my %accessed;
 2374: my $kicks=0;
 2375: my $hits=0;
 2376: sub make_key {
 2377:     my ($name,$id) = @_;
 2378:     if (length($id) > 65 
 2379: 	&& length(&escape($id)) > 200) {
 2380: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2381:     }
 2382:     return &escape($name.':'.$id);
 2383: }
 2384: 
 2385: sub devalidate_cache_new {
 2386:     my ($name,$id,$debug) = @_;
 2387:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2388:     $id=&make_key($name,$id);
 2389:     $memcache->delete($id);
 2390:     delete($remembered{$id});
 2391:     delete($accessed{$id});
 2392: }
 2393: 
 2394: sub is_cached_new {
 2395:     my ($name,$id,$debug) = @_;
 2396:     $id=&make_key($name,$id);
 2397:     if (exists($remembered{$id})) {
 2398: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
 2399: 	$accessed{$id}=[&gettimeofday()];
 2400: 	$hits++;
 2401: 	return ($remembered{$id},1);
 2402:     }
 2403:     my $value = $memcache->get($id);
 2404:     if (!(defined($value))) {
 2405: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2406: 	return (undef,undef);
 2407:     }
 2408:     if ($value eq '__undef__') {
 2409: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2410: 	$value=undef;
 2411:     }
 2412:     &make_room($id,$value,$debug);
 2413:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2414:     return ($value,1);
 2415: }
 2416: 
 2417: sub do_cache_new {
 2418:     my ($name,$id,$value,$time,$debug) = @_;
 2419:     $id=&make_key($name,$id);
 2420:     my $setvalue=$value;
 2421:     if (!defined($setvalue)) {
 2422: 	$setvalue='__undef__';
 2423:     }
 2424:     if (!defined($time) ) {
 2425: 	$time=600;
 2426:     }
 2427:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 2428:     my $result = $memcache->set($id,$setvalue,$time);
 2429:     if (! $result) {
 2430: 	&logthis("caching of id -> $id  failed");
 2431: 	$memcache->disconnect_all();
 2432:     }
 2433:     # need to make a copy of $value
 2434:     &make_room($id,$value,$debug);
 2435:     return $value;
 2436: }
 2437: 
 2438: sub make_room {
 2439:     my ($id,$value,$debug)=@_;
 2440: 
 2441:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 2442:                                     : $value;
 2443:     if ($to_remember<0) { return; }
 2444:     $accessed{$id}=[&gettimeofday()];
 2445:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 2446:     my $to_kick;
 2447:     my $max_time=0;
 2448:     foreach my $other (keys(%accessed)) {
 2449: 	if (&tv_interval($accessed{$other}) > $max_time) {
 2450: 	    $to_kick=$other;
 2451: 	    $max_time=&tv_interval($accessed{$other});
 2452: 	}
 2453:     }
 2454:     delete($remembered{$to_kick});
 2455:     delete($accessed{$to_kick});
 2456:     $kicks++;
 2457:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 2458:     return;
 2459: }
 2460: 
 2461: sub purge_remembered {
 2462:     #&logthis("Tossing ".scalar(keys(%remembered)));
 2463:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 2464:     undef(%remembered);
 2465:     undef(%accessed);
 2466: }
 2467: # ------------------------------------- Read an entry from a user's environment
 2468: 
 2469: sub userenvironment {
 2470:     my ($udom,$unam,@what)=@_;
 2471:     my $items;
 2472:     foreach my $item (@what) {
 2473:         $items.=&escape($item).'&';
 2474:     }
 2475:     $items=~s/\&$//;
 2476:     my %returnhash=();
 2477:     my $uhome = &homeserver($unam,$udom);
 2478:     unless ($uhome eq 'no_host') {
 2479:         my @answer=split(/\&/, 
 2480:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 2481:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 2482:             return %returnhash;
 2483:         }
 2484:         my $i;
 2485:         for ($i=0;$i<=$#what;$i++) {
 2486: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 2487:         }
 2488:     }
 2489:     return %returnhash;
 2490: }
 2491: 
 2492: # ---------------------------------------------------------- Get a studentphoto
 2493: sub studentphoto {
 2494:     my ($udom,$unam,$ext) = @_;
 2495:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2496:     if (defined($env{'request.course.id'})) {
 2497:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 2498:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 2499:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 2500:             } else {
 2501:                 my ($result,$perm_reqd)=
 2502: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2503:                 if ($result eq 'ok') {
 2504:                     if (!($perm_reqd eq 'yes')) {
 2505:                         return(&retrievestudentphoto($udom,$unam,$ext));
 2506:                     }
 2507:                 }
 2508:             }
 2509:         }
 2510:     } else {
 2511:         my ($result,$perm_reqd) = 
 2512: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2513:         if ($result eq 'ok') {
 2514:             if (!($perm_reqd eq 'yes')) {
 2515:                 return(&retrievestudentphoto($udom,$unam,$ext));
 2516:             }
 2517:         }
 2518:     }
 2519:     return '/adm/lonKaputt/lonlogo_broken.gif';
 2520: }
 2521: 
 2522: sub retrievestudentphoto {
 2523:     my ($udom,$unam,$ext,$type) = @_;
 2524:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2525:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 2526:     if ($ret eq 'ok') {
 2527:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 2528:         if ($type eq 'thumbnail') {
 2529:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 2530:         }
 2531:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 2532:         return $tokenurl;
 2533:     } else {
 2534:         if ($type eq 'thumbnail') {
 2535:             return '/adm/lonKaputt/genericstudent_tn.gif';
 2536:         } else { 
 2537:             return '/adm/lonKaputt/lonlogo_broken.gif';
 2538:         }
 2539:     }
 2540: }
 2541: 
 2542: # -------------------------------------------------------------------- New chat
 2543: 
 2544: sub chatsend {
 2545:     my ($newentry,$anon,$group)=@_;
 2546:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 2547:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2548:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 2549:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 2550: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 2551: 		   &escape($newentry)).':'.$group,$chome);
 2552: }
 2553: 
 2554: # ------------------------------------------ Find current version of a resource
 2555: 
 2556: sub getversion {
 2557:     my $fname=&clutter(shift);
 2558:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
 2559:     return &currentversion(&filelocation('',$fname));
 2560: }
 2561: 
 2562: sub currentversion {
 2563:     my $fname=shift;
 2564:     my $author=$fname;
 2565:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2566:     my ($udom,$uname)=split(/\//,$author);
 2567:     my $home=&homeserver($uname,$udom);
 2568:     if ($home eq 'no_host') { 
 2569:         return -1; 
 2570:     }
 2571:     my $answer=&reply("currentversion:$fname",$home);
 2572:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2573: 	return -1;
 2574:     }
 2575:     return $answer;
 2576: }
 2577: 
 2578: #
 2579: # Return special version number of resource if set by override, empty otherwise
 2580: #
 2581: sub usedversion {
 2582:     my $fname=shift;
 2583:     unless ($fname) { $fname=$env{'request.uri'}; }
 2584:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 2585:     if ($urlversion) { return $urlversion; }
 2586:     return '';
 2587: }
 2588: 
 2589: # ----------------------------- Subscribe to a resource, return URL if possible
 2590: 
 2591: sub subscribe {
 2592:     my $fname=shift;
 2593:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 2594:     $fname=~s/[\n\r]//g;
 2595:     my $author=$fname;
 2596:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2597:     my ($udom,$uname)=split(/\//,$author);
 2598:     my $home=homeserver($uname,$udom);
 2599:     if ($home eq 'no_host') {
 2600:         return 'not_found';
 2601:     }
 2602:     my $answer=reply("sub:$fname",$home);
 2603:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2604: 	$answer.=' by '.$home;
 2605:     }
 2606:     return $answer;
 2607: }
 2608:     
 2609: # -------------------------------------------------------------- Replicate file
 2610: 
 2611: sub repcopy {
 2612:     my $filename=shift;
 2613:     $filename=~s/\/+/\//g;
 2614:     my $londocroot = $perlvar{'lonDocRoot'};
 2615:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 2616:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 2617:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 2618: 	$filename=~m{^/*(uploaded|editupload)/}) {
 2619: 	return &repcopy_userfile($filename);
 2620:     }
 2621:     $filename=~s/[\n\r]//g;
 2622:     my $transname="$filename.in.transfer";
 2623: # FIXME: this should flock
 2624:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 2625:     my $remoteurl=subscribe($filename);
 2626:     if ($remoteurl =~ /^con_lost by/) {
 2627: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2628:            return 'unavailable';
 2629:     } elsif ($remoteurl eq 'not_found') {
 2630: 	   #&logthis("Subscribe returned not_found: $filename");
 2631: 	   return 'not_found';
 2632:     } elsif ($remoteurl =~ /^rejected by/) {
 2633: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2634:            return 'forbidden';
 2635:     } elsif ($remoteurl eq 'directory') {
 2636:            return 'ok';
 2637:     } else {
 2638:         my $author=$filename;
 2639:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2640:         my ($udom,$uname)=split(/\//,$author);
 2641:         my $home=homeserver($uname,$udom);
 2642:         unless ($home eq $perlvar{'lonHostID'}) {
 2643:            my @parts=split(/\//,$filename);
 2644:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 2645:            if ($path ne "$londocroot/res") {
 2646:                &logthis("Malconfiguration for replication: $filename");
 2647: 	       return 'bad_request';
 2648:            }
 2649:            my $count;
 2650:            for ($count=5;$count<$#parts;$count++) {
 2651:                $path.="/$parts[$count]";
 2652:                if ((-e $path)!=1) {
 2653: 		   mkdir($path,0777);
 2654:                }
 2655:            }
 2656:            my $ua=new LWP::UserAgent;
 2657:            my $request=new HTTP::Request('GET',"$remoteurl");
 2658:            my $response=$ua->request($request,$transname);
 2659:            if ($response->is_error()) {
 2660: 	       unlink($transname);
 2661:                my $message=$response->status_line;
 2662:                &logthis("<font color=\"blue\">WARNING:"
 2663:                        ." LWP get: $message: $filename</font>");
 2664:                return 'unavailable';
 2665:            } else {
 2666: 	       if ($remoteurl!~/\.meta$/) {
 2667:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 2668:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 2669:                   if ($mresponse->is_error()) {
 2670: 		      unlink($filename.'.meta');
 2671:                       &logthis(
 2672:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 2673:                   }
 2674: 	       }
 2675:                rename($transname,$filename);
 2676:                return 'ok';
 2677:            }
 2678:        }
 2679:     }
 2680: }
 2681: 
 2682: # ------------------------------------------------ Get server side include body
 2683: sub ssi_body {
 2684:     my ($filelink,%form)=@_;
 2685:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 2686:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 2687:     }
 2688:     my $output='';
 2689:     my $response;
 2690:     if ($filelink=~/^https?\:/) {
 2691:        ($output,$response)=&externalssi($filelink);
 2692:     } else {
 2693:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 2694:        $filelink .= 'inhibitmenu=yes';
 2695:        ($output,$response)=&ssi($filelink,%form);
 2696:     }
 2697:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 2698:     $output=~s/^.*?\<body[^\>]*\>//si;
 2699:     $output=~s/\<\/body\s*\>.*?$//si;
 2700:     if (wantarray) {
 2701:         return ($output, $response);
 2702:     } else {
 2703:         return $output;
 2704:     }
 2705: }
 2706: 
 2707: # --------------------------------------------------------- Server Side Include
 2708: 
 2709: sub absolute_url {
 2710:     my ($host_name) = @_;
 2711:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 2712:     if ($host_name eq '') {
 2713: 	$host_name = $ENV{'SERVER_NAME'};
 2714:     }
 2715:     return $protocol.$host_name;
 2716: }
 2717: 
 2718: #
 2719: #   Server side include.
 2720: # Parameters:
 2721: #  fn     Possibly encrypted resource name/id.
 2722: #  form   Hash that describes how the rendering should be done
 2723: #         and other things.
 2724: # Returns:
 2725: #   Scalar context: The content of the response.
 2726: #   Array context:  2 element list of the content and the full response object.
 2727: #     
 2728: sub ssi {
 2729: 
 2730:     my ($fn,%form)=@_;
 2731:     my $ua=new LWP::UserAgent;
 2732:     my $request;
 2733: 
 2734:     $form{'no_update_last_known'}=1;
 2735:     &Apache::lonenc::check_encrypt(\$fn);
 2736:     if (%form) {
 2737:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 2738:       $request->content(join('&',map {
 2739:             my $name = escape($_);
 2740:             "$name=" . ( ref($form{$_}) eq 'ARRAY'
 2741:             ? join("&$name=", map {escape($_) } @{$form{$_}})
 2742:             : &escape($form{$_}) );
 2743:         } keys(%form)));
 2744:     } else {
 2745:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 2746:     }
 2747: 
 2748:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 2749:     my $response= $ua->request($request);
 2750:     if (wantarray) {
 2751: 	return ($response->content, $response);
 2752:     } else {
 2753: 	return $response->content;
 2754:     }
 2755: }
 2756: 
 2757: sub externalssi {
 2758:     my ($url)=@_;
 2759:     my $ua=new LWP::UserAgent;
 2760:     my $request=new HTTP::Request('GET',$url);
 2761:     my $response=$ua->request($request);
 2762:     if (wantarray) {
 2763:         return ($response->content, $response);
 2764:     } else {
 2765:         return $response->content;
 2766:     }
 2767: }
 2768: 
 2769: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 2770: 
 2771: sub allowuploaded {
 2772:     my ($srcurl,$url)=@_;
 2773:     $url=&clutter(&declutter($url));
 2774:     my $dir=$url;
 2775:     $dir=~s/\/[^\/]+$//;
 2776:     my %httpref=();
 2777:     my $httpurl=&hreflocation('',$url);
 2778:     $httpref{'httpref.'.$httpurl}=$srcurl;
 2779:     &Apache::lonnet::appenv(\%httpref);
 2780: }
 2781: 
 2782: #
 2783: # Determine if the current user should be able to edit a particular resource,
 2784: # when viewing in course context.
 2785: # (a) When viewing resource used to determine if "Edit" item is included in
 2786: #     Functions.
 2787: # (b) When displaying folder contents in course editor, used to determine if
 2788: #     "Edit" link will be displayed alongside resource.
 2789: #
 2790: #  input: six args -- filename (decluttered), course number, course domain,
 2791: #                   url, symb (if registered) and group (if this is a group
 2792: #                   item -- e.g., bulletin board, group page etc.).
 2793: #  output: array of five scalars --
 2794: #          $cfile -- url for file editing if editable on current server
 2795: #          $home -- homeserver of resource (i.e., for author if published,
 2796: #                                           or course if uploaded.).
 2797: #          $switchserver --  1 if server switch will be needed.
 2798: #          $forceedit -- 1 if icon/link should be to go to edit mode
 2799: #          $forceview -- 1 if icon/link should be to go to view mode
 2800: #
 2801: 
 2802: sub can_edit_resource {
 2803:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
 2804:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
 2805: #
 2806: # For aboutme pages user can only edit his/her own.
 2807: #
 2808:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
 2809:         my ($sdom,$sname) = ($1,$2);
 2810:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
 2811:             $home = $env{'user.home'};
 2812:             $cfile = $resurl;
 2813:             if ($env{'form.forceedit'}) {
 2814:                 $forceview = 1;
 2815:             } else {
 2816:                 $forceedit = 1;
 2817:             }
 2818:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
 2819:         } else {
 2820:             return;
 2821:         }
 2822:     }
 2823: 
 2824:     if ($env{'request.course.id'}) {
 2825:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
 2826:         if ($group ne '') {
 2827: # if this is a group homepage or group bulletin board, check group privs
 2828:             my $allowed = 0;
 2829:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
 2830:                 if ((&allowed('mdg',$env{'request.course.id'}.
 2831:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 2832:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 2833:                     $allowed = 1;
 2834:                 }
 2835:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
 2836:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
 2837:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
 2838:                     $allowed = 1;
 2839:                 }
 2840:             }
 2841:             if ($allowed) {
 2842:                 $home=&homeserver($cnum,$cdom);
 2843:                 if ($env{'form.forceedit'}) {
 2844:                     $forceview = 1;
 2845:                 } else {
 2846:                     $forceedit = 1;
 2847:                 }
 2848:                 $cfile = $resurl;
 2849:             } else {
 2850:                 return;
 2851:             }
 2852:         } else {
 2853:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
 2854:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
 2855:                     return;
 2856:                 }
 2857:             } elsif (!$crsedit) {
 2858: #
 2859: # No edit allowed where CC has switched to student role.
 2860: #
 2861:                 return;
 2862:             }
 2863:         }
 2864:     }
 2865: 
 2866:     if ($file ne '') {
 2867:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
 2868:             if (&is_course_upload($file,$cnum,$cdom)) {
 2869:                 $uploaded = 1;
 2870:                 $incourse = 1;
 2871:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
 2872:                     $cfile = &hreflocation('',$file);
 2873:                     if ($env{'form.forceedit'}) {
 2874:                         $forceview = 1;
 2875:                     } else {
 2876:                         $forceedit = 1;
 2877:                     }
 2878:                 }
 2879:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
 2880:                 $incourse = 1;
 2881:                 if ($env{'form.forceedit'}) {
 2882:                     $forceview = 1;
 2883:                 } else {
 2884:                     $forceedit = 1;
 2885:                 }
 2886:                 $cfile = $resurl;
 2887:             } elsif (($resurl ne '') && (&is_on_map($resurl))) {
 2888:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
 2889:                     $incourse = 1;
 2890:                     if ($env{'form.forceedit'}) {
 2891:                         $forceview = 1;
 2892:                     } else {
 2893:                         $forceedit = 1;
 2894:                     }
 2895:                     $cfile = $resurl;
 2896:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
 2897:                     $incourse = 1;
 2898:                     $cfile = $resurl.'/smpedit';
 2899:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
 2900:                     $incourse = 1;
 2901:                     if ($env{'form.forceedit'}) {
 2902:                         $forceview = 1;
 2903:                     } else {
 2904:                         $forceedit = 1;
 2905:                     }
 2906:                     $cfile = $resurl;
 2907:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 2908:                     $incourse = 1;
 2909:                     if ($env{'form.forceedit'}) {
 2910:                         $forceview = 1;
 2911:                     } else {
 2912:                         $forceedit = 1;
 2913:                     }
 2914:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 2915:                 }
 2916:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
 2917:                 my $template = '/res/lib/templates/simpleproblem.problem';
 2918:                 if (&is_on_map($template)) {
 2919:                     $incourse = 1;
 2920:                     $forceview = 1;
 2921:                     $cfile = $template;
 2922:                 }
 2923:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
 2924:                     $incourse = 1;
 2925:                     if ($env{'form.forceedit'}) {
 2926:                         $forceview = 1;
 2927:                     } else {
 2928:                         $forceedit = 1;
 2929:                     }
 2930:                     $cfile = $resurl;
 2931:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
 2932:                 $incourse = 1;
 2933:                 $forceview = 1;
 2934:                 if ($symb) {
 2935:                     my ($map,$id,$res)=&decode_symb($symb);
 2936:                     $env{'request.symb'} = $symb;
 2937:                     $cfile = &clutter($res);
 2938:                 } else {
 2939:                     $cfile = $env{'form.suppurl'};
 2940:                     $cfile =~ s{^http://}{};
 2941:                     $cfile = '/adm/wrapper/ext/'.$cfile;
 2942:                 }
 2943:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
 2944:                 if ($env{'form.forceedit'}) {
 2945:                     $forceview = 1;
 2946:                 } else {
 2947:                     $forceedit = 1;
 2948:                 }
 2949:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
 2950:             }
 2951:         }
 2952:         if ($uploaded || $incourse) {
 2953:             $home=&homeserver($cnum,$cdom);
 2954:         } elsif ($file !~ m{/$}) {
 2955:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
 2956:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
 2957:             # Check that the user has permission to edit this resource
 2958:             my $setpriv = 1;
 2959:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
 2960:             if (defined($cfudom)) {
 2961:                 $home=&homeserver($cfuname,$cfudom);
 2962:                 $cfile=$file;
 2963:             }
 2964:         }
 2965:         if (($cfile ne '') && (!$incourse || $uploaded) &&
 2966:             (($home ne '') && ($home ne 'no_host'))) {
 2967:             my @ids=&current_machine_ids();
 2968:             unless (grep(/^\Q$home\E$/,@ids)) {
 2969:                 $switchserver=1;
 2970:             }
 2971:         }
 2972:     }
 2973:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
 2974: }
 2975: 
 2976: sub is_course_upload {
 2977:     my ($file,$cnum,$cdom) = @_;
 2978:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
 2979:     $uploadpath =~ s{^\/}{};
 2980:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
 2981:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
 2982:         return 1;
 2983:     }
 2984:     return;
 2985: }
 2986: 
 2987: sub in_course {
 2988:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
 2989:     if ($hideprivileged) {
 2990:         my $skipuser;
 2991:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
 2992:         my @possdoms = ($cdom);
 2993:         if ($coursehash{'checkforpriv'}) {
 2994:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 2995:         }
 2996:         if (&privileged($uname,$udom,\@possdoms)) {
 2997:             $skipuser = 1;
 2998:             if ($coursehash{'nothideprivileged'}) {
 2999:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3000:                     my $user;
 3001:                     if ($item =~ /:/) {
 3002:                         $user = $item;
 3003:                     } else {
 3004:                         $user = join(':',split(/[\@]/,$item));
 3005:                     }
 3006:                     if ($user eq $uname.':'.$udom) {
 3007:                         undef($skipuser);
 3008:                         last;
 3009:                     }
 3010:                 }
 3011:             }
 3012:             if ($skipuser) {
 3013:                 return 0;
 3014:             }
 3015:         }
 3016:     }
 3017:     $type ||= 'any';
 3018:     if (!defined($cdom) || !defined($cnum)) {
 3019:         my $cid  = $env{'request.course.id'};
 3020:         $cdom = $env{'course.'.$cid.'.domain'};
 3021:         $cnum = $env{'course.'.$cid.'.num'};
 3022:     }
 3023:     my $typesref;
 3024:     if (($type eq 'any') || ($type eq 'all')) {
 3025:         $typesref = ['active','previous','future'];
 3026:     } elsif ($type eq 'previous' || $type eq 'future') {
 3027:         $typesref = [$type];
 3028:     }
 3029:     my %roles = &get_my_roles($uname,$udom,'userroles',
 3030:                               $typesref,undef,[$cdom]);
 3031:     my ($tmp) = keys(%roles);
 3032:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
 3033:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
 3034:     if (@course_roles > 0) {
 3035:         return 1;
 3036:     }
 3037:     return 0;
 3038: }
 3039: 
 3040: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 3041: # input: action, courseID, current domain, intended
 3042: #        path to file, source of file, instruction to parse file for objects,
 3043: #        ref to hash for embedded objects,
 3044: #        ref to hash for codebase of java objects.
 3045: #        reference to scalar to accommodate mime type determined
 3046: #          from File::MMagic if $parser = parse.
 3047: #
 3048: # output: url to file (if action was uploaddoc), 
 3049: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 3050: #
 3051: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 3052: # course.
 3053: #
 3054: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3055: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 3056: #          course's home server.
 3057: #
 3058: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 3059: #          be copied from $source (current location) to 
 3060: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3061: #         and will then be copied to
 3062: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 3063: #         course's home server.
 3064: #
 3065: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3066: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 3067: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 3068: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 3069: #         in course's home server.
 3070: #
 3071: 
 3072: sub process_coursefile {
 3073:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 3074:         $mimetype)=@_;
 3075:     my $fetchresult;
 3076:     my $home=&homeserver($docuname,$docudom);
 3077:     if ($action eq 'propagate') {
 3078:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3079: 			     $home);
 3080:     } else {
 3081:         my $fpath = '';
 3082:         my $fname = $file;
 3083:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3084:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3085:         my $filepath = &build_filepath($fpath);
 3086:         if ($action eq 'copy') {
 3087:             if ($source eq '') {
 3088:                 $fetchresult = 'no source file';
 3089:                 return $fetchresult;
 3090:             } else {
 3091:                 my $destination = $filepath.'/'.$fname;
 3092:                 rename($source,$destination);
 3093:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3094:                                  $home);
 3095:             }
 3096:         } elsif ($action eq 'uploaddoc') {
 3097:             open(my $fh,'>'.$filepath.'/'.$fname);
 3098:             print $fh $env{'form.'.$source};
 3099:             close($fh);
 3100:             if ($parser eq 'parse') {
 3101:                 my $mm = new File::MMagic;
 3102:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 3103:                 if ($type eq 'text/html') {
 3104:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 3105:                     unless ($parse_result eq 'ok') {
 3106:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 3107:                     }
 3108:                 }
 3109:                 if (ref($mimetype)) {
 3110:                     $$mimetype = $type;
 3111:                 } 
 3112:             }
 3113:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3114:                                  $home);
 3115:             if ($fetchresult eq 'ok') {
 3116:                 return '/uploaded/'.$fpath.'/'.$fname;
 3117:             } else {
 3118:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3119:                         ' to host '.$home.': '.$fetchresult);
 3120:                 return '/adm/notfound.html';
 3121:             }
 3122:         }
 3123:     }
 3124:     unless ( $fetchresult eq 'ok') {
 3125:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3126:              ' to host '.$home.': '.$fetchresult);
 3127:     }
 3128:     return $fetchresult;
 3129: }
 3130: 
 3131: sub build_filepath {
 3132:     my ($fpath) = @_;
 3133:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 3134:     unless ($fpath eq '') {
 3135:         my @parts=split('/',$fpath);
 3136:         foreach my $part (@parts) {
 3137:             $filepath.= '/'.$part;
 3138:             if ((-e $filepath)!=1) {
 3139:                 mkdir($filepath,0777);
 3140:             }
 3141:         }
 3142:     }
 3143:     return $filepath;
 3144: }
 3145: 
 3146: sub store_edited_file {
 3147:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 3148:     my $file = $primary_url;
 3149:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 3150:     my $fpath = '';
 3151:     my $fname = $file;
 3152:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 3153:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 3154:     my $filepath = &build_filepath($fpath);
 3155:     open(my $fh,'>'.$filepath.'/'.$fname);
 3156:     print $fh $content;
 3157:     close($fh);
 3158:     my $home=&homeserver($docuname,$docudom);
 3159:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 3160: 			  $home);
 3161:     if ($$fetchresult eq 'ok') {
 3162:         return '/uploaded/'.$fpath.'/'.$fname;
 3163:     } else {
 3164:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 3165: 		 ' to host '.$home.': '.$$fetchresult);
 3166:         return '/adm/notfound.html';
 3167:     }
 3168: }
 3169: 
 3170: sub clean_filename {
 3171:     my ($fname,$args)=@_;
 3172: # Replace Windows backslashes by forward slashes
 3173:     $fname=~s/\\/\//g;
 3174:     if (!$args->{'keep_path'}) {
 3175:         # Get rid of everything but the actual filename
 3176: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 3177:     }
 3178: # Replace spaces by underscores
 3179:     $fname=~s/\s+/\_/g;
 3180: # Replace all other weird characters by nothing
 3181:     $fname=~s{[^/\w\.\-]}{}g;
 3182: # Replace all .\d. sequences with _\d. so they no longer look like version
 3183: # numbers
 3184:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 3185:     return $fname;
 3186: }
 3187: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 3188: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 3189: # image with the same aspect ratio as the original, but with dimensions which do 
 3190: # not exceed $resizewidth and $resizeheight.
 3191:  
 3192: sub resizeImage {
 3193:     my ($img_path,$resizewidth,$resizeheight) = @_;
 3194:     my $ima = Image::Magick->new;
 3195:     my $resized;
 3196:     if (-e $img_path) {
 3197:         $ima->Read($img_path);
 3198:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 3199:             my $width = $ima->Get('width');
 3200:             my $height = $ima->Get('height');
 3201:             if ($width > $resizewidth) {
 3202: 	        my $factor = $width/$resizewidth;
 3203:                 my $newheight = $height/$factor;
 3204:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 3205:                 $resized = 1;
 3206:             }
 3207:         }
 3208:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 3209:             my $width = $ima->Get('width');
 3210:             my $height = $ima->Get('height');
 3211:             if ($height > $resizeheight) {
 3212:                 my $factor = $height/$resizeheight;
 3213:                 my $newwidth = $width/$factor;
 3214:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 3215:                 $resized = 1;
 3216:             }
 3217:         }
 3218:         if ($resized) {
 3219:             $ima->Write($img_path);
 3220:         }
 3221:     }
 3222:     return;
 3223: }
 3224: 
 3225: # --------------- Take an uploaded file and put it into the userfiles directory
 3226: # input: $formname - the contents of the file are in $env{"form.$formname"}
 3227: #                    the desired filename is in $env{"form.$formname.filename"}
 3228: #        $context - possible values: coursedoc, existingfile, overwrite, 
 3229: #                                    canceloverwrite, or ''. 
 3230: #                   if 'coursedoc': upload to the current course
 3231: #                   if 'existingfile': write file to tmp/overwrites directory 
 3232: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 3233: #                   $context is passed as argument to &finishuserfileupload
 3234: #        $subdir - directory in userfile to store the file into
 3235: #        $parser - instruction to parse file for objects ($parser = parse)    
 3236: #        $allfiles - reference to hash for embedded objects
 3237: #        $codebase - reference to hash for codebase of java objects
 3238: #        $desuname - username for permanent storage of uploaded file
 3239: #        $dsetudom - domain for permanaent storage of uploaded file
 3240: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 3241: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 3242: #        $resizewidth - width (pixels) to which to resize uploaded image
 3243: #        $resizeheight - height (pixels) to which to resize uploaded image
 3244: #        $mimetype - reference to scalar to accommodate mime type determined
 3245: #                    from File::MMagic.
 3246: # 
 3247: # output: url of file in userspace, or error: <message> 
 3248: #             or /adm/notfound.html if failure to upload occurse
 3249: 
 3250: sub userfileupload {
 3251:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 3252:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 3253:     if (!defined($subdir)) { $subdir='unknown'; }
 3254:     my $fname=$env{'form.'.$formname.'.filename'};
 3255:     $fname=&clean_filename($fname);
 3256:     # See if there is anything left
 3257:     unless ($fname) { return 'error: no uploaded file'; }
 3258:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 3259:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 3260:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 3261:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3262:         my $now = time;
 3263:         my $filepath;
 3264:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 3265:              $filepath = 'tmp/helprequests/'.$now;
 3266:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 3267:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 3268:                          '_'.$env{'user.domain'}.'/pending';
 3269:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 3270:             my ($docuname,$docudom);
 3271:             if ($destudom) {
 3272:                 $docudom = $destudom;
 3273:             } else {
 3274:                 $docudom = $env{'user.domain'};
 3275:             }
 3276:             if ($destuname) {
 3277:                 $docuname = $destuname;
 3278:             } else {
 3279:                 $docuname = $env{'user.name'};
 3280:             }
 3281:             if (exists($env{'form.group'})) {
 3282:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3283:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3284:             }
 3285:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 3286:             if ($context eq 'canceloverwrite') {
 3287:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 3288:                 if (-e  $tempfile) {
 3289:                     my @info = stat($tempfile);
 3290:                     if ($info[9] eq $env{'form.timestamp'}) {
 3291:                         unlink($tempfile);
 3292:                     }
 3293:                 }
 3294:                 return;
 3295:             }
 3296:         }
 3297:         # Create the directory if not present
 3298:         my @parts=split(/\//,$filepath);
 3299:         my $fullpath = $perlvar{'lonDaemons'};
 3300:         for (my $i=0;$i<@parts;$i++) {
 3301:             $fullpath .= '/'.$parts[$i];
 3302:             if ((-e $fullpath)!=1) {
 3303:                 mkdir($fullpath,0777);
 3304:             }
 3305:         }
 3306:         open(my $fh,'>'.$fullpath.'/'.$fname);
 3307:         print $fh $env{'form.'.$formname};
 3308:         close($fh);
 3309:         if ($context eq 'existingfile') {
 3310:             my @info = stat($fullpath.'/'.$fname);
 3311:             return ($fullpath.'/'.$fname,$info[9]);
 3312:         } else {
 3313:             return $fullpath.'/'.$fname;
 3314:         }
 3315:     }
 3316:     if ($subdir eq 'scantron') {
 3317:         $fname = 'scantron_orig_'.$fname;
 3318:     } else {
 3319:         $fname="$subdir/$fname";
 3320:     }
 3321:     if ($context eq 'coursedoc') {
 3322: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3323: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3324:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 3325:             return &finishuserfileupload($docuname,$docudom,
 3326: 					 $formname,$fname,$parser,$allfiles,
 3327: 					 $codebase,$thumbwidth,$thumbheight,
 3328:                                          $resizewidth,$resizeheight,$context,$mimetype);
 3329:         } else {
 3330:             if ($env{'form.folder'}) {
 3331:                 $fname=$env{'form.folder'}.'/'.$fname;
 3332:             }
 3333:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 3334: 				       $fname,$formname,$parser,
 3335: 				       $allfiles,$codebase,$mimetype);
 3336:         }
 3337:     } elsif (defined($destuname)) {
 3338:         my $docuname=$destuname;
 3339:         my $docudom=$destudom;
 3340: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3341: 				     $parser,$allfiles,$codebase,
 3342:                                      $thumbwidth,$thumbheight,
 3343:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3344:     } else {
 3345:         my $docuname=$env{'user.name'};
 3346:         my $docudom=$env{'user.domain'};
 3347:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
 3348:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 3349:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 3350:         }
 3351: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 3352: 				     $parser,$allfiles,$codebase,
 3353:                                      $thumbwidth,$thumbheight,
 3354:                                      $resizewidth,$resizeheight,$context,$mimetype);
 3355:     }
 3356: }
 3357: 
 3358: sub finishuserfileupload {
 3359:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 3360:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 3361:     my $path=$docudom.'/'.$docuname.'/';
 3362:     my $filepath=$perlvar{'lonDocRoot'};
 3363:   
 3364:     my ($fnamepath,$file,$fetchthumb);
 3365:     $file=$fname;
 3366:     if ($fname=~m|/|) {
 3367:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 3368: 	$path.=$fnamepath.'/';
 3369:     }
 3370:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 3371:     my $count;
 3372:     for ($count=4;$count<=$#parts;$count++) {
 3373:         $filepath.="/$parts[$count]";
 3374:         if ((-e $filepath)!=1) {
 3375: 	    mkdir($filepath,0777);
 3376:         }
 3377:     }
 3378: 
 3379: # Save the file
 3380:     {
 3381: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 3382: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 3383: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 3384: 	    return '/adm/notfound.html';
 3385: 	}
 3386:         if ($context eq 'overwrite') {
 3387:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 3388:             my $target = $filepath.'/'.$file;
 3389:             if (-e $source) {
 3390:                 my @info = stat($source);
 3391:                 if ($info[9] eq $env{'form.timestamp'}) {   
 3392:                     unless (&File::Copy::move($source,$target)) {
 3393:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 3394:                         return "Moving from $source failed";
 3395:                     }
 3396:                 } else {
 3397:                     return "Temporary file: $source had unexpected date/time for last modification";
 3398:                 }
 3399:             } else {
 3400:                 return "Temporary file: $source missing";
 3401:             }
 3402:         } elsif (!print FH ($env{'form.'.$formname})) {
 3403: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 3404: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 3405: 	    return '/adm/notfound.html';
 3406: 	}
 3407: 	close(FH);
 3408:         if ($resizewidth && $resizeheight) {
 3409:             my $mm = new File::MMagic;
 3410:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 3411:             if ($mime_type =~ m{^image/}) {
 3412: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 3413:             }  
 3414: 	}
 3415:     }
 3416:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 3417:         if (ref($mimetype)) {
 3418:             if ($$mimetype eq '') {
 3419:                 my $mm = new File::MMagic;
 3420:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 3421:                 $$mimetype = $type;
 3422:             }
 3423:         }
 3424:     }
 3425:     if ($parser eq 'parse') {
 3426:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 3427:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 3428:                                                        $allfiles,$codebase);
 3429:             unless ($parse_result eq 'ok') {
 3430:                 &logthis('Failed to parse '.$filepath.$file.
 3431: 	   	         ' for embedded media: '.$parse_result); 
 3432:             }
 3433:         }
 3434:     }
 3435:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 3436:         my $input = $filepath.'/'.$file;
 3437:         my $output = $filepath.'/'.'tn-'.$file;
 3438:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 3439:         system("convert -sample $thumbsize $input $output");
 3440:         if (-e $filepath.'/'.'tn-'.$file) {
 3441:             $fetchthumb  = 1; 
 3442:         }
 3443:     }
 3444:  
 3445: # Notify homeserver to grep it
 3446: #
 3447:     my $docuhome=&homeserver($docuname,$docudom);	
 3448:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 3449:     if ($fetchresult eq 'ok') {
 3450:         if ($fetchthumb) {
 3451:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 3452:             if ($thumbresult ne 'ok') {
 3453:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 3454:                          $docuhome.': '.$thumbresult);
 3455:             }
 3456:         }
 3457: #
 3458: # Return the URL to it
 3459:         return '/uploaded/'.$path.$file;
 3460:     } else {
 3461:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 3462: 		 ': '.$fetchresult);
 3463:         return '/adm/notfound.html';
 3464:     }
 3465: }
 3466: 
 3467: sub extract_embedded_items {
 3468:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 3469:     my @state = ();
 3470:     my (%lastids,%related,%shockwave,%flashvars);
 3471:     my %javafiles = (
 3472:                       codebase => '',
 3473:                       code => '',
 3474:                       archive => ''
 3475:                     );
 3476:     my %mediafiles = (
 3477:                       src => '',
 3478:                       movie => '',
 3479:                      );
 3480:     my $p;
 3481:     if ($content) {
 3482:         $p = HTML::LCParser->new($content);
 3483:     } else {
 3484:         $p = HTML::LCParser->new($fullpath);
 3485:     }
 3486:     while (my $t=$p->get_token()) {
 3487: 	if ($t->[0] eq 'S') {
 3488: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 3489: 	    push(@state, $tagname);
 3490:             if (lc($tagname) eq 'allow') {
 3491:                 &add_filetype($allfiles,$attr->{'src'},'src');
 3492:             }
 3493: 	    if (lc($tagname) eq 'img') {
 3494: 		&add_filetype($allfiles,$attr->{'src'},'src');
 3495: 	    }
 3496: 	    if (lc($tagname) eq 'a') {
 3497:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
 3498: 		    &add_filetype($allfiles,$attr->{'href'},'href');
 3499:                 }
 3500: 	    }
 3501:             if (lc($tagname) eq 'script') {
 3502:                 my $src;
 3503:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 3504:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 3505:                 } else {
 3506:                     if ($attr->{'src'} ne '') {
 3507:                         $src = $attr->{'src'};
 3508:                         &add_filetype($allfiles,$src,'src');
 3509:                     }
 3510:                 }
 3511:                 my $text = $p->get_trimmed_text();
 3512:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 3513:                     my @swfargs = split(/,/,$1);
 3514:                     foreach my $item (@swfargs) {
 3515:                         $item =~ s/["']//g;
 3516:                         $item =~ s/^\s+//;
 3517:                         $item =~ s/\s+$//;
 3518:                     }
 3519:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 3520:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 3521:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 3522:                         } else {
 3523:                             $related{$swfargs[0]} = [$swfargs[2]];
 3524:                         }
 3525:                     }
 3526:                 }
 3527:             }
 3528:             if (lc($tagname) eq 'link') {
 3529:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 3530:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3531:                 }
 3532:             }
 3533: 	    if (lc($tagname) eq 'object' ||
 3534: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 3535: 		foreach my $item (keys(%javafiles)) {
 3536: 		    $javafiles{$item} = '';
 3537: 		}
 3538:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 3539:                     $lastids{lc($tagname)} = $attr->{'id'};
 3540:                 }
 3541: 	    }
 3542: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 3543: 		my $name = lc($attr->{'name'});
 3544: 		foreach my $item (keys(%javafiles)) {
 3545: 		    if ($name eq $item) {
 3546: 			$javafiles{$item} = $attr->{'value'};
 3547: 			last;
 3548: 		    }
 3549: 		}
 3550:                 my $pathfrom;
 3551: 		foreach my $item (keys(%mediafiles)) {
 3552: 		    if ($name eq $item) {
 3553:                         $pathfrom = $attr->{'value'};
 3554:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 3555: 			&add_filetype($allfiles,$pathfrom,$name);
 3556: 			last;
 3557: 		    }
 3558: 		}
 3559:                 if ($name eq 'flashvars') {
 3560:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 3561:                 }
 3562:                 if ($pathfrom ne '') {
 3563:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 3564:                                          $pathfrom);
 3565:                 }
 3566: 	    }
 3567: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 3568: 		foreach my $item (keys(%javafiles)) {
 3569: 		    if ($attr->{$item}) {
 3570: 			$javafiles{$item} = $attr->{$item};
 3571: 			last;
 3572: 		    }
 3573: 		}
 3574: 		foreach my $item (keys(%mediafiles)) {
 3575: 		    if ($attr->{$item}) {
 3576: 			&add_filetype($allfiles,$attr->{$item},$item);
 3577: 			last;
 3578: 		    }
 3579: 		}
 3580:                 if (lc($tagname) eq 'embed') {
 3581:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 3582:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 3583:                                              $attr->{'src'});
 3584:                     }
 3585:                 }
 3586: 	    }
 3587:             if (lc($tagname) eq 'iframe') {
 3588:                 my $src = $attr->{'src'} ;
 3589:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
 3590:                     &add_filetype($allfiles,$src,'src');
 3591:                 } elsif ($src =~ m{^/}) {
 3592:                     if ($env{'request.course.id'}) {
 3593:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 3594:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 3595:                         my $url = &hreflocation('',$fullpath);
 3596:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
 3597:                             my $relpath = $1;
 3598:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
 3599:                                 &add_filetype($allfiles,$1,'src');
 3600:                             }
 3601:                         }
 3602:                     }
 3603:                 }
 3604:             }
 3605:             if ($t->[4] =~ m{/>$}) {
 3606:                 pop(@state);
 3607:             }
 3608: 	} elsif ($t->[0] eq 'E') {
 3609: 	    my ($tagname) = ($t->[1]);
 3610: 	    if ($javafiles{'codebase'} ne '') {
 3611: 		$javafiles{'codebase'} .= '/';
 3612: 	    }  
 3613: 	    if (lc($tagname) eq 'applet' ||
 3614: 		lc($tagname) eq 'object' ||
 3615: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 3616: 		) {
 3617: 		foreach my $item (keys(%javafiles)) {
 3618: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 3619: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 3620: 			&add_filetype($allfiles,$file,$item);
 3621: 		    }
 3622: 		}
 3623: 	    } 
 3624: 	    pop @state;
 3625: 	}
 3626:     }
 3627:     foreach my $id (sort(keys(%flashvars))) {
 3628:         if ($shockwave{$id} ne '') {
 3629:             my @pairs = split(/\&/,$flashvars{$id});
 3630:             foreach my $pair (@pairs) {
 3631:                 my ($key,$value) = split(/\=/,$pair);
 3632:                 if ($key eq 'thumb') {
 3633:                     &add_filetype($allfiles,$value,$key);
 3634:                 } elsif ($key eq 'content') {
 3635:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 3636:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 3637:                     if ($ext ne '') {
 3638:                         &add_filetype($allfiles,$path.$value,$ext);
 3639:                     }
 3640:                 }
 3641:             }
 3642:         }
 3643:     }
 3644:     return 'ok';
 3645: }
 3646: 
 3647: sub add_filetype {
 3648:     my ($allfiles,$file,$type)=@_;
 3649:     if (exists($allfiles->{$file})) {
 3650: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 3651: 	    push(@{$allfiles->{$file}}, &escape($type));
 3652: 	}
 3653:     } else {
 3654: 	@{$allfiles->{$file}} = (&escape($type));
 3655:     }
 3656: }
 3657: 
 3658: sub embedded_dependency {
 3659:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 3660:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 3661:         if (($identifier ne '') &&
 3662:             (ref($related->{$identifier}) eq 'ARRAY') &&
 3663:             ($pathfrom ne '')) {
 3664:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 3665:             foreach my $dep (@{$related->{$identifier}}) {
 3666:                 &add_filetype($allfiles,$path.$dep,'object');
 3667:             }
 3668:         }
 3669:     }
 3670:     return;
 3671: }
 3672: 
 3673: sub removeuploadedurl {
 3674:     my ($url)=@_;	
 3675:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 3676:     return &removeuserfile($uname,$udom,$fname);
 3677: }
 3678: 
 3679: sub removeuserfile {
 3680:     my ($docuname,$docudom,$fname)=@_;
 3681:     my $home=&homeserver($docuname,$docudom);    
 3682:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 3683:     if ($result eq 'ok') {	
 3684:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 3685:             my $metafile = $fname.'.meta';
 3686:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 3687: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 3688:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 3689:             my $sqlresult = 
 3690:                 &update_portfolio_table($docuname,$docudom,$file,
 3691:                                         'portfolio_metadata',$group,
 3692:                                         'delete');
 3693:         }
 3694:     }
 3695:     return $result;
 3696: }
 3697: 
 3698: sub mkdiruserfile {
 3699:     my ($docuname,$docudom,$dir)=@_;
 3700:     my $home=&homeserver($docuname,$docudom);
 3701:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 3702: }
 3703: 
 3704: sub renameuserfile {
 3705:     my ($docuname,$docudom,$old,$new)=@_;
 3706:     my $home=&homeserver($docuname,$docudom);
 3707:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 3708:                         &escape("$old").':'.&escape("$new"),$home);
 3709:     if ($result eq 'ok') {
 3710:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 3711:             my $oldmeta = $old.'.meta';
 3712:             my $newmeta = $new.'.meta';
 3713:             my $metaresult = 
 3714:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 3715: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 3716:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 3717:             my $sqlresult = 
 3718:                 &update_portfolio_table($docuname,$docudom,$file,
 3719:                                         'portfolio_metadata',$group,
 3720:                                         'delete');
 3721:         }
 3722:     }
 3723:     return $result;
 3724: }
 3725: 
 3726: # ------------------------------------------------------------------------- Log
 3727: 
 3728: sub log {
 3729:     my ($dom,$nam,$hom,$what)=@_;
 3730:     return critical("log:$dom:$nam:$what",$hom);
 3731: }
 3732: 
 3733: # ------------------------------------------------------------------ Course Log
 3734: #
 3735: # This routine flushes several buffers of non-mission-critical nature
 3736: #
 3737: 
 3738: sub flushcourselogs {
 3739:     &logthis('Flushing log buffers');
 3740: #
 3741: # course logs
 3742: # This is a log of all transactions in a course, which can be used
 3743: # for data mining purposes
 3744: #
 3745: # It also collects the courseid database, which lists last transaction
 3746: # times and course titles for all courseids
 3747: #
 3748:     my %courseidbuffer=();
 3749:     foreach my $crsid (keys(%courselogs)) {
 3750:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 3751: 		          &escape($courselogs{$crsid}),
 3752: 		          $coursehombuf{$crsid}) eq 'ok') {
 3753: 	    delete $courselogs{$crsid};
 3754:         } else {
 3755:             &logthis('Failed to flush log buffer for '.$crsid);
 3756:             if (length($courselogs{$crsid})>40000) {
 3757:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 3758:                         " exceeded maximum size, deleting.</font>");
 3759:                delete $courselogs{$crsid};
 3760:             }
 3761:         }
 3762:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 3763:             'description' => $coursedescrbuf{$crsid},
 3764:             'inst_code'    => $courseinstcodebuf{$crsid},
 3765:             'type'        => $coursetypebuf{$crsid},
 3766:             'owner'       => $courseownerbuf{$crsid},
 3767:         };
 3768:     }
 3769: #
 3770: # Write course id database (reverse lookup) to homeserver of courses 
 3771: # Is used in pickcourse
 3772: #
 3773:     foreach my $crs_home (keys(%courseidbuffer)) {
 3774:         my $response = &courseidput(&host_domain($crs_home),
 3775:                                     $courseidbuffer{$crs_home},
 3776:                                     $crs_home,'timeonly');
 3777:     }
 3778: #
 3779: # File accesses
 3780: # Writes to the dynamic metadata of resources to get hit counts, etc.
 3781: #
 3782:     foreach my $entry (keys(%accesshash)) {
 3783:         if ($entry =~ /___count$/) {
 3784:             my ($dom,$name);
 3785:             ($dom,$name,undef)=
 3786: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 3787:             if (! defined($dom) || $dom eq '' || 
 3788:                 ! defined($name) || $name eq '') {
 3789:                 my $cid = $env{'request.course.id'};
 3790:                 $dom  = $env{'request.'.$cid.'.domain'};
 3791:                 $name = $env{'request.'.$cid.'.num'};
 3792:             }
 3793:             my $value = $accesshash{$entry};
 3794:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 3795:             my %temphash=($url => $value);
 3796:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 3797:             if ($result eq 'ok') {
 3798:                 delete $accesshash{$entry};
 3799:             }
 3800:         } else {
 3801:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 3802:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 3803:             my %temphash=($entry => $accesshash{$entry});
 3804:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 3805:                 delete $accesshash{$entry};
 3806:             }
 3807:         }
 3808:     }
 3809: #
 3810: # Roles
 3811: # Reverse lookup of user roles for course faculty/staff and co-authorship
 3812: #
 3813:     foreach my $entry (keys(%userrolehash)) {
 3814:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 3815: 	    split(/\:/,$entry);
 3816:         if (&Apache::lonnet::put('nohist_userroles',
 3817:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 3818:                 $rudom,$runame) eq 'ok') {
 3819: 	    delete $userrolehash{$entry};
 3820:         }
 3821:     }
 3822: #
 3823: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 3824: #
 3825:     my %domrolebuffer = ();
 3826:     foreach my $entry (keys(%domainrolehash)) {
 3827:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 3828:         if ($domrolebuffer{$rudom}) {
 3829:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 3830:                       '='.&escape($domainrolehash{$entry});
 3831:         } else {
 3832:             $domrolebuffer{$rudom}.=&escape($entry).
 3833:                       '='.&escape($domainrolehash{$entry});
 3834:         }
 3835:         delete $domainrolehash{$entry};
 3836:     }
 3837:     foreach my $dom (keys(%domrolebuffer)) {
 3838: 	my %servers = &get_servers($dom,'library');
 3839: 	foreach my $tryserver (keys(%servers)) {
 3840: 	    unless (&reply('domroleput:'.$dom.':'.
 3841: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 3842: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 3843: 	    }
 3844:         }
 3845:     }
 3846:     $dumpcount++;
 3847: }
 3848: 
 3849: sub courselog {
 3850:     my $what=shift;
 3851:     $what=time.':'.$what;
 3852:     unless ($env{'request.course.id'}) { return ''; }
 3853:     $coursedombuf{$env{'request.course.id'}}=
 3854:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 3855:     $coursenumbuf{$env{'request.course.id'}}=
 3856:        $env{'course.'.$env{'request.course.id'}.'.num'};
 3857:     $coursehombuf{$env{'request.course.id'}}=
 3858:        $env{'course.'.$env{'request.course.id'}.'.home'};
 3859:     $coursedescrbuf{$env{'request.course.id'}}=
 3860:        $env{'course.'.$env{'request.course.id'}.'.description'};
 3861:     $courseinstcodebuf{$env{'request.course.id'}}=
 3862:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 3863:     $courseownerbuf{$env{'request.course.id'}}=
 3864:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 3865:     $coursetypebuf{$env{'request.course.id'}}=
 3866:        $env{'course.'.$env{'request.course.id'}.'.type'};
 3867:     if (defined $courselogs{$env{'request.course.id'}}) {
 3868: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 3869:     } else {
 3870: 	$courselogs{$env{'request.course.id'}}.=$what;
 3871:     }
 3872:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 3873: 	&flushcourselogs();
 3874:     }
 3875: }
 3876: 
 3877: sub courseacclog {
 3878:     my $fnsymb=shift;
 3879:     unless ($env{'request.course.id'}) { return ''; }
 3880:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 3881:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 3882:         $what.=':POST';
 3883:         # FIXME: Probably ought to escape things....
 3884: 	foreach my $key (keys(%env)) {
 3885:             if ($key=~/^form\.(.*)/) {
 3886:                 my $formitem = $1;
 3887:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 3888:                     $what.=':'.$formitem.'='.$env{$key};
 3889:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 3890:                     $what.=':'.$formitem.'='.$env{$key};
 3891:                 }
 3892:             }
 3893:         }
 3894:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 3895:         # FIXME: We should not be depending on a form parameter that someone
 3896:         # editing lonsearchcat.pm might change in the future.
 3897:         if ($env{'form.phase'} eq 'course_search') {
 3898:             $what.= ':POST';
 3899:             # FIXME: Probably ought to escape things....
 3900:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 3901:                                  'crsdiscuss') {
 3902:                 $what.=':'.$element.'='.$env{'form.'.$element};
 3903:             }
 3904:         }
 3905:     }
 3906:     &courselog($what);
 3907: }
 3908: 
 3909: sub countacc {
 3910:     my $url=&declutter(shift);
 3911:     return if (! defined($url) || $url eq '');
 3912:     unless ($env{'request.course.id'}) { return ''; }
 3913: #
 3914: # Mark that this url was used in this course
 3915: #
 3916:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 3917: #
 3918: # Increase the access count for this resource in this child process
 3919: #
 3920:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 3921:     $accesshash{$key}++;
 3922: }
 3923: 
 3924: sub linklog {
 3925:     my ($from,$to)=@_;
 3926:     $from=&declutter($from);
 3927:     $to=&declutter($to);
 3928:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 3929:     $accesshash{$to.'___'.$from.'___goto'}=1;
 3930: }
 3931: 
 3932: sub statslog {
 3933:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 3934:     if ($users<2) { return; }
 3935:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 3936:             'course'       => $env{'request.course.id'},
 3937:             'sections'     => '"all"',
 3938:             'num_students' => $users,
 3939:             'part'         => $part,
 3940:             'symb'         => $symb,
 3941:             'mean_tries'   => $av_attempts,
 3942:             'deg_of_diff'  => $degdiff});
 3943:     foreach my $key (keys(%dynstore)) {
 3944:         $accesshash{$key}=$dynstore{$key};
 3945:     }
 3946: }
 3947:   
 3948: sub userrolelog {
 3949:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 3950:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 3951:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3952:        $userrolehash
 3953:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3954:                     =$tend.':'.$tstart;
 3955:     }
 3956:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 3957:        $userrolehash
 3958:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 3959:                     =$tend.':'.$tstart;
 3960:     }
 3961:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
 3962:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3963:        $domainrolehash
 3964:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3965:                     = $tend.':'.$tstart;
 3966:     }
 3967: }
 3968: 
 3969: sub courserolelog {
 3970:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 3971:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 3972:         my $cdom = $1;
 3973:         my $cnum = $2;
 3974:         my $sec = $3;
 3975:         my $namespace = 'rolelog';
 3976:         my %storehash = (
 3977:                            role    => $trole,
 3978:                            start   => $tstart,
 3979:                            end     => $tend,
 3980:                            selfenroll => $selfenroll,
 3981:                            context    => $context,
 3982:                         );
 3983:         if ($trole eq 'gr') {
 3984:             $namespace = 'groupslog';
 3985:             $storehash{'group'} = $sec;
 3986:         } else {
 3987:             $storehash{'section'} = $sec;
 3988:         }
 3989:         &write_log('course',$namespace,\%storehash,$delflag,$username,
 3990:                    $domain,$cnum,$cdom);
 3991:         if (($trole ne 'st') || ($sec ne '')) {
 3992:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 3993:         }
 3994:     }
 3995:     return;
 3996: }
 3997: 
 3998: sub domainrolelog {
 3999:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4000:     if ($area =~ m{^/($match_domain)/$}) {
 4001:         my $cdom = $1;
 4002:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
 4003:         my $namespace = 'rolelog';
 4004:         my %storehash = (
 4005:                            role    => $trole,
 4006:                            start   => $tstart,
 4007:                            end     => $tend,
 4008:                            context => $context,
 4009:                         );
 4010:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
 4011:                    $domain,$domconfiguser,$cdom);
 4012:     }
 4013:     return;
 4014: 
 4015: }
 4016: 
 4017: sub coauthorrolelog {
 4018:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
 4019:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
 4020:         my $audom = $1;
 4021:         my $auname = $2;
 4022:         my $namespace = 'rolelog';
 4023:         my %storehash = (
 4024:                            role    => $trole,
 4025:                            start   => $tstart,
 4026:                            end     => $tend,
 4027:                            context => $context,
 4028:                         );
 4029:         &write_log('author',$namespace,\%storehash,$delflag,$username,
 4030:                    $domain,$auname,$audom);
 4031:     }
 4032:     return;
 4033: }
 4034: 
 4035: sub get_course_adv_roles {
 4036:     my ($cid,$codes) = @_;
 4037:     $cid=$env{'request.course.id'} unless (defined($cid));
 4038:     my %coursehash=&coursedescription($cid);
 4039:     my $crstype = &Apache::loncommon::course_type($cid);
 4040:     my %nothide=();
 4041:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4042:         if ($user !~ /:/) {
 4043: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 4044:         } else {
 4045:             $nothide{$user}=1;
 4046:         }
 4047:     }
 4048:     my @possdoms = ($coursehash{'domain'});
 4049:     if ($coursehash{'checkforpriv'}) {
 4050:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
 4051:     }
 4052:     my %returnhash=();
 4053:     my %dumphash=
 4054:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 4055:     my $now=time;
 4056:     my %privileged;
 4057:     foreach my $entry (keys(%dumphash)) {
 4058: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4059:         if (($tstart) && ($tstart<0)) { next; }
 4060:         if (($tend) && ($tend<$now)) { next; }
 4061:         if (($tstart) && ($now<$tstart)) { next; }
 4062:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 4063: 	if ($username eq '' || $domain eq '') { next; }
 4064:         if ((&privileged($username,$domain,\@possdoms)) &&
 4065:             (!$nothide{$username.':'.$domain})) { next; }
 4066: 	if ($role eq 'cr') { next; }
 4067:         if ($codes) {
 4068:             if ($section) { $role .= ':'.$section; }
 4069:             if ($returnhash{$role}) {
 4070:                 $returnhash{$role}.=','.$username.':'.$domain;
 4071:             } else {
 4072:                 $returnhash{$role}=$username.':'.$domain;
 4073:             }
 4074:         } else {
 4075:             my $key=&plaintext($role,$crstype);
 4076:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 4077:             if ($returnhash{$key}) {
 4078: 	        $returnhash{$key}.=','.$username.':'.$domain;
 4079:             } else {
 4080:                 $returnhash{$key}=$username.':'.$domain;
 4081:             }
 4082:         }
 4083:     }
 4084:     return %returnhash;
 4085: }
 4086: 
 4087: sub get_my_roles {
 4088:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 4089:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 4090:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 4091:     my (%dumphash,%nothide);
 4092:     if ($context eq 'userroles') {
 4093:         %dumphash = &dump('roles',$udom,$uname);
 4094:     } else {
 4095:         %dumphash = &dump('nohist_userroles',$udom,$uname);
 4096:         if ($hidepriv) {
 4097:             my %coursehash=&coursedescription($udom.'_'.$uname);
 4098:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 4099:                 if ($user !~ /:/) {
 4100:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 4101:                 } else {
 4102:                     $nothide{$user} = 1;
 4103:                 }
 4104:             }
 4105:         }
 4106:     }
 4107:     my %returnhash=();
 4108:     my $now=time;
 4109:     my %privileged;
 4110:     foreach my $entry (keys(%dumphash)) {
 4111:         my ($role,$tend,$tstart);
 4112:         if ($context eq 'userroles') {
 4113:             next if ($entry =~ /^rolesdef/);
 4114: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 4115:         } else {
 4116:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 4117:         }
 4118:         if (($tstart) && ($tstart<0)) { next; }
 4119:         my $status = 'active';
 4120:         if (($tend) && ($tend<=$now)) {
 4121:             $status = 'previous';
 4122:         } 
 4123:         if (($tstart) && ($now<$tstart)) {
 4124:             $status = 'future';
 4125:         }
 4126:         if (ref($types) eq 'ARRAY') {
 4127:             if (!grep(/^\Q$status\E$/,@{$types})) {
 4128:                 next;
 4129:             } 
 4130:         } else {
 4131:             if ($status ne 'active') {
 4132:                 next;
 4133:             }
 4134:         }
 4135:         my ($rolecode,$username,$domain,$section,$area);
 4136:         if ($context eq 'userroles') {
 4137:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
 4138:             (undef,$domain,$username,$section) = split(/\//,$area);
 4139:         } else {
 4140:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 4141:         }
 4142:         if (ref($roledoms) eq 'ARRAY') {
 4143:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 4144:                 next;
 4145:             }
 4146:         }
 4147:         if (ref($roles) eq 'ARRAY') {
 4148:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 4149:                 if ($role =~ /^cr\//) {
 4150:                     if (!grep(/^cr$/,@{$roles})) {
 4151:                         next;
 4152:                     }
 4153:                 } elsif ($role =~ /^gr\//) {
 4154:                     if (!grep(/^gr$/,@{$roles})) {
 4155:                         next;
 4156:                     }
 4157:                 } else {
 4158:                     next;
 4159:                 }
 4160:             }
 4161:         }
 4162:         if ($hidepriv) {
 4163:             my @privroles = ('dc','su');
 4164:             if ($context eq 'userroles') {
 4165:                 next if (grep(/^\Q$role\E$/,@privroles));
 4166:             } else {
 4167:                 my $possdoms = [$domain];
 4168:                 if (ref($roledoms) eq 'ARRAY') {
 4169:                    push(@{$possdoms},@{$roledoms});
 4170:                 }
 4171:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
 4172:                     if (!$nothide{$username.':'.$domain}) {
 4173:                         next;
 4174:                     }
 4175:                 }
 4176:             }
 4177:         }
 4178:         if ($withsec) {
 4179:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 4180:                 $tstart.':'.$tend;
 4181:         } else {
 4182:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 4183:         }
 4184:     }
 4185:     return %returnhash;
 4186: }
 4187: 
 4188: # ----------------------------------------------------- Frontpage Announcements
 4189: #
 4190: #
 4191: 
 4192: sub postannounce {
 4193:     my ($server,$text)=@_;
 4194:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 4195:     unless ($text=~/\w/) { $text=''; }
 4196:     return &reply('setannounce:'.&escape($text),$server);
 4197: }
 4198: 
 4199: sub getannounce {
 4200: 
 4201:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 4202: 	my $announcement='';
 4203: 	while (my $line = <$fh>) { $announcement .= $line; }
 4204: 	close($fh);
 4205: 	if ($announcement=~/\w/) { 
 4206: 	    return 
 4207:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 4208:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 4209: 	} else {
 4210: 	    return '';
 4211: 	}
 4212:     } else {
 4213: 	return '';
 4214:     }
 4215: }
 4216: 
 4217: # ---------------------------------------------------------- Course ID routines
 4218: # Deal with domain's nohist_courseid.db files
 4219: #
 4220: 
 4221: sub courseidput {
 4222:     my ($domain,$storehash,$coursehome,$caller) = @_;
 4223:     return unless (ref($storehash) eq 'HASH');
 4224:     my $outcome;
 4225:     if ($caller eq 'timeonly') {
 4226:         my $cids = '';
 4227:         foreach my $item (keys(%$storehash)) {
 4228:             $cids.=&escape($item).'&';
 4229:         }
 4230:         $cids=~s/\&$//;
 4231:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 4232:                           $coursehome);       
 4233:     } else {
 4234:         my $items = '';
 4235:         foreach my $item (keys(%$storehash)) {
 4236:             $items.= &escape($item).'='.
 4237:                      &freeze_escape($$storehash{$item}).'&';
 4238:         }
 4239:         $items=~s/\&$//;
 4240:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 4241:                           $coursehome);
 4242:     }
 4243:     if ($outcome eq 'unknown_cmd') {
 4244:         my $what;
 4245:         foreach my $cid (keys(%$storehash)) {
 4246:             $what .= &escape($cid).'=';
 4247:             foreach my $item ('description','inst_code','owner','type') {
 4248:                 $what .= &escape($storehash->{$cid}{$item}).':';
 4249:             }
 4250:             $what =~ s/\:$/&/;
 4251:         }
 4252:         $what =~ s/\&$//;  
 4253:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 4254:     } else {
 4255:         return $outcome;
 4256:     }
 4257: }
 4258: 
 4259: sub courseiddump {
 4260:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 4261:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 4262:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 4263:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
 4264:         $hasuniquecode)=@_;
 4265:     my $as_hash = 1;
 4266:     my %returnhash;
 4267:     if (!$domfilter) { $domfilter=''; }
 4268:     my %libserv = &all_library();
 4269:     foreach my $tryserver (keys(%libserv)) {
 4270:         if ( (  $hostidflag == 1 
 4271: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 4272: 	     || (!defined($hostidflag)) ) {
 4273: 
 4274: 	    if (($domfilter eq '') ||
 4275: 		(&host_domain($tryserver) eq $domfilter)) {
 4276:                 my $rep;
 4277:                 if (grep { $_ eq $tryserver } &current_machine_ids()) {
 4278:                     $rep = &LONCAPA::Lond::dump_course_id_handler(
 4279:                         join(":", (&host_domain($tryserver), $sincefilter,
 4280:                                 &escape($descfilter), &escape($instcodefilter),
 4281:                                 &escape($ownerfilter), &escape($coursefilter),
 4282:                                 &escape($typefilter), &escape($regexp_ok),
 4283:                                 $as_hash, &escape($selfenrollonly),
 4284:                                 &escape($catfilter), $showhidden, $caller,
 4285:                                 &escape($cloner), &escape($cc_clone), $cloneonly,
 4286:                                 &escape($createdbefore), &escape($createdafter),
 4287:                                 &escape($creationcontext), $domcloner, $hasuniquecode)));
 4288:                 } else {
 4289:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 4290:                              $sincefilter.':'.&escape($descfilter).':'.
 4291:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 4292:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 4293:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 4294:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 4295:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 4296:                              &escape($cc_clone).':'.$cloneonly.':'.
 4297:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 4298:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode,
 4299:                              $tryserver);
 4300:                 }
 4301: 
 4302:                 my @pairs=split(/\&/,$rep);
 4303:                 foreach my $item (@pairs) {
 4304:                     my ($key,$value)=split(/\=/,$item,2);
 4305:                     $key = &unescape($key);
 4306:                     next if ($key =~ /^error: 2 /);
 4307:                     my $result = &thaw_unescape($value);
 4308:                     if (ref($result) eq 'HASH') {
 4309:                         $returnhash{$key}=$result;
 4310:                     } else {
 4311:                         my @responses = split(/:/,$value);
 4312:                         my @items = ('description','inst_code','owner','type');
 4313:                         for (my $i=0; $i<@responses; $i++) {
 4314:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 4315:                         }
 4316:                     }
 4317:                 }
 4318:             }
 4319:         }
 4320:     }
 4321:     return %returnhash;
 4322: }
 4323: 
 4324: sub courselastaccess {
 4325:     my ($cdom,$cnum,$hostidref) = @_;
 4326:     my %returnhash;
 4327:     if ($cdom && $cnum) {
 4328:         my $chome = &homeserver($cnum,$cdom);
 4329:         if ($chome ne 'no_host') {
 4330:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 4331:             &extract_lastaccess(\%returnhash,$rep);
 4332:         }
 4333:     } else {
 4334:         if (!$cdom) { $cdom=''; }
 4335:         my %libserv = &all_library();
 4336:         foreach my $tryserver (keys(%libserv)) {
 4337:             if (ref($hostidref) eq 'ARRAY') {
 4338:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 4339:             } 
 4340:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 4341:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 4342:                 &extract_lastaccess(\%returnhash,$rep);
 4343:             }
 4344:         }
 4345:     }
 4346:     return %returnhash;
 4347: }
 4348: 
 4349: sub extract_lastaccess {
 4350:     my ($returnhash,$rep) = @_;
 4351:     if (ref($returnhash) eq 'HASH') {
 4352:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 4353:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 4354:                  $rep eq '') {
 4355:             my @pairs=split(/\&/,$rep);
 4356:             foreach my $item (@pairs) {
 4357:                 my ($key,$value)=split(/\=/,$item,2);
 4358:                 $key = &unescape($key);
 4359:                 next if ($key =~ /^error: 2 /);
 4360:                 $returnhash->{$key} = &thaw_unescape($value);
 4361:             }
 4362:         }
 4363:     }
 4364:     return;
 4365: }
 4366: 
 4367: # ---------------------------------------------------------- DC e-mail
 4368: 
 4369: sub dcmailput {
 4370:     my ($domain,$msgid,$message,$server)=@_;
 4371:     my $status = &Apache::lonnet::critical(
 4372:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 4373:        &escape($message),$server);
 4374:     return $status;
 4375: }
 4376: 
 4377: sub dcmaildump {
 4378:     my ($dom,$startdate,$enddate,$senders) = @_;
 4379:     my %returnhash=();
 4380: 
 4381:     if (defined(&domain($dom,'primary'))) {
 4382:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 4383:                                                          &escape($enddate).':';
 4384: 	my @esc_senders=map { &escape($_)} @$senders;
 4385: 	$cmd.=&escape(join('&',@esc_senders));
 4386: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 4387:             my ($key,$value) = split(/\=/,$line,2);
 4388:             if (($key) && ($value)) {
 4389:                 $returnhash{&unescape($key)} = &unescape($value);
 4390:             }
 4391:         }
 4392:     }
 4393:     return %returnhash;
 4394: }
 4395: # ---------------------------------------------------------- Domain roles
 4396: 
 4397: sub get_domain_roles {
 4398:     my ($dom,$roles,$startdate,$enddate)=@_;
 4399:     if ((!defined($startdate)) || ($startdate eq '')) {
 4400:         $startdate = '.';
 4401:     }
 4402:     if ((!defined($enddate)) || ($enddate eq '')) {
 4403:         $enddate = '.';
 4404:     }
 4405:     my $rolelist;
 4406:     if (ref($roles) eq 'ARRAY') {
 4407:         $rolelist = join('&',@{$roles});
 4408:     }
 4409:     my %personnel = ();
 4410: 
 4411:     my %servers = &get_servers($dom,'library');
 4412:     foreach my $tryserver (keys(%servers)) {
 4413: 	%{$personnel{$tryserver}}=();
 4414: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 4415: 					    &escape($startdate).':'.
 4416: 					    &escape($enddate).':'.
 4417: 					    &escape($rolelist), $tryserver))) {
 4418: 	    my ($key,$value) = split(/\=/,$line,2);
 4419: 	    if (($key) && ($value)) {
 4420: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 4421: 	    }
 4422: 	}
 4423:     }
 4424:     return %personnel;
 4425: }
 4426: 
 4427: # ----------------------------------------------------------- Interval timing 
 4428: 
 4429: {
 4430: # Caches needed for speedup of navmaps
 4431: # We don't want to cache this for very long at all (5 seconds at most)
 4432: # 
 4433: # The user for whom we cache
 4434: my $cachedkey='';
 4435: # The cached times for this user
 4436: my %cachedtimes=();
 4437: # When this was last done
 4438: my $cachedtime=();
 4439: 
 4440: sub load_all_first_access {
 4441:     my ($uname,$udom)=@_;
 4442:     if (($cachedkey eq $uname.':'.$udom) &&
 4443:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
 4444:         return;
 4445:     }
 4446:     $cachedtime=time;
 4447:     $cachedkey=$uname.':'.$udom;
 4448:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 4449: }
 4450: 
 4451: sub get_first_access {
 4452:     my ($type,$argsymb,$argmap)=@_;
 4453:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4454:     if ($argsymb) { $symb=$argsymb; }
 4455:     my ($map,$id,$res)=&decode_symb($symb);
 4456:     if ($argmap) { $map = $argmap; }
 4457:     if ($type eq 'course') {
 4458: 	$res='course';
 4459:     } elsif ($type eq 'map') {
 4460: 	$res=&symbread($map);
 4461:     } else {
 4462: 	$res=$symb;
 4463:     }
 4464:     &load_all_first_access($uname,$udom);
 4465:     return $cachedtimes{"$courseid\0$res"};
 4466: }
 4467: 
 4468: sub set_first_access {
 4469:     my ($type,$interval)=@_;
 4470:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4471:     my ($map,$id,$res)=&decode_symb($symb);
 4472:     if ($type eq 'course') {
 4473: 	$res='course';
 4474:     } elsif ($type eq 'map') {
 4475: 	$res=&symbread($map);
 4476:     } else {
 4477: 	$res=$symb;
 4478:     }
 4479:     $cachedkey='';
 4480:     my $firstaccess=&get_first_access($type,$symb,$map);
 4481:     if (!$firstaccess) {
 4482:         my $start = time;
 4483: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 4484:                           $udom,$uname);
 4485:         if ($putres eq 'ok') {
 4486:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 4487:                  $udom,$uname); 
 4488:             &appenv(
 4489:                      {
 4490:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 4491:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 4492:                      }
 4493:                   );
 4494:         }
 4495:         return $putres;
 4496:     }
 4497:     return 'already_set';
 4498: }
 4499: }
 4500: 
 4501: sub checkout {
 4502:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 4503:     my $now=time;
 4504:     my $lonhost=$perlvar{'lonHostID'};
 4505:     my $infostr=&escape(
 4506:                  'CHECKOUTTOKEN&'.
 4507:                  $tuname.'&'.
 4508:                  $tudom.'&'.
 4509:                  $tcrsid.'&'.
 4510:                  $symb.'&'.
 4511:                  $now.'&'.$ENV{'REMOTE_ADDR'});
 4512:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 4513:     if ($token=~/^error\:/) {
 4514:         &logthis("<font color=\"blue\">WARNING: ".
 4515:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 4516:                  "</font>");
 4517:         return '';
 4518:     }
 4519: 
 4520:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 4521:     $token=~tr/a-z/A-Z/;
 4522: 
 4523:     my %infohash=('resource.0.outtoken' => $token,
 4524:                   'resource.0.checkouttime' => $now,
 4525:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 4526: 
 4527:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 4528:        return '';
 4529:     } else {
 4530:         &logthis("<font color=\"blue\">WARNING: ".
 4531:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 4532:                  "</font>");
 4533:     }
 4534: 
 4535:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 4536:                          &escape('Checkout '.$infostr.' - '.
 4537:                                                  $token)) ne 'ok') {
 4538:         return '';
 4539:     } else {
 4540:         &logthis("<font color=\"blue\">WARNING: ".
 4541:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 4542:                  "</font>");
 4543:     }
 4544:     return $token;
 4545: }
 4546: 
 4547: # ------------------------------------------------------------ Check in an item
 4548: 
 4549: sub checkin {
 4550:     my $token=shift;
 4551:     my $now=time;
 4552:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 4553:     $lonhost=~tr/A-Z/a-z/;
 4554:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
 4555:     $dtoken=~s/\W/\_/g;
 4556:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 4557:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 4558: 
 4559:     unless (($tuname) && ($tudom)) {
 4560:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 4561:         return '';
 4562:     }
 4563: 
 4564:     unless (&allowed('mgr',$tcrsid)) {
 4565:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 4566:                  $env{'user.name'}.' - '.$env{'user.domain'});
 4567:         return '';
 4568:     }
 4569: 
 4570:     my %infohash=('resource.0.intoken' => $token,
 4571:                   'resource.0.checkintime' => $now,
 4572:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 4573: 
 4574:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 4575:        return '';
 4576:     }
 4577: 
 4578:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 4579:                          &escape('Checkin - '.$token)) ne 'ok') {
 4580:         return '';
 4581:     }
 4582: 
 4583:     return ($symb,$tuname,$tudom,$tcrsid);
 4584: }
 4585: 
 4586: # --------------------------------------------- Set Expire Date for Spreadsheet
 4587: 
 4588: sub expirespread {
 4589:     my ($uname,$udom,$stype,$usymb)=@_;
 4590:     my $cid=$env{'request.course.id'}; 
 4591:     if ($cid) {
 4592:        my $now=time;
 4593:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 4594:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 4595:                             $env{'course.'.$cid.'.num'}.
 4596: 	        	    ':nohist_expirationdates:'.
 4597:                             &escape($key).'='.$now,
 4598:                             $env{'course.'.$cid.'.home'})
 4599:     }
 4600:     return 'ok';
 4601: }
 4602: 
 4603: # ----------------------------------------------------- Devalidate Spreadsheets
 4604: 
 4605: sub devalidate {
 4606:     my ($symb,$uname,$udom)=@_;
 4607:     my $cid=$env{'request.course.id'}; 
 4608:     if ($cid) {
 4609:         # delete the stored spreadsheets for
 4610:         # - the student level sheet of this user in course's homespace
 4611:         # - the assessment level sheet for this resource 
 4612:         #   for this user in user's homespace
 4613: 	# - current conditional state info
 4614: 	my $key=$uname.':'.$udom.':';
 4615:         my $status=
 4616: 	    &del('nohist_calculatedsheets',
 4617: 		 [$key.'studentcalc:'],
 4618: 		 $env{'course.'.$cid.'.domain'},
 4619: 		 $env{'course.'.$cid.'.num'})
 4620: 		.' '.
 4621: 	    &del('nohist_calculatedsheets_'.$cid,
 4622: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 4623:         unless ($status eq 'ok ok') {
 4624:            &logthis('Could not devalidate spreadsheet '.
 4625:                     $uname.' at '.$udom.' for '.
 4626: 		    $symb.': '.$status);
 4627:         }
 4628: 	&delenv('user.state.'.$cid);
 4629:     }
 4630: }
 4631: 
 4632: sub get_scalar {
 4633:     my ($string,$end) = @_;
 4634:     my $value;
 4635:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 4636: 	$value = $1;
 4637:     } elsif ($$string =~ s/^([^&]*?)&//) {
 4638: 	$value = $1;
 4639:     }
 4640:     return &unescape($value);
 4641: }
 4642: 
 4643: sub array2str {
 4644:   my (@array) = @_;
 4645:   my $result=&arrayref2str(\@array);
 4646:   $result=~s/^__ARRAY_REF__//;
 4647:   $result=~s/__END_ARRAY_REF__$//;
 4648:   return $result;
 4649: }
 4650: 
 4651: sub arrayref2str {
 4652:   my ($arrayref) = @_;
 4653:   my $result='__ARRAY_REF__';
 4654:   foreach my $elem (@$arrayref) {
 4655:     if(ref($elem) eq 'ARRAY') {
 4656:       $result.=&arrayref2str($elem).'&';
 4657:     } elsif(ref($elem) eq 'HASH') {
 4658:       $result.=&hashref2str($elem).'&';
 4659:     } elsif(ref($elem)) {
 4660:       #print("Got a ref of ".(ref($elem))." skipping.");
 4661:     } else {
 4662:       $result.=&escape($elem).'&';
 4663:     }
 4664:   }
 4665:   $result=~s/\&$//;
 4666:   $result .= '__END_ARRAY_REF__';
 4667:   return $result;
 4668: }
 4669: 
 4670: sub hash2str {
 4671:   my (%hash) = @_;
 4672:   my $result=&hashref2str(\%hash);
 4673:   $result=~s/^__HASH_REF__//;
 4674:   $result=~s/__END_HASH_REF__$//;
 4675:   return $result;
 4676: }
 4677: 
 4678: sub hashref2str {
 4679:   my ($hashref)=@_;
 4680:   my $result='__HASH_REF__';
 4681:   foreach my $key (sort(keys(%$hashref))) {
 4682:     if (ref($key) eq 'ARRAY') {
 4683:       $result.=&arrayref2str($key).'=';
 4684:     } elsif (ref($key) eq 'HASH') {
 4685:       $result.=&hashref2str($key).'=';
 4686:     } elsif (ref($key)) {
 4687:       $result.='=';
 4688:       #print("Got a ref of ".(ref($key))." skipping.");
 4689:     } else {
 4690: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 4691:     }
 4692: 
 4693:     if(ref($hashref->{$key}) eq 'ARRAY') {
 4694:       $result.=&arrayref2str($hashref->{$key}).'&';
 4695:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 4696:       $result.=&hashref2str($hashref->{$key}).'&';
 4697:     } elsif(ref($hashref->{$key})) {
 4698:        $result.='&';
 4699:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 4700:     } else {
 4701:       $result.=&escape($hashref->{$key}).'&';
 4702:     }
 4703:   }
 4704:   $result=~s/\&$//;
 4705:   $result .= '__END_HASH_REF__';
 4706:   return $result;
 4707: }
 4708: 
 4709: sub str2hash {
 4710:     my ($string)=@_;
 4711:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 4712:     return %$hash;
 4713: }
 4714: 
 4715: sub str2hashref {
 4716:   my ($string) = @_;
 4717: 
 4718:   my %hash;
 4719: 
 4720:   if($string !~ /^__HASH_REF__/) {
 4721:       if (! ($string eq '' || !defined($string))) {
 4722: 	  $hash{'error'}='Not hash reference';
 4723:       }
 4724:       return (\%hash, $string);
 4725:   }
 4726: 
 4727:   $string =~ s/^__HASH_REF__//;
 4728: 
 4729:   while($string !~ /^__END_HASH_REF__/) {
 4730:       #key
 4731:       my $key='';
 4732:       if($string =~ /^__HASH_REF__/) {
 4733:           ($key, $string)=&str2hashref($string);
 4734:           if(defined($key->{'error'})) {
 4735:               $hash{'error'}='Bad data';
 4736:               return (\%hash, $string);
 4737:           }
 4738:       } elsif($string =~ /^__ARRAY_REF__/) {
 4739:           ($key, $string)=&str2arrayref($string);
 4740:           if($key->[0] eq 'Array reference error') {
 4741:               $hash{'error'}='Bad data';
 4742:               return (\%hash, $string);
 4743:           }
 4744:       } else {
 4745:           $string =~ s/^(.*?)=//;
 4746: 	  $key=&unescape($1);
 4747:       }
 4748:       $string =~ s/^=//;
 4749: 
 4750:       #value
 4751:       my $value='';
 4752:       if($string =~ /^__HASH_REF__/) {
 4753:           ($value, $string)=&str2hashref($string);
 4754:           if(defined($value->{'error'})) {
 4755:               $hash{'error'}='Bad data';
 4756:               return (\%hash, $string);
 4757:           }
 4758:       } elsif($string =~ /^__ARRAY_REF__/) {
 4759:           ($value, $string)=&str2arrayref($string);
 4760:           if($value->[0] eq 'Array reference error') {
 4761:               $hash{'error'}='Bad data';
 4762:               return (\%hash, $string);
 4763:           }
 4764:       } else {
 4765: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 4766:       }
 4767:       $string =~ s/^&//;
 4768: 
 4769:       $hash{$key}=$value;
 4770:   }
 4771: 
 4772:   $string =~ s/^__END_HASH_REF__//;
 4773: 
 4774:   return (\%hash, $string);
 4775: }
 4776: 
 4777: sub str2array {
 4778:     my ($string)=@_;
 4779:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 4780:     return @$array;
 4781: }
 4782: 
 4783: sub str2arrayref {
 4784:   my ($string) = @_;
 4785:   my @array;
 4786: 
 4787:   if($string !~ /^__ARRAY_REF__/) {
 4788:       if (! ($string eq '' || !defined($string))) {
 4789: 	  $array[0]='Array reference error';
 4790:       }
 4791:       return (\@array, $string);
 4792:   }
 4793: 
 4794:   $string =~ s/^__ARRAY_REF__//;
 4795: 
 4796:   while($string !~ /^__END_ARRAY_REF__/) {
 4797:       my $value='';
 4798:       if($string =~ /^__HASH_REF__/) {
 4799:           ($value, $string)=&str2hashref($string);
 4800:           if(defined($value->{'error'})) {
 4801:               $array[0] ='Array reference error';
 4802:               return (\@array, $string);
 4803:           }
 4804:       } elsif($string =~ /^__ARRAY_REF__/) {
 4805:           ($value, $string)=&str2arrayref($string);
 4806:           if($value->[0] eq 'Array reference error') {
 4807:               $array[0] ='Array reference error';
 4808:               return (\@array, $string);
 4809:           }
 4810:       } else {
 4811: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 4812:       }
 4813:       $string =~ s/^&//;
 4814: 
 4815:       push(@array, $value);
 4816:   }
 4817: 
 4818:   $string =~ s/^__END_ARRAY_REF__//;
 4819: 
 4820:   return (\@array, $string);
 4821: }
 4822: 
 4823: # -------------------------------------------------------------------Temp Store
 4824: 
 4825: sub tmpreset {
 4826:   my ($symb,$namespace,$domain,$stuname) = @_;
 4827:   if (!$symb) {
 4828:     $symb=&symbread();
 4829:     if (!$symb) { $symb= $env{'request.url'}; }
 4830:   }
 4831:   $symb=escape($symb);
 4832: 
 4833:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4834:   $namespace=~s/\//\_/g;
 4835:   $namespace=~s/\W//g;
 4836: 
 4837:   if (!$domain) { $domain=$env{'user.domain'}; }
 4838:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4839:   if ($domain eq 'public' && $stuname eq 'public') {
 4840:       $stuname=$ENV{'REMOTE_ADDR'};
 4841:   }
 4842:   my $path=LONCAPA::tempdir();
 4843:   my %hash;
 4844:   if (tie(%hash,'GDBM_File',
 4845: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4846: 	  &GDBM_WRCREAT(),0640)) {
 4847:     foreach my $key (keys(%hash)) {
 4848:       if ($key=~ /:$symb/) {
 4849: 	delete($hash{$key});
 4850:       }
 4851:     }
 4852:   }
 4853: }
 4854: 
 4855: sub tmpstore {
 4856:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4857: 
 4858:   if (!$symb) {
 4859:     $symb=&symbread();
 4860:     if (!$symb) { $symb= $env{'request.url'}; }
 4861:   }
 4862:   $symb=escape($symb);
 4863: 
 4864:   if (!$namespace) {
 4865:     # I don't think we would ever want to store this for a course.
 4866:     # it seems this will only be used if we don't have a course.
 4867:     #$namespace=$env{'request.course.id'};
 4868:     #if (!$namespace) {
 4869:       $namespace=$env{'request.state'};
 4870:     #}
 4871:   }
 4872:   $namespace=~s/\//\_/g;
 4873:   $namespace=~s/\W//g;
 4874:   if (!$domain) { $domain=$env{'user.domain'}; }
 4875:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4876:   if ($domain eq 'public' && $stuname eq 'public') {
 4877:       $stuname=$ENV{'REMOTE_ADDR'};
 4878:   }
 4879:   my $now=time;
 4880:   my %hash;
 4881:   my $path=LONCAPA::tempdir();
 4882:   if (tie(%hash,'GDBM_File',
 4883: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4884: 	  &GDBM_WRCREAT(),0640)) {
 4885:     $hash{"version:$symb"}++;
 4886:     my $version=$hash{"version:$symb"};
 4887:     my $allkeys=''; 
 4888:     foreach my $key (keys(%$storehash)) {
 4889:       $allkeys.=$key.':';
 4890:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 4891:     }
 4892:     $hash{"$version:$symb:timestamp"}=$now;
 4893:     $allkeys.='timestamp';
 4894:     $hash{"$version:keys:$symb"}=$allkeys;
 4895:     if (untie(%hash)) {
 4896:       return 'ok';
 4897:     } else {
 4898:       return "error:$!";
 4899:     }
 4900:   } else {
 4901:     return "error:$!";
 4902:   }
 4903: }
 4904: 
 4905: # -----------------------------------------------------------------Temp Restore
 4906: 
 4907: sub tmprestore {
 4908:   my ($symb,$namespace,$domain,$stuname) = @_;
 4909: 
 4910:   if (!$symb) {
 4911:     $symb=&symbread();
 4912:     if (!$symb) { $symb= $env{'request.url'}; }
 4913:   }
 4914:   $symb=escape($symb);
 4915: 
 4916:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4917: 
 4918:   if (!$domain) { $domain=$env{'user.domain'}; }
 4919:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4920:   if ($domain eq 'public' && $stuname eq 'public') {
 4921:       $stuname=$ENV{'REMOTE_ADDR'};
 4922:   }
 4923:   my %returnhash;
 4924:   $namespace=~s/\//\_/g;
 4925:   $namespace=~s/\W//g;
 4926:   my %hash;
 4927:   my $path=LONCAPA::tempdir();
 4928:   if (tie(%hash,'GDBM_File',
 4929: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4930: 	  &GDBM_READER(),0640)) {
 4931:     my $version=$hash{"version:$symb"};
 4932:     $returnhash{'version'}=$version;
 4933:     my $scope;
 4934:     for ($scope=1;$scope<=$version;$scope++) {
 4935:       my $vkeys=$hash{"$scope:keys:$symb"};
 4936:       my @keys=split(/:/,$vkeys);
 4937:       my $key;
 4938:       $returnhash{"$scope:keys"}=$vkeys;
 4939:       foreach $key (@keys) {
 4940: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4941: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4942:       }
 4943:     }
 4944:     if (!(untie(%hash))) {
 4945:       return "error:$!";
 4946:     }
 4947:   } else {
 4948:     return "error:$!";
 4949:   }
 4950:   return %returnhash;
 4951: }
 4952: 
 4953: # ----------------------------------------------------------------------- Store
 4954: 
 4955: sub store {
 4956:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4957:     my $home='';
 4958: 
 4959:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4960: 
 4961:     $symb=&symbclean($symb);
 4962:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4963: 
 4964:     if (!$domain) { $domain=$env{'user.domain'}; }
 4965:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4966: 
 4967:     &devalidate($symb,$stuname,$domain);
 4968: 
 4969:     $symb=escape($symb);
 4970:     if (!$namespace) { 
 4971:        unless ($namespace=$env{'request.course.id'}) { 
 4972:           return ''; 
 4973:        } 
 4974:     }
 4975:     if (!$home) { $home=$env{'user.home'}; }
 4976: 
 4977:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4978:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4979: 
 4980:     my $namevalue='';
 4981:     foreach my $key (keys(%$storehash)) {
 4982:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4983:     }
 4984:     $namevalue=~s/\&$//;
 4985:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 4986:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4987: }
 4988: 
 4989: # -------------------------------------------------------------- Critical Store
 4990: 
 4991: sub cstore {
 4992:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4993:     my $home='';
 4994: 
 4995:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4996: 
 4997:     $symb=&symbclean($symb);
 4998:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4999: 
 5000:     if (!$domain) { $domain=$env{'user.domain'}; }
 5001:     if (!$stuname) { $stuname=$env{'user.name'}; }
 5002: 
 5003:     &devalidate($symb,$stuname,$domain);
 5004: 
 5005:     $symb=escape($symb);
 5006:     if (!$namespace) { 
 5007:        unless ($namespace=$env{'request.course.id'}) { 
 5008:           return ''; 
 5009:        } 
 5010:     }
 5011:     if (!$home) { $home=$env{'user.home'}; }
 5012: 
 5013:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 5014:     $$storehash{'host'}=$perlvar{'lonHostID'};
 5015: 
 5016:     my $namevalue='';
 5017:     foreach my $key (keys(%$storehash)) {
 5018:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5019:     }
 5020:     $namevalue=~s/\&$//;
 5021:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 5022:     return critical
 5023:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 5024: }
 5025: 
 5026: # --------------------------------------------------------------------- Restore
 5027: 
 5028: sub restore {
 5029:     my ($symb,$namespace,$domain,$stuname) = @_;
 5030:     my $home='';
 5031: 
 5032:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 5033: 
 5034:     if (!$symb) {
 5035:         return if ($namespace eq 'courserequests');
 5036:         unless ($symb=escape(&symbread())) { return ''; }
 5037:     } else {
 5038:         unless ($namespace eq 'courserequests') {
 5039:             $symb=&escape(&symbclean($symb));
 5040:         }
 5041:     }
 5042:     if (!$namespace) { 
 5043:        unless ($namespace=$env{'request.course.id'}) { 
 5044:           return ''; 
 5045:        } 
 5046:     }
 5047:     if (!$domain) { $domain=$env{'user.domain'}; }
 5048:     if (!$stuname) { $stuname=$env{'user.name'}; }
 5049:     if (!$home) { $home=$env{'user.home'}; }
 5050:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 5051: 
 5052:     my %returnhash=();
 5053:     foreach my $line (split(/\&/,$answer)) {
 5054: 	my ($name,$value)=split(/\=/,$line);
 5055:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 5056:     }
 5057:     my $version;
 5058:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 5059:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 5060:           $returnhash{$item}=$returnhash{$version.':'.$item};
 5061:        }
 5062:     }
 5063:     return %returnhash;
 5064: }
 5065: 
 5066: # ---------------------------------------------------------- Course Description
 5067: #
 5068: #  
 5069: 
 5070: sub coursedescription {
 5071:     my ($courseid,$args)=@_;
 5072:     $courseid=~s/^\///;
 5073:     $courseid=~s/\_/\//g;
 5074:     my ($cdomain,$cnum)=split(/\//,$courseid);
 5075:     my $chome=&homeserver($cnum,$cdomain);
 5076:     my $normalid=$cdomain.'_'.$cnum;
 5077:     # need to always cache even if we get errors otherwise we keep 
 5078:     # trying and trying and trying to get the course description.
 5079:     my %envhash=();
 5080:     my %returnhash=();
 5081:     
 5082:     my $expiretime=600;
 5083:     if ($env{'request.course.id'} eq $normalid) {
 5084: 	$expiretime=120;
 5085:     }
 5086: 
 5087:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 5088:     if (!$args->{'freshen_cache'}
 5089: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 5090: 	foreach my $key (keys(%env)) {
 5091: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 5092: 	    my ($setting) = $1;
 5093: 	    $returnhash{$setting} = $env{$key};
 5094: 	}
 5095: 	return %returnhash;
 5096:     }
 5097: 
 5098:     # get the data again
 5099: 
 5100:     if (!$args->{'one_time'}) {
 5101: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 5102:     }
 5103: 
 5104:     if ($chome ne 'no_host') {
 5105:        %returnhash=&dump('environment',$cdomain,$cnum);
 5106:        if (!exists($returnhash{'con_lost'})) {
 5107: 	   my $username = $env{'user.name'}; # Defult username
 5108: 	   if(defined $args->{'user'}) {
 5109: 	       $username = $args->{'user'};
 5110: 	   }
 5111:            $returnhash{'home'}= $chome;
 5112: 	   $returnhash{'domain'} = $cdomain;
 5113: 	   $returnhash{'num'} = $cnum;
 5114:            if (!defined($returnhash{'type'})) {
 5115:                $returnhash{'type'} = 'Course';
 5116:            }
 5117:            while (my ($name,$value) = each %returnhash) {
 5118:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 5119:            }
 5120:            $returnhash{'url'}=&clutter($returnhash{'url'});
 5121:            $returnhash{'fn'}=LONCAPA::tempdir() .
 5122: 	       $username.'_'.$cdomain.'_'.$cnum;
 5123:            $envhash{'course.'.$normalid.'.home'}=$chome;
 5124:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 5125:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 5126:        }
 5127:     }
 5128:     if (!$args->{'one_time'}) {
 5129: 	&appenv(\%envhash);
 5130:     }
 5131:     return %returnhash;
 5132: }
 5133: 
 5134: sub update_released_required {
 5135:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 5136:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 5137:         $cid = $env{'request.course.id'};
 5138:         $cdom = $env{'course.'.$cid.'.domain'};
 5139:         $cnum = $env{'course.'.$cid.'.num'};
 5140:         $chome = $env{'course.'.$cid.'.home'};
 5141:     }
 5142:     if ($needsrelease) {
 5143:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 5144:         my $needsupdate;
 5145:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 5146:             $needsupdate = 1;
 5147:         } else {
 5148:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 5149:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 5150:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 5151:                 $needsupdate = 1;
 5152:             }
 5153:         }
 5154:         if ($needsupdate) {
 5155:             my %needshash = (
 5156:                              'internal.releaserequired' => $needsrelease,
 5157:                             );
 5158:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 5159:             if ($putresult eq 'ok') {
 5160:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 5161:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 5162:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 5163:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 5164:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 5165:                 }
 5166:             }
 5167:         }
 5168:     }
 5169:     return;
 5170: }
 5171: 
 5172: # -------------------------------------------------See if a user is privileged
 5173: 
 5174: sub privileged {
 5175:     my ($username,$domain,$possdomains,$possroles)=@_;
 5176:     my $now = time;
 5177:     my $roles;
 5178:     if (ref($possroles) eq 'ARRAY') {
 5179:         $roles = $possroles;
 5180:     } else {
 5181:         $roles = ['dc','su'];
 5182:     }
 5183:     if (ref($possdomains) eq 'ARRAY') {
 5184:         my %privileged = &privileged_by_domain($possdomains,$roles);
 5185:         foreach my $dom (@{$possdomains}) {
 5186:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
 5187:                 (ref($privileged{$dom}) eq 'HASH')) {
 5188:                 foreach my $role (@{$roles}) {
 5189:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5190:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
 5191:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
 5192:                             return 1 unless (($end && $end < $now) ||
 5193:                                              ($start && $start > $now));
 5194:                         }
 5195:                     }
 5196:                 }
 5197:             }
 5198:         }
 5199:     } else {
 5200:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
 5201:         my $now = time;
 5202: 
 5203:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
 5204:             my ($trole, $tend, $tstart) = split(/_/, $role);
 5205:             if (grep(/^\Q$trole\E$/,@{$roles})) {
 5206:                 return 1 unless ($tend && $tend < $now)
 5207:                         or ($tstart && $tstart > $now);
 5208:             }
 5209:         }
 5210:     }
 5211:     return 0;
 5212: }
 5213: 
 5214: sub privileged_by_domain {
 5215:     my ($domains,$roles) = @_;
 5216:     my %privileged = ();
 5217:     my $cachetime = 60*60*24;
 5218:     my $now = time;
 5219:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
 5220:         return %privileged;
 5221:     }
 5222:     foreach my $dom (@{$domains}) {
 5223:         next if (ref($privileged{$dom}) eq 'HASH');
 5224:         my $needroles;
 5225:         foreach my $role (@{$roles}) {
 5226:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
 5227:             if (defined($cached)) {
 5228:                 if (ref($result) eq 'HASH') {
 5229:                     $privileged{$dom}{$role} = $result;
 5230:                 }
 5231:             } else {
 5232:                 $needroles = 1;
 5233:             }
 5234:         }
 5235:         if ($needroles) {
 5236:             my %dompersonnel = &get_domain_roles($dom,$roles);
 5237:             $privileged{$dom} = {};
 5238:             foreach my $server (keys(%dompersonnel)) {
 5239:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 5240:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
 5241:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
 5242:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
 5243:                         next if ($end && $end < $now);
 5244:                         $privileged{$dom}{$trole}{$uname.':'.$udom} =
 5245:                             $dompersonnel{$server}{$item};
 5246:                     }
 5247:                 }
 5248:             }
 5249:             if (ref($privileged{$dom}) eq 'HASH') {
 5250:                 foreach my $role (@{$roles}) {
 5251:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
 5252:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
 5253:                     } else {
 5254:                         my %hash = ();
 5255:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
 5256:                     }
 5257:                 }
 5258:             }
 5259:         }
 5260:     }
 5261:     return %privileged;
 5262: }
 5263: 
 5264: # -------------------------------------------------------- Get user privileges
 5265: 
 5266: sub rolesinit {
 5267:     my ($domain, $username) = @_;
 5268:     my %userroles = ('user.login.time' => time);
 5269:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 5270: 
 5271:     # firstaccess and timerinterval are related to timed maps/resources. 
 5272:     # also, blocking can be triggered by an activating timer
 5273:     # it's saved in the user's %env.
 5274:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 5275:     my %timerinterval = &dump('timerinterval', $domain, $username);
 5276:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 5277:         %timerintchk, %timerintenv);
 5278: 
 5279:     foreach my $key (keys(%firstaccess)) {
 5280:         my ($cid, $rest) = split(/\0/, $key);
 5281:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 5282:     }
 5283: 
 5284:     foreach my $key (keys(%timerinterval)) {
 5285:         my ($cid,$rest) = split(/\0/,$key);
 5286:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 5287:     }
 5288: 
 5289:     my %allroles=();
 5290:     my %allgroups=();
 5291: 
 5292:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
 5293:         my $role = $rolesdump{$area};
 5294:         $area =~ s/\_\w\w$//;
 5295: 
 5296:         my ($trole, $tend, $tstart, $group_privs);
 5297: 
 5298:         if ($role =~ /^cr/) {
 5299:         # Custom role, defined by a user 
 5300:         # e.g., user.role.cr/msu/smith/mynewrole
 5301:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 5302:                 $trole = $1;
 5303:                 ($tend, $tstart) = split('_', $2);
 5304:             } else {
 5305:                 $trole = $role;
 5306:             }
 5307:         } elsif ($role =~ m|^gr/|) {
 5308:         # Role of member in a group, defined within a course/community
 5309:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 5310:             ($trole, $tend, $tstart) = split(/_/, $role);
 5311:             next if $tstart eq '-1';
 5312:             ($trole, $group_privs) = split(/\//, $trole);
 5313:             $group_privs = &unescape($group_privs);
 5314:         } else {
 5315:         # Just a normal role, defined in roles.tab
 5316:             ($trole, $tend, $tstart) = split(/_/,$role);
 5317:         }
 5318: 
 5319:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 5320:                  $username);
 5321:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 5322: 
 5323:         # role expired or not available yet?
 5324:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 5325:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 5326: 
 5327:         next if $area eq '' or $trole eq '';
 5328: 
 5329:         my $spec = "$trole.$area";
 5330:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 5331: 
 5332:         if ($trole =~ /^cr\//) {
 5333:         # Custom role, defined by a user
 5334:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 5335:         } elsif ($trole eq 'gr') {
 5336:         # Role of a member in a group, defined within a course/community
 5337:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 5338:             next;
 5339:         } else {
 5340:         # Normal role, defined in roles.tab
 5341:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 5342:         }
 5343: 
 5344:         my $cid = $tdomain.'_'.$trest;
 5345:         unless ($firstaccchk{$cid}) {
 5346:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 5347:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 5348:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 5349:                         $coursetimerstarts{$cid}{$item}; 
 5350:                 }
 5351:             }
 5352:             $firstaccchk{$cid} = 1;
 5353:         }
 5354:         unless ($timerintchk{$cid}) {
 5355:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 5356:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 5357:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 5358:                        $coursetimerintervals{$cid}{$item};
 5359:                 }
 5360:             }
 5361:             $timerintchk{$cid} = 1;
 5362:         }
 5363:     }
 5364: 
 5365:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
 5366:         \%allroles, \%allgroups);
 5367:     $env{'user.adv'} = $userroles{'user.adv'};
 5368: 
 5369:     return (\%userroles,\%firstaccenv,\%timerintenv);
 5370: }
 5371: 
 5372: sub set_arearole {
 5373:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
 5374:     unless ($nolog) {
 5375: # log the associated role with the area
 5376:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 5377:     }
 5378:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 5379: }
 5380: 
 5381: sub custom_roleprivs {
 5382:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 5383:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 5384:     my $homsvr = &homeserver($rauthor,$rdomain);
 5385:     if (&hostname($homsvr) ne '') {
 5386:         my ($rdummy,$roledef)=
 5387:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 5388:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 5389:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 5390:             if (defined($syspriv)) {
 5391:                 if ($trest =~ /^$match_community$/) {
 5392:                     $syspriv =~ s/bre\&S//; 
 5393:                 }
 5394:                 $$allroles{'cm./'}.=':'.$syspriv;
 5395:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 5396:             }
 5397:             if ($tdomain ne '') {
 5398:                 if (defined($dompriv)) {
 5399:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 5400:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 5401:                 }
 5402:                 if (($trest ne '') && (defined($coursepriv))) {
 5403:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 5404:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 5405:                 }
 5406:             }
 5407:         }
 5408:     }
 5409: }
 5410: 
 5411: sub group_roleprivs {
 5412:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 5413:     my $access = 1;
 5414:     my $now = time;
 5415:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 5416:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 5417:     if ($access) {
 5418:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 5419:         $$allgroups{$course}{$group} .=':'.$group_privs;
 5420:     }
 5421: }
 5422: 
 5423: sub standard_roleprivs {
 5424:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 5425:     if (defined($pr{$trole.':s'})) {
 5426:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 5427:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 5428:     }
 5429:     if ($tdomain ne '') {
 5430:         if (defined($pr{$trole.':d'})) {
 5431:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 5432:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 5433:         }
 5434:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 5435:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 5436:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 5437:         }
 5438:     }
 5439: }
 5440: 
 5441: sub set_userprivs {
 5442:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 5443:     my $author=0;
 5444:     my $adv=0;
 5445:     my %grouproles = ();
 5446:     if (keys(%{$allgroups}) > 0) {
 5447:         my @groupkeys; 
 5448:         foreach my $role (keys(%{$allroles})) {
 5449:             push(@groupkeys,$role);
 5450:         }
 5451:         if (ref($groups_roles) eq 'HASH') {
 5452:             foreach my $key (keys(%{$groups_roles})) {
 5453:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 5454:                     push(@groupkeys,$key);
 5455:                 }
 5456:             }
 5457:         }
 5458:         if (@groupkeys > 0) {
 5459:             foreach my $role (@groupkeys) {
 5460:                 my ($trole,$area,$sec,$extendedarea);
 5461:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 5462:                     $trole = $1;
 5463:                     $area = $2;
 5464:                     $sec = $3;
 5465:                     $extendedarea = $area.$sec;
 5466:                     if (exists($$allgroups{$area})) {
 5467:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 5468:                             my $spec = $trole.'.'.$extendedarea;
 5469:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 5470:                                                 $$allgroups{$area}{$group};
 5471:                         }
 5472:                     }
 5473:                 }
 5474:             }
 5475:         }
 5476:     }
 5477:     foreach my $group (keys(%grouproles)) {
 5478:         $$allroles{$group} = $grouproles{$group};
 5479:     }
 5480:     foreach my $role (keys(%{$allroles})) {
 5481:         my %thesepriv;
 5482:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 5483:         foreach my $item (split(/:/,$$allroles{$role})) {
 5484:             if ($item ne '') {
 5485:                 my ($privilege,$restrictions)=split(/&/,$item);
 5486:                 if ($restrictions eq '') {
 5487:                     $thesepriv{$privilege}='F';
 5488:                 } elsif ($thesepriv{$privilege} ne 'F') {
 5489:                     $thesepriv{$privilege}.=$restrictions;
 5490:                 }
 5491:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 5492:             }
 5493:         }
 5494:         my $thesestr='';
 5495:         foreach my $priv (sort(keys(%thesepriv))) {
 5496: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 5497: 	}
 5498:         $userroles->{'user.priv.'.$role} = $thesestr;
 5499:     }
 5500:     return ($author,$adv);
 5501: }
 5502: 
 5503: sub role_status {
 5504:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 5505:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 5506:         my ($one,$two) = split(m{\./},$rolekey,2);
 5507:         (undef,undef,$$role) = split(/\./,$one,3);
 5508:         unless (!defined($$role) || $$role eq '') {
 5509:             $$where = '/'.$two;
 5510:             $$trolecode=$$role.'.'.$$where;
 5511:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 5512:             $$tstatus='is';
 5513:             if ($$tstart && $$tstart>$update) {
 5514:                 $$tstatus='future';
 5515:                 if ($$tstart<$now) {
 5516:                     if ($$tstart && $$tstart>$refresh) {
 5517:                         if (($$where ne '') && ($$role ne '')) {
 5518:                             my (%allroles,%allgroups,$group_privs,
 5519:                                 %groups_roles,@rolecodes);
 5520:                             my %userroles = (
 5521:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 5522:                             );
 5523:                             @rolecodes = ('cm'); 
 5524:                             my $spec=$$role.'.'.$$where;
 5525:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 5526:                             if ($$role =~ /^cr\//) {
 5527:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 5528:                                 push(@rolecodes,'cr');
 5529:                             } elsif ($$role eq 'gr') {
 5530:                                 push(@rolecodes,$$role);
 5531:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 5532:                                                     $env{'user.name'});
 5533:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 5534:                                 (undef,my $group_privs) = split(/\//,$trole);
 5535:                                 $group_privs = &unescape($group_privs);
 5536:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 5537:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 5538:                                 &get_groups_roles($tdomain,$trest,
 5539:                                                   \%course_roles,\@rolecodes,
 5540:                                                   \%groups_roles);
 5541:                             } else {
 5542:                                 push(@rolecodes,$$role);
 5543:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 5544:                             }
 5545:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
 5546:                             &appenv(\%userroles,\@rolecodes);
 5547:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5548:                         }
 5549:                     }
 5550:                     $$tstatus = 'is';
 5551:                 }
 5552:             }
 5553:             if ($$tend) {
 5554:                 if ($$tend<$update) {
 5555:                     $$tstatus='expired';
 5556:                 } elsif ($$tend<$now) {
 5557:                     $$tstatus='will_not';
 5558:                 }
 5559:             }
 5560:         }
 5561:     }
 5562: }
 5563: 
 5564: sub get_groups_roles {
 5565:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 5566:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 5567:                   (ref($rolecodes) eq 'ARRAY') && 
 5568:                   (ref($groups_roles) eq 'HASH')); 
 5569:     if (keys(%{$cdom_courseroles}) > 0) {
 5570:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 5571:         if ($cdom ne '' && $cnum ne '') {
 5572:             foreach my $key (keys(%{$cdom_courseroles})) {
 5573:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 5574:                     my $crsrole = $1;
 5575:                     my $crssec = $2;
 5576:                     if ($crsrole =~ /^cr/) {
 5577:                         unless (grep(/^cr$/,@{$rolecodes})) {
 5578:                             push(@{$rolecodes},'cr');
 5579:                         }
 5580:                     } else {
 5581:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 5582:                             push(@{$rolecodes},$crsrole);
 5583:                         }
 5584:                     }
 5585:                     my $rolekey = "$crsrole./$cdom/$cnum";
 5586:                     if ($crssec ne '') {
 5587:                         $rolekey .= "/$crssec";
 5588:                     }
 5589:                     $rolekey .= './';
 5590:                     $groups_roles->{$rolekey} = $rolecodes;
 5591:                 }
 5592:             }
 5593:         }
 5594:     }
 5595:     return;
 5596: }
 5597: 
 5598: sub delete_env_groupprivs {
 5599:     my ($where,$courseroles,$possroles) = @_;
 5600:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 5601:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 5602:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 5603:         %{$courseroles->{$udom}} =
 5604:             &get_my_roles('','','userroles',['active'],
 5605:                           $possroles,[$udom],1);
 5606:     }
 5607:     if (ref($courseroles->{$udom}) eq 'HASH') {
 5608:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 5609:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 5610:             my $area = '/'.$cdom.'/'.$cnum;
 5611:             my $privkey = "user.priv.$crsrole.$area";
 5612:             if ($crssec ne '') {
 5613:                 $privkey .= '/'.$crssec;
 5614:             }
 5615:             $privkey .= ".$area/$group";
 5616:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 5617:         }
 5618:     }
 5619:     return;
 5620: }
 5621: 
 5622: sub check_adhoc_privs {
 5623:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
 5624:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 5625:     my $setprivs;
 5626:     if ($env{$cckey}) {
 5627:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 5628:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 5629:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 5630:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5631:             $setprivs = 1;
 5632:         }
 5633:     } else {
 5634:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5635:         $setprivs = 1;
 5636:     }
 5637:     return $setprivs;
 5638: }
 5639: 
 5640: sub set_adhoc_privileges {
 5641: # role can be cc or ca
 5642:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
 5643:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 5644:     my $spec = $role.'.'.$area;
 5645:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 5646:                                   $env{'user.name'},1);
 5647:     my %ccrole = ();
 5648:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
 5649:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
 5650:     &appenv(\%userroles,[$role,'cm']);
 5651:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5652:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 5653:         &appenv( {'request.role'        => $spec,
 5654:                   'request.role.domain' => $dcdom,
 5655:                   'request.course.sec'  => ''
 5656:                  }
 5657:                );
 5658:         my $tadv=0;
 5659:         if (&allowed('adv') eq 'F') { $tadv=1; }
 5660:         &appenv({'request.role.adv'    => $tadv});
 5661:     }
 5662: }
 5663: 
 5664: # --------------------------------------------------------------- get interface
 5665: 
 5666: sub get {
 5667:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5668:    my $items='';
 5669:    foreach my $item (@$storearr) {
 5670:        $items.=&escape($item).'&';
 5671:    }
 5672:    $items=~s/\&$//;
 5673:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5674:    if (!$uname) { $uname=$env{'user.name'}; }
 5675:    my $uhome=&homeserver($uname,$udomain);
 5676: 
 5677:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 5678:    my @pairs=split(/\&/,$rep);
 5679:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 5680:      return @pairs;
 5681:    }
 5682:    my %returnhash=();
 5683:    my $i=0;
 5684:    foreach my $item (@$storearr) {
 5685:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5686:       $i++;
 5687:    }
 5688:    return %returnhash;
 5689: }
 5690: 
 5691: # --------------------------------------------------------------- del interface
 5692: 
 5693: sub del {
 5694:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5695:    my $items='';
 5696:    foreach my $item (@$storearr) {
 5697:        $items.=&escape($item).'&';
 5698:    }
 5699: 
 5700:    $items=~s/\&$//;
 5701:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5702:    if (!$uname) { $uname=$env{'user.name'}; }
 5703:    my $uhome=&homeserver($uname,$udomain);
 5704:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 5705: }
 5706: 
 5707: # -------------------------------------------------------------- dump interface
 5708: 
 5709: sub unserialize {
 5710:     my ($rep, $escapedkeys) = @_;
 5711: 
 5712:     return {} if $rep =~ /^error/;
 5713: 
 5714:     my %returnhash=();
 5715:     foreach my $item (split(/\&/,$rep)) {
 5716:         my ($key, $value) = split(/=/, $item, 2);
 5717:         $key = unescape($key) unless $escapedkeys;
 5718:         next if $key =~ /^error: 2 /;
 5719:         $returnhash{$key} = &thaw_unescape($value);
 5720:     }
 5721:     return \%returnhash;
 5722: }
 5723: 
 5724: # see Lond::dump_with_regexp
 5725: # if $escapedkeys hash keys won't get unescaped.
 5726: sub dump {
 5727:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 5728:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5729:     if (!$uname) { $uname=$env{'user.name'}; }
 5730:     my $uhome=&homeserver($uname,$udomain);
 5731: 
 5732:     if ($regexp) {
 5733:         $regexp=&escape($regexp);
 5734:     } else {
 5735:         $regexp='.';
 5736:     }
 5737:     if (grep { $_ eq $uhome } &current_machine_ids()) {
 5738:         # user is hosted on this machine
 5739:         my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
 5740:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
 5741:         return %{&unserialize($reply, $escapedkeys)};
 5742:     }
 5743:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 5744:     my @pairs=split(/\&/,$rep);
 5745:     my %returnhash=();
 5746:     if (!($rep =~ /^error/ )) {
 5747: 	foreach my $item (@pairs) {
 5748: 	    my ($key,$value)=split(/=/,$item,2);
 5749:             $key = &unescape($key) unless ($escapedkeys);
 5750: 	    next if ($key =~ /^error: 2 /);
 5751: 	    $returnhash{$key}=&thaw_unescape($value);
 5752: 	}
 5753:     }
 5754:     return %returnhash;
 5755: }
 5756: 
 5757: 
 5758: # --------------------------------------------------------- dumpstore interface
 5759: 
 5760: sub dumpstore {
 5761:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 5762:    # same as dump but keys must be escaped. They may contain colon separated
 5763:    # lists of values that may themself contain colons (e.g. symbs).
 5764:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 5765: }
 5766: 
 5767: # -------------------------------------------------------------- keys interface
 5768: 
 5769: sub getkeys {
 5770:    my ($namespace,$udomain,$uname)=@_;
 5771:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5772:    if (!$uname) { $uname=$env{'user.name'}; }
 5773:    my $uhome=&homeserver($uname,$udomain);
 5774:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 5775:    my @keyarray=();
 5776:    foreach my $key (split(/\&/,$rep)) {
 5777:       next if ($key =~ /^error: 2 /);
 5778:       push(@keyarray,&unescape($key));
 5779:    }
 5780:    return @keyarray;
 5781: }
 5782: 
 5783: # --------------------------------------------------------------- currentdump
 5784: sub currentdump {
 5785:    my ($courseid,$sdom,$sname)=@_;
 5786:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 5787:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 5788:    $sname    = $env{'user.name'}         if (! defined($sname));
 5789:    my $uhome = &homeserver($sname,$sdom);
 5790:    my $rep;
 5791: 
 5792:    if (grep { $_ eq $uhome } current_machine_ids()) {
 5793:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
 5794:                    $courseid)));
 5795:    } else {
 5796:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 5797:    }
 5798: 
 5799:    return if ($rep =~ /^(error:|no_such_host)/);
 5800:    #
 5801:    my %returnhash=();
 5802:    #
 5803:    if ($rep eq "unknown_cmd") { 
 5804:        # an old lond will not know currentdump
 5805:        # Do a dump and make it look like a currentdump
 5806:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 5807:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 5808:        my %hash = @tmp;
 5809:        @tmp=();
 5810:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 5811:    } else {
 5812:        my @pairs=split(/\&/,$rep);
 5813:        foreach my $pair (@pairs) {
 5814:            my ($key,$value)=split(/=/,$pair,2);
 5815:            my ($symb,$param) = split(/:/,$key);
 5816:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 5817:                                                         &thaw_unescape($value);
 5818:        }
 5819:    }
 5820:    return %returnhash;
 5821: }
 5822: 
 5823: sub convert_dump_to_currentdump{
 5824:     my %hash = %{shift()};
 5825:     my %returnhash;
 5826:     # Code ripped from lond, essentially.  The only difference
 5827:     # here is the unescaping done by lonnet::dump().  Conceivably
 5828:     # we might run in to problems with parameter names =~ /^v\./
 5829:     while (my ($key,$value) = each(%hash)) {
 5830:         my ($v,$symb,$param) = split(/:/,$key);
 5831: 	$symb  = &unescape($symb);
 5832: 	$param = &unescape($param);
 5833:         next if ($v eq 'version' || $symb eq 'keys');
 5834:         next if (exists($returnhash{$symb}) &&
 5835:                  exists($returnhash{$symb}->{$param}) &&
 5836:                  $returnhash{$symb}->{'v.'.$param} > $v);
 5837:         $returnhash{$symb}->{$param}=$value;
 5838:         $returnhash{$symb}->{'v.'.$param}=$v;
 5839:     }
 5840:     #
 5841:     # Remove all of the keys in the hashes which keep track of
 5842:     # the version of the parameter.
 5843:     while (my ($symb,$param_hash) = each(%returnhash)) {
 5844:         # use a foreach because we are going to delete from the hash.
 5845:         foreach my $key (keys(%$param_hash)) {
 5846:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 5847:         }
 5848:     }
 5849:     return \%returnhash;
 5850: }
 5851: 
 5852: # ------------------------------------------------------ critical inc interface
 5853: 
 5854: sub cinc {
 5855:     return &inc(@_,'critical');
 5856: }
 5857: 
 5858: # --------------------------------------------------------------- inc interface
 5859: 
 5860: sub inc {
 5861:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 5862:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5863:     if (!$uname) { $uname=$env{'user.name'}; }
 5864:     my $uhome=&homeserver($uname,$udomain);
 5865:     my $items='';
 5866:     if (! ref($store)) {
 5867:         # got a single value, so use that instead
 5868:         $items = &escape($store).'=&';
 5869:     } elsif (ref($store) eq 'SCALAR') {
 5870:         $items = &escape($$store).'=&';        
 5871:     } elsif (ref($store) eq 'ARRAY') {
 5872:         $items = join('=&',map {&escape($_);} @{$store});
 5873:     } elsif (ref($store) eq 'HASH') {
 5874:         while (my($key,$value) = each(%{$store})) {
 5875:             $items.= &escape($key).'='.&escape($value).'&';
 5876:         }
 5877:     }
 5878:     $items=~s/\&$//;
 5879:     if ($critical) {
 5880: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 5881:     } else {
 5882: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 5883:     }
 5884: }
 5885: 
 5886: # --------------------------------------------------------------- put interface
 5887: 
 5888: sub put {
 5889:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5890:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5891:    if (!$uname) { $uname=$env{'user.name'}; }
 5892:    my $uhome=&homeserver($uname,$udomain);
 5893:    my $items='';
 5894:    foreach my $item (keys(%$storehash)) {
 5895:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5896:    }
 5897:    $items=~s/\&$//;
 5898:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5899: }
 5900: 
 5901: # ------------------------------------------------------------ newput interface
 5902: 
 5903: sub newput {
 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 $key (keys(%$storehash)) {
 5910:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5911:    }
 5912:    $items=~s/\&$//;
 5913:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 5914: }
 5915: 
 5916: # ---------------------------------------------------------  putstore interface
 5917: 
 5918: sub putstore {
 5919:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
 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:    my $esc_symb=&escape($symb);
 5929:    my $esc_v=&escape($version);
 5930:    my $reply =
 5931:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 5932: 	      $uhome);
 5933:    if (($tolog) && ($reply eq 'ok')) {
 5934:        my $namevalue='';
 5935:        foreach my $key (keys(%{$storehash})) {
 5936:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 5937:        }
 5938:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
 5939:                      '&host='.&escape($perlvar{'lonHostID'}).
 5940:                      '&version='.$esc_v.
 5941:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
 5942:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
 5943:    }
 5944:    if ($reply eq 'unknown_cmd') {
 5945:        # gfall back to way things use to be done
 5946:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 5947: 			    $uname);
 5948:    }
 5949:    return $reply;
 5950: }
 5951: 
 5952: sub old_putstore {
 5953:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5954:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5955:     if (!$uname) { $uname=$env{'user.name'}; }
 5956:     my $uhome=&homeserver($uname,$udomain);
 5957:     my %newstorehash;
 5958:     foreach my $item (keys(%$storehash)) {
 5959: 	my $key = $version.':'.&escape($symb).':'.$item;
 5960: 	$newstorehash{$key} = $storehash->{$item};
 5961:     }
 5962:     my $items='';
 5963:     my %allitems = ();
 5964:     foreach my $item (keys(%newstorehash)) {
 5965: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 5966: 	    my $key = $1.':keys:'.$2;
 5967: 	    $allitems{$key} .= $3.':';
 5968: 	}
 5969: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 5970:     }
 5971:     foreach my $item (keys(%allitems)) {
 5972: 	$allitems{$item} =~ s/\:$//;
 5973: 	$items.= $item.'='.$allitems{$item}.'&';
 5974:     }
 5975:     $items=~s/\&$//;
 5976:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5977: }
 5978: 
 5979: # ------------------------------------------------------ critical put interface
 5980: 
 5981: sub cput {
 5982:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5983:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5984:    if (!$uname) { $uname=$env{'user.name'}; }
 5985:    my $uhome=&homeserver($uname,$udomain);
 5986:    my $items='';
 5987:    foreach my $item (keys(%$storehash)) {
 5988:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5989:    }
 5990:    $items=~s/\&$//;
 5991:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 5992: }
 5993: 
 5994: # -------------------------------------------------------------- eget interface
 5995: 
 5996: sub eget {
 5997:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5998:    my $items='';
 5999:    foreach my $item (@$storearr) {
 6000:        $items.=&escape($item).'&';
 6001:    }
 6002:    $items=~s/\&$//;
 6003:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 6004:    if (!$uname) { $uname=$env{'user.name'}; }
 6005:    my $uhome=&homeserver($uname,$udomain);
 6006:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 6007:    my @pairs=split(/\&/,$rep);
 6008:    my %returnhash=();
 6009:    my $i=0;
 6010:    foreach my $item (@$storearr) {
 6011:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 6012:       $i++;
 6013:    }
 6014:    return %returnhash;
 6015: }
 6016: 
 6017: # ------------------------------------------------------------ tmpput interface
 6018: sub tmpput {
 6019:     my ($storehash,$server,$context)=@_;
 6020:     my $items='';
 6021:     foreach my $item (keys(%$storehash)) {
 6022: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 6023:     }
 6024:     $items=~s/\&$//;
 6025:     if (defined($context)) {
 6026:         $items .= ':'.&escape($context);
 6027:     }
 6028:     return &reply("tmpput:$items",$server);
 6029: }
 6030: 
 6031: # ------------------------------------------------------------ tmpget interface
 6032: sub tmpget {
 6033:     my ($token,$server)=@_;
 6034:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 6035:     my $rep=&reply("tmpget:$token",$server);
 6036:     my %returnhash;
 6037:     foreach my $item (split(/\&/,$rep)) {
 6038: 	my ($key,$value)=split(/=/,$item);
 6039:         next if ($key =~ /^error: 2 /);
 6040: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 6041:     }
 6042:     return %returnhash;
 6043: }
 6044: 
 6045: # ------------------------------------------------------------ tmpdel interface
 6046: sub tmpdel {
 6047:     my ($token,$server)=@_;
 6048:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 6049:     return &reply("tmpdel:$token",$server);
 6050: }
 6051: 
 6052: # ------------------------------------------------------------ get_timebased_id
 6053: 
 6054: sub get_timebased_id {
 6055:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
 6056:         $maxtries) = @_;
 6057:     my ($newid,$error,$dellock);
 6058:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
 6059:         return ('','ok','invalid call to get suffix');
 6060:     }
 6061: 
 6062: # set defaults for any optional args for which values were not supplied
 6063:     if ($who eq '') {
 6064:         $who = $env{'user.name'}.':'.$env{'user.domain'};
 6065:     }
 6066:     if (!$locktries) {
 6067:         $locktries = 3;
 6068:     }
 6069:     if (!$maxtries) {
 6070:         $maxtries = 10;
 6071:     }
 6072: 
 6073:     if (($cdom eq '') || ($cnum eq '')) {
 6074:         if ($env{'request.course.id'}) {
 6075:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6076:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6077:         }
 6078:         if (($cdom eq '') || ($cnum eq '')) {
 6079:             return ('','ok','call to get suffix not in course context');
 6080:         }
 6081:     }
 6082: 
 6083: # construct locking item
 6084:     my $lockhash = {
 6085:                       $prefix."\0".'locked_'.$keyid => $who,
 6086:                    };
 6087:     my $tries = 0;
 6088: 
 6089: # attempt to get lock on nohist_$namespace file
 6090:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 6091:     while (($gotlock ne 'ok') && $tries <$locktries) {
 6092:         $tries ++;
 6093:         sleep 1;
 6094:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
 6095:     }
 6096: 
 6097: # attempt to get unique identifier, based on current timestamp
 6098:     if ($gotlock eq 'ok') {
 6099:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
 6100:         my $id = time;
 6101:         $newid = $id;
 6102:         if ($idtype eq 'addcode') {
 6103:             $newid .= &sixnum_code();
 6104:         }
 6105:         my $idtries = 0;
 6106:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
 6107:             if ($idtype eq 'concat') {
 6108:                 $newid = $id.$idtries;
 6109:             } elsif ($idtype eq 'addcode') {
 6110:                 $newid = $newid.&sixnum_code();
 6111:             } else {
 6112:                 $newid ++;
 6113:             }
 6114:             $idtries ++;
 6115:         }
 6116:         if (!exists($inuse{$prefix."\0".$newid})) {
 6117:             my %new_item =  (
 6118:                               $prefix."\0".$newid => $who,
 6119:                             );
 6120:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
 6121:                                                  $cdom,$cnum);
 6122:             if ($putresult ne 'ok') {
 6123:                 undef($newid);
 6124:                 $error = 'error saving new item: '.$putresult;
 6125:             }
 6126:         } else {
 6127:              undef($newid);
 6128:              $error = ('error: no unique suffix available for the new item ');
 6129:         }
 6130: #  remove lock
 6131:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
 6132:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
 6133:     } else {
 6134:         $error = "error: could not obtain lockfile\n";
 6135:         $dellock = 'ok';
 6136:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
 6137:             $dellock = 'nolock';
 6138:         }
 6139:     }
 6140:     return ($newid,$dellock,$error);
 6141: }
 6142: 
 6143: sub sixnum_code {
 6144:     my $code;
 6145:     for (0..6) {
 6146:         $code .= int( rand(9) );
 6147:     }
 6148:     return $code;
 6149: }
 6150: 
 6151: # -------------------------------------------------- portfolio access checking
 6152: 
 6153: sub portfolio_access {
 6154:     my ($requrl) = @_;
 6155:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 6156:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 6157:     if ($result) {
 6158:         my %setters;
 6159:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 6160:             my ($startblock,$endblock) =
 6161:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 6162:             if ($startblock && $endblock) {
 6163:                 return 'B';
 6164:             }
 6165:         } else {
 6166:             my ($startblock,$endblock) =
 6167:                 &Apache::loncommon::blockcheck(\%setters,'port');
 6168:             if ($startblock && $endblock) {
 6169:                 return 'B';
 6170:             }
 6171:         }
 6172:     }
 6173:     if ($result eq 'ok') {
 6174:        return 'F';
 6175:     } elsif ($result =~ /^[^:]+:guest_/) {
 6176:        return 'A';
 6177:     }
 6178:     return '';
 6179: }
 6180: 
 6181: sub get_portfolio_access {
 6182:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 6183: 
 6184:     if (!ref($access_hash)) {
 6185: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 6186: 	my %access_controls = &get_access_controls($current_perms,$group,
 6187: 						   $file_name);
 6188: 	$access_hash = $access_controls{$file_name};
 6189:     }
 6190: 
 6191:     my ($public,$guest,@domains,@users,@courses,@groups);
 6192:     my $now = time;
 6193:     if (ref($access_hash) eq 'HASH') {
 6194:         foreach my $key (keys(%{$access_hash})) {
 6195:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 6196:             if ($start > $now) {
 6197:                 next;
 6198:             }
 6199:             if ($end && $end<$now) {
 6200:                 next;
 6201:             }
 6202:             if ($scope eq 'public') {
 6203:                 $public = $key;
 6204:                 last;
 6205:             } elsif ($scope eq 'guest') {
 6206:                 $guest = $key;
 6207:             } elsif ($scope eq 'domains') {
 6208:                 push(@domains,$key);
 6209:             } elsif ($scope eq 'users') {
 6210:                 push(@users,$key);
 6211:             } elsif ($scope eq 'course') {
 6212:                 push(@courses,$key);
 6213:             } elsif ($scope eq 'group') {
 6214:                 push(@groups,$key);
 6215:             }
 6216:         }
 6217:         if ($public) {
 6218:             return 'ok';
 6219:         }
 6220:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 6221:             if ($guest) {
 6222:                 return $guest;
 6223:             }
 6224:         } else {
 6225:             if (@domains > 0) {
 6226:                 foreach my $domkey (@domains) {
 6227:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 6228:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 6229:                             return 'ok';
 6230:                         }
 6231:                     }
 6232:                 }
 6233:             }
 6234:             if (@users > 0) {
 6235:                 foreach my $userkey (@users) {
 6236:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 6237:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 6238:                             if (ref($item) eq 'HASH') {
 6239:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 6240:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 6241:                                     return 'ok';
 6242:                                 }
 6243:                             }
 6244:                         }
 6245:                     } 
 6246:                 }
 6247:             }
 6248:             my %roleshash;
 6249:             my @courses_and_groups = @courses;
 6250:             push(@courses_and_groups,@groups); 
 6251:             if (@courses_and_groups > 0) {
 6252:                 my (%allgroups,%allroles); 
 6253:                 my ($start,$end,$role,$sec,$group);
 6254:                 foreach my $envkey (%env) {
 6255:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 6256:                         my $cid = $2.'_'.$3; 
 6257:                         if ($1 eq 'gr') {
 6258:                             $group = $4;
 6259:                             $allgroups{$cid}{$group} = $env{$envkey};
 6260:                         } else {
 6261:                             if ($4 eq '') {
 6262:                                 $sec = 'none';
 6263:                             } else {
 6264:                                 $sec = $4;
 6265:                             }
 6266:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 6267:                         }
 6268:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 6269:                         my $cid = $2.'_'.$3;
 6270:                         if ($4 eq '') {
 6271:                             $sec = 'none';
 6272:                         } else {
 6273:                             $sec = $4;
 6274:                         }
 6275:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 6276:                     }
 6277:                 }
 6278:                 if (keys(%allroles) == 0) {
 6279:                     return;
 6280:                 }
 6281:                 foreach my $key (@courses_and_groups) {
 6282:                     my %content = %{$$access_hash{$key}};
 6283:                     my $cnum = $content{'number'};
 6284:                     my $cdom = $content{'domain'};
 6285:                     my $cid = $cdom.'_'.$cnum;
 6286:                     if (!exists($allroles{$cid})) {
 6287:                         next;
 6288:                     }    
 6289:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 6290:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 6291:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 6292:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 6293:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 6294:                         foreach my $role (keys(%{$allroles{$cid}})) {
 6295:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 6296:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 6297:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 6298:                                         if (grep/^all$/,@sections) {
 6299:                                             return 'ok';
 6300:                                         } else {
 6301:                                             if (grep/^$sec$/,@sections) {
 6302:                                                 return 'ok';
 6303:                                             }
 6304:                                         }
 6305:                                     }
 6306:                                 }
 6307:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 6308:                                     if (grep/^none$/,@groups) {
 6309:                                         return 'ok';
 6310:                                     }
 6311:                                 } else {
 6312:                                     if (grep/^all$/,@groups) {
 6313:                                         return 'ok';
 6314:                                     } 
 6315:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 6316:                                         if (grep/^$group$/,@groups) {
 6317:                                             return 'ok';
 6318:                                         }
 6319:                                     }
 6320:                                 } 
 6321:                             }
 6322:                         }
 6323:                     }
 6324:                 }
 6325:             }
 6326:             if ($guest) {
 6327:                 return $guest;
 6328:             }
 6329:         }
 6330:     }
 6331:     return;
 6332: }
 6333: 
 6334: sub course_group_datechecker {
 6335:     my ($dates,$now,$status) = @_;
 6336:     my ($start,$end) = split(/\./,$dates);
 6337:     if (!$start && !$end) {
 6338:         return 'ok';
 6339:     }
 6340:     if (grep/^active$/,@{$status}) {
 6341:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 6342:             return 'ok';
 6343:         }
 6344:     }
 6345:     if (grep/^previous$/,@{$status}) {
 6346:         if ($end > $now ) {
 6347:             return 'ok';
 6348:         }
 6349:     }
 6350:     if (grep/^future$/,@{$status}) {
 6351:         if ($start > $now) {
 6352:             return 'ok';
 6353:         }
 6354:     }
 6355:     return; 
 6356: }
 6357: 
 6358: sub parse_portfolio_url {
 6359:     my ($url) = @_;
 6360: 
 6361:     my ($type,$udom,$unum,$group,$file_name);
 6362:     
 6363:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 6364: 	$type = 1;
 6365:         $udom = $1;
 6366:         $unum = $2;
 6367:         $file_name = $3;
 6368:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 6369: 	$type = 2;
 6370:         $udom = $1;
 6371:         $unum = $2;
 6372:         $group = $3;
 6373:         $file_name = $3.'/'.$4;
 6374:     }
 6375:     if (wantarray) {
 6376: 	return ($type,$udom,$unum,$file_name,$group);
 6377:     }
 6378:     return $type;
 6379: }
 6380: 
 6381: sub is_portfolio_url {
 6382:     my ($url) = @_;
 6383:     return scalar(&parse_portfolio_url($url));
 6384: }
 6385: 
 6386: sub is_portfolio_file {
 6387:     my ($file) = @_;
 6388:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 6389:         return 1;
 6390:     }
 6391:     return;
 6392: }
 6393: 
 6394: sub usertools_access {
 6395:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 6396:     my ($access,%tools);
 6397:     if ($context eq '') {
 6398:         $context = 'tools';
 6399:     }
 6400:     if ($context eq 'requestcourses') {
 6401:         %tools = (
 6402:                       official   => 1,
 6403:                       unofficial => 1,
 6404:                       community  => 1,
 6405:                       textbook   => 1,
 6406:                  );
 6407:     } elsif ($context eq 'requestauthor') {
 6408:         %tools = (
 6409:                       requestauthor => 1,
 6410:                  );
 6411:     } else {
 6412:         %tools = (
 6413:                       aboutme   => 1,
 6414:                       blog      => 1,
 6415:                       webdav    => 1,
 6416:                       portfolio => 1,
 6417:                  );
 6418:     }
 6419:     return if (!defined($tools{$tool}));
 6420: 
 6421:     if (($udom eq '') || ($uname eq '')) {
 6422:         $udom = $env{'user.domain'};
 6423:         $uname = $env{'user.name'};
 6424:     }
 6425: 
 6426:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6427:         if ($action ne 'reload') {
 6428:             if ($context eq 'requestcourses') {
 6429:                 return $env{'environment.canrequest.'.$tool};
 6430:             } elsif ($context eq 'requestauthor') {
 6431:                 return $env{'environment.canrequest.author'};
 6432:             } else {
 6433:                 return $env{'environment.availabletools.'.$tool};
 6434:             }
 6435:         }
 6436:     }
 6437: 
 6438:     my ($toolstatus,$inststatus,$envkey);
 6439:     if ($context eq 'requestauthor') {
 6440:         $envkey = $context;
 6441:     } else {
 6442:         $envkey = $context.'.'.$tool;
 6443:     }
 6444: 
 6445:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 6446:          ($action ne 'reload')) {
 6447:         $toolstatus = $env{'environment.'.$envkey};
 6448:         $inststatus = $env{'environment.inststatus'};
 6449:     } else {
 6450:         if (ref($userenvref) eq 'HASH') {
 6451:             $toolstatus = $userenvref->{$envkey};
 6452:             $inststatus = $userenvref->{'inststatus'};
 6453:         } else {
 6454:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 6455:             $toolstatus = $userenv{$envkey};
 6456:             $inststatus = $userenv{'inststatus'};
 6457:         }
 6458:     }
 6459: 
 6460:     if ($toolstatus ne '') {
 6461:         if ($toolstatus) {
 6462:             $access = 1;
 6463:         } else {
 6464:             $access = 0;
 6465:         }
 6466:         return $access;
 6467:     }
 6468: 
 6469:     my ($is_adv,%domdef);
 6470:     if (ref($is_advref) eq 'HASH') {
 6471:         $is_adv = $is_advref->{'is_adv'};
 6472:     } else {
 6473:         $is_adv = &is_advanced_user($udom,$uname);
 6474:     }
 6475:     if (ref($domdefref) eq 'HASH') {
 6476:         %domdef = %{$domdefref};
 6477:     } else {
 6478:         %domdef = &get_domain_defaults($udom);
 6479:     }
 6480:     if (ref($domdef{$tool}) eq 'HASH') {
 6481:         if ($is_adv) {
 6482:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 6483:                 if ($domdef{$tool}{'_LC_adv'}) { 
 6484:                     $access = 1;
 6485:                 } else {
 6486:                     $access = 0;
 6487:                 }
 6488:                 return $access;
 6489:             }
 6490:         }
 6491:         if ($inststatus ne '') {
 6492:             my ($hasaccess,$hasnoaccess);
 6493:             foreach my $affiliation (split(/:/,$inststatus)) {
 6494:                 if ($domdef{$tool}{$affiliation} ne '') { 
 6495:                     if ($domdef{$tool}{$affiliation}) {
 6496:                         $hasaccess = 1;
 6497:                     } else {
 6498:                         $hasnoaccess = 1;
 6499:                     }
 6500:                 }
 6501:             }
 6502:             if ($hasaccess || $hasnoaccess) {
 6503:                 if ($hasaccess) {
 6504:                     $access = 1;
 6505:                 } elsif ($hasnoaccess) {
 6506:                     $access = 0; 
 6507:                 }
 6508:                 return $access;
 6509:             }
 6510:         } else {
 6511:             if ($domdef{$tool}{'default'} ne '') {
 6512:                 if ($domdef{$tool}{'default'}) {
 6513:                     $access = 1;
 6514:                 } elsif ($domdef{$tool}{'default'} == 0) {
 6515:                     $access = 0;
 6516:                 }
 6517:                 return $access;
 6518:             }
 6519:         }
 6520:     } else {
 6521:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 6522:             $access = 1;
 6523:         } else {
 6524:             $access = 0;
 6525:         }
 6526:         return $access;
 6527:     }
 6528: }
 6529: 
 6530: sub is_course_owner {
 6531:     my ($cdom,$cnum,$udom,$uname) = @_;
 6532:     if (($udom eq '') || ($uname eq '')) {
 6533:         $udom = $env{'user.domain'};
 6534:         $uname = $env{'user.name'};
 6535:     }
 6536:     unless (($udom eq '') || ($uname eq '')) {
 6537:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 6538:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 6539:                 return 1;
 6540:             } else {
 6541:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 6542:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 6543:                     return 1;
 6544:                 }
 6545:             }
 6546:         }
 6547:     }
 6548:     return;
 6549: }
 6550: 
 6551: sub is_advanced_user {
 6552:     my ($udom,$uname) = @_;
 6553:     if ($udom ne '' && $uname ne '') {
 6554:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6555:             if (wantarray) {
 6556:                 return ($env{'user.adv'},$env{'user.author'});
 6557:             } else {
 6558:                 return $env{'user.adv'};
 6559:             }
 6560:         }
 6561:     }
 6562:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 6563:     my %allroles;
 6564:     my ($is_adv,$is_author);
 6565:     foreach my $role (keys(%roleshash)) {
 6566:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 6567:         my $area = '/'.$tdomain.'/'.$trest;
 6568:         if ($sec ne '') {
 6569:             $area .= '/'.$sec;
 6570:         }
 6571:         if (($area ne '') && ($trole ne '')) {
 6572:             my $spec=$trole.'.'.$area;
 6573:             if ($trole =~ /^cr\//) {
 6574:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 6575:             } elsif ($trole ne 'gr') {
 6576:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 6577:             }
 6578:             if ($trole eq 'au') {
 6579:                 $is_author = 1;
 6580:             }
 6581:         }
 6582:     }
 6583:     foreach my $role (keys(%allroles)) {
 6584:         last if ($is_adv);
 6585:         foreach my $item (split(/:/,$allroles{$role})) {
 6586:             if ($item ne '') {
 6587:                 my ($privilege,$restrictions)=split(/&/,$item);
 6588:                 if ($privilege eq 'adv') {
 6589:                     $is_adv = 1;
 6590:                     last;
 6591:                 }
 6592:             }
 6593:         }
 6594:     }
 6595:     if (wantarray) {
 6596:         return ($is_adv,$is_author);
 6597:     }
 6598:     return $is_adv;
 6599: }
 6600: 
 6601: sub check_can_request {
 6602:     my ($dom,$can_request,$request_domains) = @_;
 6603:     my $canreq = 0;
 6604:     my ($types,$typename) = &Apache::loncommon::course_types();
 6605:     my @options = ('approval','validate','autolimit');
 6606:     my $optregex = join('|',@options);
 6607:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 6608:         foreach my $type (@{$types}) {
 6609:             if (&usertools_access($env{'user.name'},
 6610:                                   $env{'user.domain'},
 6611:                                   $type,undef,'requestcourses')) {
 6612:                 $canreq ++;
 6613:                 if (ref($request_domains) eq 'HASH') {
 6614:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 6615:                 }
 6616:                 if ($dom eq $env{'user.domain'}) {
 6617:                     $can_request->{$type} = 1;
 6618:                 }
 6619:             }
 6620:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 6621:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 6622:                 if (@curr > 0) {
 6623:                     foreach my $item (@curr) {
 6624:                         if (ref($request_domains) eq 'HASH') {
 6625:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 6626:                             if ($otherdom ne '') {
 6627:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 6628:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 6629:                                         push(@{$request_domains->{$type}},$otherdom);
 6630:                                     }
 6631:                                 } else {
 6632:                                     push(@{$request_domains->{$type}},$otherdom);
 6633:                                 }
 6634:                             }
 6635:                         }
 6636:                     }
 6637:                     unless($dom eq $env{'user.domain'}) {
 6638:                         $canreq ++;
 6639:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 6640:                             $can_request->{$type} = 1;
 6641:                         }
 6642:                     }
 6643:                 }
 6644:             }
 6645:         }
 6646:     }
 6647:     return $canreq;
 6648: }
 6649: 
 6650: # ---------------------------------------------- Custom access rule evaluation
 6651: 
 6652: sub customaccess {
 6653:     my ($priv,$uri)=@_;
 6654:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 6655:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 6656:     $udom = &LONCAPA::clean_domain($udom);
 6657:     $ucrs = &LONCAPA::clean_username($ucrs);
 6658:     my $access=0;
 6659:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 6660: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 6661: 	if ($type eq 'user') {
 6662: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 6663: 		my ($tdom,$tuname)=split(m{/},$scope);
 6664: 		if ($tdom) {
 6665: 		    if ($tdom ne $env{'user.domain'}) { next; }
 6666: 		}
 6667: 		if ($tuname) {
 6668: 		    if ($tuname ne $env{'user.name'}) { next; }
 6669: 		}
 6670: 		$access=($effect eq 'allow');
 6671: 		last;
 6672: 	    }
 6673: 	} else {
 6674: 	    if ($role) {
 6675: 		if ($role ne $urole) { next; }
 6676: 	    }
 6677: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 6678: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 6679: 		if ($tdom) {
 6680: 		    if ($tdom ne $udom) { next; }
 6681: 		}
 6682: 		if ($tcrs) {
 6683: 		    if ($tcrs ne $ucrs) { next; }
 6684: 		}
 6685: 		if ($tsec) {
 6686: 		    if ($tsec ne $usec) { next; }
 6687: 		}
 6688: 		$access=($effect eq 'allow');
 6689: 		last;
 6690: 	    }
 6691: 	    if ($realm eq '' && $role eq '') {
 6692: 		$access=($effect eq 'allow');
 6693: 	    }
 6694: 	}
 6695:     }
 6696:     return $access;
 6697: }
 6698: 
 6699: # ------------------------------------------------- Check for a user privilege
 6700: 
 6701: sub allowed {
 6702:     my ($priv,$uri,$symb,$role)=@_;
 6703:     my $ver_orguri=$uri;
 6704:     $uri=&deversion($uri);
 6705:     my $orguri=$uri;
 6706:     $uri=&declutter($uri);
 6707: 
 6708:     if ($priv eq 'evb') {
 6709: # Evade communication block restrictions for specified role in a course
 6710:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 6711:             return $1;
 6712:         } else {
 6713:             return;
 6714:         }
 6715:     }
 6716: 
 6717:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 6718: # Free bre access to adm and meta resources
 6719:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 6720: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 6721: 	&& ($priv eq 'bre')) {
 6722: 	return 'F';
 6723:     }
 6724: 
 6725: # Free bre access to user's own portfolio contents
 6726:     my ($space,$domain,$name,@dir)=split('/',$uri);
 6727:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 6728: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 6729:         my %setters;
 6730:         my ($startblock,$endblock) = 
 6731:             &Apache::loncommon::blockcheck(\%setters,'port');
 6732:         if ($startblock && $endblock) {
 6733:             return 'B';
 6734:         } else {
 6735:             return 'F';
 6736:         }
 6737:     }
 6738: 
 6739: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 6740:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 6741:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 6742:         if (exists($env{'request.course.id'})) {
 6743:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6744:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6745:             if (($domain eq $cdom) && ($name eq $cnum)) {
 6746:                 my $courseprivid=$env{'request.course.id'};
 6747:                 $courseprivid=~s/\_/\//;
 6748:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 6749:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 6750:                     return $1; 
 6751:                 } else {
 6752:                     if ($env{'request.course.sec'}) {
 6753:                         $courseprivid.='/'.$env{'request.course.sec'};
 6754:                     }
 6755:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 6756:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 6757:                         return $2;
 6758:                     }
 6759:                 }
 6760:             }
 6761:         }
 6762:     }
 6763: 
 6764: # Free bre to public access
 6765: 
 6766:     if ($priv eq 'bre') {
 6767:         my $copyright=&metadata($uri,'copyright');
 6768: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 6769:            return 'F'; 
 6770:         }
 6771:         if ($copyright eq 'priv') {
 6772:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6773: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 6774: 		return '';
 6775:             }
 6776:         }
 6777:         if ($copyright eq 'domain') {
 6778:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6779: 	    unless (($env{'user.domain'} eq $1) ||
 6780:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 6781: 		return '';
 6782:             }
 6783:         }
 6784:         if ($env{'request.role'}=~ /li\.\//) {
 6785:             # Library role, so allow browsing of resources in this domain.
 6786:             return 'F';
 6787:         }
 6788:         if ($copyright eq 'custom') {
 6789: 	    unless (&customaccess($priv,$uri)) { return ''; }
 6790:         }
 6791:     }
 6792:     # Domain coordinator is trying to create a course
 6793:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 6794:         # uri is the requested domain in this case.
 6795:         # comparison to 'request.role.domain' shows if the user has selected
 6796:         # a role of dc for the domain in question.
 6797:         return 'F' if ($uri eq $env{'request.role.domain'});
 6798:     }
 6799: 
 6800:     my $thisallowed='';
 6801:     my $statecond=0;
 6802:     my $courseprivid='';
 6803: 
 6804:     my $ownaccess;
 6805:     # Community Coordinator or Assistant Co-author browsing resource space.
 6806:     if (($priv eq 'bro') && ($env{'user.author'})) {
 6807:         if ($uri eq '') {
 6808:             $ownaccess = 1;
 6809:         } else {
 6810:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 6811:                 my $udom = $env{'user.domain'};
 6812:                 my $uname = $env{'user.name'};
 6813:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 6814:                     $ownaccess = 1;
 6815:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 6816:                     unless ($uri =~ m{\.\./}) {
 6817:                         $ownaccess = 1;
 6818:                     }
 6819:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 6820:                     my $now = time;
 6821:                     if ($uri =~ m{^([^/]+)/?$}) {
 6822:                         my $adom = $1;
 6823:                         foreach my $key (keys(%env)) {
 6824:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 6825:                                 my ($start,$end) = split('.',$env{$key});
 6826:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6827:                                     $ownaccess = 1;
 6828:                                     last;
 6829:                                 }
 6830:                             }
 6831:                         }
 6832:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 6833:                         my $adom = $1;
 6834:                         my $aname = $2;
 6835:                         foreach my $role ('ca','aa') { 
 6836:                             if ($env{"user.role.$role./$adom/$aname"}) {
 6837:                                 my ($start,$end) =
 6838:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 6839:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6840:                                     $ownaccess = 1;
 6841:                                     last;
 6842:                                 }
 6843:                             }
 6844:                         }
 6845:                     }
 6846:                 }
 6847:             }
 6848:         }
 6849:     }
 6850: 
 6851: # Course
 6852: 
 6853:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 6854:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6855:             $thisallowed.=$1;
 6856:         }
 6857:     }
 6858: 
 6859: # Domain
 6860: 
 6861:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 6862:        =~/\Q$priv\E\&([^\:]*)/) {
 6863:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6864:             $thisallowed.=$1;
 6865:         }
 6866:     }
 6867: 
 6868: # User who is not author or co-author might still be able to edit
 6869: # resource of an author in the domain (e.g., if Domain Coordinator).
 6870:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 6871:         (&allowed('mdc',$env{'request.course.id'}))) {
 6872:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 6873:             $thisallowed.=$1;
 6874:         }
 6875:     }
 6876: 
 6877: # Course: uri itself is a course
 6878:     my $courseuri=$uri;
 6879:     $courseuri=~s/\_(\d)/\/$1/;
 6880:     $courseuri=~s/^([^\/])/\/$1/;
 6881: 
 6882:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 6883:        =~/\Q$priv\E\&([^\:]*)/) {
 6884:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6885:             $thisallowed.=$1;
 6886:         }
 6887:     }
 6888: 
 6889: # URI is an uploaded document for this course, default permissions don't matter
 6890: # not allowing 'edit' access (editupload) to uploaded course docs
 6891:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 6892: 	$thisallowed='';
 6893:         my ($match)=&is_on_map($uri);
 6894:         if ($match) {
 6895:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 6896:                   =~/\Q$priv\E\&([^\:]*)/) {
 6897:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6898:                 if (@blockers > 0) {
 6899:                     $thisallowed = 'B';
 6900:                 } else {
 6901:                     $thisallowed.=$1;
 6902:                 }
 6903:             }
 6904:         } else {
 6905:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 6906:             if ($refuri) {
 6907:                 if ($refuri =~ m|^/adm/|) {
 6908:                     $thisallowed='F';
 6909:                 } else {
 6910:                     $refuri=&declutter($refuri);
 6911:                     my ($match) = &is_on_map($refuri);
 6912:                     if ($match) {
 6913:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6914:                         if (@blockers > 0) {
 6915:                             $thisallowed = 'B';
 6916:                         } else {
 6917:                             $thisallowed='F';
 6918:                         }
 6919:                     }
 6920:                 }
 6921:             }
 6922:         }
 6923:     }
 6924: 
 6925:     if ($priv eq 'bre'
 6926: 	&& $thisallowed ne 'F' 
 6927: 	&& $thisallowed ne '2'
 6928: 	&& &is_portfolio_url($uri)) {
 6929: 	$thisallowed = &portfolio_access($uri);
 6930:     }
 6931:     
 6932: # Full access at system, domain or course-wide level? Exit.
 6933:     if ($thisallowed=~/F/) {
 6934: 	return 'F';
 6935:     }
 6936: 
 6937: # If this is generating or modifying users, exit with special codes
 6938: 
 6939:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 6940: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 6941: 	    my ($audom,$auname)=split('/',$uri);
 6942: # no author name given, so this just checks on the general right to make a co-author in this domain
 6943: 	    unless ($auname) { return $thisallowed; }
 6944: # an author name is given, so we are about to actually make a co-author for a certain account
 6945: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 6946: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 6947: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 6948: 	}
 6949: 	return $thisallowed;
 6950:     }
 6951: #
 6952: # Gathered so far: system, domain and course wide privileges
 6953: #
 6954: # Course: See if uri or referer is an individual resource that is part of 
 6955: # the course
 6956: 
 6957:     if ($env{'request.course.id'}) {
 6958: 
 6959:        $courseprivid=$env{'request.course.id'};
 6960:        if ($env{'request.course.sec'}) {
 6961:           $courseprivid.='/'.$env{'request.course.sec'};
 6962:        }
 6963:        $courseprivid=~s/\_/\//;
 6964:        my $checkreferer=1;
 6965:        my ($match,$cond)=&is_on_map($uri);
 6966:        if ($match) {
 6967:            $statecond=$cond;
 6968:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6969:                =~/\Q$priv\E\&([^\:]*)/) {
 6970:                my $value = $1;
 6971:                if ($priv eq 'bre') {
 6972:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6973:                    if (@blockers > 0) {
 6974:                        $thisallowed = 'B';
 6975:                    } else {
 6976:                        $thisallowed.=$value;
 6977:                    }
 6978:                } else {
 6979:                    $thisallowed.=$value;
 6980:                }
 6981:                $checkreferer=0;
 6982:            }
 6983:        }
 6984:        
 6985:        if ($checkreferer) {
 6986: 	  my $refuri=$env{'httpref.'.$orguri};
 6987:             unless ($refuri) {
 6988:                 foreach my $key (keys(%env)) {
 6989: 		    if ($key=~/^httpref\..*\*/) {
 6990: 			my $pattern=$key;
 6991:                         $pattern=~s/^httpref\.\/res\///;
 6992:                         $pattern=~s/\*/\[\^\/\]\+/g;
 6993:                         $pattern=~s/\//\\\//g;
 6994:                         if ($orguri=~/$pattern/) {
 6995: 			    $refuri=$env{$key};
 6996:                         }
 6997:                     }
 6998:                 }
 6999:             }
 7000: 
 7001:          if ($refuri) { 
 7002: 	  $refuri=&declutter($refuri);
 7003:           my ($match,$cond)=&is_on_map($refuri);
 7004:             if ($match) {
 7005:               my $refstatecond=$cond;
 7006:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 7007:                   =~/\Q$priv\E\&([^\:]*)/) {
 7008:                   my $value = $1;
 7009:                   if ($priv eq 'bre') {
 7010:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 7011:                       if (@blockers > 0) {
 7012:                           $thisallowed = 'B';
 7013:                       } else {
 7014:                           $thisallowed.=$value;
 7015:                       }
 7016:                   } else {
 7017:                       $thisallowed.=$value;
 7018:                   }
 7019:                   $uri=$refuri;
 7020:                   $statecond=$refstatecond;
 7021:               }
 7022:           }
 7023:         }
 7024:        }
 7025:    }
 7026: 
 7027: #
 7028: # Gathered now: all privileges that could apply, and condition number
 7029: # 
 7030: #
 7031: # Full or no access?
 7032: #
 7033: 
 7034:     if ($thisallowed=~/F/) {
 7035: 	return 'F';
 7036:     }
 7037: 
 7038:     unless ($thisallowed) {
 7039:         return '';
 7040:     }
 7041: 
 7042: # Restrictions exist, deal with them
 7043: #
 7044: #   C:according to course preferences
 7045: #   R:according to resource settings
 7046: #   L:unless locked
 7047: #   X:according to user session state
 7048: #
 7049: 
 7050: # Possibly locked functionality, check all courses
 7051: # Locks might take effect only after 10 minutes cache expiration for other
 7052: # courses, and 2 minutes for current course
 7053: 
 7054:     my $envkey;
 7055:     if ($thisallowed=~/L/) {
 7056:         foreach $envkey (keys(%env)) {
 7057:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 7058:                my $courseid=$2;
 7059:                my $roleid=$1.'.'.$2;
 7060:                $courseid=~s/^\///;
 7061:                my $expiretime=600;
 7062:                if ($env{'request.role'} eq $roleid) {
 7063: 		  $expiretime=120;
 7064:                }
 7065: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 7066:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 7067:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 7068: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 7069:                }
 7070:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 7071:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 7072: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 7073:                        &log($env{'user.domain'},$env{'user.name'},
 7074:                             $env{'user.home'},
 7075:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 7076:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 7077:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 7078: 		       return '';
 7079:                    }
 7080:                }
 7081:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 7082:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 7083: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 7084:                        &log($env{'user.domain'},$env{'user.name'},
 7085:                             $env{'user.home'},
 7086:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 7087:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 7088:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 7089: 		       return '';
 7090:                    }
 7091:                }
 7092: 	   }
 7093:        }
 7094:     }
 7095:    
 7096: #
 7097: # Rest of the restrictions depend on selected course
 7098: #
 7099: 
 7100:     unless ($env{'request.course.id'}) {
 7101: 	if ($thisallowed eq 'A') {
 7102: 	    return 'A';
 7103:         } elsif ($thisallowed eq 'B') {
 7104:             return 'B';
 7105: 	} else {
 7106: 	    return '1';
 7107: 	}
 7108:     }
 7109: 
 7110: #
 7111: # Now user is definitely in a course
 7112: #
 7113: 
 7114: 
 7115: # Course preferences
 7116: 
 7117:    if ($thisallowed=~/C/) {
 7118:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 7119:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 7120:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 7121: 	   =~/\Q$rolecode\E/) {
 7122: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 7123: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 7124: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 7125: 			$env{'request.course.id'});
 7126: 	   }
 7127:            return '';
 7128:        }
 7129: 
 7130:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 7131: 	   =~/\Q$unamedom\E/) {
 7132: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 7133: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 7134: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 7135: 			$env{'request.course.id'});
 7136: 	   }
 7137:            return '';
 7138:        }
 7139:    }
 7140: 
 7141: # Resource preferences
 7142: 
 7143:    if ($thisallowed=~/R/) {
 7144:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 7145:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 7146: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 7147: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 7148: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 7149: 	   }
 7150: 	   return '';
 7151:        }
 7152:    }
 7153: 
 7154: # Restricted by state or randomout?
 7155: 
 7156:    if ($thisallowed=~/X/) {
 7157:       if ($env{'acc.randomout'}) {
 7158: 	 if (!$symb) { $symb=&symbread($uri,1); }
 7159:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 7160:             return ''; 
 7161:          }
 7162:       }
 7163:       if (&condval($statecond)) {
 7164: 	 return '2';
 7165:       } else {
 7166:          return '';
 7167:       }
 7168:    }
 7169: 
 7170:     if ($thisallowed eq 'A') {
 7171: 	return 'A';
 7172:     } elsif ($thisallowed eq 'B') {
 7173:         return 'B';
 7174:     }
 7175:    return 'F';
 7176: }
 7177: 
 7178: # ------------------------------------------- Check construction space access
 7179: 
 7180: sub constructaccess {
 7181:     my ($url,$setpriv)=@_;
 7182: 
 7183: # We do not allow editing of previous versions of files
 7184:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
 7185: 
 7186: # Get username and domain from URL
 7187:     my ($ownername,$ownerdomain,$ownerhome);
 7188: 
 7189:     ($ownerdomain,$ownername) =
 7190:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
 7191: 
 7192: # The URL does not really point to any authorspace, forget it
 7193:     unless (($ownername) && ($ownerdomain)) { return ''; }
 7194: 
 7195: # Now we need to see if the user has access to the authorspace of
 7196: # $ownername at $ownerdomain
 7197: 
 7198:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
 7199: # Real author for this?
 7200:        $ownerhome = $env{'user.home'};
 7201:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
 7202:           return ($ownername,$ownerdomain,$ownerhome);
 7203:        }
 7204:     } else {
 7205: # Co-author for this?
 7206:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
 7207:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
 7208:             $ownerhome = &homeserver($ownername,$ownerdomain);
 7209:             return ($ownername,$ownerdomain,$ownerhome);
 7210:         }
 7211:     }
 7212: 
 7213: # We don't have any access right now. If we are not possibly going to do anything about this,
 7214: # we might as well leave
 7215:    unless ($setpriv) { return ''; }
 7216: 
 7217: # Backdoor access?
 7218:     my $allowed=&allowed('eco',$ownerdomain);
 7219: # Nope
 7220:     unless ($allowed) { return ''; }
 7221: # Looks like we may have access, but could be locked by the owner of the construction space
 7222:     if ($allowed eq 'U') {
 7223:         my %blocked=&get('environment',['domcoord.author'],
 7224:                          $ownerdomain,$ownername);
 7225: # Is blocked by owner
 7226:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
 7227:     }
 7228:     if (($allowed eq 'F') || ($allowed eq 'U')) {
 7229: # Grant temporary access
 7230:         my $then=$env{'user.login.time'};
 7231:         my $update=$env{'user.update.time'};
 7232:         if (!$update) { $update = $then; }
 7233:         my $refresh=$env{'user.refresh.time'};
 7234:         if (!$refresh) { $refresh = $update; }
 7235:         my $now = time;
 7236:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
 7237:                            $now,'ca','constructaccess');
 7238:         $ownerhome = &homeserver($ownername,$ownerdomain);
 7239:         return($ownername,$ownerdomain,$ownerhome);
 7240:     }
 7241: # No business here
 7242:     return '';
 7243: }
 7244: 
 7245: sub get_comm_blocks {
 7246:     my ($cdom,$cnum) = @_;
 7247:     if ($cdom eq '' || $cnum eq '') {
 7248:         return unless ($env{'request.course.id'});
 7249:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 7250:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 7251:     }
 7252:     my %commblocks;
 7253:     my $hashid=$cdom.'_'.$cnum;
 7254:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 7255:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 7256:         %commblocks = %{$blocksref};
 7257:     } else {
 7258:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 7259:         my $cachetime = 600;
 7260:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 7261:     }
 7262:     return %commblocks;
 7263: }
 7264: 
 7265: sub has_comm_blocking {
 7266:     my ($priv,$symb,$uri,$blocks) = @_;
 7267:     return unless ($env{'request.course.id'});
 7268:     return unless ($priv eq 'bre');
 7269:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 7270:     my %commblocks;
 7271:     if (ref($blocks) eq 'HASH') {
 7272:         %commblocks = %{$blocks};
 7273:     } else {
 7274:         %commblocks = &get_comm_blocks();
 7275:     }
 7276:     return unless (keys(%commblocks) > 0);
 7277:     if (!$symb) { $symb=&symbread($uri,1); }
 7278:     my ($map,$resid,undef)=&decode_symb($symb);
 7279:     my %tocheck = (
 7280:                     maps      => $map,
 7281:                     resources => $symb,
 7282:                   );
 7283:     my @blockers;
 7284:     my $now = time;
 7285:     my $navmap = Apache::lonnavmaps::navmap->new();
 7286:     foreach my $block (keys(%commblocks)) {
 7287:         if ($block =~ /^(\d+)____(\d+)$/) {
 7288:             my ($start,$end) = ($1,$2);
 7289:             if ($start <= $now && $end >= $now) {
 7290:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 7291:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 7292:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 7293:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
 7294:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 7295:                                     push(@blockers,$block);
 7296:                                 }
 7297:                             }
 7298:                         }
 7299:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 7300:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
 7301:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
 7302:                                     push(@blockers,$block);
 7303:                                 }
 7304:                             }
 7305:                         }
 7306:                     }
 7307:                 }
 7308:             }
 7309:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 7310:             my $item = $1;
 7311:             my @to_test;
 7312:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 7313:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 7314:                     my $check_interval;
 7315:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
 7316:                         my @interval;
 7317:                         my $type = 'map';
 7318:                         if ($item eq 'course') {
 7319:                             $type = 'course';
 7320:                             @interval=&EXT("resource.0.interval");
 7321:                         } else {
 7322:                             if ($item =~ /___\d+___/) {
 7323:                                 $type = 'resource';
 7324:                                 @interval=&EXT("resource.0.interval",$item);
 7325:                                 if (ref($navmap)) {                        
 7326:                                     my $res = $navmap->getBySymb($item); 
 7327:                                     push(@to_test,$res);
 7328:                                 }
 7329:                             } else {
 7330:                                 my $mapsymb = &symbread($item,1);
 7331:                                 if ($mapsymb) {
 7332:                                     if (ref($navmap)) {
 7333:                                         my $mapres = $navmap->getBySymb($mapsymb);
 7334:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
 7335:                                         foreach my $res (@to_test) {
 7336:                                             my $symb = $res->symb();
 7337:                                             next if ($symb eq $mapsymb);
 7338:                                             if ($symb ne '') {
 7339:                                                 @interval=&EXT("resource.0.interval",$symb);
 7340:                                                 last;
 7341:                                             }
 7342:                                         }
 7343:                                     }
 7344:                                 }
 7345:                             }
 7346:                         }
 7347:                         if ($interval[0] =~ /\d+/) {
 7348:                             my $first_access;
 7349:                             if ($type eq 'resource') {
 7350:                                 $first_access=&get_first_access($interval[1],$item);
 7351:                             } elsif ($type eq 'map') {
 7352:                                 $first_access=&get_first_access($interval[1],undef,$item);
 7353:                             } else {
 7354:                                 $first_access=&get_first_access($interval[1]);
 7355:                             }
 7356:                             if ($first_access) {
 7357:                                 my $timesup = $first_access+$interval[0];
 7358:                                 if ($timesup > $now) {
 7359:                                     foreach my $res (@to_test) {
 7360:                                         if ($res->is_problem()) {
 7361:                                             if ($res->completable()) {
 7362:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 7363:                                                     push(@blockers,$block);
 7364:                                                 }
 7365:                                                 last;
 7366:                                             }
 7367:                                         }
 7368:                                     }
 7369:                                 }
 7370:                             }
 7371:                         }
 7372:                     }
 7373:                 }
 7374:             }
 7375:         }
 7376:     }
 7377:     return @blockers;
 7378: }
 7379: 
 7380: sub check_docs_block {
 7381:     my ($docsblock,$tocheck) =@_;
 7382:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
 7383:         return;
 7384:     }
 7385:     if (ref($docsblock->{'maps'}) eq 'HASH') {
 7386:         if ($tocheck->{'maps'}) {
 7387:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
 7388:                 return 1;
 7389:             }
 7390:         }
 7391:     }
 7392:     if (ref($docsblock->{'resources'}) eq 'HASH') {
 7393:         if ($tocheck->{'resources'}) {
 7394:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
 7395:                 return 1;
 7396:             }
 7397:         }
 7398:     }
 7399:     return;
 7400: }
 7401: 
 7402: #
 7403: #   Removes the versino from a URI and
 7404: #   splits it in to its filename and path to the filename.
 7405: #   Seems like File::Basename could have done this more clearly.
 7406: #   Parameters:
 7407: #      $uri   - input URI
 7408: #   Returns:
 7409: #     Two element list consisting of 
 7410: #     $pathname  - the URI up to and excluding the trailing /
 7411: #     $filename  - The part of the URI following the last /
 7412: #  NOTE:
 7413: #    Another realization of this is simply:
 7414: #    use File::Basename;
 7415: #    ...
 7416: #    $uri = shift;
 7417: #    $filename = basename($uri);
 7418: #    $path     = dirname($uri);
 7419: #    return ($filename, $path);
 7420: #
 7421: #     The implementation below is probably faster however.
 7422: #
 7423: sub split_uri_for_cond {
 7424:     my $uri=&deversion(&declutter(shift));
 7425:     my @uriparts=split(/\//,$uri);
 7426:     my $filename=pop(@uriparts);
 7427:     my $pathname=join('/',@uriparts);
 7428:     return ($pathname,$filename);
 7429: }
 7430: # --------------------------------------------------- Is a resource on the map?
 7431: 
 7432: sub is_on_map {
 7433:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 7434:     #Trying to find the conditional for the file
 7435:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 7436: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 7437:     if ($match) {
 7438: 	return (1,$1);
 7439:     } else {
 7440: 	return (0,0);
 7441:     }
 7442: }
 7443: 
 7444: # --------------------------------------------------------- Get symb from alias
 7445: 
 7446: sub get_symb_from_alias {
 7447:     my $symb=shift;
 7448:     my ($map,$resid,$url)=&decode_symb($symb);
 7449: # Already is a symb
 7450:     if ($url) { return $symb; }
 7451: # Must be an alias
 7452:     my $aliassymb='';
 7453:     my %bighash;
 7454:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7455:                             &GDBM_READER(),0640)) {
 7456:         my $rid=$bighash{'mapalias_'.$symb};
 7457: 	if ($rid) {
 7458: 	    my ($mapid,$resid)=split(/\./,$rid);
 7459: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 7460: 				    $resid,$bighash{'src_'.$rid});
 7461: 	}
 7462:         untie %bighash;
 7463:     }
 7464:     return $aliassymb;
 7465: }
 7466: 
 7467: # ----------------------------------------------------------------- Define Role
 7468: 
 7469: sub definerole {
 7470:   if (allowed('mcr','/')) {
 7471:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 7472:     foreach my $role (split(':',$sysrole)) {
 7473: 	my ($crole,$cqual)=split(/\&/,$role);
 7474:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 7475:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 7476: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 7477:                return "refused:s:$crole&$cqual"; 
 7478:             }
 7479:         }
 7480:     }
 7481:     foreach my $role (split(':',$domrole)) {
 7482: 	my ($crole,$cqual)=split(/\&/,$role);
 7483:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 7484:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 7485: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 7486:                return "refused:d:$crole&$cqual"; 
 7487:             }
 7488:         }
 7489:     }
 7490:     foreach my $role (split(':',$courole)) {
 7491: 	my ($crole,$cqual)=split(/\&/,$role);
 7492:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 7493:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 7494: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 7495:                return "refused:c:$crole&$cqual"; 
 7496:             }
 7497:         }
 7498:     }
 7499:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 7500:                 "$env{'user.domain'}:$env{'user.name'}:".
 7501: 	        "rolesdef_$rolename=".
 7502:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 7503:     return reply($command,$env{'user.home'});
 7504:   } else {
 7505:     return 'refused';
 7506:   }
 7507: }
 7508: 
 7509: # ---------------- Make a metadata query against the network of library servers
 7510: 
 7511: sub metadata_query {
 7512:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
 7513:     my %rhash;
 7514:     my %libserv = &all_library();
 7515:     my @server_list = (defined($server_array) ? @$server_array
 7516:                                               : keys(%libserv) );
 7517:     for my $server (@server_list) {
 7518:         my $domains = '';
 7519:         if (ref($domains_hash) eq 'HASH') {
 7520:             $domains = $domains_hash->{$server};    
 7521:         }
 7522: 	unless ($custom or $customshow) {
 7523: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
 7524: 	    $rhash{$server}=$reply;
 7525: 	}
 7526: 	else {
 7527: 	    my $reply=&reply("querysend:".&escape($query).':'.
 7528: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
 7529: 			     $server);
 7530: 	    $rhash{$server}=$reply;
 7531: 	}
 7532:     }
 7533:     return \%rhash;
 7534: }
 7535: 
 7536: # ----------------------------------------- Send log queries and wait for reply
 7537: 
 7538: sub log_query {
 7539:     my ($uname,$udom,$query,%filters)=@_;
 7540:     my $uhome=&homeserver($uname,$udom);
 7541:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 7542:     my $uhost=&hostname($uhome);
 7543:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 7544:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 7545:                        $uhome);
 7546:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 7547:     return get_query_reply($queryid);
 7548: }
 7549: 
 7550: # -------------------------- Update MySQL table for portfolio file
 7551: 
 7552: sub update_portfolio_table {
 7553:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 7554:     if ($group ne '') {
 7555:         $file_name =~s /^\Q$group\E//;
 7556:     }
 7557:     my $homeserver = &homeserver($uname,$udom);
 7558:     my $queryid=
 7559:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 7560:                ':'.&escape($file_name).':'.$action,$homeserver);
 7561:     my $reply = &get_query_reply($queryid);
 7562:     return $reply;
 7563: }
 7564: 
 7565: # -------------------------- Update MySQL allusers table
 7566: 
 7567: sub update_allusers_table {
 7568:     my ($uname,$udom,$names) = @_;
 7569:     my $homeserver = &homeserver($uname,$udom);
 7570:     my $queryid=
 7571:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 7572:                'lastname='.&escape($names->{'lastname'}).'%%'.
 7573:                'firstname='.&escape($names->{'firstname'}).'%%'.
 7574:                'middlename='.&escape($names->{'middlename'}).'%%'.
 7575:                'generation='.&escape($names->{'generation'}).'%%'.
 7576:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 7577:                'id='.&escape($names->{'id'}),$homeserver);
 7578:     return;
 7579: }
 7580: 
 7581: # ------- Request retrieval of institutional classlists for course(s)
 7582: 
 7583: sub fetch_enrollment_query {
 7584:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 7585:     my $homeserver;
 7586:     my $maxtries = 1;
 7587:     if ($context eq 'automated') {
 7588:         $homeserver = $perlvar{'lonHostID'};
 7589:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 7590:     } else {
 7591:         $homeserver = &homeserver($cnum,$dom);
 7592:     }
 7593:     my $host=&hostname($homeserver);
 7594:     my $cmd = '';
 7595:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7596:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7597:     }
 7598:     $cmd =~ s/%%$//;
 7599:     $cmd = &escape($cmd);
 7600:     my $query = 'fetchenrollment';
 7601:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 7602:     unless ($queryid=~/^\Q$host\E\_/) { 
 7603:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 7604:         return 'error: '.$queryid;
 7605:     }
 7606:     my $reply = &get_query_reply($queryid);
 7607:     my $tries = 1;
 7608:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7609:         $reply = &get_query_reply($queryid);
 7610:         $tries ++;
 7611:     }
 7612:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7613:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7614:     } else {
 7615:         my @responses = split(/:/,$reply);
 7616:         if ($homeserver eq $perlvar{'lonHostID'}) {
 7617:             foreach my $line (@responses) {
 7618:                 my ($key,$value) = split(/=/,$line,2);
 7619:                 $$replyref{$key} = $value;
 7620:             }
 7621:         } else {
 7622:             my $pathname = LONCAPA::tempdir();
 7623:             foreach my $line (@responses) {
 7624:                 my ($key,$value) = split(/=/,$line);
 7625:                 $$replyref{$key} = $value;
 7626:                 if ($value > 0) {
 7627:                     foreach my $item (@{$$affiliatesref{$key}}) {
 7628:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 7629:                         my $destname = $pathname.'/'.$filename;
 7630:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 7631:                         if ($xml_classlist =~ /^error/) {
 7632:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 7633:                         } else {
 7634:                             if ( open(FILE,">$destname") ) {
 7635:                                 print FILE &unescape($xml_classlist);
 7636:                                 close(FILE);
 7637:                             } else {
 7638:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 7639:                             }
 7640:                         }
 7641:                     }
 7642:                 }
 7643:             }
 7644:         }
 7645:         return 'ok';
 7646:     }
 7647:     return 'error';
 7648: }
 7649: 
 7650: sub get_query_reply {
 7651:     my $queryid=shift;
 7652:     my $replyfile=LONCAPA::tempdir().$queryid;
 7653:     my $reply='';
 7654:     for (1..100) {
 7655: 	sleep 2;
 7656:         if (-e $replyfile.'.end') {
 7657: 	    if (open(my $fh,$replyfile)) {
 7658: 		$reply = join('',<$fh>);
 7659: 		close($fh);
 7660: 	   } else { return 'error: reply_file_error'; }
 7661:            return &unescape($reply);
 7662: 	}
 7663:     }
 7664:     return 'timeout:'.$queryid;
 7665: }
 7666: 
 7667: sub courselog_query {
 7668: #
 7669: # possible filters:
 7670: # url: url or symb
 7671: # username
 7672: # domain
 7673: # action: view, submit, grade
 7674: # start: timestamp
 7675: # end: timestamp
 7676: #
 7677:     my (%filters)=@_;
 7678:     unless ($env{'request.course.id'}) { return 'no_course'; }
 7679:     if ($filters{'url'}) {
 7680: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 7681:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 7682:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 7683:     }
 7684:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 7685:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 7686:     return &log_query($cname,$cdom,'courselog',%filters);
 7687: }
 7688: 
 7689: sub userlog_query {
 7690: #
 7691: # possible filters:
 7692: # action: log check role
 7693: # start: timestamp
 7694: # end: timestamp
 7695: #
 7696:     my ($uname,$udom,%filters)=@_;
 7697:     return &log_query($uname,$udom,'userlog',%filters);
 7698: }
 7699: 
 7700: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 7701: 
 7702: sub auto_run {
 7703:     my ($cnum,$cdom) = @_;
 7704:     my $response = 0;
 7705:     my $settings;
 7706:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 7707:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 7708:         $settings = $domconfig{'autoenroll'};
 7709:         if ($settings->{'run'} eq '1') {
 7710:             $response = 1;
 7711:         }
 7712:     } else {
 7713:         my $homeserver;
 7714:         if (&is_course($cdom,$cnum)) {
 7715:             $homeserver = &homeserver($cnum,$cdom);
 7716:         } else {
 7717:             $homeserver = &domain($cdom,'primary');
 7718:         }
 7719:         if ($homeserver ne 'no_host') {
 7720:             $response = &reply('autorun:'.$cdom,$homeserver);
 7721:         }
 7722:     }
 7723:     return $response;
 7724: }
 7725: 
 7726: sub auto_get_sections {
 7727:     my ($cnum,$cdom,$inst_coursecode) = @_;
 7728:     my $homeserver;
 7729:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 7730:         $homeserver = &homeserver($cnum,$cdom);
 7731:     }
 7732:     if (!defined($homeserver)) { 
 7733:         if ($cdom =~ /^$match_domain$/) {
 7734:             $homeserver = &domain($cdom,'primary');
 7735:         }
 7736:     }
 7737:     my @secs;
 7738:     if (defined($homeserver)) {
 7739:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 7740:         unless ($response eq 'refused') {
 7741:             @secs = split(/:/,$response);
 7742:         }
 7743:     }
 7744:     return @secs;
 7745: }
 7746: 
 7747: sub auto_new_course {
 7748:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 7749:     my $homeserver = &homeserver($cnum,$cdom);
 7750:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 7751:     return $response;
 7752: }
 7753: 
 7754: sub auto_validate_courseID {
 7755:     my ($cnum,$cdom,$inst_course_id) = @_;
 7756:     my $homeserver = &homeserver($cnum,$cdom);
 7757:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 7758:     return $response;
 7759: }
 7760: 
 7761: sub auto_validate_instcode {
 7762:     my ($cnum,$cdom,$instcode,$owner) = @_;
 7763:     my ($homeserver,$response);
 7764:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7765:         $homeserver = &homeserver($cnum,$cdom);
 7766:     }
 7767:     if (!defined($homeserver)) {
 7768:         if ($cdom =~ /^$match_domain$/) {
 7769:             $homeserver = &domain($cdom,'primary');
 7770:         }
 7771:     }
 7772:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 7773:                         &escape($instcode).':'.&escape($owner),$homeserver));
 7774:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
 7775:     return ($outcome,$description,$defaultcredits);
 7776: }
 7777: 
 7778: sub auto_create_password {
 7779:     my ($cnum,$cdom,$authparam,$udom) = @_;
 7780:     my ($homeserver,$response);
 7781:     my $create_passwd = 0;
 7782:     my $authchk = '';
 7783:     if ($udom =~ /^$match_domain$/) {
 7784:         $homeserver = &domain($udom,'primary');
 7785:     }
 7786:     if ($homeserver eq '') {
 7787:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 7788:             $homeserver = &homeserver($cnum,$cdom);
 7789:         }
 7790:     }
 7791:     if ($homeserver eq '') {
 7792:         $authchk = 'nodomain';
 7793:     } else {
 7794:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 7795:         if ($response eq 'refused') {
 7796:             $authchk = 'refused';
 7797:         } else {
 7798:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 7799:         }
 7800:     }
 7801:     return ($authparam,$create_passwd,$authchk);
 7802: }
 7803: 
 7804: sub auto_photo_permission {
 7805:     my ($cnum,$cdom,$students) = @_;
 7806:     my $homeserver = &homeserver($cnum,$cdom);
 7807:     my ($outcome,$perm_reqd,$conditions) = 
 7808: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 7809:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7810: 	return (undef,undef);
 7811:     }
 7812:     return ($outcome,$perm_reqd,$conditions);
 7813: }
 7814: 
 7815: sub auto_checkphotos {
 7816:     my ($uname,$udom,$pid) = @_;
 7817:     my $homeserver = &homeserver($uname,$udom);
 7818:     my ($result,$resulttype);
 7819:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 7820: 				   &escape($uname).':'.&escape($pid),
 7821: 				   $homeserver));
 7822:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7823: 	return (undef,undef);
 7824:     }
 7825:     if ($outcome) {
 7826:         ($result,$resulttype) = split(/:/,$outcome);
 7827:     } 
 7828:     return ($result,$resulttype);
 7829: }
 7830: 
 7831: sub auto_photochoice {
 7832:     my ($cnum,$cdom) = @_;
 7833:     my $homeserver = &homeserver($cnum,$cdom);
 7834:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 7835: 						       &escape($cdom),
 7836: 						       $homeserver)));
 7837:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7838: 	return (undef,undef);
 7839:     }
 7840:     return ($update,$comment);
 7841: }
 7842: 
 7843: sub auto_photoupdate {
 7844:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 7845:     my $homeserver = &homeserver($cnum,$dom);
 7846:     my $host=&hostname($homeserver);
 7847:     my $cmd = '';
 7848:     my $maxtries = 1;
 7849:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7850:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7851:     }
 7852:     $cmd =~ s/%%$//;
 7853:     $cmd = &escape($cmd);
 7854:     my $query = 'institutionalphotos';
 7855:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 7856:     unless ($queryid=~/^\Q$host\E\_/) {
 7857:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 7858:         return 'error: '.$queryid;
 7859:     }
 7860:     my $reply = &get_query_reply($queryid);
 7861:     my $tries = 1;
 7862:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7863:         $reply = &get_query_reply($queryid);
 7864:         $tries ++;
 7865:     }
 7866:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7867:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7868:     } else {
 7869:         my @responses = split(/:/,$reply);
 7870:         my $outcome = shift(@responses); 
 7871:         foreach my $item (@responses) {
 7872:             my ($key,$value) = split(/=/,$item);
 7873:             $$photo{$key} = $value;
 7874:         }
 7875:         return $outcome;
 7876:     }
 7877:     return 'error';
 7878: }
 7879: 
 7880: sub auto_instcode_format {
 7881:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 7882: 	$cat_order) = @_;
 7883:     my $courses = '';
 7884:     my @homeservers;
 7885:     if ($caller eq 'global') {
 7886: 	my %servers = &get_servers($codedom,'library');
 7887: 	foreach my $tryserver (keys(%servers)) {
 7888: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7889: 		push(@homeservers,$tryserver);
 7890: 	    }
 7891:         }
 7892:     } elsif ($caller eq 'requests') {
 7893:         if ($codedom =~ /^$match_domain$/) {
 7894:             my $chome = &domain($codedom,'primary');
 7895:             unless ($chome eq 'no_host') {
 7896:                 push(@homeservers,$chome);
 7897:             }
 7898:         }
 7899:     } else {
 7900:         push(@homeservers,&homeserver($caller,$codedom));
 7901:     }
 7902:     foreach my $code (keys(%{$instcodes})) {
 7903:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 7904:     }
 7905:     chop($courses);
 7906:     my $ok_response = 0;
 7907:     my $response;
 7908:     while (@homeservers > 0 && $ok_response == 0) {
 7909:         my $server = shift(@homeservers); 
 7910:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 7911:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 7912:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 7913: 		split(/:/,$response);
 7914:             %{$codes} = (%{$codes},&str2hash($codes_str));
 7915:             push(@{$codetitles},&str2array($codetitles_str));
 7916:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 7917:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 7918:             $ok_response = 1;
 7919:         }
 7920:     }
 7921:     if ($ok_response) {
 7922:         return 'ok';
 7923:     } else {
 7924:         return $response;
 7925:     }
 7926: }
 7927: 
 7928: sub auto_instcode_defaults {
 7929:     my ($domain,$returnhash,$code_order) = @_;
 7930:     my @homeservers;
 7931: 
 7932:     my %servers = &get_servers($domain,'library');
 7933:     foreach my $tryserver (keys(%servers)) {
 7934: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7935: 	    push(@homeservers,$tryserver);
 7936: 	}
 7937:     }
 7938: 
 7939:     my $response;
 7940:     foreach my $server (@homeservers) {
 7941:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 7942:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7943: 	
 7944: 	foreach my $pair (split(/\&/,$response)) {
 7945: 	    my ($name,$value)=split(/\=/,$pair);
 7946: 	    if ($name eq 'code_order') {
 7947: 		@{$code_order} = split(/\&/,&unescape($value));
 7948: 	    } else {
 7949: 		$returnhash->{&unescape($name)}=&unescape($value);
 7950: 	    }
 7951: 	}
 7952: 	return 'ok';
 7953:     }
 7954: 
 7955:     return $response;
 7956: }
 7957: 
 7958: sub auto_possible_instcodes {
 7959:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 7960:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 7961:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 7962:         return;
 7963:     }
 7964:     my (@homeservers,$uhome);
 7965:     if (defined(&domain($domain,'primary'))) {
 7966:         $uhome=&domain($domain,'primary');
 7967:         push(@homeservers,&domain($domain,'primary'));
 7968:     } else {
 7969:         my %servers = &get_servers($domain,'library');
 7970:         foreach my $tryserver (keys(%servers)) {
 7971:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7972:                 push(@homeservers,$tryserver);
 7973:             }
 7974:         }
 7975:     }
 7976:     my $response;
 7977:     foreach my $server (@homeservers) {
 7978:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 7979:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7980:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 7981:             split(':',$response);
 7982:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 7983:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 7984:         foreach my $item (split('&',$cat_title)) {   
 7985:             my ($name,$value)=split('=',$item);
 7986:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 7987:         }
 7988:         foreach my $item (split('&',$cat_order)) {
 7989:             my ($name,$value)=split('=',$item);
 7990:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 7991:         }
 7992:         return 'ok';
 7993:     }
 7994:     return $response;
 7995: }
 7996: 
 7997: sub auto_courserequest_checks {
 7998:     my ($dom) = @_;
 7999:     my ($homeserver,%validations);
 8000:     if ($dom =~ /^$match_domain$/) {
 8001:         $homeserver = &domain($dom,'primary');
 8002:     }
 8003:     unless ($homeserver eq 'no_host') {
 8004:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 8005:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 8006:             my @items = split(/&/,$response);
 8007:             foreach my $item (@items) {
 8008:                 my ($key,$value) = split('=',$item);
 8009:                 $validations{&unescape($key)} = &thaw_unescape($value);
 8010:             }
 8011:         }
 8012:     }
 8013:     return %validations; 
 8014: }
 8015: 
 8016: sub auto_courserequest_validation {
 8017:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
 8018:     my ($homeserver,$response);
 8019:     if ($dom =~ /^$match_domain$/) {
 8020:         $homeserver = &domain($dom,'primary');
 8021:     }
 8022:     unless ($homeserver eq 'no_host') {
 8023:         my $customdata;
 8024:         if (ref($custominfo) eq 'HASH') {
 8025:             $customdata = &freeze_escape($custominfo);
 8026:         }
 8027:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 8028:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 8029:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
 8030:                                     $customdata,$homeserver));
 8031:     }
 8032:     return $response;
 8033: }
 8034: 
 8035: sub auto_validate_class_sec {
 8036:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 8037:     my $homeserver = &homeserver($cnum,$cdom);
 8038:     my $ownerlist;
 8039:     if (ref($owners) eq 'ARRAY') {
 8040:         $ownerlist = join(',',@{$owners});
 8041:     } else {
 8042:         $ownerlist = $owners;
 8043:     }
 8044:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 8045:                         &escape($ownerlist).':'.$cdom,$homeserver);
 8046:     return $response;
 8047: }
 8048: 
 8049: sub auto_crsreq_update {
 8050:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
 8051:         $code,$accessstart,$accessend,$inbound) = @_;
 8052:     my ($homeserver,%crsreqresponse);
 8053:     if ($cdom =~ /^$match_domain$/) {
 8054:         $homeserver = &domain($cdom,'primary');
 8055:     }
 8056:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
 8057:         my $info;
 8058:         if (ref($inbound) eq 'HASH') {
 8059:             $info = &freeze_escape($inbound);
 8060:         }
 8061:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
 8062:                             ':'.&escape($action).':'.&escape($ownername).':'.
 8063:                             &escape($ownerdomain).':'.&escape($fullname).':'.
 8064:                             &escape($title).':'.&escape($code).':'.
 8065:                             &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
 8066:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 8067:             my @items = split(/&/,$response);
 8068:             foreach my $item (@items) {
 8069:                 my ($key,$value) = split('=',$item);
 8070:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
 8071:             }
 8072:         }
 8073:     }
 8074:     return \%crsreqresponse;
 8075: }
 8076: 
 8077: # ------------------------------------------------------- Course Group routines
 8078: 
 8079: sub get_coursegroups {
 8080:     my ($cdom,$cnum,$group,$namespace) = @_;
 8081:     return(&dump($namespace,$cdom,$cnum,$group));
 8082: }
 8083: 
 8084: sub modify_coursegroup {
 8085:     my ($cdom,$cnum,$groupsettings) = @_;
 8086:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 8087: }
 8088: 
 8089: sub toggle_coursegroup_status {
 8090:     my ($cdom,$cnum,$group,$action) = @_;
 8091:     my ($from_namespace,$to_namespace);
 8092:     if ($action eq 'delete') {
 8093:         $from_namespace = 'coursegroups';
 8094:         $to_namespace = 'deleted_groups';
 8095:     } else {
 8096:         $from_namespace = 'deleted_groups';
 8097:         $to_namespace = 'coursegroups';
 8098:     }
 8099:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 8100:     if (my $tmp = &error(%curr_group)) {
 8101:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 8102:         return ('read error',$tmp);
 8103:     } else {
 8104:         my %savedsettings = %curr_group; 
 8105:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 8106:         my $deloutcome;
 8107:         if ($result eq 'ok') {
 8108:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 8109:         } else {
 8110:             return ('write error',$result);
 8111:         }
 8112:         if ($deloutcome eq 'ok') {
 8113:             return 'ok';
 8114:         } else {
 8115:             return ('delete error',$deloutcome);
 8116:         }
 8117:     }
 8118: }
 8119: 
 8120: sub modify_group_roles {
 8121:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 8122:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 8123:     my $role = 'gr/'.&escape($userprivs);
 8124:     my ($uname,$udom) = split(/:/,$user);
 8125:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 8126:     if ($result eq 'ok') {
 8127:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 8128:     }
 8129:     return $result;
 8130: }
 8131: 
 8132: sub modify_coursegroup_membership {
 8133:     my ($cdom,$cnum,$membership) = @_;
 8134:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 8135:     return $result;
 8136: }
 8137: 
 8138: sub get_active_groups {
 8139:     my ($udom,$uname,$cdom,$cnum) = @_;
 8140:     my $now = time;
 8141:     my %groups = ();
 8142:     foreach my $key (keys(%env)) {
 8143:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 8144:             my ($start,$end) = split(/\./,$env{$key});
 8145:             if (($end!=0) && ($end<$now)) { next; }
 8146:             if (($start!=0) && ($start>$now)) { next; }
 8147:             if ($1 eq $cdom && $2 eq $cnum) {
 8148:                 $groups{$3} = $env{$key} ;
 8149:             }
 8150:         }
 8151:     }
 8152:     return %groups;
 8153: }
 8154: 
 8155: sub get_group_membership {
 8156:     my ($cdom,$cnum,$group) = @_;
 8157:     return(&dump('groupmembership',$cdom,$cnum,$group));
 8158: }
 8159: 
 8160: sub get_users_groups {
 8161:     my ($udom,$uname,$courseid) = @_;
 8162:     my @usersgroups;
 8163:     my $cachetime=1800;
 8164: 
 8165:     my $hashid="$udom:$uname:$courseid";
 8166:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 8167:     if (defined($cached)) {
 8168:         @usersgroups = split(/:/,$grouplist);
 8169:     } else {  
 8170:         $grouplist = '';
 8171:         my $courseurl = &courseid_to_courseurl($courseid);
 8172:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 8173:         my $access_end = $env{'course.'.$courseid.
 8174:                               '.default_enrollment_end_date'};
 8175:         my $now = time;
 8176:         foreach my $key (keys(%roleshash)) {
 8177:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 8178:                 my $group = $1;
 8179:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 8180:                     my $start = $2;
 8181:                     my $end = $1;
 8182:                     if ($start == -1) { next; } # deleted from group
 8183:                     if (($start!=0) && ($start>$now)) { next; }
 8184:                     if (($end!=0) && ($end<$now)) {
 8185:                         if ($access_end && $access_end < $now) {
 8186:                             if ($access_end - $end < 86400) {
 8187:                                 push(@usersgroups,$group);
 8188:                             }
 8189:                         }
 8190:                         next;
 8191:                     }
 8192:                     push(@usersgroups,$group);
 8193:                 }
 8194:             }
 8195:         }
 8196:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 8197:         $grouplist = join(':',@usersgroups);
 8198:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 8199:     }
 8200:     return @usersgroups;
 8201: }
 8202: 
 8203: sub devalidate_getgroups_cache {
 8204:     my ($udom,$uname,$cdom,$cnum)=@_;
 8205:     my $courseid = $cdom.'_'.$cnum;
 8206: 
 8207:     my $hashid="$udom:$uname:$courseid";
 8208:     &devalidate_cache_new('getgroups',$hashid);
 8209: }
 8210: 
 8211: # ------------------------------------------------------------------ Plain Text
 8212: 
 8213: sub plaintext {
 8214:     my ($short,$type,$cid,$forcedefault) = @_;
 8215:     if ($short =~ m{^cr/}) {
 8216: 	return (split('/',$short))[-1];
 8217:     }
 8218:     if (!defined($cid)) {
 8219:         $cid = $env{'request.course.id'};
 8220:     }
 8221:     my %rolenames = (
 8222:                       Course    => 'std',
 8223:                       Community => 'alt1',
 8224:                     );
 8225:     if ($cid ne '') {
 8226:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 8227:             unless ($forcedefault) {
 8228:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 8229:                 &Apache::lonlocal::mt_escape(\$roletext);
 8230:                 return &Apache::lonlocal::mt($roletext);
 8231:             }
 8232:         }
 8233:     }
 8234:     if ((defined($type)) && (defined($rolenames{$type})) &&
 8235:         (defined($rolenames{$type})) && 
 8236:         (defined($prp{$short}{$rolenames{$type}}))) {
 8237:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 8238:     } elsif ($cid ne '') {
 8239:         my $crstype = $env{'course.'.$cid.'.type'};
 8240:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 8241:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 8242:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 8243:         }
 8244:     }
 8245:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 8246: }
 8247: 
 8248: # ----------------------------------------------------------------- Assign Role
 8249: 
 8250: sub assignrole {
 8251:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 8252:         $context)=@_;
 8253:     my $mrole;
 8254:     if ($role =~ /^cr\//) {
 8255:         my $cwosec=$url;
 8256:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 8257: 	unless (&allowed('ccr',$cwosec)) {
 8258:            my $refused = 1;
 8259:            if ($context eq 'requestcourses') {
 8260:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 8261:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 8262:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 8263:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 8264:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8265:                            if ($crsenv{'internal.courseowner'} eq
 8266:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 8267:                                $refused = '';
 8268:                            }
 8269:                        }
 8270:                    }
 8271:                }
 8272:            }
 8273:            if ($refused) {
 8274:                &logthis('Refused custom assignrole: '.
 8275:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 8276:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 8277:                return 'refused';
 8278:            }
 8279:         }
 8280:         $mrole='cr';
 8281:     } elsif ($role =~ /^gr\//) {
 8282:         my $cwogrp=$url;
 8283:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 8284:         unless (&allowed('mdg',$cwogrp)) {
 8285:             &logthis('Refused group assignrole: '.
 8286:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 8287:                     $env{'user.name'}.' at '.$env{'user.domain'});
 8288:             return 'refused';
 8289:         }
 8290:         $mrole='gr';
 8291:     } else {
 8292:         my $cwosec=$url;
 8293:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 8294:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 8295:             my $refused;
 8296:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 8297:                 if (!(&allowed('c'.$role,$url))) {
 8298:                     $refused = 1;
 8299:                 }
 8300:             } else {
 8301:                 $refused = 1;
 8302:             }
 8303:             if ($refused) {
 8304:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 8305:                 if (!$selfenroll && $context eq 'course') {
 8306:                     my %crsenv;
 8307:                     if ($role eq 'cc' || $role eq 'co') {
 8308:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8309:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 8310:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 8311:                                 if ($crsenv{'internal.courseowner'} eq 
 8312:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 8313:                                     $refused = '';
 8314:                                 }
 8315:                             }
 8316:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 8317:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 8318:                                 if ($crsenv{'internal.courseowner'} eq 
 8319:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 8320:                                     $refused = '';
 8321:                                 }
 8322:                             }
 8323:                         }
 8324:                     }
 8325:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 8326:                     $refused = '';
 8327:                 } elsif ($context eq 'requestcourses') {
 8328:                     my @possroles = ('st','ta','ep','in','cc','co');
 8329:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 8330:                         my $wrongcc;
 8331:                         if ($cnum =~ /^$match_community$/) {
 8332:                             $wrongcc = 1 if ($role eq 'cc');
 8333:                         } else {
 8334:                             $wrongcc = 1 if ($role eq 'co');
 8335:                         }
 8336:                         unless ($wrongcc) {
 8337:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 8338:                             if ($crsenv{'internal.courseowner'} eq 
 8339:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 8340:                                 $refused = '';
 8341:                             }
 8342:                         }
 8343:                     }
 8344:                 } elsif ($context eq 'requestauthor') {
 8345:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 8346:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 8347:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 8348:                             $refused = '';
 8349:                         } else {
 8350:                             my %domdefaults = &get_domain_defaults($udom);
 8351:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 8352:                                 my $checkbystatus;
 8353:                                 if ($env{'user.adv'}) {
 8354:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 8355:                                     if ($disposition eq 'automatic') {
 8356:                                         $refused = '';
 8357:                                     } elsif ($disposition eq '') {
 8358:                                         $checkbystatus = 1;
 8359:                                     }
 8360:                                 } else {
 8361:                                     $checkbystatus = 1;
 8362:                                 }
 8363:                                 if ($checkbystatus) {
 8364:                                     if ($env{'environment.inststatus'}) {
 8365:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 8366:                                         foreach my $type (@inststatuses) {
 8367:                                             if (($type ne '') &&
 8368:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 8369:                                                 $refused = '';
 8370:                                             }
 8371:                                         }
 8372:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 8373:                                         $refused = '';
 8374:                                     }
 8375:                                 }
 8376:                             }
 8377:                         }
 8378:                     }
 8379:                 }
 8380:                 if ($refused) {
 8381:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 8382:                              ' '.$role.' '.$end.' '.$start.' by '.
 8383: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 8384:                     return 'refused';
 8385:                 }
 8386:             }
 8387:         } elsif ($role eq 'au') {
 8388:             if ($url ne '/'.$udom.'/') {
 8389:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 8390:                          ' to assign author role for '.$uname.':'.$udom.
 8391:                          ' in domain: '.$url.' refused (wrong domain).');
 8392:                 return 'refused';
 8393:             }
 8394:         }
 8395:         $mrole=$role;
 8396:     }
 8397:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 8398:                 "$udom:$uname:$url".'_'."$mrole=$role";
 8399:     if ($end) { $command.='_'.$end; }
 8400:     if ($start) {
 8401: 	if ($end) { 
 8402:            $command.='_'.$start; 
 8403:         } else {
 8404:            $command.='_0_'.$start;
 8405:         }
 8406:     }
 8407:     my $origstart = $start;
 8408:     my $origend = $end;
 8409:     my $delflag;
 8410: # actually delete
 8411:     if ($deleteflag) {
 8412: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 8413: # modify command to delete the role
 8414:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 8415:                 "$udom:$uname:$url".'_'."$mrole";
 8416: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 8417: # set start and finish to negative values for userrolelog
 8418:            $start=-1;
 8419:            $end=-1;
 8420:            $delflag = 1;
 8421:         }
 8422:     }
 8423: # send command
 8424:     my $answer=&reply($command,&homeserver($uname,$udom));
 8425: # log new user role if status is ok
 8426:     if ($answer eq 'ok') {
 8427: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 8428:         if (($role eq 'cc') || ($role eq 'in') ||
 8429:             ($role eq 'ep') || ($role eq 'ad') ||
 8430:             ($role eq 'ta') || ($role eq 'st') ||
 8431:             ($role=~/^cr/) || ($role eq 'gr') ||
 8432:             ($role eq 'co')) {
 8433: # for course roles, perform group memberships changes triggered by role change.
 8434:             unless ($role =~ /^gr/) {
 8435:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 8436:                                                  $origstart,$selfenroll,$context);
 8437:             }
 8438:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8439:                            $selfenroll,$context);
 8440:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
 8441:                  ($role eq 'au') || ($role eq 'dc')) {
 8442:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8443:                            $context);
 8444:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
 8445:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
 8446:                              $context);
 8447:         }
 8448:         if ($role eq 'cc') {
 8449:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 8450:         }
 8451:     }
 8452:     return $answer;
 8453: }
 8454: 
 8455: sub autoupdate_coowners {
 8456:     my ($url,$end,$start,$uname,$udom) = @_;
 8457:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 8458:     if (($cdom ne '') && ($cnum ne '')) {
 8459:         my $now = time;
 8460:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 8461:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 8462:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 8463:             my $instcode = $coursehash{'internal.coursecode'};
 8464:             if ($instcode ne '') {
 8465:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 8466:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 8467:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 8468:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 8469:                         if ($result eq 'valid') {
 8470:                             if ($coursehash{'internal.co-owners'}) {
 8471:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 8472:                                     push(@newcoowners,$coowner);
 8473:                                 }
 8474:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 8475:                                     push(@newcoowners,$uname.':'.$udom);
 8476:                                 }
 8477:                                 @newcoowners = sort(@newcoowners);
 8478:                             } else {
 8479:                                 push(@newcoowners,$uname.':'.$udom);
 8480:                             }
 8481:                         } else {
 8482:                             if ($coursehash{'internal.co-owners'}) {
 8483:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 8484:                                     unless ($coowner eq $uname.':'.$udom) {
 8485:                                         push(@newcoowners,$coowner);
 8486:                                     }
 8487:                                 }
 8488:                                 unless (@newcoowners > 0) {
 8489:                                     $delcoowners = 1;
 8490:                                     $coowners = '';
 8491:                                 }
 8492:                             }
 8493:                         }
 8494:                         if (@newcoowners || $delcoowners) {
 8495:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 8496:                                             $delcoowners,@newcoowners);
 8497:                         }
 8498:                     }
 8499:                 }
 8500:             }
 8501:         }
 8502:     }
 8503: }
 8504: 
 8505: sub store_coowners {
 8506:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 8507:     my $cid = $cdom.'_'.$cnum;
 8508:     my ($coowners,$delresult,$putresult);
 8509:     if (@newcoowners) {
 8510:         $coowners = join(',',@newcoowners);
 8511:         my %coownershash = (
 8512:                             'internal.co-owners' => $coowners,
 8513:                            );
 8514:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 8515:         if ($putresult eq 'ok') {
 8516:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 8517:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 8518:             }
 8519:         }
 8520:     }
 8521:     if ($delcoowners) {
 8522:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 8523:         if ($delresult eq 'ok') {
 8524:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 8525:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 8526:             }
 8527:         }
 8528:     }
 8529:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 8530:         my %crsinfo =
 8531:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 8532:         if (ref($crsinfo{$cid}) eq 'HASH') {
 8533:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 8534:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 8535:         }
 8536:     }
 8537: }
 8538: 
 8539: # -------------------------------------------------- Modify user authentication
 8540: # Overrides without validation
 8541: 
 8542: sub modifyuserauth {
 8543:     my ($udom,$uname,$umode,$upass)=@_;
 8544:     my $uhome=&homeserver($uname,$udom);
 8545:     unless (&allowed('mau',$udom)) { return 'refused'; }
 8546:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 8547:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 8548:              ' in domain '.$env{'request.role.domain'});  
 8549:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 8550: 		     &escape($upass),$uhome);
 8551:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 8552:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 8553:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 8554:     &log($udom,,$uname,$uhome,
 8555:         'Authentication changed by '.$env{'user.domain'}.', '.
 8556:                                      $env{'user.name'}.', '.$umode.
 8557:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 8558:     unless ($reply eq 'ok') {
 8559:         &logthis('Authentication mode error: '.$reply);
 8560: 	return 'error: '.$reply;
 8561:     }   
 8562:     return 'ok';
 8563: }
 8564: 
 8565: # --------------------------------------------------------------- Modify a user
 8566: 
 8567: sub modifyuser {
 8568:     my ($udom,    $uname, $uid,
 8569:         $umode,   $upass, $first,
 8570:         $middle,  $last,  $gene,
 8571:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 8572:     $udom= &LONCAPA::clean_domain($udom);
 8573:     $uname=&LONCAPA::clean_username($uname);
 8574:     my $showcandelete = 'none';
 8575:     if (ref($candelete) eq 'ARRAY') {
 8576:         if (@{$candelete} > 0) {
 8577:             $showcandelete = join(', ',@{$candelete});
 8578:         }
 8579:     }
 8580:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 8581:              $umode.', '.$first.', '.$middle.', '.
 8582: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 8583:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 8584:                                      ' desiredhome not specified'). 
 8585:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 8586:              ' in domain '.$env{'request.role.domain'});
 8587:     my $uhome=&homeserver($uname,$udom,'true');
 8588:     my $newuser;
 8589:     if ($uhome eq 'no_host') {
 8590:         $newuser = 1;
 8591:     }
 8592: # ----------------------------------------------------------------- Create User
 8593:     if (($uhome eq 'no_host') && 
 8594: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 8595:         my $unhome='';
 8596:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 8597:             $unhome = $desiredhome;
 8598: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 8599: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 8600:         } else { # load balancing routine for determining $unhome
 8601:             my $loadm=10000000;
 8602: 	    my %servers = &get_servers($udom,'library');
 8603: 	    foreach my $tryserver (keys(%servers)) {
 8604: 		my $answer=reply('load',$tryserver);
 8605: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 8606: 		    $loadm=$answer;
 8607: 		    $unhome=$tryserver;
 8608: 		}
 8609: 	    }
 8610:         }
 8611:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 8612: 	    return 'error: unable to find a home server for '.$uname.
 8613:                    ' in domain '.$udom;
 8614:         }
 8615:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 8616:                          &escape($upass),$unhome);
 8617: 	unless ($reply eq 'ok') {
 8618:             return 'error: '.$reply;
 8619:         }   
 8620:         $uhome=&homeserver($uname,$udom,'true');
 8621:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 8622: 	    return 'error: unable verify users home machine.';
 8623:         }
 8624:     }   # End of creation of new user
 8625: # ---------------------------------------------------------------------- Add ID
 8626:     if ($uid) {
 8627:        $uid=~tr/A-Z/a-z/;
 8628:        my %uidhash=&idrget($udom,$uname);
 8629:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 8630:          && (!$forceid)) {
 8631: 	  unless ($uid eq $uidhash{$uname}) {
 8632: 	      return 'error: user id "'.$uid.'" does not match '.
 8633:                   'current user id "'.$uidhash{$uname}.'".';
 8634:           }
 8635:        } else {
 8636: 	  &idput($udom,($uname => $uid));
 8637:        }
 8638:     }
 8639: # -------------------------------------------------------------- Add names, etc
 8640:     my @tmp=&get('environment',
 8641: 		   ['firstname','middlename','lastname','generation','id',
 8642:                     'permanentemail','inststatus'],
 8643: 		   $udom,$uname);
 8644:     my (%names,%oldnames);
 8645:     if ($tmp[0] =~ m/^error:.*/) { 
 8646:         %names=(); 
 8647:     } else {
 8648:         %names = @tmp;
 8649:         %oldnames = %names;
 8650:     }
 8651: #
 8652: # If name, email and/or uid are blank (e.g., because an uploaded file
 8653: # of users did not contain them), do not overwrite existing values
 8654: # unless field is in $candelete array ref.  
 8655: #
 8656: 
 8657:     my @fields = ('firstname','middlename','lastname','generation',
 8658:                   'permanentemail','id');
 8659:     my %newvalues;
 8660:     if (ref($candelete) eq 'ARRAY') {
 8661:         foreach my $field (@fields) {
 8662:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 8663:                 if ($field eq 'firstname') {
 8664:                     $names{$field} = $first;
 8665:                 } elsif ($field eq 'middlename') {
 8666:                     $names{$field} = $middle;
 8667:                 } elsif ($field eq 'lastname') {
 8668:                     $names{$field} = $last;
 8669:                 } elsif ($field eq 'generation') { 
 8670:                     $names{$field} = $gene;
 8671:                 } elsif ($field eq 'permanentemail') {
 8672:                     $names{$field} = $email;
 8673:                 } elsif ($field eq 'id') {
 8674:                     $names{$field}  = $uid;
 8675:                 }
 8676:             }
 8677:         }
 8678:     }
 8679:     if ($first)  { $names{'firstname'}  = $first; }
 8680:     if (defined($middle)) { $names{'middlename'} = $middle; }
 8681:     if ($last)   { $names{'lastname'}   = $last; }
 8682:     if (defined($gene))   { $names{'generation'} = $gene; }
 8683:     if ($email) {
 8684:        $email=~s/[^\w\@\.\-\,]//gs;
 8685:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 8686:     }
 8687:     if ($uid) { $names{'id'}  = $uid; }
 8688:     if (defined($inststatus)) {
 8689:         $names{'inststatus'} = '';
 8690:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 8691:         if (ref($usertypes) eq 'HASH') {
 8692:             my @okstatuses; 
 8693:             foreach my $item (split(/:/,$inststatus)) {
 8694:                 if (defined($usertypes->{$item})) {
 8695:                     push(@okstatuses,$item);  
 8696:                 }
 8697:             }
 8698:             if (@okstatuses) {
 8699:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 8700:             }
 8701:         }
 8702:     }
 8703:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 8704:                  $umode.', '.$first.', '.$middle.', '.
 8705:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 8706:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 8707:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 8708:     } else {
 8709:         $logmsg .= ' during self creation';
 8710:     }
 8711:     my $changed;
 8712:     if ($newuser) {
 8713:         $changed = 1;
 8714:     } else {
 8715:         foreach my $field (@fields) {
 8716:             if ($names{$field} ne $oldnames{$field}) {
 8717:                 $changed = 1;
 8718:                 last;
 8719:             }
 8720:         }
 8721:     }
 8722:     unless ($changed) {
 8723:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 8724:         &logthis($logmsg);
 8725:         return 'ok';
 8726:     }
 8727:     my $reply = &put('environment', \%names, $udom,$uname);
 8728:     if ($reply ne 'ok') { 
 8729:         return 'error: '.$reply;
 8730:     }
 8731:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
 8732:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
 8733:     }
 8734:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 8735:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 8736:     $logmsg = 'Success modifying user '.$logmsg;
 8737:     &logthis($logmsg);
 8738:     return 'ok';
 8739: }
 8740: 
 8741: # -------------------------------------------------------------- Modify student
 8742: 
 8743: sub modifystudent {
 8744:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 8745:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 8746:         $selfenroll,$context,$inststatus,$credits)=@_;
 8747:     if (!$cid) {
 8748: 	unless ($cid=$env{'request.course.id'}) {
 8749: 	    return 'not_in_class';
 8750: 	}
 8751:     }
 8752: # --------------------------------------------------------------- Make the user
 8753:     my $reply=&modifyuser
 8754: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 8755:          $desiredhome,$email,$inststatus);
 8756:     unless ($reply eq 'ok') { return $reply; }
 8757:     # This will cause &modify_student_enrollment to get the uid from the
 8758:     # student's environment
 8759:     $uid = undef if (!$forceid);
 8760:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 8761: 					$gene,$usec,$end,$start,$type,$locktype,
 8762:                                         $cid,$selfenroll,$context,$credits);
 8763:     return $reply;
 8764: }
 8765: 
 8766: sub modify_student_enrollment {
 8767:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
 8768:         $locktype,$cid,$selfenroll,$context,$credits) = @_;
 8769:     my ($cdom,$cnum,$chome);
 8770:     if (!$cid) {
 8771: 	unless ($cid=$env{'request.course.id'}) {
 8772: 	    return 'not_in_class';
 8773: 	}
 8774: 	$cdom=$env{'course.'.$cid.'.domain'};
 8775: 	$cnum=$env{'course.'.$cid.'.num'};
 8776:     } else {
 8777: 	($cdom,$cnum)=split(/_/,$cid);
 8778:     }
 8779:     $chome=$env{'course.'.$cid.'.home'};
 8780:     if (!$chome) {
 8781: 	$chome=&homeserver($cnum,$cdom);
 8782:     }
 8783:     if (!$chome) { return 'unknown_course'; }
 8784:     # Make sure the user exists
 8785:     my $uhome=&homeserver($uname,$udom);
 8786:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8787: 	return 'error: no such user';
 8788:     }
 8789:     # Get student data if we were not given enough information
 8790:     if (!defined($first)  || $first  eq '' || 
 8791:         !defined($last)   || $last   eq '' || 
 8792:         !defined($uid)    || $uid    eq '' || 
 8793:         !defined($middle) || $middle eq '' || 
 8794:         !defined($gene)   || $gene   eq '') {
 8795:         # They did not supply us with enough data to enroll the student, so
 8796:         # we need to pick up more information.
 8797:         my %tmp = &get('environment',
 8798:                        ['firstname','middlename','lastname', 'generation','id']
 8799:                        ,$udom,$uname);
 8800: 
 8801:         #foreach my $key (keys(%tmp)) {
 8802:         #    &logthis("key $key = ".$tmp{$key});
 8803:         #}
 8804:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 8805:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 8806:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 8807:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 8808:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 8809:     }
 8810:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 8811:     my $user = "$uname:$udom";
 8812:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
 8813:     my $reply=cput('classlist',
 8814: 		   {$user => 
 8815: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
 8816: 		   $cdom,$cnum);
 8817:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
 8818:         &devalidate_getsection_cache($udom,$uname,$cid);
 8819:     } else { 
 8820: 	return 'error: '.$reply;
 8821:     }
 8822:     # Add student role to user
 8823:     my $uurl='/'.$cid;
 8824:     $uurl=~s/\_/\//g;
 8825:     if ($usec) {
 8826: 	$uurl.='/'.$usec;
 8827:     }
 8828:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
 8829:                              $selfenroll,$context);
 8830:     if ($result ne 'ok') {
 8831:         if ($old_entry{$user} ne '') {
 8832:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
 8833:         } else {
 8834:             $reply = &del('classlist',[$user],$cdom,$cnum);
 8835:         }
 8836:     }
 8837:     return $result; 
 8838: }
 8839: 
 8840: sub format_name {
 8841:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 8842:     my $name;
 8843:     if ($first ne 'lastname') {
 8844: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 8845:     } else {
 8846: 	if ($lastname=~/\S/) {
 8847: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 8848: 	    $name=~s/\s+,/,/;
 8849: 	} else {
 8850: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 8851: 	}
 8852:     }
 8853:     $name=~s/^\s+//;
 8854:     $name=~s/\s+$//;
 8855:     $name=~s/\s+/ /g;
 8856:     return $name;
 8857: }
 8858: 
 8859: # ------------------------------------------------- Write to course preferences
 8860: 
 8861: sub writecoursepref {
 8862:     my ($courseid,%prefs)=@_;
 8863:     $courseid=~s/^\///;
 8864:     $courseid=~s/\_/\//g;
 8865:     my ($cdomain,$cnum)=split(/\//,$courseid);
 8866:     my $chome=homeserver($cnum,$cdomain);
 8867:     if (($chome eq '') || ($chome eq 'no_host')) { 
 8868: 	return 'error: no such course';
 8869:     }
 8870:     my $cstring='';
 8871:     foreach my $pref (keys(%prefs)) {
 8872: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 8873:     }
 8874:     $cstring=~s/\&$//;
 8875:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 8876: }
 8877: 
 8878: # ---------------------------------------------------------- Make/modify course
 8879: 
 8880: sub createcourse {
 8881:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 8882:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 8883:     $url=&declutter($url);
 8884:     my $cid='';
 8885:     if ($context eq 'requestcourses') {
 8886:         my $can_create = 0;
 8887:         my ($ownername,$ownerdom) = split(':',$course_owner);
 8888:         if ($udom eq $ownerdom) {
 8889:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 8890:                                   $context)) {
 8891:                 $can_create = 1;
 8892:             }
 8893:         } else {
 8894:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 8895:                                            $category);
 8896:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 8897:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 8898:                 if (@curr > 0) {
 8899:                     my @options = qw(approval validate autolimit);
 8900:                     my $optregex = join('|',@options);
 8901:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 8902:                         $can_create = 1;
 8903:                     }
 8904:                 }
 8905:             }
 8906:         }
 8907:         if ($can_create) {
 8908:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 8909:                 unless (&allowed('ccc',$udom)) {
 8910:                     return 'refused'; 
 8911:                 }
 8912:             }
 8913:         } else {
 8914:             return 'refused';
 8915:         }
 8916:     } elsif (!&allowed('ccc',$udom)) {
 8917:         return 'refused';
 8918:     }
 8919: # --------------------------------------------------------------- Get Unique ID
 8920:     my $uname;
 8921:     if ($cnum =~ /^$match_courseid$/) {
 8922:         my $chome=&homeserver($cnum,$udom,'true');
 8923:         if (($chome eq '') || ($chome eq 'no_host')) {
 8924:             $uname = $cnum;
 8925:         } else {
 8926:             $uname = &generate_coursenum($udom,$crstype);
 8927:         }
 8928:     } else {
 8929:         $uname = &generate_coursenum($udom,$crstype);
 8930:     }
 8931:     return $uname if ($uname =~ /^error/);
 8932: # -------------------------------------------------- Check supplied server name
 8933:     if (!defined($course_server)) {
 8934:         if (defined(&domain($udom,'primary'))) {
 8935:             $course_server = &domain($udom,'primary');
 8936:         } else {
 8937:             $course_server = $env{'user.home'}; 
 8938:         }
 8939:     }
 8940:     my %host_servers =
 8941:         &Apache::lonnet::get_servers($udom,'library');
 8942:     unless ($host_servers{$course_server}) {
 8943:         return 'error: invalid home server for course: '.$course_server;
 8944:     }
 8945: # ------------------------------------------------------------- Make the course
 8946:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 8947:                       $course_server);
 8948:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 8949:     my $uhome=&homeserver($uname,$udom,'true');
 8950:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8951: 	return 'error: no such course';
 8952:     }
 8953: # ----------------------------------------------------------------- Course made
 8954: # log existence
 8955:     my $now = time;
 8956:     my $newcourse = {
 8957:                     $udom.'_'.$uname => {
 8958:                                      description => $description,
 8959:                                      inst_code   => $inst_code,
 8960:                                      owner       => $course_owner,
 8961:                                      type        => $crstype,
 8962:                                      creator     => $env{'user.name'}.':'.
 8963:                                                     $env{'user.domain'},
 8964:                                      created     => $now,
 8965:                                      context     => $context,
 8966:                                                 },
 8967:                     };
 8968:     &courseidput($udom,$newcourse,$uhome,'notime');
 8969: # set toplevel url
 8970:     my $topurl=$url;
 8971:     unless ($nonstandard) {
 8972: # ------------------------------------------ For standard courses, make top url
 8973:         my $mapurl=&clutter($url);
 8974:         if ($mapurl eq '/res/') { $mapurl=''; }
 8975:         $env{'form.initmap'}=(<<ENDINITMAP);
 8976: <map>
 8977: <resource id="1" type="start"></resource>
 8978: <resource id="2" src="$mapurl"></resource>
 8979: <resource id="3" type="finish"></resource>
 8980: <link index="1" from="1" to="2"></link>
 8981: <link index="2" from="2" to="3"></link>
 8982: </map>
 8983: ENDINITMAP
 8984:         $topurl=&declutter(
 8985:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 8986:                           );
 8987:     }
 8988: # ----------------------------------------------------------- Write preferences
 8989:     &writecoursepref($udom.'_'.$uname,
 8990:                      ('description'              => $description,
 8991:                       'url'                      => $topurl,
 8992:                       'internal.creator'         => $env{'user.name'}.':'.
 8993:                                                     $env{'user.domain'},
 8994:                       'internal.created'         => $now,
 8995:                       'internal.creationcontext' => $context)
 8996:                     );
 8997:     return '/'.$udom.'/'.$uname;
 8998: }
 8999: 
 9000: # ------------------------------------------------------------------- Create ID
 9001: sub generate_coursenum {
 9002:     my ($udom,$crstype) = @_;
 9003:     my $domdesc = &domain($udom);
 9004:     return 'error: invalid domain' if ($domdesc eq '');
 9005:     my $first;
 9006:     if ($crstype eq 'Community') {
 9007:         $first = '0';
 9008:     } else {
 9009:         $first = int(1+rand(9)); 
 9010:     } 
 9011:     my $uname=$first.
 9012:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 9013:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
 9014:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 9015: # ----------------------------------------------- Make sure that does not exist
 9016:     my $uhome=&homeserver($uname,$udom,'true');
 9017:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
 9018:         if ($crstype eq 'Community') {
 9019:             $first = '0';
 9020:         } else {
 9021:             $first = int(1+rand(9));
 9022:         }
 9023:         $uname=$first.
 9024:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 9025:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
 9026:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 9027:         $uhome=&homeserver($uname,$udom,'true');
 9028:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
 9029:             return 'error: unable to generate unique course-ID';
 9030:         }
 9031:     }
 9032:     return $uname;
 9033: }
 9034: 
 9035: sub is_course {
 9036:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
 9037:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
 9038: 
 9039:     return unless $cdom and $cnum;
 9040: 
 9041:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
 9042:         '.');
 9043: 
 9044:     return unless(exists($courses{$cdom.'_'.$cnum}));
 9045:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
 9046: }
 9047: 
 9048: sub store_userdata {
 9049:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
 9050:     my $result;
 9051:     if ($datakey ne '') {
 9052:         if (ref($storehash) eq 'HASH') {
 9053:             if ($udom eq '' || $uname eq '') {
 9054:                 $udom = $env{'user.domain'};
 9055:                 $uname = $env{'user.name'};
 9056:             }
 9057:             my $uhome=&homeserver($uname,$udom);
 9058:             if (($uhome eq '') || ($uhome eq 'no_host')) {
 9059:                 $result = 'error: no_host';
 9060:             } else {
 9061:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
 9062:                 $storehash->{'host'} = $perlvar{'lonHostID'};
 9063: 
 9064:                 my $namevalue='';
 9065:                 foreach my $key (keys(%{$storehash})) {
 9066:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 9067:                 }
 9068:                 $namevalue=~s/\&$//;
 9069:                 unless ($namespace eq 'courserequests') {
 9070:                     $datakey = &escape($datakey);
 9071:                 }
 9072:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
 9073:                                   $namevalue,$uhome);
 9074:             }
 9075:         } else {
 9076:             $result = 'error: data to store was not a hash reference'; 
 9077:         }
 9078:     } else {
 9079:         $result= 'error: invalid requestkey'; 
 9080:     }
 9081:     return $result;
 9082: }
 9083: 
 9084: # ---------------------------------------------------------- Assign Custom Role
 9085: 
 9086: sub assigncustomrole {
 9087:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 9088:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 9089:                        $end,$start,$deleteflag,$selfenroll,$context);
 9090: }
 9091: 
 9092: # ----------------------------------------------------------------- Revoke Role
 9093: 
 9094: sub revokerole {
 9095:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 9096:     my $now=time;
 9097:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 9098: }
 9099: 
 9100: # ---------------------------------------------------------- Revoke Custom Role
 9101: 
 9102: sub revokecustomrole {
 9103:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 9104:     my $now=time;
 9105:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 9106:            $deleteflag,$selfenroll,$context);
 9107: }
 9108: 
 9109: # ------------------------------------------------------------ Disk usage
 9110: sub diskusage {
 9111:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 9112:     $directorypath =~ s/\/$//;
 9113:     my $listing=&reply('du2:'.&escape($directorypath).':'
 9114:                        .&escape($getpropath).':'.&escape($uname).':'
 9115:                        .&escape($udom),homeserver($uname,$udom));
 9116:     if ($listing eq 'unknown_cmd') {
 9117:         if ($getpropath) {
 9118:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 9119:         }
 9120:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 9121:     }
 9122:     return $listing;
 9123: }
 9124: 
 9125: sub is_locked {
 9126:     my ($file_name, $domain, $user, $which) = @_;
 9127:     my @check;
 9128:     my $is_locked;
 9129:     push (@check,$file_name);
 9130:     my %locked = &get('file_permissions',\@check,
 9131: 		      $env{'user.domain'},$env{'user.name'});
 9132:     my ($tmp)=keys(%locked);
 9133:     if ($tmp=~/^error:/) { undef(%locked); }
 9134:     
 9135:     if (ref($locked{$file_name}) eq 'ARRAY') {
 9136:         $is_locked = 'false';
 9137:         foreach my $entry (@{$locked{$file_name}}) {
 9138:            if (ref($entry) eq 'ARRAY') {
 9139:                $is_locked = 'true';
 9140:                if (ref($which) eq 'ARRAY') {
 9141:                    push(@{$which},$entry);
 9142:                } else {
 9143:                    last;
 9144:                }
 9145:            }
 9146:        }
 9147:     } else {
 9148:         $is_locked = 'false';
 9149:     }
 9150:     return $is_locked;
 9151: }
 9152: 
 9153: sub declutter_portfile {
 9154:     my ($file) = @_;
 9155:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 9156:     return $file;
 9157: }
 9158: 
 9159: # ------------------------------------------------------------- Mark as Read Only
 9160: 
 9161: sub mark_as_readonly {
 9162:     my ($domain,$user,$files,$what) = @_;
 9163:     my %current_permissions = &dump('file_permissions',$domain,$user);
 9164:     my ($tmp)=keys(%current_permissions);
 9165:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9166:     foreach my $file (@{$files}) {
 9167: 	$file = &declutter_portfile($file);
 9168:         push(@{$current_permissions{$file}},$what);
 9169:     }
 9170:     &put('file_permissions',\%current_permissions,$domain,$user);
 9171:     return;
 9172: }
 9173: 
 9174: # ------------------------------------------------------------Save Selected Files
 9175: 
 9176: sub save_selected_files {
 9177:     my ($user, $path, @files) = @_;
 9178:     my $filename = $user."savedfiles";
 9179:     my @other_files = &files_not_in_path($user, $path);
 9180:     open (OUT, '>'.$tmpdir.$filename);
 9181:     foreach my $file (@files) {
 9182:         print (OUT $env{'form.currentpath'}.$file."\n");
 9183:     }
 9184:     foreach my $file (@other_files) {
 9185:         print (OUT $file."\n");
 9186:     }
 9187:     close (OUT);
 9188:     return 'ok';
 9189: }
 9190: 
 9191: sub clear_selected_files {
 9192:     my ($user) = @_;
 9193:     my $filename = $user."savedfiles";
 9194:     open (OUT, '>'.LONCAPA::tempdir().$filename);
 9195:     print (OUT undef);
 9196:     close (OUT);
 9197:     return ("ok");    
 9198: }
 9199: 
 9200: sub files_in_path {
 9201:     my ($user, $path) = @_;
 9202:     my $filename = $user."savedfiles";
 9203:     my %return_files;
 9204:     open (IN, '<'.LONCAPA::tempdir().$filename);
 9205:     while (my $line_in = <IN>) {
 9206:         chomp ($line_in);
 9207:         my @paths_and_file = split (m!/!, $line_in);
 9208:         my $file_part = pop (@paths_and_file);
 9209:         my $path_part = join ('/', @paths_and_file);
 9210:         $path_part.='/';
 9211:         my $path_and_file = $path_part.$file_part;
 9212:         if ($path_part eq $path) {
 9213:             $return_files{$file_part}= 'selected';
 9214:         }
 9215:     }
 9216:     close (IN);
 9217:     return (\%return_files);
 9218: }
 9219: 
 9220: # called in portfolio select mode, to show files selected NOT in current directory
 9221: sub files_not_in_path {
 9222:     my ($user, $path) = @_;
 9223:     my $filename = $user."savedfiles";
 9224:     my @return_files;
 9225:     my $path_part;
 9226:     open(IN, '<'.LONCAPA::.$filename);
 9227:     while (my $line = <IN>) {
 9228:         #ok, I know it's clunky, but I want it to work
 9229:         my @paths_and_file = split(m|/|, $line);
 9230:         my $file_part = pop(@paths_and_file);
 9231:         chomp($file_part);
 9232:         my $path_part = join('/', @paths_and_file);
 9233:         $path_part .= '/';
 9234:         my $path_and_file = $path_part.$file_part;
 9235:         if ($path_part ne $path) {
 9236:             push(@return_files, ($path_and_file));
 9237:         }
 9238:     }
 9239:     close(OUT);
 9240:     return (@return_files);
 9241: }
 9242: 
 9243: #----------------------------------------------Get portfolio file permissions
 9244: 
 9245: sub get_portfile_permissions {
 9246:     my ($domain,$user) = @_;
 9247:     my %current_permissions = &dump('file_permissions',$domain,$user);
 9248:     my ($tmp)=keys(%current_permissions);
 9249:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9250:     return \%current_permissions;
 9251: }
 9252: 
 9253: #---------------------------------------------Get portfolio file access controls
 9254: 
 9255: sub get_access_controls {
 9256:     my ($current_permissions,$group,$file) = @_;
 9257:     my %access;
 9258:     my $real_file = $file;
 9259:     $file =~ s/\.meta$//;
 9260:     if (defined($file)) {
 9261:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 9262:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 9263:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 9264:             }
 9265:         }
 9266:     } else {
 9267:         foreach my $key (keys(%{$current_permissions})) {
 9268:             if ($key =~ /\0accesscontrol$/) {
 9269:                 if (defined($group)) {
 9270:                     if ($key !~ m-^\Q$group\E/-) {
 9271:                         next;
 9272:                     }
 9273:                 }
 9274:                 my ($fullpath) = split(/\0/,$key);
 9275:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 9276:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 9277:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 9278:                     }
 9279:                 }
 9280:             }
 9281:         }
 9282:     }
 9283:     return %access;
 9284: }
 9285: 
 9286: sub modify_access_controls {
 9287:     my ($file_name,$changes,$domain,$user)=@_;
 9288:     my ($outcome,$deloutcome);
 9289:     my %store_permissions;
 9290:     my %new_values;
 9291:     my %new_control;
 9292:     my %translation;
 9293:     my @deletions = ();
 9294:     my $now = time;
 9295:     if (exists($$changes{'activate'})) {
 9296:         if (ref($$changes{'activate'}) eq 'HASH') {
 9297:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 9298:             my $numnew = scalar(@newitems);
 9299:             for (my $i=0; $i<$numnew; $i++) {
 9300:                 my $newkey = $newitems[$i];
 9301:                 my $newid = &Apache::loncommon::get_cgi_id();
 9302:                 if ($newkey =~ /^\d+:/) { 
 9303:                     $newkey =~ s/^(\d+)/$newid/;
 9304:                     $translation{$1} = $newid;
 9305:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 9306:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 9307:                     $translation{$1} = $newid;
 9308:                 }
 9309:                 $new_values{$file_name."\0".$newkey} = 
 9310:                                           $$changes{'activate'}{$newitems[$i]};
 9311:                 $new_control{$newkey} = $now;
 9312:             }
 9313:         }
 9314:     }
 9315:     my %todelete;
 9316:     my %changed_items;
 9317:     foreach my $action ('delete','update') {
 9318:         if (exists($$changes{$action})) {
 9319:             if (ref($$changes{$action}) eq 'HASH') {
 9320:                 foreach my $key (keys(%{$$changes{$action}})) {
 9321:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 9322:                     if ($action eq 'delete') { 
 9323:                         $todelete{$itemnum} = 1;
 9324:                     } else {
 9325:                         $changed_items{$itemnum} = $key;
 9326:                     }
 9327:                 }
 9328:             }
 9329:         }
 9330:     }
 9331:     # get lock on access controls for file.
 9332:     my $lockhash = {
 9333:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 9334:                                                        ':'.$env{'user.domain'},
 9335:                    }; 
 9336:     my $tries = 0;
 9337:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 9338:    
 9339:     while (($gotlock ne 'ok') && $tries <3) {
 9340:         $tries ++;
 9341:         sleep 1;
 9342:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 9343:     }
 9344:     if ($gotlock eq 'ok') {
 9345:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 9346:         my ($tmp)=keys(%curr_permissions);
 9347:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 9348:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 9349:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 9350:             if (ref($curr_controls) eq 'HASH') {
 9351:                 foreach my $control_item (keys(%{$curr_controls})) {
 9352:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 9353:                     if (defined($todelete{$itemnum})) {
 9354:                         push(@deletions,$file_name."\0".$control_item);
 9355:                     } else {
 9356:                         if (defined($changed_items{$itemnum})) {
 9357:                             $new_control{$changed_items{$itemnum}} = $now;
 9358:                             push(@deletions,$file_name."\0".$control_item);
 9359:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 9360:                         } else {
 9361:                             $new_control{$control_item} = $$curr_controls{$control_item};
 9362:                         }
 9363:                     }
 9364:                 }
 9365:             }
 9366:         }
 9367:         my ($group);
 9368:         if (&is_course($domain,$user)) {
 9369:             ($group,my $file) = split(/\//,$file_name,2);
 9370:         }
 9371:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 9372:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 9373:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 9374:         #  remove lock
 9375:         my @del_lock = ($file_name."\0".'locked_access_records');
 9376:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 9377:         my $sqlresult =
 9378:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 9379:                                     $group);
 9380:     } else {
 9381:         $outcome = "error: could not obtain lockfile\n";  
 9382:     }
 9383:     return ($outcome,$deloutcome,\%new_values,\%translation);
 9384: }
 9385: 
 9386: sub make_public_indefinitely {
 9387:     my ($requrl) = @_;
 9388:     my $now = time;
 9389:     my $action = 'activate';
 9390:     my $aclnum = 0;
 9391:     if (&is_portfolio_url($requrl)) {
 9392:         my (undef,$udom,$unum,$file_name,$group) =
 9393:             &parse_portfolio_url($requrl);
 9394:         my $current_perms = &get_portfile_permissions($udom,$unum);
 9395:         my %access_controls = &get_access_controls($current_perms,
 9396:                                                    $group,$file_name);
 9397:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 9398:             my ($num,$scope,$end,$start) = 
 9399:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 9400:             if ($scope eq 'public') {
 9401:                 if ($start <= $now && $end == 0) {
 9402:                     $action = 'none';
 9403:                 } else {
 9404:                     $action = 'update';
 9405:                     $aclnum = $num;
 9406:                 }
 9407:                 last;
 9408:             }
 9409:         }
 9410:         if ($action eq 'none') {
 9411:              return 'ok';
 9412:         } else {
 9413:             my %changes;
 9414:             my $newend = 0;
 9415:             my $newstart = $now;
 9416:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 9417:             $changes{$action}{$newkey} = {
 9418:                 type => 'public',
 9419:                 time => {
 9420:                     start => $newstart,
 9421:                     end   => $newend,
 9422:                 },
 9423:             };
 9424:             my ($outcome,$deloutcome,$new_values,$translation) =
 9425:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 9426:             return $outcome;
 9427:         }
 9428:     } else {
 9429:         return 'invalid';
 9430:     }
 9431: }
 9432: 
 9433: #------------------------------------------------------Get Marked as Read Only
 9434: 
 9435: sub get_marked_as_readonly {
 9436:     my ($domain,$user,$what,$group) = @_;
 9437:     my $current_permissions = &get_portfile_permissions($domain,$user);
 9438:     my @readonly_files;
 9439:     my $cmp1=$what;
 9440:     if (ref($what)) { $cmp1=join('',@{$what}) };
 9441:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 9442:         if (defined($group)) {
 9443:             if ($file_name !~ m-^\Q$group\E/-) {
 9444:                 next;
 9445:             }
 9446:         }
 9447:         if (ref($value) eq "ARRAY"){
 9448:             foreach my $stored_what (@{$value}) {
 9449:                 my $cmp2=$stored_what;
 9450:                 if (ref($stored_what) eq 'ARRAY') {
 9451:                     $cmp2=join('',@{$stored_what});
 9452:                 }
 9453:                 if ($cmp1 eq $cmp2) {
 9454:                     push(@readonly_files, $file_name);
 9455:                     last;
 9456:                 } elsif (!defined($what)) {
 9457:                     push(@readonly_files, $file_name);
 9458:                     last;
 9459:                 }
 9460:             }
 9461:         }
 9462:     }
 9463:     return @readonly_files;
 9464: }
 9465: #-----------------------------------------------------------Get Marked as Read Only Hash
 9466: 
 9467: sub get_marked_as_readonly_hash {
 9468:     my ($current_permissions,$group,$what) = @_;
 9469:     my %readonly_files;
 9470:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 9471:         if (defined($group)) {
 9472:             if ($file_name !~ m-^\Q$group\E/-) {
 9473:                 next;
 9474:             }
 9475:         }
 9476:         if (ref($value) eq "ARRAY"){
 9477:             foreach my $stored_what (@{$value}) {
 9478:                 if (ref($stored_what) eq 'ARRAY') {
 9479:                     foreach my $lock_descriptor(@{$stored_what}) {
 9480:                         if ($lock_descriptor eq 'graded') {
 9481:                             $readonly_files{$file_name} = 'graded';
 9482:                         } elsif ($lock_descriptor eq 'handback') {
 9483:                             $readonly_files{$file_name} = 'handback';
 9484:                         } else {
 9485:                             if (!exists($readonly_files{$file_name})) {
 9486:                                 $readonly_files{$file_name} = 'locked';
 9487:                             }
 9488:                         }
 9489:                     }
 9490:                 } 
 9491:             }
 9492:         } 
 9493:     }
 9494:     return %readonly_files;
 9495: }
 9496: # ------------------------------------------------------------ Unmark as Read Only
 9497: 
 9498: sub unmark_as_readonly {
 9499:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 9500:     # for portfolio submissions, $what contains [$symb,$crsid] 
 9501:     my ($domain,$user,$what,$file_name,$group) = @_;
 9502:     $file_name = &declutter_portfile($file_name);
 9503:     my $symb_crs = $what;
 9504:     if (ref($what)) { $symb_crs=join('',@$what); }
 9505:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 9506:     my ($tmp)=keys(%current_permissions);
 9507:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 9508:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 9509:     foreach my $file (@readonly_files) {
 9510: 	my $clean_file = &declutter_portfile($file);
 9511: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 9512: 	my $current_locks = $current_permissions{$file};
 9513:         my @new_locks;
 9514:         my @del_keys;
 9515:         if (ref($current_locks) eq "ARRAY"){
 9516:             foreach my $locker (@{$current_locks}) {
 9517:                 my $compare=$locker;
 9518:                 if (ref($locker) eq 'ARRAY') {
 9519:                     $compare=join('',@{$locker});
 9520:                     if ($compare ne $symb_crs) {
 9521:                         push(@new_locks, $locker);
 9522:                     }
 9523:                 }
 9524:             }
 9525:             if (scalar(@new_locks) > 0) {
 9526:                 $current_permissions{$file} = \@new_locks;
 9527:             } else {
 9528:                 push(@del_keys, $file);
 9529:                 &del('file_permissions',\@del_keys, $domain, $user);
 9530:                 delete($current_permissions{$file});
 9531:             }
 9532:         }
 9533:     }
 9534:     &put('file_permissions',\%current_permissions,$domain,$user);
 9535:     return;
 9536: }
 9537: 
 9538: # ------------------------------------------------------------ Directory lister
 9539: 
 9540: sub dirlist {
 9541:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 9542:     $uri=~s/^\///;
 9543:     $uri=~s/\/$//;
 9544:     my ($udom, $uname);
 9545:     if ($getuserdir) {
 9546:         $udom = $userdomain;
 9547:         $uname = $username;
 9548:     } else {
 9549:         (undef,$udom,$uname)=split(/\//,$uri);
 9550:         if(defined($userdomain)) {
 9551:             $udom = $userdomain;
 9552:         }
 9553:         if(defined($username)) {
 9554:             $uname = $username;
 9555:         }
 9556:     }
 9557:     my ($dirRoot,$listing,@listing_results);
 9558: 
 9559:     $dirRoot = $perlvar{'lonDocRoot'};
 9560:     if (defined($getpropath)) {
 9561:         $dirRoot = &propath($udom,$uname);
 9562:         $dirRoot =~ s/\/$//;
 9563:     } elsif (defined($getuserdir)) {
 9564:         my $subdir=$uname.'__';
 9565:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 9566:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 9567:                    ."/$udom/$subdir/$uname";
 9568:     } elsif (defined($alternateRoot)) {
 9569:         $dirRoot = $alternateRoot;
 9570:     }
 9571: 
 9572:     if($udom) {
 9573:         if($uname) {
 9574:             my $uhome = &homeserver($uname,$udom);
 9575:             if ($uhome eq 'no_host') {
 9576:                 return ([],'no_host');
 9577:             }
 9578:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 9579:                               .$getuserdir.':'.&escape($dirRoot)
 9580:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
 9581:             if ($listing eq 'unknown_cmd') {
 9582:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
 9583:             } else {
 9584:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 9585:             }
 9586:             if ($listing eq 'unknown_cmd') {
 9587:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
 9588:                 @listing_results = split(/:/,$listing);
 9589:             } else {
 9590:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 9591:             }
 9592:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
 9593:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
 9594:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 9595:                 return ([],$listing);
 9596:             } else {
 9597:                 return (\@listing_results);
 9598:             }
 9599:         } elsif(!$alternateRoot) {
 9600:             my (%allusers,%listerror);
 9601: 	    my %servers = &get_servers($udom,'library');
 9602:  	    foreach my $tryserver (keys(%servers)) {
 9603:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 9604:                                   &escape($udom),$tryserver);
 9605:                 if ($listing eq 'unknown_cmd') {
 9606: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 9607: 				      $udom, $tryserver);
 9608:                 } else {
 9609:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 9610:                 }
 9611: 		if ($listing eq 'unknown_cmd') {
 9612: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 9613: 				      $udom, $tryserver);
 9614: 		    @listing_results = split(/:/,$listing);
 9615: 		} else {
 9616: 		    @listing_results =
 9617: 			map { &unescape($_); } split(/:/,$listing);
 9618: 		}
 9619:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
 9620:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
 9621:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 9622:                     $listerror{$tryserver} = $listing;
 9623:                 } else {
 9624: 		    foreach my $line (@listing_results) {
 9625: 			my ($entry) = split(/&/,$line,2);
 9626: 			$allusers{$entry} = 1;
 9627: 		    }
 9628: 		}
 9629:             }
 9630:             my @alluserslist=();
 9631:             foreach my $user (sort(keys(%allusers))) {
 9632:                 push(@alluserslist,$user.'&user');
 9633:             }
 9634:             return (\@alluserslist);
 9635:         } else {
 9636:             return ([],'missing username');
 9637:         }
 9638:     } elsif(!defined($getpropath)) {
 9639:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
 9640:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
 9641:         return (\@all_domains);
 9642:     } else {
 9643:         return ([],'missing domain');
 9644:     }
 9645: }
 9646: 
 9647: # --------------------------------------------- GetFileTimestamp
 9648: # This function utilizes dirlist and returns the date stamp for
 9649: # when it was last modified.  It will also return an error of -1
 9650: # if an error occurs
 9651: 
 9652: sub GetFileTimestamp {
 9653:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 9654:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 9655:     $studentName   = &LONCAPA::clean_username($studentName);
 9656:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
 9657:                                     undef,$getuserdir);
 9658:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 9659:         return -1;
 9660:     }
 9661:     if (ref($fileref) eq 'ARRAY') {
 9662:         my @stats = split('&',$fileref->[0]);
 9663:         # @stats contains first the filename, then the stat output
 9664:         return $stats[10]; # so this is 10 instead of 9.
 9665:     } else {
 9666:         return -1;
 9667:     }
 9668: }
 9669: 
 9670: sub stat_file {
 9671:     my ($uri) = @_;
 9672:     $uri = &clutter_with_no_wrapper($uri);
 9673: 
 9674:     my ($udom,$uname,$file);
 9675:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 9676: 	($udom,$uname,$file) =
 9677: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 9678: 	$file = 'userfiles/'.$file;
 9679:     }
 9680:     if ($uri =~ m-^/res/-) {
 9681: 	($udom,$uname) = 
 9682: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 9683: 	$file = $uri;
 9684:     }
 9685: 
 9686:     if (!$udom || !$uname || !$file) {
 9687: 	# unable to handle the uri
 9688: 	return ();
 9689:     }
 9690:     my $getpropath;
 9691:     if ($file =~ /^userfiles\//) {
 9692:         $getpropath = 1;
 9693:     }
 9694:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
 9695:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 9696:         return ();
 9697:     } else {
 9698:         if (ref($listref) eq 'ARRAY') {
 9699:             my @stats = split('&',$listref->[0]);
 9700: 	    shift(@stats); #filename is first
 9701: 	    return @stats;
 9702:         }
 9703:     }
 9704:     return ();
 9705: }
 9706: 
 9707: # -------------------------------------------------------- Value of a Condition
 9708: 
 9709: # gets the value of a specific preevaluated condition
 9710: #    stored in the string  $env{user.state.<cid>}
 9711: # or looks up a condition reference in the bighash and if if hasn't
 9712: # already been evaluated recurses into docondval to get the value of
 9713: # the condition, then memoizing it to 
 9714: #   $env{user.state.<cid>.<condition>}
 9715: sub directcondval {
 9716:     my $number=shift;
 9717:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 9718: 	&Apache::lonuserstate::evalstate();
 9719:     }
 9720:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 9721: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 9722:     } elsif ($number =~ /^_/) {
 9723: 	my $sub_condition;
 9724: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9725: 		&GDBM_READER(),0640)) {
 9726: 	    $sub_condition=$bighash{'conditions'.$number};
 9727: 	    untie(%bighash);
 9728: 	}
 9729: 	my $value = &docondval($sub_condition);
 9730: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 9731: 	return $value;
 9732:     }
 9733:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 9734:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 9735:     } else {
 9736:        return 2;
 9737:     }
 9738: }
 9739: 
 9740: # get the collection of conditions for this resource
 9741: sub condval {
 9742:     my $condidx=shift;
 9743:     my $allpathcond='';
 9744:     foreach my $cond (split(/\|/,$condidx)) {
 9745: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 9746: 	    $allpathcond.=
 9747: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 9748: 	}
 9749:     }
 9750:     $allpathcond=~s/\|$//;
 9751:     return &docondval($allpathcond);
 9752: }
 9753: 
 9754: #evaluates an expression of conditions
 9755: sub docondval {
 9756:     my ($allpathcond) = @_;
 9757:     my $result=0;
 9758:     if ($env{'request.course.id'}
 9759: 	&& defined($allpathcond)) {
 9760: 	my $operand='|';
 9761: 	my @stack;
 9762: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 9763: 	    if ($chunk eq '(') {
 9764: 		push @stack,($operand,$result);
 9765: 	    } elsif ($chunk eq ')') {
 9766: 		my $before=pop @stack;
 9767: 		if (pop @stack eq '&') {
 9768: 		    $result=$result>$before?$before:$result;
 9769: 		} else {
 9770: 		    $result=$result>$before?$result:$before;
 9771: 		}
 9772: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 9773: 		$operand=$chunk;
 9774: 	    } else {
 9775: 		my $new=directcondval($chunk);
 9776: 		if ($operand eq '&') {
 9777: 		    $result=$result>$new?$new:$result;
 9778: 		} else {
 9779: 		    $result=$result>$new?$result:$new;
 9780: 		}
 9781: 	    }
 9782: 	}
 9783:     }
 9784:     return $result;
 9785: }
 9786: 
 9787: # ---------------------------------------------------- Devalidate courseresdata
 9788: 
 9789: sub devalidatecourseresdata {
 9790:     my ($coursenum,$coursedomain)=@_;
 9791:     my $hashid=$coursenum.':'.$coursedomain;
 9792:     &devalidate_cache_new('courseres',$hashid);
 9793: }
 9794: 
 9795: 
 9796: # --------------------------------------------------- Course Resourcedata Query
 9797: #
 9798: #  Parameters:
 9799: #      $coursenum    - Number of the course.
 9800: #      $coursedomain - Domain at which the course was created.
 9801: #  Returns:
 9802: #     A hash of the course parameters along (I think) with timestamps
 9803: #     and version info.
 9804: 
 9805: sub get_courseresdata {
 9806:     my ($coursenum,$coursedomain)=@_;
 9807:     my $coursehom=&homeserver($coursenum,$coursedomain);
 9808:     my $hashid=$coursenum.':'.$coursedomain;
 9809:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 9810:     my %dumpreply;
 9811:     unless (defined($cached)) {
 9812: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 9813: 	$result=\%dumpreply;
 9814: 	my ($tmp) = keys(%dumpreply);
 9815: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9816: 	    &do_cache_new('courseres',$hashid,$result,600);
 9817: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 9818: 	    return $tmp;
 9819: 	} elsif ($tmp =~ /^(error)/) {
 9820: 	    $result=undef;
 9821: 	    &do_cache_new('courseres',$hashid,$result,600);
 9822: 	}
 9823:     }
 9824:     return $result;
 9825: }
 9826: 
 9827: sub devalidateuserresdata {
 9828:     my ($uname,$udom)=@_;
 9829:     my $hashid="$udom:$uname";
 9830:     &devalidate_cache_new('userres',$hashid);
 9831: }
 9832: 
 9833: sub get_userresdata {
 9834:     my ($uname,$udom)=@_;
 9835:     #most student don\'t have any data set, check if there is some data
 9836:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 9837: 
 9838:     my $hashid="$udom:$uname";
 9839:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 9840:     if (!defined($cached)) {
 9841: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 9842: 	$result=\%resourcedata;
 9843: 	&do_cache_new('userres',$hashid,$result,600);
 9844:     }
 9845:     my ($tmp)=keys(%$result);
 9846:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 9847: 	return $result;
 9848:     }
 9849:     #error 2 occurs when the .db doesn't exist
 9850:     if ($tmp!~/error: 2 /) {
 9851: 	&logthis("<font color=\"blue\">WARNING:".
 9852: 		 " Trying to get resource data for ".
 9853: 		 $uname." at ".$udom.": ".
 9854: 		 $tmp."</font>");
 9855:     } elsif ($tmp=~/error: 2 /) {
 9856: 	#&EXT_cache_set($udom,$uname);
 9857: 	&do_cache_new('userres',$hashid,undef,600);
 9858: 	undef($tmp); # not really an error so don't send it back
 9859:     }
 9860:     return $tmp;
 9861: }
 9862: #----------------------------------------------- resdata - return resource data
 9863: #  Purpose:
 9864: #    Return resource data for either users or for a course.
 9865: #  Parameters:
 9866: #     $name      - Course/user name.
 9867: #     $domain    - Name of the domain the user/course is registered on.
 9868: #     $type      - Type of thing $name is (must be 'course' or 'user'
 9869: #     @which     - Array of names of resources desired.
 9870: #  Returns:
 9871: #     The value of the first reasource in @which that is found in the
 9872: #     resource hash.
 9873: #  Exceptional Conditions:
 9874: #     If the $type passed in is not valid (not the string 'course' or 
 9875: #     'user', an undefined  reference is returned.
 9876: #     If none of the resources are found, an undef is returned
 9877: sub resdata {
 9878:     my ($name,$domain,$type,@which)=@_;
 9879:     my $result;
 9880:     if ($type eq 'course') {
 9881: 	$result=&get_courseresdata($name,$domain);
 9882:     } elsif ($type eq 'user') {
 9883: 	$result=&get_userresdata($name,$domain);
 9884:     }
 9885:     if (!ref($result)) { return $result; }    
 9886:     foreach my $item (@which) {
 9887: 	if (defined($result->{$item->[0]})) {
 9888: 	    return [$result->{$item->[0]},$item->[1]];
 9889: 	}
 9890:     }
 9891:     return undef;
 9892: }
 9893: 
 9894: sub get_numsuppfiles {
 9895:     my ($cnum,$cdom,$ignorecache)=@_;
 9896:     my $hashid=$cnum.':'.$cdom;
 9897:     my ($suppcount,$cached);
 9898:     unless ($ignorecache) {
 9899:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
 9900:     }
 9901:     unless (defined($cached)) {
 9902:         my $chome=&homeserver($cnum,$cdom);
 9903:         unless ($chome eq 'no_host') {
 9904:             ($suppcount,my $errors) = (0,0);
 9905:             my $suppmap = 'supplemental.sequence';
 9906:             ($suppcount,$errors) =
 9907:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
 9908:         }
 9909:         &do_cache_new('suppcount',$hashid,$suppcount,600);
 9910:     }
 9911:     return $suppcount;
 9912: }
 9913: 
 9914: #
 9915: # EXT resource caching routines
 9916: #
 9917: 
 9918: sub clear_EXT_cache_status {
 9919:     &delenv('cache.EXT.');
 9920: }
 9921: 
 9922: sub EXT_cache_status {
 9923:     my ($target_domain,$target_user) = @_;
 9924:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 9925:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 9926:         # We know already the user has no data
 9927:         return 1;
 9928:     } else {
 9929:         return 0;
 9930:     }
 9931: }
 9932: 
 9933: sub EXT_cache_set {
 9934:     my ($target_domain,$target_user) = @_;
 9935:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 9936:     #&appenv({$cachename => time});
 9937: }
 9938: 
 9939: # --------------------------------------------------------- Value of a Variable
 9940: sub EXT {
 9941: 
 9942:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
 9943:     unless ($varname) { return ''; }
 9944:     #get real user name/domain, courseid and symb
 9945:     my $courseid;
 9946:     my $publicuser;
 9947:     if ($symbparm) {
 9948: 	$symbparm=&get_symb_from_alias($symbparm);
 9949:     }
 9950:     if (!($uname && $udom)) {
 9951:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 9952:       if (!$symbparm) {	$symbparm=$cursymb; }
 9953:     } else {
 9954: 	$courseid=$env{'request.course.id'};
 9955:     }
 9956:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 9957:     my $rest;
 9958:     if (defined($therest[0])) {
 9959:        $rest=join('.',@therest);
 9960:     } else {
 9961:        $rest='';
 9962:     }
 9963: 
 9964:     my $qualifierrest=$qualifier;
 9965:     if ($rest) { $qualifierrest.='.'.$rest; }
 9966:     my $spacequalifierrest=$space;
 9967:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 9968:     if ($realm eq 'user') {
 9969: # --------------------------------------------------------------- user.resource
 9970: 	if ($space eq 'resource') {
 9971: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 9972: 		  || defined($Apache::lonhomework::parsing_a_task))
 9973: 		 &&
 9974: 		 ($symbparm eq &symbread()) ) {	
 9975: 		# if we are in the middle of processing the resource the
 9976: 		# get the value we are planning on committing
 9977:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 9978:                     return $Apache::lonhomework::results{$qualifierrest};
 9979:                 } else {
 9980:                     return $Apache::lonhomework::history{$qualifierrest};
 9981:                 }
 9982: 	    } else {
 9983: 		my %restored;
 9984: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 9985: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 9986: 		} else {
 9987: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 9988: 		}
 9989: 		return $restored{$qualifierrest};
 9990: 	    }
 9991: # ----------------------------------------------------------------- user.access
 9992:         } elsif ($space eq 'access') {
 9993: 	    # FIXME - not supporting calls for a specific user
 9994:             return &allowed($qualifier,$rest);
 9995: # ------------------------------------------ user.preferences, user.environment
 9996:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 9997: 	    if (($uname eq $env{'user.name'}) &&
 9998: 		($udom eq $env{'user.domain'})) {
 9999: 		return $env{join('.',('environment',$qualifierrest))};
10000: 	    } else {
10001: 		my %returnhash;
10002: 		if (!$publicuser) {
10003: 		    %returnhash=&userenvironment($udom,$uname,
10004: 						 $qualifierrest);
10005: 		}
10006: 		return $returnhash{$qualifierrest};
10007: 	    }
10008: # ----------------------------------------------------------------- user.course
10009:         } elsif ($space eq 'course') {
10010: 	    # FIXME - not supporting calls for a specific user
10011:             return $env{join('.',('request.course',$qualifier))};
10012: # ------------------------------------------------------------------- user.role
10013:         } elsif ($space eq 'role') {
10014: 	    # FIXME - not supporting calls for a specific user
10015:             my ($role,$where)=split(/\./,$env{'request.role'});
10016:             if ($qualifier eq 'value') {
10017: 		return $role;
10018:             } elsif ($qualifier eq 'extent') {
10019:                 return $where;
10020:             }
10021: # ----------------------------------------------------------------- user.domain
10022:         } elsif ($space eq 'domain') {
10023:             return $udom;
10024: # ------------------------------------------------------------------- user.name
10025:         } elsif ($space eq 'name') {
10026:             return $uname;
10027: # ---------------------------------------------------- Any other user namespace
10028:         } else {
10029: 	    my %reply;
10030: 	    if (!$publicuser) {
10031: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
10032: 	    }
10033: 	    return $reply{$qualifierrest};
10034:         }
10035:     } elsif ($realm eq 'query') {
10036: # ---------------------------------------------- pull stuff out of query string
10037:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
10038: 						[$spacequalifierrest]);
10039: 	return $env{'form.'.$spacequalifierrest}; 
10040:    } elsif ($realm eq 'request') {
10041: # ------------------------------------------------------------- request.browser
10042:         if ($space eq 'browser') {
10043:             return $env{'browser.'.$qualifier};
10044: # ------------------------------------------------------------ request.filename
10045:         } else {
10046:             return $env{'request.'.$spacequalifierrest};
10047:         }
10048:     } elsif ($realm eq 'course') {
10049: # ---------------------------------------------------------- course.description
10050:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
10051:     } elsif ($realm eq 'resource') {
10052: 
10053: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
10054: 	    if (!$symbparm) { $symbparm=&symbread(); }
10055: 	}
10056: 
10057:         if ($qualifier eq '') {
10058: 	    if ($space eq 'title') {
10059: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
10060: 	        return &gettitle($symbparm);
10061: 	    }
10062: 	
10063: 	    if ($space eq 'map') {
10064: 	        my ($map) = &decode_symb($symbparm);
10065: 	        return &symbread($map);
10066: 	    }
10067:             if ($space eq 'maptitle') {
10068:                 my ($map) = &decode_symb($symbparm);
10069:                 return &gettitle($map);
10070:             }
10071: 	    if ($space eq 'filename') {
10072: 	        if ($symbparm) {
10073: 		    return &clutter((&decode_symb($symbparm))[2]);
10074: 	        }
10075: 	        return &hreflocation('',$env{'request.filename'});
10076: 	    }
10077: 
10078:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
10079:                 if ($space eq 'visibleparts') {
10080:                     my $navmap = Apache::lonnavmaps::navmap->new();
10081:                     my $item;
10082:                     if (ref($navmap)) {
10083:                         my $res = $navmap->getBySymb($symbparm);
10084:                         my $parts = $res->parts();
10085:                         if (ref($parts) eq 'ARRAY') {
10086:                             $item = join(',',@{$parts});
10087:                         }
10088:                         undef($navmap);
10089:                     }
10090:                     return $item;
10091:                 }
10092:             }
10093:         }
10094: 
10095: 	my ($section, $group, @groups);
10096: 	my ($courselevelm,$courselevel);
10097:         if (($courseid eq '') && ($cid)) {
10098:             $courseid = $cid;
10099:         }
10100: 	if (($symbparm && $courseid) && 
10101: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
10102: 
10103: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
10104: 
10105: # ----------------------------------------------------- Cascading lookup scheme
10106: 	    my $symbp=$symbparm;
10107: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
10108: 
10109: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
10110: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
10111: 
10112: 	    if (($env{'user.name'} eq $uname) &&
10113: 		($env{'user.domain'} eq $udom)) {
10114: 		$section=$env{'request.course.sec'};
10115:                 @groups = split(/:/,$env{'request.course.groups'});  
10116:                 @groups=&sort_course_groups($courseid,@groups); 
10117: 	    } else {
10118: 		if (! defined($usection)) {
10119: 		    $section=&getsection($udom,$uname,$courseid);
10120: 		} else {
10121: 		    $section = $usection;
10122: 		}
10123:                 @groups = &get_users_groups($udom,$uname,$courseid);
10124: 	    }
10125: 
10126: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
10127: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
10128: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
10129: 
10130: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
10131: 	    my $courselevelr=$courseid.'.'.$symbparm;
10132: 	    $courselevelm=$courseid.'.'.$mapparm;
10133: 
10134: # ----------------------------------------------------------- first, check user
10135: 
10136: 	    my $userreply=&resdata($uname,$udom,'user',
10137: 				       ([$courselevelr,'resource'],
10138: 					[$courselevelm,'map'     ],
10139: 					[$courselevel, 'course'  ]));
10140: 	    if (defined($userreply)) { return &get_reply($userreply); }
10141: 
10142: # ------------------------------------------------ second, check some of course
10143:             my $coursereply;
10144:             if (@groups > 0) {
10145:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
10146:                                        $mapparm,$spacequalifierrest);
10147:                 if (defined($coursereply)) { return &get_reply($coursereply); }
10148:             }
10149: 
10150: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10151: 				  $env{'course.'.$courseid.'.domain'},
10152: 				  'course',
10153: 				  ([$seclevelr,   'resource'],
10154: 				   [$seclevelm,   'map'     ],
10155: 				   [$seclevel,    'course'  ],
10156: 				   [$courselevelr,'resource']));
10157: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
10158: 
10159: # ------------------------------------------------------ third, check map parms
10160: 	    my %parmhash=();
10161: 	    my $thisparm='';
10162: 	    if (tie(%parmhash,'GDBM_File',
10163: 		    $env{'request.course.fn'}.'_parms.db',
10164: 		    &GDBM_READER(),0640)) {
10165: 		$thisparm=$parmhash{$symbparm};
10166: 		untie(%parmhash);
10167: 	    }
10168: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
10169: 	}
10170: # ------------------------------------------ fourth, look in resource metadata
10171: 
10172: 	$spacequalifierrest=~s/\./\_/;
10173: 	my $filename;
10174: 	if (!$symbparm) { $symbparm=&symbread(); }
10175: 	if ($symbparm) {
10176: 	    $filename=(&decode_symb($symbparm))[2];
10177: 	} else {
10178: 	    $filename=$env{'request.filename'};
10179: 	}
10180: 	my $metadata=&metadata($filename,$spacequalifierrest);
10181: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
10182: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
10183: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
10184: 
10185: # ---------------------------------------------- fourth, look in rest of course
10186: 	if ($symbparm && defined($courseid) && 
10187: 	    $courseid eq $env{'request.course.id'}) {
10188: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10189: 				     $env{'course.'.$courseid.'.domain'},
10190: 				     'course',
10191: 				     ([$courselevelm,'map'   ],
10192: 				      [$courselevel, 'course']));
10193: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
10194: 	}
10195: # ------------------------------------------------------------------ Cascade up
10196: 	unless ($space eq '0') {
10197: 	    my @parts=split(/_/,$space);
10198: 	    my $id=pop(@parts);
10199: 	    my $part=join('_',@parts);
10200: 	    if ($part eq '') { $part='0'; }
10201: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
10202: 				 $symbparm,$udom,$uname,$section,1);
10203: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
10204: 	}
10205: 	if ($recurse) { return undef; }
10206: 	my $pack_def=&packages_tab_default($filename,$varname);
10207: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
10208: # ---------------------------------------------------- Any other user namespace
10209:     } elsif ($realm eq 'environment') {
10210: # ----------------------------------------------------------------- environment
10211: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
10212: 	    return $env{'environment.'.$spacequalifierrest};
10213: 	} else {
10214: 	    if ($uname eq 'anonymous' && $udom eq '') {
10215: 		return '';
10216: 	    }
10217: 	    my %returnhash=&userenvironment($udom,$uname,
10218: 					    $spacequalifierrest);
10219: 	    return $returnhash{$spacequalifierrest};
10220: 	}
10221:     } elsif ($realm eq 'system') {
10222: # ----------------------------------------------------------------- system.time
10223: 	if ($space eq 'time') {
10224: 	    return time;
10225:         }
10226:     } elsif ($realm eq 'server') {
10227: # ----------------------------------------------------------------- system.time
10228: 	if ($space eq 'name') {
10229: 	    return $ENV{'SERVER_NAME'};
10230:         }
10231:     }
10232:     return '';
10233: }
10234: 
10235: sub get_reply {
10236:     my ($reply_value) = @_;
10237:     if (ref($reply_value) eq 'ARRAY') {
10238:         if (wantarray) {
10239: 	    return @$reply_value;
10240:         }
10241:         return $reply_value->[0];
10242:     } else {
10243:         return $reply_value;
10244:     }
10245: }
10246: 
10247: sub check_group_parms {
10248:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10249:     my @groupitems = ();
10250:     my $resultitem;
10251:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
10252:     foreach my $group (@{$groups}) {
10253:         foreach my $level (@levels) {
10254:              my $item = $courseid.'.['.$group.'].'.$level->[0];
10255:              push(@groupitems,[$item,$level->[1]]);
10256:         }
10257:     }
10258:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10259:                             $env{'course.'.$courseid.'.domain'},
10260:                                      'course',@groupitems);
10261:     return $coursereply;
10262: }
10263: 
10264: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
10265:     my ($courseid,@groups) = @_;
10266:     @groups = sort(@groups);
10267:     return @groups;
10268: }
10269: 
10270: sub packages_tab_default {
10271:     my ($uri,$varname)=@_;
10272:     my (undef,$part,$name)=split(/\./,$varname);
10273: 
10274:     my (@extension,@specifics,$do_default);
10275:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
10276: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
10277: 	if ($pack_type eq 'default') {
10278: 	    $do_default=1;
10279: 	} elsif ($pack_type eq 'extension') {
10280: 	    push(@extension,[$package,$pack_type,$pack_part]);
10281: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
10282: 	    # only look at packages defaults for packages that this id is
10283: 	    push(@specifics,[$package,$pack_type,$pack_part]);
10284: 	}
10285:     }
10286:     # first look for a package that matches the requested part id
10287:     foreach my $package (@specifics) {
10288: 	my (undef,$pack_type,$pack_part)=@{$package};
10289: 	next if ($pack_part ne $part);
10290: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10291: 	    return $packagetab{"$pack_type&$name&default"};
10292: 	}
10293:     }
10294:     # look for any possible matching non extension_ package
10295:     foreach my $package (@specifics) {
10296: 	my (undef,$pack_type,$pack_part)=@{$package};
10297: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10298: 	    return $packagetab{"$pack_type&$name&default"};
10299: 	}
10300: 	if ($pack_type eq 'part') { $pack_part='0'; }
10301: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10302: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
10303: 	}
10304:     }
10305:     # look for any posible extension_ match
10306:     foreach my $package (@extension) {
10307: 	my ($package,$pack_type)=@{$package};
10308: 	if (defined($packagetab{"$pack_type&$name&default"})) {
10309: 	    return $packagetab{"$pack_type&$name&default"};
10310: 	}
10311: 	if (defined($packagetab{$package."&$name&default"})) {
10312: 	    return $packagetab{$package."&$name&default"};
10313: 	}
10314:     }
10315:     # look for a global default setting
10316:     if ($do_default && defined($packagetab{"default&$name&default"})) {
10317: 	return $packagetab{"default&$name&default"};
10318:     }
10319:     return undef;
10320: }
10321: 
10322: sub add_prefix_and_part {
10323:     my ($prefix,$part)=@_;
10324:     my $keyroot;
10325:     if (defined($prefix) && $prefix !~ /^__/) {
10326: 	# prefix that has a part already
10327: 	$keyroot=$prefix;
10328:     } elsif (defined($prefix)) {
10329: 	# prefix that is missing a part
10330: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10331:     } else {
10332: 	# no prefix at all
10333: 	if (defined($part)) { $keyroot='_'.$part; }
10334:     }
10335:     return $keyroot;
10336: }
10337: 
10338: # ---------------------------------------------------------------- Get metadata
10339: 
10340: my %metaentry;
10341: my %importedpartids;
10342: sub metadata {
10343:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
10344:     $uri=&declutter($uri);
10345:     # if it is a non metadata possible uri return quickly
10346:     if (($uri eq '') || 
10347: 	(($uri =~ m|^/*adm/|) && 
10348: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
10349:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
10350: 	return undef;
10351:     }
10352:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
10353: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
10354: 	return undef;
10355:     }
10356:     my $filename=$uri;
10357:     $uri=~s/\.meta$//;
10358: #
10359: # Is the metadata already cached?
10360: # Look at timestamp of caching
10361: # Everything is cached by the main uri, libraries are never directly cached
10362: #
10363:     if (!defined($liburi)) {
10364: 	my ($result,$cached)=&is_cached_new('meta',$uri);
10365: 	if (defined($cached)) { return $result->{':'.$what}; }
10366:     }
10367:     {
10368: # Imported parts would go here
10369:         my %importedids=();
10370:         my @origfileimportpartids=();
10371:         my $importedparts=0;
10372: #
10373: # Is this a recursive call for a library?
10374: #
10375: #	if (! exists($metacache{$uri})) {
10376: #	    $metacache{$uri}={};
10377: #	}
10378: 	my $cachetime = 60*60;
10379:         if ($liburi) {
10380: 	    $liburi=&declutter($liburi);
10381:             $filename=$liburi;
10382:         } else {
10383: 	    &devalidate_cache_new('meta',$uri);
10384: 	    undef(%metaentry);
10385: 	}
10386:         my %metathesekeys=();
10387:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
10388: 	my $metastring;
10389: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
10390: 	    my $which = &hreflocation('','/'.($liburi || $uri));
10391: 	    $metastring = 
10392: 		&Apache::lonnet::ssi_body($which,
10393: 					  ('grade_target' => 'meta'));
10394: 	    $cachetime = 1; # only want this cached in the child not long term
10395: 	} elsif (($uri !~ m -^(editupload)/-) && 
10396:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
10397: 	    my $file=&filelocation('',&clutter($filename));
10398: 	    #push(@{$metaentry{$uri.'.file'}},$file);
10399: 	    $metastring=&getfile($file);
10400: 	}
10401:         my $parser=HTML::LCParser->new(\$metastring);
10402:         my $token;
10403:         undef %metathesekeys;
10404:         while ($token=$parser->get_token) {
10405: 	    if ($token->[0] eq 'S') {
10406: 		if (defined($token->[2]->{'package'})) {
10407: #
10408: # This is a package - get package info
10409: #
10410: 		    my $package=$token->[2]->{'package'};
10411: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10412: 		    if (defined($token->[2]->{'id'})) { 
10413: 			$keyroot.='_'.$token->[2]->{'id'}; 
10414: 		    }
10415: 		    if ($metaentry{':packages'}) {
10416: 			$metaentry{':packages'}.=','.$package.$keyroot;
10417: 		    } else {
10418: 			$metaentry{':packages'}=$package.$keyroot;
10419: 		    }
10420: 		    foreach my $pack_entry (keys(%packagetab)) {
10421: 			my $part=$keyroot;
10422: 			$part=~s/^\_//;
10423: 			if ($pack_entry=~/^\Q$package\E\&/ || 
10424: 			    $pack_entry=~/^\Q$package\E_0\&/) {
10425: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
10426: 			    # ignore package.tab specified default values
10427:                             # here &package_tab_default() will fetch those
10428: 			    if ($subp eq 'default') { next; }
10429: 			    my $value=$packagetab{$pack_entry};
10430: 			    my $unikey;
10431: 			    if ($pack =~ /_0$/) {
10432: 				$unikey='parameter_0_'.$name;
10433: 				$part=0;
10434: 			    } else {
10435: 				$unikey='parameter'.$keyroot.'_'.$name;
10436: 			    }
10437: 			    if ($subp eq 'display') {
10438: 				$value.=' [Part: '.$part.']';
10439: 			    }
10440: 			    $metaentry{':'.$unikey.'.part'}=$part;
10441: 			    $metathesekeys{$unikey}=1;
10442: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10443: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
10444: 			    }
10445: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
10446: 				$metaentry{':'.$unikey}=
10447: 				    $metaentry{':'.$unikey.'.default'};
10448: 			    }
10449: 			}
10450: 		    }
10451: 		} else {
10452: #
10453: # This is not a package - some other kind of start tag
10454: #
10455: 		    my $entry=$token->[1];
10456: 		    my $unikey='';
10457: 
10458: 		    if ($entry eq 'import') {
10459: #
10460: # Importing a library here
10461: #
10462:                         my $location=$parser->get_text('/import');
10463:                         my $dir=$filename;
10464:                         $dir=~s|[^/]*$||;
10465:                         $location=&filelocation($dir,$location);
10466:                        
10467:                         my $importmode=$token->[2]->{'importmode'};
10468:                         if ($importmode eq 'problem') {
10469: # Import as problem/response
10470:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10471:                         } elsif ($importmode eq 'part') {
10472: # Import as part(s)
10473:                            $importedparts=1;
10474: # We need to get the original file and the imported file to get the part order correct
10475: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10476: # Load and inspect original file
10477:                            if ($#origfileimportpartids<0) {
10478:                               undef(%importedpartids);
10479:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10480:                               my $origfile=&getfile($origfilelocation);
10481:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10482:                            }
10483: 
10484: # Load and inspect imported file
10485:                            my $impfile=&getfile($location);
10486:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10487:                            if ($#impfilepartids>=0) {
10488: # This problem had parts
10489:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
10490:                            } else {
10491: # Importing by turning a single problem into a problem part
10492: # It gets the import-tags ID as part-ID
10493:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
10494:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
10495:                            }
10496:                         } else {
10497: # Normal import
10498:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10499:                            if (defined($token->[2]->{'id'})) {
10500:                               $unikey.='_'.$token->[2]->{'id'};
10501:                            }
10502:                         }
10503: 
10504: 			if ($depthcount<20) {
10505: 			    my $metadata = 
10506: 				&metadata($uri,'keys', $location,$unikey,
10507: 					  $depthcount+1);
10508: 			    foreach my $meta (split(',',$metadata)) {
10509: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
10510: 				$metathesekeys{$meta}=1;
10511: 			    }
10512: 			
10513:                         }
10514: 		    } else {
10515: #
10516: # Not importing, some other kind of non-package, non-library start tag
10517: # 
10518:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10519:                         if (defined($token->[2]->{'id'})) {
10520:                             $unikey.='_'.$token->[2]->{'id'};
10521:                         }
10522: 			if (defined($token->[2]->{'name'})) { 
10523: 			    $unikey.='_'.$token->[2]->{'name'}; 
10524: 			}
10525: 			$metathesekeys{$unikey}=1;
10526: 			foreach my $param (@{$token->[3]}) {
10527: 			    $metaentry{':'.$unikey.'.'.$param} =
10528: 				$token->[2]->{$param};
10529: 			}
10530: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
10531: 			my $default=$metaentry{':'.$unikey.'.default'};
10532: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10533: 		 # only ws inside the tag, and not in default, so use default
10534: 		 # as value
10535: 			    $metaentry{':'.$unikey}=$default;
10536: 			} elsif ( $internaltext =~ /\S/ ) {
10537: 		  # something interesting inside the tag
10538: 			    $metaentry{':'.$unikey}=$internaltext;
10539: 			} else {
10540: 		  # no interesting values, don't set a default
10541: 			}
10542: # end of not-a-package not-a-library import
10543: 		    }
10544: # end of not-a-package start tag
10545: 		}
10546: # the next is the end of "start tag"
10547: 	    }
10548: 	}
10549: 	my ($extension) = ($uri =~ /\.(\w+)$/);
10550: 	$extension = lc($extension);
10551: 	if ($extension eq 'htm') { $extension='html'; }
10552: 
10553: 	foreach my $key (keys(%packagetab)) {
10554: 	    #no specific packages #how's our extension
10555: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
10556: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
10557: 					 \%metathesekeys);
10558: 	}
10559: 
10560: 	if (!exists($metaentry{':packages'})
10561: 	    || $packagetab{"import_defaults&extension_$extension"}) {
10562: 	    foreach my $key (keys(%packagetab)) {
10563: 		#no specific packages well let's get default then
10564: 		if ($key!~/^default&/) { next; }
10565: 		&metadata_create_package_def($uri,$key,'default',
10566: 					     \%metathesekeys);
10567: 	    }
10568: 	}
10569: # are there custom rights to evaluate
10570: 	if ($metaentry{':copyright'} eq 'custom') {
10571: 
10572:     #
10573:     # Importing a rights file here
10574:     #
10575: 	    unless ($depthcount) {
10576: 		my $location=$metaentry{':customdistributionfile'};
10577: 		my $dir=$filename;
10578: 		$dir=~s|[^/]*$||;
10579: 		$location=&filelocation($dir,$location);
10580: 		my $rights_metadata =
10581: 		    &metadata($uri,'keys',$location,'_rights',
10582: 			      $depthcount+1);
10583: 		foreach my $rights (split(',',$rights_metadata)) {
10584: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10585: 		    $metathesekeys{$rights}=1;
10586: 		}
10587: 	    }
10588: 	}
10589: 	# uniqifiy package listing
10590: 	my %seen;
10591: 	my @uniq_packages =
10592: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10593: 	$metaentry{':packages'} = join(',',@uniq_packages);
10594: 
10595:         if ($importedparts) {
10596: # We had imported parts and need to rebuild partorder
10597:            $metaentry{':partorder'}='';
10598:            $metathesekeys{'partorder'}=1;
10599:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10600:                if ($origfileimportpartids[$index] eq 'part') {
10601: # original part, part of the problem
10602:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10603:                } else {
10604: # we have imported parts at this position
10605:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10606:                }
10607:            }
10608:            $metaentry{':partorder'}=~s/^\,//;
10609:         }
10610: 
10611: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
10612: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
10613: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
10614: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
10615: # this is the end of "was not already recently cached
10616:     }
10617:     return $metaentry{':'.$what};
10618: }
10619: 
10620: sub metadata_create_package_def {
10621:     my ($uri,$key,$package,$metathesekeys)=@_;
10622:     my ($pack,$name,$subp)=split(/\&/,$key);
10623:     if ($subp eq 'default') { next; }
10624:     
10625:     if (defined($metaentry{':packages'})) {
10626: 	$metaentry{':packages'}.=','.$package;
10627:     } else {
10628: 	$metaentry{':packages'}=$package;
10629:     }
10630:     my $value=$packagetab{$key};
10631:     my $unikey;
10632:     $unikey='parameter_0_'.$name;
10633:     $metaentry{':'.$unikey.'.part'}=0;
10634:     $$metathesekeys{$unikey}=1;
10635:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10636: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
10637:     }
10638:     if (defined($metaentry{':'.$unikey.'.default'})) {
10639: 	$metaentry{':'.$unikey}=
10640: 	    $metaentry{':'.$unikey.'.default'};
10641:     }
10642: }
10643: 
10644: sub metadata_generate_part0 {
10645:     my ($metadata,$metacache,$uri) = @_;
10646:     my %allnames;
10647:     foreach my $metakey (keys(%$metadata)) {
10648: 	if ($metakey=~/^parameter\_(.*)/) {
10649: 	  my $part=$$metacache{':'.$metakey.'.part'};
10650: 	  my $name=$$metacache{':'.$metakey.'.name'};
10651: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
10652: 	    $allnames{$name}=$part;
10653: 	  }
10654: 	}
10655:     }
10656:     foreach my $name (keys(%allnames)) {
10657:       $$metadata{"parameter_0_$name"}=1;
10658:       my $key=":parameter_0_$name";
10659:       $$metacache{"$key.part"}='0';
10660:       $$metacache{"$key.name"}=$name;
10661:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
10662: 					   $allnames{$name}.'_'.$name.
10663: 					   '.type'};
10664:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
10665: 			     '.display'};
10666:       my $expr='[Part: '.$allnames{$name}.']';
10667:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
10668:       $$metacache{"$key.display"}=$olddis;
10669:     }
10670: }
10671: 
10672: # ------------------------------------------------------ Devalidate title cache
10673: 
10674: sub devalidate_title_cache {
10675:     my ($url)=@_;
10676:     if (!$env{'request.course.id'}) { return; }
10677:     my $symb=&symbread($url);
10678:     if (!$symb) { return; }
10679:     my $key=$env{'request.course.id'}."\0".$symb;
10680:     &devalidate_cache_new('title',$key);
10681: }
10682: 
10683: # ------------------------------------------------- Get the title of a course
10684: 
10685: sub current_course_title {
10686:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10687: }
10688: # ------------------------------------------------- Get the title of a resource
10689: 
10690: sub gettitle {
10691:     my $urlsymb=shift;
10692:     my $symb=&symbread($urlsymb);
10693:     if ($symb) {
10694: 	my $key=$env{'request.course.id'}."\0".$symb;
10695: 	my ($result,$cached)=&is_cached_new('title',$key);
10696: 	if (defined($cached)) { 
10697: 	    return $result;
10698: 	}
10699: 	my ($map,$resid,$url)=&decode_symb($symb);
10700: 	my $title='';
10701: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10702: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10703: 	} else {
10704: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10705: 		    &GDBM_READER(),0640)) {
10706: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
10707: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
10708: 		untie(%bighash);
10709: 	    }
10710: 	}
10711: 	$title=~s/\&colon\;/\:/gs;
10712: 	if ($title) {
10713: # Remember both $symb and $title for dynamic metadata
10714:             $accesshash{$symb.'___crstitle'}=$title;
10715:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
10716: # Cache this title and then return it
10717: 	    return &do_cache_new('title',$key,$title,600);
10718: 	}
10719: 	$urlsymb=$url;
10720:     }
10721:     my $title=&metadata($urlsymb,'title');
10722:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
10723:     return $title;
10724: }
10725: 
10726: sub get_slot {
10727:     my ($which,$cnum,$cdom)=@_;
10728:     if (!$cnum || !$cdom) {
10729: 	(undef,my $courseid)=&whichuser();
10730: 	$cdom=$env{'course.'.$courseid.'.domain'};
10731: 	$cnum=$env{'course.'.$courseid.'.num'};
10732:     }
10733:     my $key=join("\0",'slots',$cdom,$cnum,$which);
10734:     my %slotinfo;
10735:     if (exists($remembered{$key})) {
10736: 	$slotinfo{$which} = $remembered{$key};
10737:     } else {
10738: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
10739: 	&Apache::lonhomework::showhash(%slotinfo);
10740: 	my ($tmp)=keys(%slotinfo);
10741: 	if ($tmp=~/^error:/) { return (); }
10742: 	$remembered{$key} = $slotinfo{$which};
10743:     }
10744:     if (ref($slotinfo{$which}) eq 'HASH') {
10745: 	return %{$slotinfo{$which}};
10746:     }
10747:     return $slotinfo{$which};
10748: }
10749: 
10750: sub get_reservable_slots {
10751:     my ($cnum,$cdom,$uname,$udom) = @_;
10752:     my $now = time;
10753:     my $reservable_info;
10754:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10755:     if (exists($remembered{$key})) {
10756:         $reservable_info = $remembered{$key};
10757:     } else {
10758:         my %resv;
10759:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10760:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10761:         $reservable_info = \%resv;
10762:         $remembered{$key} = $reservable_info;
10763:     }
10764:     return $reservable_info;
10765: }
10766: 
10767: sub get_course_slots {
10768:     my ($cnum,$cdom) = @_;
10769:     my $hashid=$cnum.':'.$cdom;
10770:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10771:     if (defined($cached)) {
10772:         if (ref($result) eq 'HASH') {
10773:             return %{$result};
10774:         }
10775:     } else {
10776:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10777:         my ($tmp) = keys(%slots);
10778:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10779:             &do_cache_new('allslots',$hashid,\%slots,600);
10780:             return %slots;
10781:         }
10782:     }
10783:     return;
10784: }
10785: 
10786: sub devalidate_slots_cache {
10787:     my ($cnum,$cdom)=@_;
10788:     my $hashid=$cnum.':'.$cdom;
10789:     &devalidate_cache_new('allslots',$hashid);
10790: }
10791: 
10792: sub get_coursechange {
10793:     my ($cdom,$cnum) = @_;
10794:     if ($cdom eq '' || $cnum eq '') {
10795:         return unless ($env{'request.course.id'});
10796:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10797:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10798:     }
10799:     my $hashid=$cdom.'_'.$cnum;
10800:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
10801:     if ((defined($cached)) && ($change ne '')) {
10802:         return $change;
10803:     } else {
10804:         my %crshash;
10805:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10806:         if ($crshash{'internal.contentchange'} eq '') {
10807:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
10808:             if ($change eq '') {
10809:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
10810:                 $change = $crshash{'internal.created'};
10811:             }
10812:         } else {
10813:             $change = $crshash{'internal.contentchange'};
10814:         }
10815:         my $cachetime = 600;
10816:         &do_cache_new('crschange',$hashid,$change,$cachetime);
10817:     }
10818:     return $change;
10819: }
10820: 
10821: sub devalidate_coursechange_cache {
10822:     my ($cnum,$cdom)=@_;
10823:     my $hashid=$cnum.':'.$cdom;
10824:     &devalidate_cache_new('crschange',$hashid);
10825: }
10826: 
10827: # ------------------------------------------------- Update symbolic store links
10828: 
10829: sub symblist {
10830:     my ($mapname,%newhash)=@_;
10831:     $mapname=&deversion(&declutter($mapname));
10832:     my %hash;
10833:     if (($env{'request.course.fn'}) && (%newhash)) {
10834:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10835:                       &GDBM_WRCREAT(),0640)) {
10836: 	    foreach my $url (keys(%newhash)) {
10837: 		next if ($url eq 'last_known'
10838: 			 && $env{'form.no_update_last_known'});
10839: 		$hash{declutter($url)}=&encode_symb($mapname,
10840: 						    $newhash{$url}->[1],
10841: 						    $newhash{$url}->[0]);
10842:             }
10843:             if (untie(%hash)) {
10844: 		return 'ok';
10845:             }
10846:         }
10847:     }
10848:     return 'error';
10849: }
10850: 
10851: # --------------------------------------------------------------- Verify a symb
10852: 
10853: sub symbverify {
10854:     my ($symb,$thisurl,$encstate)=@_;
10855:     my $thisfn=$thisurl;
10856:     $thisfn=&declutter($thisfn);
10857: # direct jump to resource in page or to a sequence - will construct own symbs
10858:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10859: # check URL part
10860:     my ($map,$resid,$url)=&decode_symb($symb);
10861: 
10862:     unless ($url eq $thisfn) { return 0; }
10863: 
10864:     $symb=&symbclean($symb);
10865:     $thisurl=&deversion($thisurl);
10866:     $thisfn=&deversion($thisfn);
10867: 
10868:     my %bighash;
10869:     my $okay=0;
10870: 
10871:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10872:                             &GDBM_READER(),0640)) {
10873:         my $noclutter;
10874:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10875:             $thisurl =~ s/\?.+$//;
10876:             if ($map =~ m{^uploaded/.+\.page$}) {
10877:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
10878:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
10879:                 $noclutter = 1;
10880:             }
10881:         }
10882:         my $ids;
10883:         if ($noclutter) {
10884:             $ids=$bighash{'ids_'.$thisurl};
10885:         } else {
10886:             $ids=$bighash{'ids_'.&clutter($thisurl)};
10887:         }
10888:         unless ($ids) {
10889:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
10890:             $ids=$bighash{$idkey};
10891:         }
10892:         if ($ids) {
10893: # ------------------------------------------------------------------- Has ID(s)
10894:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
10895:                 $symb =~ s/\?.+$//;
10896:             }
10897: 	    foreach my $id (split(/\,/,$ids)) {
10898: 	       my ($mapid,$resid)=split(/\./,$id);
10899:                if (
10900:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
10901:    eq $symb) {
10902:                    if (ref($encstate)) {
10903:                        $$encstate = $bighash{'encrypted_'.$id};
10904:                    }
10905:                    if (($env{'request.role.adv'}) ||
10906:                        ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
10907:                        ($thisurl eq '/adm/navmaps')) {
10908:                        $okay=1;
10909:                        last;
10910:                    }
10911:                }
10912:            }
10913:         }
10914: 	untie(%bighash);
10915:     }
10916:     return $okay;
10917: }
10918: 
10919: # --------------------------------------------------------------- Clean-up symb
10920: 
10921: sub symbclean {
10922:     my $symb=shift;
10923:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10924: # remove version from map
10925:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
10926: 
10927: # remove version from URL
10928:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
10929: 
10930: # remove wrapper
10931: 
10932:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
10933:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
10934:     return $symb;
10935: }
10936: 
10937: # ---------------------------------------------- Split symb to find map and url
10938: 
10939: sub encode_symb {
10940:     my ($map,$resid,$url)=@_;
10941:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
10942: }
10943: 
10944: sub decode_symb {
10945:     my $symb=shift;
10946:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10947:     my ($map,$resid,$url)=split(/___/,$symb);
10948:     return (&fixversion($map),$resid,&fixversion($url));
10949: }
10950: 
10951: sub fixversion {
10952:     my $fn=shift;
10953:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
10954:     my %bighash;
10955:     my $uri=&clutter($fn);
10956:     my $key=$env{'request.course.id'}.'_'.$uri;
10957: # is this cached?
10958:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
10959:     if (defined($cached)) { return $result; }
10960: # unfortunately not cached, or expired
10961:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10962: 	    &GDBM_READER(),0640)) {
10963:  	if ($bighash{'version_'.$uri}) {
10964:  	    my $version=$bighash{'version_'.$uri};
10965:  	    unless (($version eq 'mostrecent') || 
10966: 		    ($version==&getversion($uri))) {
10967:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
10968:  	    }
10969:  	}
10970:  	untie %bighash;
10971:     }
10972:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
10973: }
10974: 
10975: sub deversion {
10976:     my $url=shift;
10977:     $url=~s/\.\d+\.(\w+)$/\.$1/;
10978:     return $url;
10979: }
10980: 
10981: # ------------------------------------------------------ Return symb list entry
10982: 
10983: sub symbread {
10984:     my ($thisfn,$donotrecurse)=@_;
10985:     my $cache_str='request.symbread.cached.'.$thisfn;
10986:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
10987: # no filename provided? try from environment
10988:     unless ($thisfn) {
10989:         if ($env{'request.symb'}) {
10990:             return $env{$cache_str}=&symbclean($env{'request.symb'});
10991:         }
10992:         $thisfn=$env{'request.filename'};
10993:     }
10994:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
10995: # is that filename actually a symb? Verify, clean, and return
10996:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
10997: 	if (&symbverify($thisfn,$1)) {
10998: 	    return $env{$cache_str}=&symbclean($thisfn);
10999: 	}
11000:     }
11001:     $thisfn=declutter($thisfn);
11002:     my %hash;
11003:     my %bighash;
11004:     my $syval='';
11005:     if (($env{'request.course.fn'}) && ($thisfn)) {
11006:         my $targetfn = $thisfn;
11007:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
11008:             $targetfn = 'adm/wrapper/'.$thisfn;
11009:         }
11010: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
11011: 	    $targetfn=$1;
11012: 	}
11013:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
11014:                       &GDBM_READER(),0640)) {
11015: 	    $syval=$hash{$targetfn};
11016:             untie(%hash);
11017:         }
11018: # ---------------------------------------------------------- There was an entry
11019:         if ($syval) {
11020: 	    #unless ($syval=~/\_\d+$/) {
11021: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
11022: 		    #&appenv({'request.ambiguous' => $thisfn});
11023: 		    #return $env{$cache_str}='';
11024: 		#}    
11025: 		#$syval.=$1;
11026: 	    #}
11027:         } else {
11028: # ------------------------------------------------------- Was not in symb table
11029:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11030:                             &GDBM_READER(),0640)) {
11031: # ---------------------------------------------- Get ID(s) for current resource
11032:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
11033:               unless ($ids) { 
11034:                  $ids=$bighash{'ids_/'.$thisfn};
11035:               }
11036:               unless ($ids) {
11037: # alias?
11038: 		  $ids=$bighash{'mapalias_'.$thisfn};
11039:               }
11040:               if ($ids) {
11041: # ------------------------------------------------------------------- Has ID(s)
11042:                  my @possibilities=split(/\,/,$ids);
11043:                  if ($#possibilities==0) {
11044: # ----------------------------------------------- There is only one possibility
11045: 		     my ($mapid,$resid)=split(/\./,$ids);
11046: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
11047: 						    $resid,$thisfn);
11048:                  } elsif (!$donotrecurse) {
11049: # ------------------------------------------ There is more than one possibility
11050:                      my $realpossible=0;
11051:                      foreach my $id (@possibilities) {
11052: 			 my $file=$bighash{'src_'.$id};
11053:                          if (&allowed('bre',$file)) {
11054:          		    my ($mapid,$resid)=split(/\./,$id);
11055:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
11056: 				$realpossible++;
11057:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
11058: 						    $resid,$thisfn);
11059:                             }
11060: 			 }
11061:                      }
11062: 		     if ($realpossible!=1) { $syval=''; }
11063:                  } else {
11064:                      $syval='';
11065:                  }
11066: 	      }
11067:               untie(%bighash)
11068:            }
11069:         }
11070:         if ($syval) {
11071: 	    return $env{$cache_str}=$syval;
11072:         }
11073:     }
11074:     &appenv({'request.ambiguous' => $thisfn});
11075:     return $env{$cache_str}='';
11076: }
11077: 
11078: # ---------------------------------------------------------- Return random seed
11079: 
11080: sub numval {
11081:     my $txt=shift;
11082:     $txt=~tr/A-J/0-9/;
11083:     $txt=~tr/a-j/0-9/;
11084:     $txt=~tr/K-T/0-9/;
11085:     $txt=~tr/k-t/0-9/;
11086:     $txt=~tr/U-Z/0-5/;
11087:     $txt=~tr/u-z/0-5/;
11088:     $txt=~s/\D//g;
11089:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
11090:     return int($txt);
11091: }
11092: 
11093: sub numval2 {
11094:     my $txt=shift;
11095:     $txt=~tr/A-J/0-9/;
11096:     $txt=~tr/a-j/0-9/;
11097:     $txt=~tr/K-T/0-9/;
11098:     $txt=~tr/k-t/0-9/;
11099:     $txt=~tr/U-Z/0-5/;
11100:     $txt=~tr/u-z/0-5/;
11101:     $txt=~s/\D//g;
11102:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11103:     my $total;
11104:     foreach my $val (@txts) { $total+=$val; }
11105:     if ($_64bit) { if ($total > 2**32) { return -1; } }
11106:     return int($total);
11107: }
11108: 
11109: sub numval3 {
11110:     use integer;
11111:     my $txt=shift;
11112:     $txt=~tr/A-J/0-9/;
11113:     $txt=~tr/a-j/0-9/;
11114:     $txt=~tr/K-T/0-9/;
11115:     $txt=~tr/k-t/0-9/;
11116:     $txt=~tr/U-Z/0-5/;
11117:     $txt=~tr/u-z/0-5/;
11118:     $txt=~s/\D//g;
11119:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11120:     my $total;
11121:     foreach my $val (@txts) { $total+=$val; }
11122:     if ($_64bit) { $total=(($total<<32)>>32); }
11123:     return $total;
11124: }
11125: 
11126: sub digest {
11127:     my ($data)=@_;
11128:     my $digest=&Digest::MD5::md5($data);
11129:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
11130:     my ($e,$f);
11131:     {
11132:         use integer;
11133:         $e=($a+$b);
11134:         $f=($c+$d);
11135:         if ($_64bit) {
11136:             $e=(($e<<32)>>32);
11137:             $f=(($f<<32)>>32);
11138:         }
11139:     }
11140:     if (wantarray) {
11141: 	return ($e,$f);
11142:     } else {
11143: 	my $g;
11144: 	{
11145: 	    use integer;
11146: 	    $g=($e+$f);
11147: 	    if ($_64bit) {
11148: 		$g=(($g<<32)>>32);
11149: 	    }
11150: 	}
11151: 	return $g;
11152:     }
11153: }
11154: 
11155: sub latest_rnd_algorithm_id {
11156:     return '64bit5';
11157: }
11158: 
11159: sub get_rand_alg {
11160:     my ($courseid)=@_;
11161:     if (!$courseid) { $courseid=(&whichuser())[1]; }
11162:     if ($courseid) {
11163: 	return $env{"course.$courseid.rndseed"};
11164:     }
11165:     return &latest_rnd_algorithm_id();
11166: }
11167: 
11168: sub validCODE {
11169:     my ($CODE)=@_;
11170:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
11171:     return 0;
11172: }
11173: 
11174: sub getCODE {
11175:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
11176:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
11177: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
11178: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
11179: 	return $Apache::lonhomework::history{'resource.CODE'};
11180:     }
11181:     return undef;
11182: }
11183: #
11184: #  Determines the random seed for a specific context:
11185: #
11186: # parameters:
11187: #   symb      - in course context the symb for the seed.
11188: #   course_id - The course id of the form domain_coursenum.
11189: #   domain    - Domain for the user.
11190: #   course    - Course for the user.
11191: #   cenv      - environment of the course.
11192: #
11193: # NOTE:
11194: #   All parameters are picked out of the environment if missing
11195: #   or not defined.
11196: #   If a symb cannot be determined the current time is used instead.
11197: #
11198: #  For a given well defined symb, courside, domain, username,
11199: #  and course environment, the seed is reproducible.
11200: #
11201: sub rndseed {
11202:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
11203:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
11204:     if (!defined($symb)) {
11205: 	unless ($symb=$wsymb) { return time; }
11206:     }
11207:     if (!defined $courseid) { 
11208: 	$courseid=$wcourseid; 
11209:     }
11210:     if (!defined $domain) { $domain=$wdomain; }
11211:     if (!defined $username) { $username=$wusername }
11212: 
11213:     my $which;
11214:     if (defined($cenv->{'rndseed'})) {
11215: 	$which = $cenv->{'rndseed'};
11216:     } else {
11217: 	$which =&get_rand_alg($courseid);
11218:     }
11219:     if (defined(&getCODE())) {
11220: 	if ($which eq '64bit5') {
11221: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
11222: 	} elsif ($which eq '64bit4') {
11223: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
11224: 	} else {
11225: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
11226: 	}
11227:     } elsif ($which eq '64bit5') {
11228: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
11229:     } elsif ($which eq '64bit4') {
11230: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
11231:     } elsif ($which eq '64bit3') {
11232: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
11233:     } elsif ($which eq '64bit2') {
11234: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
11235:     } elsif ($which eq '64bit') {
11236: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
11237:     }
11238:     return &rndseed_32bit($symb,$courseid,$domain,$username);
11239: }
11240: 
11241: sub rndseed_32bit {
11242:     my ($symb,$courseid,$domain,$username)=@_;
11243:     {
11244: 	use integer;
11245: 	my $symbchck=unpack("%32C*",$symb) << 27;
11246: 	my $symbseed=numval($symb) << 22;
11247: 	my $namechck=unpack("%32C*",$username) << 17;
11248: 	my $nameseed=numval($username) << 12;
11249: 	my $domainseed=unpack("%32C*",$domain) << 7;
11250: 	my $courseseed=unpack("%32C*",$courseid);
11251: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
11252: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11253: 	#&logthis("rndseed :$num:$symb");
11254: 	if ($_64bit) { $num=(($num<<32)>>32); }
11255: 	return $num;
11256:     }
11257: }
11258: 
11259: sub rndseed_64bit {
11260:     my ($symb,$courseid,$domain,$username)=@_;
11261:     {
11262: 	use integer;
11263: 	my $symbchck=unpack("%32S*",$symb) << 21;
11264: 	my $symbseed=numval($symb) << 10;
11265: 	my $namechck=unpack("%32S*",$username);
11266: 	
11267: 	my $nameseed=numval($username) << 21;
11268: 	my $domainseed=unpack("%32S*",$domain) << 10;
11269: 	my $courseseed=unpack("%32S*",$courseid);
11270: 	
11271: 	my $num1=$symbchck+$symbseed+$namechck;
11272: 	my $num2=$nameseed+$domainseed+$courseseed;
11273: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11274: 	#&logthis("rndseed :$num:$symb");
11275: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11276: 	return "$num1,$num2";
11277:     }
11278: }
11279: 
11280: sub rndseed_64bit2 {
11281:     my ($symb,$courseid,$domain,$username)=@_;
11282:     {
11283: 	use integer;
11284: 	# strings need to be an even # of cahracters long, it it is odd the
11285:         # last characters gets thrown away
11286: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11287: 	my $symbseed=numval($symb) << 10;
11288: 	my $namechck=unpack("%32S*",$username.' ');
11289: 	
11290: 	my $nameseed=numval($username) << 21;
11291: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11292: 	my $courseseed=unpack("%32S*",$courseid.' ');
11293: 	
11294: 	my $num1=$symbchck+$symbseed+$namechck;
11295: 	my $num2=$nameseed+$domainseed+$courseseed;
11296: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11297: 	#&logthis("rndseed :$num:$symb");
11298: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11299: 	return "$num1,$num2";
11300:     }
11301: }
11302: 
11303: sub rndseed_64bit3 {
11304:     my ($symb,$courseid,$domain,$username)=@_;
11305:     {
11306: 	use integer;
11307: 	# strings need to be an even # of cahracters long, it it is odd the
11308:         # last characters gets thrown away
11309: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11310: 	my $symbseed=numval2($symb) << 10;
11311: 	my $namechck=unpack("%32S*",$username.' ');
11312: 	
11313: 	my $nameseed=numval2($username) << 21;
11314: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11315: 	my $courseseed=unpack("%32S*",$courseid.' ');
11316: 	
11317: 	my $num1=$symbchck+$symbseed+$namechck;
11318: 	my $num2=$nameseed+$domainseed+$courseseed;
11319: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11320: 	#&logthis("rndseed :$num1:$num2:$_64bit");
11321: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11322: 	
11323: 	return "$num1:$num2";
11324:     }
11325: }
11326: 
11327: sub rndseed_64bit4 {
11328:     my ($symb,$courseid,$domain,$username)=@_;
11329:     {
11330: 	use integer;
11331: 	# strings need to be an even # of cahracters long, it it is odd the
11332:         # last characters gets thrown away
11333: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
11334: 	my $symbseed=numval3($symb) << 10;
11335: 	my $namechck=unpack("%32S*",$username.' ');
11336: 	
11337: 	my $nameseed=numval3($username) << 21;
11338: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
11339: 	my $courseseed=unpack("%32S*",$courseid.' ');
11340: 	
11341: 	my $num1=$symbchck+$symbseed+$namechck;
11342: 	my $num2=$nameseed+$domainseed+$courseseed;
11343: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11344: 	#&logthis("rndseed :$num1:$num2:$_64bit");
11345: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11346: 	
11347: 	return "$num1:$num2";
11348:     }
11349: }
11350: 
11351: sub rndseed_64bit5 {
11352:     my ($symb,$courseid,$domain,$username)=@_;
11353:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11354:     return "$num1:$num2";
11355: }
11356: 
11357: sub rndseed_CODE_64bit {
11358:     my ($symb,$courseid,$domain,$username)=@_;
11359:     {
11360: 	use integer;
11361: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
11362: 	my $symbseed=numval2($symb);
11363: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11364: 	my $CODEseed=numval(&getCODE());
11365: 	my $courseseed=unpack("%32S*",$courseid.' ');
11366: 	my $num1=$symbseed+$CODEchck;
11367: 	my $num2=$CODEseed+$courseseed+$symbchck;
11368: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11369: 	#&logthis("rndseed :$num1:$num2:$symb");
11370: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
11371: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
11372: 	return "$num1:$num2";
11373:     }
11374: }
11375: 
11376: sub rndseed_CODE_64bit4 {
11377:     my ($symb,$courseid,$domain,$username)=@_;
11378:     {
11379: 	use integer;
11380: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
11381: 	my $symbseed=numval3($symb);
11382: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11383: 	my $CODEseed=numval3(&getCODE());
11384: 	my $courseseed=unpack("%32S*",$courseid.' ');
11385: 	my $num1=$symbseed+$CODEchck;
11386: 	my $num2=$CODEseed+$courseseed+$symbchck;
11387: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11388: 	#&logthis("rndseed :$num1:$num2:$symb");
11389: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
11390: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
11391: 	return "$num1:$num2";
11392:     }
11393: }
11394: 
11395: sub rndseed_CODE_64bit5 {
11396:     my ($symb,$courseid,$domain,$username)=@_;
11397:     my $code = &getCODE();
11398:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
11399:     return "$num1:$num2";
11400: }
11401: 
11402: sub setup_random_from_rndseed {
11403:     my ($rndseed)=@_;
11404:     if ($rndseed =~/([,:])/) {
11405: 	my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
11406:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
11407:             &Math::Random::random_set_seed_from_phrase($rndseed);
11408:         } else {
11409:             &Math::Random::random_set_seed($num1,$num2);
11410:         }
11411:     } else {
11412: 	&Math::Random::random_set_seed_from_phrase($rndseed);
11413:     }
11414: }
11415: 
11416: sub latest_receipt_algorithm_id {
11417:     return 'receipt3';
11418: }
11419: 
11420: sub recunique {
11421:     my $fucourseid=shift;
11422:     my $unique;
11423:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11424: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11425: 	$unique=$env{"course.$fucourseid.internal.encseed"};
11426:     } else {
11427: 	$unique=$perlvar{'lonReceipt'};
11428:     }
11429:     return unpack("%32C*",$unique);
11430: }
11431: 
11432: sub recprefix {
11433:     my $fucourseid=shift;
11434:     my $prefix;
11435:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11436: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11437: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
11438:     } else {
11439: 	$prefix=$perlvar{'lonHostID'};
11440:     }
11441:     return unpack("%32C*",$prefix);
11442: }
11443: 
11444: sub ireceipt {
11445:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
11446: 
11447:     my $return =&recprefix($fucourseid).'-';
11448: 
11449:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11450: 	$env{'request.state'} eq 'construct') {
11451: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11452: 	return $return;
11453:     }
11454: 
11455:     my $cuname=unpack("%32C*",$funame);
11456:     my $cudom=unpack("%32C*",$fudom);
11457:     my $cucourseid=unpack("%32C*",$fucourseid);
11458:     my $cusymb=unpack("%32C*",$fusymb);
11459:     my $cunique=&recunique($fucourseid);
11460:     my $cpart=unpack("%32S*",$part);
11461:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11462: 
11463: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
11464: 			       
11465: 	$return.= ($cunique%$cuname+
11466: 		   $cunique%$cudom+
11467: 		   $cusymb%$cuname+
11468: 		   $cusymb%$cudom+
11469: 		   $cucourseid%$cuname+
11470: 		   $cucourseid%$cudom+
11471: 		   $cpart%$cuname+
11472: 		   $cpart%$cudom);
11473:     } else {
11474: 	$return.= ($cunique%$cuname+
11475: 		   $cunique%$cudom+
11476: 		   $cusymb%$cuname+
11477: 		   $cusymb%$cudom+
11478: 		   $cucourseid%$cuname+
11479: 		   $cucourseid%$cudom);
11480:     }
11481:     return $return;
11482: }
11483: 
11484: sub receipt {
11485:     my ($part)=@_;
11486:     my ($symb,$courseid,$domain,$name) = &whichuser();
11487:     return &ireceipt($name,$domain,$courseid,$symb,$part);
11488: }
11489: 
11490: sub whichuser {
11491:     my ($passedsymb)=@_;
11492:     my ($symb,$courseid,$domain,$name,$publicuser);
11493:     if (defined($env{'form.grade_symb'})) {
11494: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11495: 	my $allowed=&allowed('vgr',$tmp_courseid);
11496: 	if (!$allowed &&
11497: 	    exists($env{'request.course.sec'}) &&
11498: 	    $env{'request.course.sec'} !~ /^\s*$/) {
11499: 	    $allowed=&allowed('vgr',$tmp_courseid.
11500: 			      '/'.$env{'request.course.sec'});
11501: 	}
11502: 	if ($allowed) {
11503: 	    ($symb)=&get_env_multiple('form.grade_symb');
11504: 	    $courseid=$tmp_courseid;
11505: 	    ($domain)=&get_env_multiple('form.grade_domain');
11506: 	    ($name)=&get_env_multiple('form.grade_username');
11507: 	    return ($symb,$courseid,$domain,$name,$publicuser);
11508: 	}
11509:     }
11510:     if (!$passedsymb) {
11511: 	$symb=&symbread();
11512:     } else {
11513: 	$symb=$passedsymb;
11514:     }
11515:     $courseid=$env{'request.course.id'};
11516:     $domain=$env{'user.domain'};
11517:     $name=$env{'user.name'};
11518:     if ($name eq 'public' && $domain eq 'public') {
11519: 	if (!defined($env{'form.username'})) {
11520: 	    $env{'form.username'}.=time.rand(10000000);
11521: 	}
11522: 	$name.=$env{'form.username'};
11523:     }
11524:     return ($symb,$courseid,$domain,$name,$publicuser);
11525: 
11526: }
11527: 
11528: # ------------------------------------------------------------ Serves up a file
11529: # returns either the contents of the file or 
11530: # -1 if the file doesn't exist
11531: #
11532: # if the target is a file that was uploaded via DOCS, 
11533: # a check will be made to see if a current copy exists on the local server,
11534: # if it does this will be served, otherwise a copy will be retrieved from
11535: # the home server for the course and stored in /home/httpd/html/userfiles on
11536: # the local server.   
11537: 
11538: sub getfile {
11539:     my ($file) = @_;
11540:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
11541:     &repcopy($file);
11542:     return &readfile($file);
11543: }
11544: 
11545: sub repcopy_userfile {
11546:     my ($file)=@_;
11547:     my $londocroot = $perlvar{'lonDocRoot'};
11548:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
11549:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
11550:     my ($cdom,$cnum,$filename) = 
11551: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
11552:     my $uri="/uploaded/$cdom/$cnum/$filename";
11553:     if (-e "$file") {
11554: # we already have a local copy, check it out
11555: 	my @fileinfo = stat($file);
11556: 	my $rtncode;
11557: 	my $info;
11558: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
11559: 	if ($lwpresp ne 'ok') {
11560: # there is no such file anymore, even though we had a local copy
11561: 	    if ($rtncode eq '404') {
11562: 		unlink($file);
11563: 	    }
11564: 	    return -1;
11565: 	}
11566: 	if ($info < $fileinfo[9]) {
11567: # nice, the file we have is up-to-date, just say okay
11568: 	    return 'ok';
11569: 	} else {
11570: # the file is outdated, get rid of it
11571: 	    unlink($file);
11572: 	}
11573:     }
11574: # one way or the other, at this point, we don't have the file
11575: # construct the correct path for the file
11576:     my @parts = ($cdom,$cnum); 
11577:     if ($filename =~ m|^(.+)/[^/]+$|) {
11578: 	push @parts, split(/\//,$1);
11579:     }
11580:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11581:     foreach my $part (@parts) {
11582: 	$path .= '/'.$part;
11583: 	if (!-e $path) {
11584: 	    mkdir($path,0770);
11585: 	}
11586:     }
11587: # now the path exists for sure
11588: # get a user agent
11589:     my $ua=new LWP::UserAgent;
11590:     my $transferfile=$file.'.in.transfer';
11591: # FIXME: this should flock
11592:     if (-e $transferfile) { return 'ok'; }
11593:     my $request;
11594:     $uri=~s/^\///;
11595:     my $homeserver = &homeserver($cnum,$cdom);
11596:     my $protocol = $protocol{$homeserver};
11597:     $protocol = 'http' if ($protocol ne 'https');
11598:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
11599:     my $response=$ua->request($request,$transferfile);
11600: # did it work?
11601:     if ($response->is_error()) {
11602: 	unlink($transferfile);
11603: 	&logthis("Userfile repcopy failed for $uri");
11604: 	return -1;
11605:     }
11606: # worked, rename the transfer file
11607:     rename($transferfile,$file);
11608:     return 'ok';
11609: }
11610: 
11611: sub tokenwrapper {
11612:     my $uri=shift;
11613:     $uri=~s|^https?\://([^/]+)||;
11614:     $uri=~s|^/||;
11615:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
11616:     my $token=$1;
11617:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
11618:     if ($udom && $uname && $file) {
11619: 	$file=~s|(\?\.*)*$||;
11620:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
11621:         my $homeserver = &homeserver($uname,$udom);
11622:         my $protocol = $protocol{$homeserver};
11623:         $protocol = 'http' if ($protocol ne 'https');
11624:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
11625:                (($uri=~/\?/)?'&':'?').'token='.$token.
11626:                                '&tokenissued='.$perlvar{'lonHostID'};
11627:     } else {
11628:         return '/adm/notfound.html';
11629:     }
11630: }
11631: 
11632: # call with reqtype HEAD: get last modification time
11633: # call with reqtype GET: get the file contents
11634: # Do not call this with reqtype GET for large files! It loads everything into memory
11635: #
11636: sub getuploaded {
11637:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11638:     $uri=~s/^\///;
11639:     my $homeserver = &homeserver($cnum,$cdom);
11640:     my $protocol = $protocol{$homeserver};
11641:     $protocol = 'http' if ($protocol ne 'https');
11642:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
11643:     my $ua=new LWP::UserAgent;
11644:     my $request=new HTTP::Request($reqtype,$uri);
11645:     my $response=$ua->request($request);
11646:     $$rtncode = $response->code;
11647:     if (! $response->is_success()) {
11648: 	return 'failed';
11649:     }      
11650:     if ($reqtype eq 'HEAD') {
11651: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
11652:     } elsif ($reqtype eq 'GET') {
11653: 	$$info = $response->content;
11654:     }
11655:     return 'ok';
11656: }
11657: 
11658: sub readfile {
11659:     my $file = shift;
11660:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
11661:     my $fh;
11662:     open($fh,"<$file");
11663:     my $a='';
11664:     while (my $line = <$fh>) { $a .= $line; }
11665:     return $a;
11666: }
11667: 
11668: sub filelocation {
11669:     my ($dir,$file) = @_;
11670:     my $location;
11671:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
11672: 
11673:     if ($file =~ m-^/adm/-) {
11674: 	$file=~s-^/adm/wrapper/-/-;
11675: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
11676:     }
11677: 
11678:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
11679:         $location = $file;
11680:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
11681:         my ($udom,$uname,$filename)=
11682:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
11683:         my $home=&homeserver($uname,$udom);
11684:         my $is_me=0;
11685:         my @ids=&current_machine_ids();
11686:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11687:         if ($is_me) {
11688:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
11689:         } else {
11690:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11691:   	      $udom.'/'.$uname.'/'.$filename;
11692:         }
11693:     } elsif ($file =~ m-^/adm/-) {
11694: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
11695:     } else {
11696:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
11697:         $file=~s:^/(res|priv)/:/:;
11698:         my $space=$1;
11699:         if ( !( $file =~ m:^/:) ) {
11700:             $location = $dir. '/'.$file;
11701:         } else {
11702:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
11703:         }
11704:     }
11705:     $location=~s://+:/:g; # remove duplicate /
11706:     while ($location=~m{/\.\./}) {
11707: 	if ($location =~ m{/[^/]+/\.\./}) {
11708: 	    $location=~ s{/[^/]+/\.\./}{/}g;
11709: 	} else {
11710: 	    $location=~ s{/\.\./}{/}g;
11711: 	}
11712:     } #remove dir/..
11713:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11714:     return $location;
11715: }
11716: 
11717: sub hreflocation {
11718:     my ($dir,$file)=@_;
11719:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
11720: 	$file=filelocation($dir,$file);
11721:     } elsif ($file=~m-^/adm/-) {
11722: 	$file=~s-^/adm/wrapper/-/-;
11723: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
11724:     }
11725:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11726: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11727:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
11728: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11729: 	        {/uploaded/$1/$2/}x;
11730:     }
11731:     if ($file=~ m{^/userfiles/}) {
11732: 	$file =~ s{^/userfiles/}{/uploaded/};
11733:     }
11734:     return $file;
11735: }
11736: 
11737: 
11738: 
11739: 
11740: 
11741: sub current_machine_domains {
11742:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
11743: }
11744: 
11745: sub machine_domains {
11746:     my ($hostname) = @_;
11747:     my @domains;
11748:     my %hostname = &all_hostnames();
11749:     while( my($id, $name) = each(%hostname)) {
11750: #	&logthis("-$id-$name-$hostname-");
11751: 	if ($hostname eq $name) {
11752: 	    push(@domains,&host_domain($id));
11753: 	}
11754:     }
11755:     return @domains;
11756: }
11757: 
11758: sub current_machine_ids {
11759:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
11760: }
11761: 
11762: sub machine_ids {
11763:     my ($hostname) = @_;
11764:     $hostname ||= &hostname($perlvar{'lonHostID'});
11765:     my @ids;
11766:     my %name_to_host = &all_names();
11767:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11768: 	return @{ $name_to_host{$hostname} };
11769:     }
11770:     return;
11771: }
11772: 
11773: sub additional_machine_domains {
11774:     my @domains;
11775:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
11776:     while( my $line = <$fh>) {
11777:         $line =~ s/\s//g;
11778:         push(@domains,$line);
11779:     }
11780:     return @domains;
11781: }
11782: 
11783: sub default_login_domain {
11784:     my $domain = $perlvar{'lonDefDomain'};
11785:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
11786:     foreach my $posdom (&current_machine_domains(),
11787:                         &additional_machine_domains()) {
11788:         if (lc($posdom) eq lc($testdomain)) {
11789:             $domain=$posdom;
11790:             last;
11791:         }
11792:     }
11793:     return $domain;
11794: }
11795: 
11796: # ------------------------------------------------------------- Declutters URLs
11797: 
11798: sub declutter {
11799:     my $thisfn=shift;
11800:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
11801:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
11802:         $thisfn=~s{^/home/httpd/html}{};
11803:     }
11804:     $thisfn=~s/^\///;
11805:     $thisfn=~s|^adm/wrapper/||;
11806:     $thisfn=~s|^adm/coursedocs/showdoc/||;
11807:     $thisfn=~s/^res\///;
11808:     $thisfn=~s/^priv\///;
11809:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
11810:         $thisfn=~s/\?.+$//;
11811:     }
11812:     return $thisfn;
11813: }
11814: 
11815: # ------------------------------------------------------------- Clutter up URLs
11816: 
11817: sub clutter {
11818:     my $thisfn='/'.&declutter(shift);
11819:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
11820: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
11821:        $thisfn='/res'.$thisfn; 
11822:     }
11823:     if ($thisfn !~m|^/adm|) {
11824: 	if ($thisfn =~ m|^/ext/|) {
11825: 	    $thisfn='/adm/wrapper'.$thisfn;
11826: 	} else {
11827: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
11828: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
11829: 	    if ($embstyle eq 'ssi'
11830: 		|| ($embstyle eq 'hdn')
11831: 		|| ($embstyle eq 'rat')
11832: 		|| ($embstyle eq 'prv')
11833: 		|| ($embstyle eq 'ign')) {
11834: 		#do nothing with these
11835: 	    } elsif (($embstyle eq 'img') 
11836: 		|| ($embstyle eq 'emb')
11837: 		|| ($embstyle eq 'wrp')) {
11838: 		$thisfn='/adm/wrapper'.$thisfn;
11839: 	    } elsif ($embstyle eq 'unk'
11840: 		     && $thisfn!~/\.(sequence|page)$/) {
11841: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
11842: 	    } else {
11843: #		&logthis("Got a blank emb style");
11844: 	    }
11845: 	}
11846:     }
11847:     return $thisfn;
11848: }
11849: 
11850: sub clutter_with_no_wrapper {
11851:     my $uri = &clutter(shift);
11852:     if ($uri =~ m-^/adm/-) {
11853: 	$uri =~ s-^/adm/wrapper/-/-;
11854: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
11855:     }
11856:     return $uri;
11857: }
11858: 
11859: sub freeze_escape {
11860:     my ($value)=@_;
11861:     if (ref($value)) {
11862: 	$value=&nfreeze($value);
11863: 	return '__FROZEN__'.&escape($value);
11864:     }
11865:     return &escape($value);
11866: }
11867: 
11868: 
11869: sub thaw_unescape {
11870:     my ($value)=@_;
11871:     if ($value =~ /^__FROZEN__/) {
11872: 	substr($value,0,10,undef);
11873: 	$value=&unescape($value);
11874: 	return &thaw($value);
11875:     }
11876:     return &unescape($value);
11877: }
11878: 
11879: sub correct_line_ends {
11880:     my ($result)=@_;
11881:     $$result =~s/\r\n/\n/mg;
11882:     $$result =~s/\r/\n/mg;
11883: }
11884: # ================================================================ Main Program
11885: 
11886: sub goodbye {
11887:    &logthis("Starting Shut down");
11888: #not converted to using infrastruture and probably shouldn't be
11889:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
11890: #converted
11891: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
11892:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
11893: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
11894: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
11895: #1.1 only
11896: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
11897: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
11898: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
11899: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
11900:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
11901:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
11902:    &logthis(sprintf("%-20s is %s",'hits',$hits));
11903:    &flushcourselogs();
11904:    &logthis("Shutting down");
11905: }
11906: 
11907: sub get_dns {
11908:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
11909:     if (!$ignore_cache) {
11910: 	my ($content,$cached)=
11911: 	    &Apache::lonnet::is_cached_new('dns',$url);
11912: 	if ($cached) {
11913: 	    &$func($content,$hashref);
11914: 	    return;
11915: 	}
11916:     }
11917: 
11918:     my %alldns;
11919:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11920:     foreach my $dns (<$config>) {
11921: 	next if ($dns !~ /^\^(\S*)/x);
11922:         my $line = $1;
11923:         my ($host,$protocol) = split(/:/,$line);
11924:         if ($protocol ne 'https') {
11925:             $protocol = 'http';
11926:         }
11927: 	$alldns{$host} = $protocol;
11928:     }
11929:     while (%alldns) {
11930: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
11931: 	my $ua=new LWP::UserAgent;
11932:         $ua->timeout(30);
11933: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
11934: 	my $response=$ua->request($request);
11935:         delete($alldns{$dns});
11936: 	next if ($response->is_error());
11937: 	my @content = split("\n",$response->content);
11938:         unless ($nocache) {
11939: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
11940:         }
11941: 	&$func(\@content,$hashref);
11942: 	return;
11943:     }
11944:     close($config);
11945:     my $which = (split('/',$url))[3];
11946:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
11947:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
11948:     my @content = <$config>;
11949:     &$func(\@content,$hashref);
11950:     return;
11951: }
11952: 
11953: # ------------------------------------------------------Get DNS checksums file
11954: sub parse_dns_checksums_tab {
11955:     my ($lines,$hashref) = @_;
11956:     my $lonhost = $perlvar{'lonHostID'};
11957:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
11958:     my $loncaparev = &get_server_loncaparev($machine_dom);
11959:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
11960:     my $webconfdir = '/etc/httpd/conf';
11961:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
11962:         $webconfdir = '/etc/apache2';
11963:     } elsif ($distro =~ /^sles(\d+)$/) {
11964:         if ($1 >= 10) {
11965:             $webconfdir = '/etc/apache2';
11966:         }
11967:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
11968:         if ($1 >= 10.0) {
11969:             $webconfdir = '/etc/apache2';
11970:         }
11971:     }
11972:     my ($release,$timestamp) = split(/\-/,$loncaparev);
11973:     my (%chksum,%revnum);
11974:     if (ref($lines) eq 'ARRAY') {
11975:         chomp(@{$lines});
11976:         my $version = shift(@{$lines});
11977:         if ($version eq $release) {
11978:             foreach my $line (@{$lines}) {
11979:                 my ($file,$version,$shasum) = split(/,/,$line);
11980:                 if ($file =~ m{^/etc/httpd/conf}) {
11981:                     if ($webconfdir eq '/etc/apache2') {
11982:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
11983:                     }
11984:                 }
11985:                 $chksum{$file} = $shasum;
11986:                 $revnum{$file} = $version;
11987:             }
11988:             if (ref($hashref) eq 'HASH') {
11989:                 %{$hashref} = (
11990:                                 sums     => \%chksum,
11991:                                 versions => \%revnum,
11992:                               );
11993:             }
11994:         }
11995:     }
11996:     return;
11997: }
11998: 
11999: sub fetch_dns_checksums {
12000:     my %checksums;
12001:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
12002:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
12003:     my ($release,$timestamp) = split(/\-/,$loncaparev);
12004:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
12005:              \%checksums);
12006:     return \%checksums;
12007: }
12008: 
12009: # ------------------------------------------------------------ Read domain file
12010: {
12011:     my $loaded;
12012:     my %domain;
12013: 
12014:     sub parse_domain_tab {
12015: 	my ($lines) = @_;
12016: 	foreach my $line (@$lines) {
12017: 	    next if ($line =~ /^(\#|\s*$ )/x);
12018: 
12019: 	    chomp($line);
12020: 	    my ($name,@elements) = split(/:/,$line,9);
12021: 	    my %this_domain;
12022: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
12023: 			       'lang_def', 'city', 'longi', 'lati',
12024: 			       'primary') {
12025: 		$this_domain{$field} = shift(@elements);
12026: 	    }
12027: 	    $domain{$name} = \%this_domain;
12028: 	}
12029:     }
12030: 
12031:     sub reset_domain_info {
12032: 	undef($loaded);
12033: 	undef(%domain);
12034:     }
12035: 
12036:     sub load_domain_tab {
12037: 	my ($ignore_cache) = @_;
12038: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
12039: 	my $fh;
12040: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
12041: 	    my @lines = <$fh>;
12042: 	    &parse_domain_tab(\@lines);
12043: 	}
12044: 	close($fh);
12045: 	$loaded = 1;
12046:     }
12047: 
12048:     sub domain {
12049: 	&load_domain_tab() if (!$loaded);
12050: 
12051: 	my ($name,$what) = @_;
12052: 	return if ( !exists($domain{$name}) );
12053: 
12054: 	if (!$what) {
12055: 	    return $domain{$name}{'description'};
12056: 	}
12057: 	return $domain{$name}{$what};
12058:     }
12059: 
12060:     sub domain_info {
12061:         &load_domain_tab() if (!$loaded);
12062:         return %domain;
12063:     }
12064: 
12065: }
12066: 
12067: 
12068: # ------------------------------------------------------------- Read hosts file
12069: {
12070:     my %hostname;
12071:     my %hostdom;
12072:     my %libserv;
12073:     my $loaded;
12074:     my %name_to_host;
12075:     my %internetdom;
12076:     my %LC_dns_serv;
12077: 
12078:     sub parse_hosts_tab {
12079: 	my ($file) = @_;
12080: 	foreach my $configline (@$file) {
12081: 	    next if ($configline =~ /^(\#|\s*$ )/x);
12082:             chomp($configline);
12083: 	    if ($configline =~ /^\^/) {
12084:                 if ($configline =~ /^\^([\w.\-]+)/) {
12085:                     $LC_dns_serv{$1} = 1;
12086:                 }
12087:                 next;
12088:             }
12089: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
12090: 	    $name=~s/\s//g;
12091: 	    if ($id && $domain && $role && $name) {
12092: 		$hostname{$id}=$name;
12093: 		push(@{$name_to_host{$name}}, $id);
12094: 		$hostdom{$id}=$domain;
12095: 		if ($role eq 'library') { $libserv{$id}=$name; }
12096:                 if (defined($protocol)) {
12097:                     if ($protocol eq 'https') {
12098:                         $protocol{$id} = $protocol;
12099:                     } else {
12100:                         $protocol{$id} = 'http'; 
12101:                     }
12102:                 } else {
12103:                     $protocol{$id} = 'http';
12104:                 }
12105:                 if (defined($intdom)) {
12106:                     $internetdom{$id} = $intdom;
12107:                 }
12108: 	    }
12109: 	}
12110:     }
12111:     
12112:     sub reset_hosts_info {
12113: 	&purge_remembered();
12114: 	&reset_domain_info();
12115: 	&reset_hosts_ip_info();
12116: 	undef(%name_to_host);
12117: 	undef(%hostname);
12118: 	undef(%hostdom);
12119: 	undef(%libserv);
12120: 	undef($loaded);
12121:     }
12122: 
12123:     sub load_hosts_tab {
12124: 	my ($ignore_cache) = @_;
12125: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
12126: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12127: 	my @config = <$config>;
12128: 	&parse_hosts_tab(\@config);
12129: 	close($config);
12130: 	$loaded=1;
12131:     }
12132: 
12133:     sub hostname {
12134: 	&load_hosts_tab() if (!$loaded);
12135: 
12136: 	my ($lonid) = @_;
12137: 	return $hostname{$lonid};
12138:     }
12139: 
12140:     sub all_hostnames {
12141: 	&load_hosts_tab() if (!$loaded);
12142: 
12143: 	return %hostname;
12144:     }
12145: 
12146:     sub all_names {
12147: 	&load_hosts_tab() if (!$loaded);
12148: 
12149: 	return %name_to_host;
12150:     }
12151: 
12152:     sub all_host_domain {
12153:         &load_hosts_tab() if (!$loaded);
12154:         return %hostdom;
12155:     }
12156: 
12157:     sub is_library {
12158: 	&load_hosts_tab() if (!$loaded);
12159: 
12160: 	return exists($libserv{$_[0]});
12161:     }
12162: 
12163:     sub all_library {
12164: 	&load_hosts_tab() if (!$loaded);
12165: 
12166: 	return %libserv;
12167:     }
12168: 
12169:     sub unique_library {
12170: 	#2x reverse removes all hostnames that appear more than once
12171:         my %unique = reverse &all_library();
12172:         return reverse %unique;
12173:     }
12174: 
12175:     sub get_servers {
12176: 	&load_hosts_tab() if (!$loaded);
12177: 
12178: 	my ($domain,$type) = @_;
12179: 	my %possible_hosts = ($type eq 'library') ? %libserv
12180: 	                                          : %hostname;
12181: 	my %result;
12182: 	if (ref($domain) eq 'ARRAY') {
12183: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
12184: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
12185: 		    $result{$host} = $hostname;
12186: 		}
12187: 	    }
12188: 	} else {
12189: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
12190: 		if ($hostdom{$host} eq $domain) {
12191: 		    $result{$host} = $hostname;
12192: 		}
12193: 	    }
12194: 	}
12195: 	return %result;
12196:     }
12197: 
12198:     sub get_unique_servers {
12199:         my %unique = reverse &get_servers(@_);
12200: 	return reverse %unique;
12201:     }
12202: 
12203:     sub host_domain {
12204: 	&load_hosts_tab() if (!$loaded);
12205: 
12206: 	my ($lonid) = @_;
12207: 	return $hostdom{$lonid};
12208:     }
12209: 
12210:     sub all_domains {
12211: 	&load_hosts_tab() if (!$loaded);
12212: 
12213: 	my %seen;
12214: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
12215: 	return @uniq;
12216:     }
12217: 
12218:     sub internet_dom {
12219:         &load_hosts_tab() if (!$loaded);
12220: 
12221:         my ($lonid) = @_;
12222:         return $internetdom{$lonid};
12223:     }
12224: 
12225:     sub is_LC_dns {
12226:         &load_hosts_tab() if (!$loaded);
12227: 
12228:         my ($hostname) = @_;
12229:         return exists($LC_dns_serv{$hostname});
12230:     }
12231: 
12232: }
12233: 
12234: { 
12235:     my %iphost;
12236:     my %name_to_ip;
12237:     my %lonid_to_ip;
12238: 
12239:     sub get_hosts_from_ip {
12240: 	my ($ip) = @_;
12241: 	my %iphosts = &get_iphost();
12242: 	if (ref($iphosts{$ip})) {
12243: 	    return @{$iphosts{$ip}};
12244: 	}
12245: 	return;
12246:     }
12247:     
12248:     sub reset_hosts_ip_info {
12249: 	undef(%iphost);
12250: 	undef(%name_to_ip);
12251: 	undef(%lonid_to_ip);
12252:     }
12253: 
12254:     sub get_host_ip {
12255: 	my ($lonid) = @_;
12256: 	if (exists($lonid_to_ip{$lonid})) {
12257: 	    return $lonid_to_ip{$lonid};
12258: 	}
12259: 	my $name=&hostname($lonid);
12260:    	my $ip = gethostbyname($name);
12261: 	return if (!$ip || length($ip) ne 4);
12262: 	$ip=inet_ntoa($ip);
12263: 	$name_to_ip{$name}   = $ip;
12264: 	$lonid_to_ip{$lonid} = $ip;
12265: 	return $ip;
12266:     }
12267:     
12268:     sub get_iphost {
12269: 	my ($ignore_cache) = @_;
12270: 
12271: 	if (!$ignore_cache) {
12272: 	    if (%iphost) {
12273: 		return %iphost;
12274: 	    }
12275: 	    my ($ip_info,$cached)=
12276: 		&Apache::lonnet::is_cached_new('iphost','iphost');
12277: 	    if ($cached) {
12278: 		%iphost      = %{$ip_info->[0]};
12279: 		%name_to_ip  = %{$ip_info->[1]};
12280: 		%lonid_to_ip = %{$ip_info->[2]};
12281: 		return %iphost;
12282: 	    }
12283: 	}
12284: 
12285: 	# get yesterday's info for fallback
12286: 	my %old_name_to_ip;
12287: 	my ($ip_info,$cached)=
12288: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
12289: 	if ($cached) {
12290: 	    %old_name_to_ip = %{$ip_info->[1]};
12291: 	}
12292: 
12293: 	my %name_to_host = &all_names();
12294: 	foreach my $name (keys(%name_to_host)) {
12295: 	    my $ip;
12296: 	    if (!exists($name_to_ip{$name})) {
12297: 		$ip = gethostbyname($name);
12298: 		if (!$ip || length($ip) ne 4) {
12299: 		    if (defined($old_name_to_ip{$name})) {
12300: 			$ip = $old_name_to_ip{$name};
12301: 			&logthis("Can't find $name defaulting to old $ip");
12302: 		    } else {
12303: 			&logthis("Name $name no IP found");
12304: 			next;
12305: 		    }
12306: 		} else {
12307: 		    $ip=inet_ntoa($ip);
12308: 		}
12309: 		$name_to_ip{$name} = $ip;
12310: 	    } else {
12311: 		$ip = $name_to_ip{$name};
12312: 	    }
12313: 	    foreach my $id (@{ $name_to_host{$name} }) {
12314: 		$lonid_to_ip{$id} = $ip;
12315: 	    }
12316: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
12317: 	}
12318: 	&do_cache_new('iphost','iphost',
12319: 		      [\%iphost,\%name_to_ip,\%lonid_to_ip],
12320: 		      48*60*60);
12321: 
12322: 	return %iphost;
12323:     }
12324: 
12325:     #
12326:     #  Given a DNS returns the loncapa host name for that DNS 
12327:     # 
12328:     sub host_from_dns {
12329:         my ($dns) = @_;
12330:         my @hosts;
12331:         my $ip;
12332: 
12333:         if (exists($name_to_ip{$dns})) {
12334:             $ip = $name_to_ip{$dns};
12335:         }
12336:         if (!$ip) {
12337:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12338:             if (length($ip) == 4) { 
12339: 	        $ip   = &IO::Socket::inet_ntoa($ip);
12340:             }
12341:         }
12342:         if ($ip) {
12343: 	    @hosts = get_hosts_from_ip($ip);
12344: 	    return $hosts[0];
12345:         }
12346:         return undef;
12347:     }
12348: 
12349:     sub get_internet_names {
12350:         my ($lonid) = @_;
12351:         return if ($lonid eq '');
12352:         my ($idnref,$cached)=
12353:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
12354:         if ($cached) {
12355:             return $idnref;
12356:         }
12357:         my $ip = &get_host_ip($lonid);
12358:         my @hosts = &get_hosts_from_ip($ip);
12359:         my %iphost = &get_iphost();
12360:         my (@idns,%seen);
12361:         foreach my $id (@hosts) {
12362:             my $dom = &host_domain($id);
12363:             my $prim_id = &domain($dom,'primary');
12364:             my $prim_ip = &get_host_ip($prim_id);
12365:             next if ($seen{$prim_ip});
12366:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12367:                 foreach my $id (@{$iphost{$prim_ip}}) {
12368:                     my $intdom = &internet_dom($id);
12369:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
12370:                         push(@idns,$intdom);
12371:                     }
12372:                 }
12373:             }
12374:             $seen{$prim_ip} = 1;
12375:         }
12376:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
12377:     }
12378: 
12379: }
12380: 
12381: sub all_loncaparevs {
12382:     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);
12383: }
12384: 
12385: # ------------------------------------------------------- Read loncaparev table
12386: {
12387:     sub load_loncaparevs {
12388:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12389:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12390:                 while (my $configline=<$config>) {
12391:                     chomp($configline);
12392:                     my ($hostid,$loncaparev)=split(/:/,$configline);
12393:                     $loncaparevs{$hostid}=$loncaparev;
12394:                 }
12395:                 close($config);
12396:             }
12397:         }
12398:     }
12399: }
12400: 
12401: # ----------------------------------------------------- Read serverhostID table
12402: {
12403:     sub load_serverhomeIDs {
12404:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12405:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12406:                 while (my $configline=<$config>) {
12407:                     chomp($configline);
12408:                     my ($name,$id)=split(/:/,$configline);
12409:                     $serverhomeIDs{$name}=$id;
12410:                 }
12411:                 close($config);
12412:             }
12413:         }
12414:     }
12415: }
12416: 
12417: 
12418: BEGIN {
12419: 
12420: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12421:     unless ($readit) {
12422: {
12423:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12424:     %perlvar = (%perlvar,%{$configvars});
12425: }
12426: 
12427: 
12428: # ------------------------------------------------------ Read spare server file
12429: {
12430:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
12431: 
12432:     while (my $configline=<$config>) {
12433:        chomp($configline);
12434:        if ($configline) {
12435: 	   my ($host,$type) = split(':',$configline,2);
12436: 	   if (!defined($type) || $type eq '') { $type = 'default' };
12437: 	   push(@{ $spareid{$type} }, $host);
12438:        }
12439:     }
12440:     close($config);
12441: }
12442: # ------------------------------------------------------------ Read permissions
12443: {
12444:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
12445: 
12446:     while (my $configline=<$config>) {
12447: 	chomp($configline);
12448: 	if ($configline) {
12449: 	    my ($role,$perm)=split(/ /,$configline);
12450: 	    if ($perm ne '') { $pr{$role}=$perm; }
12451: 	}
12452:     }
12453:     close($config);
12454: }
12455: 
12456: # -------------------------------------------- Read plain texts for permissions
12457: {
12458:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
12459: 
12460:     while (my $configline=<$config>) {
12461: 	chomp($configline);
12462: 	if ($configline) {
12463: 	    my ($short,@plain)=split(/:/,$configline);
12464:             %{$prp{$short}} = ();
12465: 	    if (@plain > 0) {
12466:                 $prp{$short}{'std'} = $plain[0];
12467:                 for (my $i=1; $i<@plain; $i++) {
12468:                     $prp{$short}{'alt'.$i} = $plain[$i];  
12469:                 }
12470:             }
12471: 	}
12472:     }
12473:     close($config);
12474: }
12475: 
12476: # ---------------------------------------------------------- Read package table
12477: {
12478:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
12479: 
12480:     while (my $configline=<$config>) {
12481: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
12482: 	chomp($configline);
12483: 	my ($short,$plain)=split(/:/,$configline);
12484: 	my ($pack,$name)=split(/\&/,$short);
12485: 	if ($plain ne '') {
12486: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
12487: 	    $packagetab{$short}=$plain; 
12488: 	}
12489:     }
12490:     close($config);
12491: }
12492: 
12493: # --------------------------------------------------------- Read loncaparev table
12494: 
12495: &load_loncaparevs();
12496: 
12497: # ------------------------------------------------------- Read serverhostID table
12498: 
12499: &load_serverhomeIDs();
12500: 
12501: # ---------------------------------------------------------- Read releaseslist XML
12502: {
12503:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12504:     if (-e $file) {
12505:         my $parser = HTML::LCParser->new($file);
12506:         while (my $token = $parser->get_token()) {
12507:             if ($token->[0] eq 'S') {
12508:                 my $item = $token->[1];
12509:                 my $name = $token->[2]{'name'};
12510:                 my $value = $token->[2]{'value'};
12511:                 if ($item ne '' && $name ne '' && $value ne '') {
12512:                     my $release = $parser->get_text();
12513:                     $release =~ s/(^\s*|\s*$ )//gx;
12514:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
12515:                 }
12516:             }
12517:         }
12518:     }
12519: }
12520: 
12521: # ---------------------------------------------------------- Read managers table
12522: {
12523:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12524:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12525:             while (my $configline=<$config>) {
12526:                 chomp($configline);
12527:                 next if ($configline =~ /^\#/);
12528:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12529:                     $managerstab{$configline} = 1;
12530:                 }
12531:             }
12532:             close($config);
12533:         }
12534:     }
12535: }
12536: 
12537: # ------------- set up temporary directory
12538: {
12539:     $tmpdir = LONCAPA::tempdir();
12540: 
12541: }
12542: 
12543: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
12544: 				'compress_threshold'=> 20_000,
12545:  			        });
12546: 
12547: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
12548: $dumpcount=0;
12549: $locknum=0;
12550: 
12551: &logtouch();
12552: &logthis('<font color="yellow">INFO: Read configuration</font>');
12553: $readit=1;
12554:     {
12555: 	use integer;
12556: 	my $test=(2**32)+1;
12557: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
12558: 	&logthis(" Detected 64bit platform ($_64bit)");
12559:     }
12560: }
12561: }
12562: 
12563: 1;
12564: __END__
12565: 
12566: =pod
12567: 
12568: =head1 NAME
12569: 
12570: Apache::lonnet - Subroutines to ask questions about things in the network.
12571: 
12572: =head1 SYNOPSIS
12573: 
12574: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
12575: 
12576:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12577: 
12578: Common parameters:
12579: 
12580: =over 4
12581: 
12582: =item *
12583: 
12584: $uname : an internal username (if $cname expecting a course Id specifically)
12585: 
12586: =item *
12587: 
12588: $udom : a domain (if $cdom expecting a course's domain specifically)
12589: 
12590: =item *
12591: 
12592: $symb : a resource instance identifier
12593: 
12594: =item *
12595: 
12596: $namespace : the name of a .db file that contains the data needed or
12597: being set.
12598: 
12599: =back
12600: 
12601: =head1 OVERVIEW
12602: 
12603: lonnet provides subroutines which interact with the
12604: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12605: about classes, users, and resources.
12606: 
12607: For many of these objects you can also use this to store data about
12608: them or modify them in various ways.
12609: 
12610: =head2 Symbs
12611: 
12612: To identify a specific instance of a resource, LON-CAPA uses symbols
12613: or "symbs"X<symb>. These identifiers are built from the URL of the
12614: map, the resource number of the resource in the map, and the URL of
12615: the resource itself. The latter is somewhat redundant, but might help
12616: if maps change.
12617: 
12618: An example is
12619: 
12620:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12621: 
12622: The respective map entry is
12623: 
12624:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
12625:   title="Problem 2">
12626:  </resource>
12627: 
12628: Symbs are used by the random number generator, as well as to store and
12629: restore data specific to a certain instance of for example a problem.
12630: 
12631: =head2 Storing And Retrieving Data
12632: 
12633: X<store()>X<cstore()>X<restore()>Three of the most important functions
12634: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12635: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12636: is is the non-critical message twin of cstore. These functions are for
12637: handlers to store a perl hash to a user's permanent data space in an
12638: easy manner, and to retrieve it again on another call. It is expected
12639: that a handler would use this once at the beginning to retrieve data,
12640: and then again once at the end to send only the new data back.
12641: 
12642: The data is stored in the user's data directory on the user's
12643: homeserver under the ID of the course.
12644: 
12645: The hash that is returned by restore will have all of the previous
12646: value for all of the elements of the hash.
12647: 
12648: Example:
12649: 
12650:  #creating a hash
12651:  my %hash;
12652:  $hash{'foo'}='bar';
12653: 
12654:  #storing it
12655:  &Apache::lonnet::cstore(\%hash);
12656: 
12657:  #changing a value
12658:  $hash{'foo'}='notbar';
12659: 
12660:  #adding a new value
12661:  $hash{'bar'}='foo';
12662:  &Apache::lonnet::cstore(\%hash);
12663: 
12664:  #retrieving the hash
12665:  my %history=&Apache::lonnet::restore();
12666: 
12667:  #print the hash
12668:  foreach my $key (sort(keys(%history))) {
12669:    print("\%history{$key} = $history{$key}");
12670:  }
12671: 
12672: Will print out:
12673: 
12674:  %history{1:foo} = bar
12675:  %history{1:keys} = foo:timestamp
12676:  %history{1:timestamp} = 990455579
12677:  %history{2:bar} = foo
12678:  %history{2:foo} = notbar
12679:  %history{2:keys} = foo:bar:timestamp
12680:  %history{2:timestamp} = 990455580
12681:  %history{bar} = foo
12682:  %history{foo} = notbar
12683:  %history{timestamp} = 990455580
12684:  %history{version} = 2
12685: 
12686: Note that the special hash entries C<keys>, C<version> and
12687: C<timestamp> were added to the hash. C<version> will be equal to the
12688: total number of versions of the data that have been stored. The
12689: C<timestamp> attribute will be the UNIX time the hash was
12690: stored. C<keys> is available in every historical section to list which
12691: keys were added or changed at a specific historical revision of a
12692: hash.
12693: 
12694: B<Warning>: do not store the hash that restore returns directly. This
12695: will cause a mess since it will restore the historical keys as if the
12696: were new keys. I.E. 1:foo will become 1:1:foo etc.
12697: 
12698: Calling convention:
12699: 
12700:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
12701:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname);
12702: 
12703: For more detailed information, see lonnet specific documentation.
12704: 
12705: =head1 RETURN MESSAGES
12706: 
12707: =over 4
12708: 
12709: =item * B<con_lost>: unable to contact remote host
12710: 
12711: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12712: when the connection is brought back up
12713: 
12714: =item * B<con_failed>: unable to contact remote host and unable to save message
12715: for later delivery
12716: 
12717: =item * B<error:>: an error a occurred, a description of the error follows the :
12718: 
12719: =item * B<no_such_host>: unable to fund a host associated with the user/domain
12720: that was requested
12721: 
12722: =back
12723: 
12724: =head1 PUBLIC SUBROUTINES
12725: 
12726: =head2 Session Environment Functions
12727: 
12728: =over 4
12729: 
12730: =item * 
12731: X<appenv()>
12732: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
12733: the user envirnoment file, and will be restored for each access this
12734: user makes during this session, also modifies the %env for the current
12735: process. Optional rolesarrayref - if defined contains a reference to an array
12736: of roles which are exempt from the restriction on modifying user.role entries 
12737: in the user's environment.db and in %env.    
12738: 
12739: =item *
12740: X<delenv()>
12741: B<delenv($delthis,$regexp)>: removes all items from the session
12742: environment file that begin with $delthis. If the 
12743: optional second arg - $regexp - is true, $delthis is treated as a 
12744: regular expression, otherwise \Q$delthis\E is used. 
12745: The values are also deleted from the current processes %env.
12746: 
12747: =item * get_env_multiple($name) 
12748: 
12749: gets $name from the %env hash, it seemlessly handles the cases where multiple
12750: values may be defined and end up as an array ref.
12751: 
12752: returns an array of values
12753: 
12754: =back
12755: 
12756: =head2 User Information
12757: 
12758: =over 4
12759: 
12760: =item *
12761: X<queryauthenticate()>
12762: B<queryauthenticate($uname,$udom)>: try to determine user's current 
12763: authentication scheme
12764: 
12765: =item *
12766: X<authenticate()>
12767: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
12768: authenticate user from domain's lib servers (first use the current
12769: one). C<$upass> should be the users password.
12770: $checkdefauth is optional (value is 1 if a check should be made to
12771:    authenticate user using default authentication method, and allow
12772:    account creation if username does not have account in the domain).
12773: $clientcancheckhost is optional (value is 1 if checking whether the
12774:    server can host will occur on the client side in lonauth.pm).   
12775: 
12776: =item *
12777: X<homeserver()>
12778: B<homeserver($uname,$udom)>: find the server which has
12779: the user's directory and files (there must be only one), this caches
12780: the answer, and also caches if there is a borken connection.
12781: 
12782: =item *
12783: X<idget()>
12784: B<idget($udom,@ids)>: find the usernames behind a list of IDs
12785: (IDs are a unique resource in a domain, there must be only 1 ID per
12786: username, and only 1 username per ID in a specific domain) (returns
12787: hash: id=>name,id=>name)
12788: 
12789: =item *
12790: X<idrget()>
12791: B<idrget($udom,@unames)>: find the IDs behind a list of
12792: usernames (returns hash: name=>id,name=>id)
12793: 
12794: =item *
12795: X<idput()>
12796: B<idput($udom,%ids)>: store away a list of names and associated IDs
12797: 
12798: =item *
12799: X<rolesinit()>
12800: B<rolesinit($udom,$username)>: get user privileges.
12801: returns user role, first access and timer interval hashes
12802: 
12803: =item *
12804: X<privileged()>
12805: B<privileged($username,$domain)>: returns a true if user has a
12806: privileged and active role (i.e. su or dc), false otherwise.
12807: 
12808: =item *
12809: X<getsection()>
12810: B<getsection($udom,$uname,$cname)>: finds the section of student in the
12811: course $cname, return section name/number or '' for "not in course"
12812: and '-1' for "no section"
12813: 
12814: =item *
12815: X<userenvironment()>
12816: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
12817: passed in @what from the requested user's environment, returns a hash
12818: 
12819: =item * 
12820: X<userlog_query()>
12821: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
12822: activity.log file. %filters defines filters applied when parsing the
12823: log file. These can be start or end timestamps, or the type of action
12824: - log to look for Login or Logout events, check for Checkin or
12825: Checkout, role for role selection. The response is in the form
12826: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
12827: escaped strings of the action recorded in the activity.log file.
12828: 
12829: =back
12830: 
12831: =head2 User Roles
12832: 
12833: =over 4
12834: 
12835: =item *
12836: 
12837: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
12838:  F: full access
12839:  U,I,K: authentication modes (cxx only)
12840:  '': forbidden
12841:  1: user needs to choose course
12842:  2: browse allowed
12843:  A: passphrase authentication needed
12844: 
12845: =item *
12846: 
12847: constructaccess($url,$setpriv) : check for access to construction space URL
12848: 
12849: See if the owner domain and name in the URL match those in the
12850: expected environment.  If so, return three element list
12851: ($ownername,$ownerdomain,$ownerhome).
12852: 
12853: Otherwise return the null string.
12854: 
12855: If second argument 'setpriv' is true, it assigns the privileges,
12856: and returns the same three element list, unless the owner has
12857: blocked "ad hoc" Domain Coordinator access to the Author Space,
12858: in which case the null string is returned.
12859: 
12860: =item *
12861: 
12862: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
12863: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
12864: and course level
12865: 
12866: =item *
12867: 
12868: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
12869: (rolesplain.tab); plain text explanation of a user role term.
12870: $type is Course (default) or Community.
12871: If $forcedefault evaluates to true, text returned will be default 
12872: text for $type. Otherwise, if this is a course, the text returned 
12873: will be a custom name for the role (if defined in the course's 
12874: environment).  If no custom name is defined the default is returned.
12875:    
12876: =item *
12877: 
12878: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
12879: All arguments are optional. Returns a hash of a roles, either for
12880: co-author/assistant author roles for a user's Construction Space
12881: (default), or if $context is 'userroles', roles for the user himself,
12882: In the hash, keys are set to colon-separated $uname,$udom,$role, and
12883: (optionally) if $withsec is true, a fourth colon-separated item - $section.
12884: For each key, value is set to colon-separated start and end times for
12885: the role.  If no username and domain are specified, will default to
12886: current user/domain. Types, roles, and roledoms are references to arrays
12887: of role statuses (active, future or previous), roles 
12888: (e.g., cc,in, st etc.) and domains of the roles which can be used
12889: to restrict the list of roles reported. If no array ref is 
12890: provided for types, will default to return only active roles.
12891: 
12892: =item *
12893: 
12894: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
12895: user: $uname:$udom has a role in the course: $cdom_$cnum.
12896: 
12897: Additional optional arguments are: $type (if role checking is to be restricted
12898: to certain user status types -- previous (expired roles), active (currently
12899: available roles) or future (roles available in the future), and
12900: $hideprivileged -- if true will not report course roles for users who
12901: have active Domain Coordinator role in course's domain or in additional
12902: domains (specified in 'Domains to check for privileged users' in course
12903: environment -- set via:  Course Settings -> Classlists and staff listing).
12904: 
12905: =item *
12906: 
12907: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
12908: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
12909: $possdomains and $possroles are optional array refs -- to domains to check and
12910: roles to check.  If $possdomains is not specified, a dump will be done of the
12911: users' roles.db to check for a dc or su role in any domain. This can be
12912: time consuming if &privileged is called repeatedly (e.g., when displaying a
12913: classlist), so in such cases, supplying a $possdomains array is preferred, as
12914: this then allows &privileged_by_domain() to be used, which caches the identity
12915: of privileged users, eliminating the need for repeated calls to &dump().
12916: 
12917: =item *
12918: 
12919: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
12920: where the outer hash keys are domains specified in the $possdomains array ref,
12921: next inner hash keys are privileged roles specified in the $roles array ref,
12922: and the innermost hash contains key = value pairs for username:domain = end:start
12923: for active or future "privileged" users with that role in that domain. To avoid
12924: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
12925: innerhash are cached using priv_$role and $dom as the identifiers.
12926: 
12927: =back
12928: 
12929: =head2 User Modification
12930: 
12931: =over 4
12932: 
12933: =item *
12934: 
12935: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
12936: user for the level given by URL.  Optional start and end dates (leave empty
12937: string or zero for "no date")
12938: 
12939: =item *
12940: 
12941: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
12942: change a users, password, possible return values are: ok,
12943: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
12944: refused
12945: 
12946: =item *
12947: 
12948: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
12949: 
12950: =item *
12951: 
12952: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
12953:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
12954: 
12955: will update user information (firstname,middlename,lastname,generation,
12956: permanentemail), and if forceid is true, student/employee ID also.
12957: A user's institutional affiliation(s) can also be updated.
12958: User information fields will not be overwritten with empty entries 
12959: unless the field is included in the $candelete array reference.
12960: This array is included when a single user is modified via "Manage Users",
12961: or when Autoupdate.pl is run by cron in a domain.
12962: 
12963: =item *
12964: 
12965: modifystudent
12966: 
12967: modify a student's enrollment and identification information.
12968: The course id is resolved based on the current user's environment.  
12969: This means the invoking user must be a course coordinator or otherwise
12970: associated with a course.
12971: 
12972: This call is essentially a wrapper for lonnet::modifyuser and
12973: lonnet::modify_student_enrollment
12974: 
12975: Inputs: 
12976: 
12977: =over 4
12978: 
12979: =item B<$udom> Student's loncapa domain
12980: 
12981: =item B<$uname> Student's loncapa login name
12982: 
12983: =item B<$uid> Student/Employee ID
12984: 
12985: =item B<$umode> Student's authentication mode
12986: 
12987: =item B<$upass> Student's password
12988: 
12989: =item B<$first> Student's first name
12990: 
12991: =item B<$middle> Student's middle name
12992: 
12993: =item B<$last> Student's last name
12994: 
12995: =item B<$gene> Student's generation
12996: 
12997: =item B<$usec> Student's section in course
12998: 
12999: =item B<$end> Unix time of the roles expiration
13000: 
13001: =item B<$start> Unix time of the roles start date
13002: 
13003: =item B<$forceid> If defined, allow $uid to be changed
13004: 
13005: =item B<$desiredhome> server to use as home server for student
13006: 
13007: =item B<$email> Student's permanent e-mail address
13008: 
13009: =item B<$type> Type of enrollment (auto or manual)
13010: 
13011: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
13012: 
13013: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
13014: 
13015: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
13016: 
13017: =item B<$context> role change context (shown in User Management Logs display in a course)
13018: 
13019: =item B<$inststatus> institutional status of user - : separated string of escaped status types
13020: 
13021: =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.
13022: 
13023: =back
13024: 
13025: =item *
13026: 
13027: modify_student_enrollment
13028: 
13029: Change a student's enrollment status in a class.  The environment variable
13030: 'role.request.course' must be defined for this function to proceed.
13031: 
13032: Inputs:
13033: 
13034: =over 4
13035: 
13036: =item $udom, student's domain
13037: 
13038: =item $uname, student's name
13039: 
13040: =item $uid, student's user id
13041: 
13042: =item $first, student's first name
13043: 
13044: =item $middle
13045: 
13046: =item $last
13047: 
13048: =item $gene
13049: 
13050: =item $usec
13051: 
13052: =item $end
13053: 
13054: =item $start
13055: 
13056: =item $type
13057: 
13058: =item $locktype
13059: 
13060: =item $cid
13061: 
13062: =item $selfenroll
13063: 
13064: =item $context
13065: 
13066: =item $credits, number of credits student will earn from this class
13067: 
13068: =back
13069: 
13070: 
13071: =item *
13072: 
13073: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
13074: custom role; give a custom role to a user for the level given by URL.  Specify
13075: name and domain of role author, and role name
13076: 
13077: =item *
13078: 
13079: revokerole($udom,$uname,$url,$role) : revoke a role for url
13080: 
13081: =item *
13082: 
13083: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
13084: 
13085: =back
13086: 
13087: =head2 Course Infomation
13088: 
13089: =over 4
13090: 
13091: =item *
13092: 
13093: coursedescription($courseid,$options) : returns a hash of information about the
13094: specified course id, including all environment settings for the
13095: course, the description of the course will be in the hash under the
13096: key 'description'
13097: 
13098: $options is an optional parameter that if supplied is a hash reference that controls
13099: what how this function works.  It has the following key/values:
13100: 
13101: =over 4
13102: 
13103: =item freshen_cache
13104: 
13105: If defined, and the environment cache for the course is valid, it is 
13106: returned in the returned hash.
13107: 
13108: =item one_time
13109: 
13110: If defined, the last cache time is set to _now_
13111: 
13112: =item user
13113: 
13114: If defined, the supplied username is used instead of the current user.
13115: 
13116: 
13117: =back
13118: 
13119: =item *
13120: 
13121: resdata($name,$domain,$type,@which) : request for current parameter
13122: setting for a specific $type, where $type is either 'course' or 'user',
13123: @what should be a list of parameters to ask about. This routine caches
13124: answers for 10 minutes.
13125: 
13126: =item *
13127: 
13128: get_courseresdata($courseid, $domain) : dump the entire course resource
13129: data base, returning a hash that is keyed by the resource name and has
13130: values that are the resource value.  I believe that the timestamps and
13131: versions are also returned.
13132: 
13133: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
13134: supplemental content area. This routine caches the number of files for
13135: 10 minutes.
13136: 
13137: =back
13138: 
13139: =head2 Course Modification
13140: 
13141: =over 4
13142: 
13143: =item *
13144: 
13145: writecoursepref($courseid,%prefs) : write preferences (environment
13146: database) for a course
13147: 
13148: =item *
13149: 
13150: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
13151: 
13152: =item *
13153: 
13154: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
13155: 
13156: =item *
13157: 
13158: is_course($courseid), is_course($cdom, $cnum)
13159: 
13160: Accepts either a combined $courseid (in the form of domain_courseid) or the
13161: two component version $cdom, $cnum. It checks if the specified course exists.
13162: 
13163: Returns:
13164:     undef if the course doesn't exist, otherwise
13165:     in scalar context the combined courseid.
13166:     in list context the two components of the course identifier, domain and 
13167:     courseid.    
13168: 
13169: =back
13170: 
13171: =head2 Resource Subroutines
13172: 
13173: =over 4
13174: 
13175: =item *
13176: 
13177: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
13178: 
13179: =item *
13180: 
13181: repcopy($filename) : subscribes to the requested file, and attempts to
13182: replicate from the owning library server, Might return
13183: 'unavailable', 'not_found', 'forbidden', 'ok', or
13184: 'bad_request', also attempts to grab the metadata for the
13185: resource. Expects the local filesystem pathname
13186: (/home/httpd/html/res/....)
13187: 
13188: =back
13189: 
13190: =head2 Resource Information
13191: 
13192: =over 4
13193: 
13194: =item *
13195: 
13196: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
13197: and returns the value of a variety of different possible values,
13198: $varname should be a request string, and the other parameters can be
13199: used to specify who and what one is asking about. Ordinarily, $cid 
13200: does not need to be specified, as it is retrived from 
13201: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
13202: within lonuserstate::loadmap() when initializing a course, before
13203: $env{'request.course.id'} has been set, so it needs to be provided
13204: in that one case.
13205: 
13206: Possible values for $varname are environment.lastname (or other item
13207: from the envirnment hash), user.name (or someother aspect about the
13208: user), resource.0.maxtries (or some other part and parameter of a
13209: resource)
13210: 
13211: =item *
13212: 
13213: directcondval($number) : get current value of a condition; reads from a state
13214: string
13215: 
13216: =item *
13217: 
13218: condval($condidx) : value of condition index based on state
13219: 
13220: =item *
13221: 
13222: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
13223: resource's metadata, $what should be either a specific key, or either
13224: 'keys' (to get a list of possible keys) or 'packages' to get a list of
13225: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
13226: 
13227: this function automatically caches all requests
13228: 
13229: =item *
13230: 
13231: metadata_query($query,$custom,$customshow) : make a metadata query against the
13232: network of library servers; returns file handle of where SQL and regex results
13233: will be stored for query
13234: 
13235: =item *
13236: 
13237: symbread($filename) : return symbolic list entry (filename argument optional);
13238: returns the data handle
13239: 
13240: =item *
13241: 
13242: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
13243: and is a possible symb for the URL in $thisfn, and if is an encrypted
13244: resource that the user accessed using /enc/ returns a 1 on success, 0
13245: on failure, user must be in a course, as it assumes the existence of
13246: the course initial hash, and uses $env('request.course.id'}.  The third
13247: arg is an optional reference to a scalar.  If this arg is passed in the
13248: call to symbverify, it will be set to 1 if the symb has been set to be 
13249: encrypted; otherwise it will be null.
13250: 
13251: =item *
13252: 
13253: symbclean($symb) : removes versions numbers from a symb, returns the
13254: cleaned symb
13255: 
13256: =item *
13257: 
13258: is_on_map($uri) : checks if the $uri is somewhere on the current
13259: course map, user must be in a course for it to work.
13260: 
13261: =item *
13262: 
13263: numval($salt) : return random seed value (addend for rndseed)
13264: 
13265: =item *
13266: 
13267: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13268: a random seed, all arguments are optional, if they aren't sent it uses the
13269: environment to derive them. Note: if symb isn't sent and it can't get one
13270: from &symbread it will use the current time as its return value
13271: 
13272: =item *
13273: 
13274: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13275: unfakeable, receipt
13276: 
13277: =item *
13278: 
13279: receipt() : API to ireceipt working off of env values; given out to users
13280: 
13281: =item *
13282: 
13283: countacc($url) : count the number of accesses to a given URL
13284: 
13285: =item *
13286: 
13287: 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
13288: 
13289: =item *
13290: 
13291: 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)
13292: 
13293: =item *
13294: 
13295: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
13296: 
13297: =item *
13298: 
13299: devalidate($symb) : devalidate temporary spreadsheet calculations,
13300: forcing spreadsheet to reevaluate the resource scores next time.
13301: 
13302: =item *
13303: 
13304: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13305: when viewing in course context.
13306: 
13307:  input: six args -- filename (decluttered), course number, course domain,
13308:                     url, symb (if registered) and group (if this is a
13309:                     group item -- e.g., bulletin board, group page etc.).
13310: 
13311:  output: array of five scalars --
13312:          $cfile -- url for file editing if editable on current server
13313:          $home -- homeserver of resource (i.e., for author if published,
13314:                                           or course if uploaded.).
13315:          $switchserver --  1 if server switch will be needed.
13316:          $forceedit -- 1 if icon/link should be to go to edit mode
13317:          $forceview -- 1 if icon/link should be to go to view mode
13318: 
13319: =item *
13320: 
13321: is_course_upload($file,$cnum,$cdom)
13322: 
13323: Used in course context to determine if current file was uploaded to
13324: the course (i.e., would be found in /userfiles/docs on the course's
13325: homeserver.
13326: 
13327:   input: 3 args -- filename (decluttered), course number and course domain.
13328:   output: boolean -- 1 if file was uploaded.
13329: 
13330: =back
13331: 
13332: =head2 Storing/Retreiving Data
13333: 
13334: =over 4
13335: 
13336: =item *
13337: 
13338: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
13339: for this url; hashref needs to be given and should be a \%hashname; the
13340: remaining args aren't required and if they aren't passed or are '' they will
13341: be derived from the env
13342: 
13343: =item *
13344: 
13345: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
13346: uses critical subroutine
13347: 
13348: =item *
13349: 
13350: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13351: all args are optional
13352: 
13353: =item *
13354: 
13355: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
13356: dumps the complete (or key matching regexp) namespace into a hash
13357: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13358: normally &store()ed into
13359: 
13360: $range should be either an integer '100' (give me the first 100
13361:                                            matching records)
13362:               or be  two integers sperated by a - with no spaces
13363:                  '30-50' (give me the 30th through the 50th matching
13364:                           records)
13365: 
13366: 
13367: =item *
13368: 
13369: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
13370: replaces a &store() version of data with a replacement set of data
13371: for a particular resource in a namespace passed in the $storehash hash 
13372: reference. If $tolog is true, the transaction is logged in the courselog
13373: with an action=PUTSTORE.
13374: 
13375: =item *
13376: 
13377: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13378: works very similar to store/cstore, but all data is stored in a
13379: temporary location and can be reset using tmpreset, $storehash should
13380: be a hash reference, returns nothing on success
13381: 
13382: =item *
13383: 
13384: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13385: similar to restore, but all data is stored in a temporary location and
13386: can be reset using tmpreset. Returns a hash of values on success,
13387: error string otherwise.
13388: 
13389: =item *
13390: 
13391: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13392: deltes all keys for $symb form the temporary storage hash.
13393: 
13394: =item *
13395: 
13396: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13397: reference filled in from namesp ($udom and $uname are optional)
13398: 
13399: =item *
13400: 
13401: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13402: namesp ($udom and $uname are optional)
13403: 
13404: =item *
13405: 
13406: dump($namespace,$udom,$uname,$regexp,$range) : 
13407: dumps the complete (or key matching regexp) namespace into a hash
13408: ($udom, $uname, $regexp, $range are optional)
13409: 
13410: $range should be either an integer '100' (give me the first 100
13411:                                            matching records)
13412:               or be  two integers sperated by a - with no spaces
13413:                  '30-50' (give me the 30th through the 50th matching
13414:                           records)
13415: =item *
13416: 
13417: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13418: $store can be a scalar, an array reference, or if the amount to be 
13419: incremented is > 1, a hash reference.
13420: 
13421: ($udom and $uname are optional)
13422: 
13423: =item *
13424: 
13425: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13426: ($udom and $uname are optional)
13427: 
13428: =item *
13429: 
13430: cput($namespace,$storehash,$udom,$uname) : critical put
13431: ($udom and $uname are optional)
13432: 
13433: =item *
13434: 
13435: newput($namespace,$storehash,$udom,$uname) :
13436: 
13437: Attempts to store the items in the $storehash, but only if they don't
13438: currently exist, if this succeeds you can be certain that you have 
13439: successfully created a new key value pair in the $namespace db.
13440: 
13441: 
13442: Args:
13443:  $namespace: name of database to store values to
13444:  $storehash: hashref to store to the db
13445:  $udom: (optional) domain of user containing the db
13446:  $uname: (optional) name of user caontaining the db
13447: 
13448: Returns:
13449:  'ok' -> succeeded in storing all keys of $storehash
13450:  'key_exists: <key>' -> failed to anything out of $storehash, as at
13451:                         least <key> already existed in the db (other
13452:                         requested keys may also already exist)
13453:  'error: <msg>' -> unable to tie the DB or other error occurred
13454:  'con_lost' -> unable to contact request server
13455:  'refused' -> action was not allowed by remote machine
13456: 
13457: 
13458: =item *
13459: 
13460: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13461: reference filled in from namesp (encrypts the return communication)
13462: ($udom and $uname are optional)
13463: 
13464: =item *
13465: 
13466: log($udom,$name,$home,$message) : write to permanent log for user; use
13467: critical subroutine
13468: 
13469: =item *
13470: 
13471: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13472: array reference filled in from namespace found in domain level on either
13473: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
13474: 
13475: =item *
13476: 
13477: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
13478: domain level either on specified domain server ($uhome) or primary domain 
13479: server ($udom and $uhome are optional)
13480: 
13481: =item * 
13482: 
13483: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
13484: for: authentication, language, quotas, timezone, date locale, and portal URL in
13485: the target domain.
13486: 
13487: May also include additional key => value pairs for the following groups:
13488: 
13489: =over
13490: 
13491: =item
13492: disk quotas (MB allocated by default to portfolios and authoring spaces).
13493: 
13494: =over
13495: 
13496: =item defaultquota, authorquota
13497: 
13498: =back
13499: 
13500: =item
13501: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
13502: portfolio for users).
13503: 
13504: =over
13505: 
13506: =item
13507: aboutme, blog, webdav, portfolio
13508: 
13509: =back
13510: 
13511: =item
13512: requestcourses: ability to request courses, and how requests are processed.
13513: 
13514: =over
13515: 
13516: =item
13517: official, unofficial, community, textbook
13518: 
13519: =back
13520: 
13521: =item
13522: inststatus: types of institutional affiliation, and order in which they are displayed.
13523: 
13524: =over
13525: 
13526: =item
13527: inststatustypes, inststatusorder, inststatusguest
13528: 
13529: =back
13530: 
13531: =item
13532: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
13533: for course's uploaded content.
13534: 
13535: =over
13536: 
13537: =item
13538: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, communityquota, textbookquota
13539: 
13540: =back
13541: 
13542: =item
13543: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
13544: on your servers.
13545: 
13546: =over
13547: 
13548: =item
13549: remotesessions, hostedsessions
13550: 
13551: =back
13552: 
13553: =back
13554: 
13555: In cases where a domain coordinator has never used the "Set Domain Configuration"
13556: utility to create a configuration.db file on a domain's primary library server
13557: only the following domain defaults: auth_def, auth_arg_def, lang_def
13558: -- corresponding values are authentication type (internal, krb4, krb5,
13559: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
13560: will be available. Values are retrieved from cache (if current), unless the
13561: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
13562: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
13563: 
13564: Typical usage:
13565: 
13566: %domdefaults = &get_domain_defaults($target_domain);
13567: 
13568: =back
13569: 
13570: =head2 Network Status Functions
13571: 
13572: =over 4
13573: 
13574: =item *
13575: 
13576: dirlist() : return directory list based on URI (first arg).
13577: 
13578: Inputs: 1 required, 5 optional.
13579: 
13580: =over
13581: 
13582: =item 
13583: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13584: 
13585: =item
13586: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
13587: 
13588: =item
13589: $username -  username of user/course to be listed. Extracted from $uri if absent. 
13590: 
13591: =item
13592: $getpropath - boolean: 1 if prepend path using &propath(). 
13593: 
13594: =item
13595: $getuserdir - boolean: 1 if prepend path for "userfiles".
13596: 
13597: =item 
13598: $alternateRoot - path to prepend in place of path from $uri.
13599: 
13600: =back
13601: 
13602: Returns: Array of up to two items.
13603: 
13604: =over
13605: 
13606: a reference to an array of files/subdirectories
13607: 
13608: =over
13609: 
13610: Each element in the array of files/subdirectories is a & separated list of
13611: item name and the result of running stat on the item.  If dirlist was requested
13612: for a file instead of a directory, the item name will be ''. For a directory 
13613: listing, if the item is a metadata file, the element will end &N&M 
13614: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13615: default copyright set (1).  
13616: 
13617: =back
13618: 
13619: a scalar containing error condition (if encountered).
13620: 
13621: =over
13622: 
13623: =item 
13624: no_host (no homeserver identified for $username:$domain).
13625: 
13626: =item 
13627: no_such_host (server contacted for listing not identified as valid host).
13628: 
13629: =item 
13630: con_lost (connection to remote server failed).
13631: 
13632: =item 
13633: refused (invalid $username:$domain received on lond side).
13634: 
13635: =item 
13636: no_such_dir (directory at specified path on lond side does not exist). 
13637: 
13638: =item 
13639: empty (directory at specified path on lond side is empty).
13640: 
13641: =over
13642: 
13643: This is currently not encountered because the &ls3, &ls2, 
13644: &ls (_handler) routines on the lond side do not filter out
13645: . and .. from a directory listing. 
13646: 
13647: =back
13648: 
13649: =back
13650: 
13651: =back
13652: 
13653: =item *
13654: 
13655: spareserver() : find server with least workload from spare.tab
13656: 
13657: 
13658: =item *
13659: 
13660: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13661: if there is no corresponding loncapa host.
13662: 
13663: =back
13664: 
13665: 
13666: =head2 Apache Request
13667: 
13668: =over 4
13669: 
13670: =item *
13671: 
13672: ssi($url,%hash) : server side include, does a complete request cycle on url to
13673: localhost, posts hash
13674: 
13675: =back
13676: 
13677: =head2 Data to String to Data
13678: 
13679: =over 4
13680: 
13681: =item *
13682: 
13683: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13684: and '&' separators, supports elements that are arrayrefs and hashrefs
13685: 
13686: =item *
13687: 
13688: hashref2str($hashref) : convert a hashref into a string complete with
13689: escaping and '=' and '&' separators, supports elements that are
13690: arrayrefs and hashrefs
13691: 
13692: =item *
13693: 
13694: arrayref2str($arrayref) : convert an arrayref into a string complete
13695: with escaping and '&' separators, supports elements that are arrayrefs
13696: and hashrefs
13697: 
13698: =item *
13699: 
13700: str2hash($string) : convert string to hash using unescaping and
13701: splitting on '=' and '&', supports elements that are arrayrefs and
13702: hashrefs
13703: 
13704: =item *
13705: 
13706: str2array($string) : convert string to hash using unescaping and
13707: splitting on '&', supports elements that are arrayrefs and hashrefs
13708: 
13709: =back
13710: 
13711: =head2 Logging Routines
13712: 
13713: 
13714: These routines allow one to make log messages in the lonnet.log and
13715: lonnet.perm logfiles.
13716: 
13717: =over 4
13718: 
13719: =item *
13720: 
13721: logtouch() : make sure the logfile, lonnet.log, exists
13722: 
13723: =item *
13724: 
13725: logthis() : append message to the normal lonnet.log file, it gets
13726: preiodically rolled over and deleted.
13727: 
13728: =item *
13729: 
13730: logperm() : append a permanent message to lonnet.perm.log, this log
13731: file never gets deleted by any automated portion of the system, only
13732: messages of critical importance should go in here.
13733: 
13734: 
13735: =back
13736: 
13737: =head2 General File Helper Routines
13738: 
13739: =over 4
13740: 
13741: =item *
13742: 
13743: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
13744: (a) files in /uploaded
13745:   (i) If a local copy of the file exists - 
13746:       compares modification date of local copy with last-modified date for 
13747:       definitive version stored on home server for course. If local copy is 
13748:       stale, requests a new version from the home server and stores it. 
13749:       If the original has been removed from the home server, then local copy 
13750:       is unlinked.
13751:   (ii) If local copy does not exist -
13752:       requests the file from the home server and stores it. 
13753:   
13754:   If $caller is 'uploadrep':  
13755:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
13756:     for request for files originally uploaded via DOCS. 
13757:      - returns 'ok' if fresh local copy now available, -1 otherwise.
13758:   
13759:   Otherwise:
13760:      This indicates a call from the content generation phase of the request.
13761:      -  returns the entire contents of the file or -1.
13762:      
13763: (b) files in /res
13764:    - returns the entire contents of a file or -1; 
13765:    it properly subscribes to and replicates the file if neccessary.
13766: 
13767: 
13768: =item *
13769: 
13770: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
13771:                   reference
13772: 
13773: returns either a stat() list of data about the file or an empty list
13774: if the file doesn't exist or couldn't find out about it (connection
13775: problems or user unknown)
13776: 
13777: =item *
13778: 
13779: filelocation($dir,$file) : returns file system location of a file
13780: based on URI; meant to be "fairly clean" absolute reference, $dir is a
13781: directory that relative $file lookups are to looked in ($dir of /a/dir
13782: and a file of ../bob will become /a/bob)
13783: 
13784: =item *
13785: 
13786: hreflocation($dir,$file) : returns file system location or a URL; same as
13787: filelocation except for hrefs
13788: 
13789: =item *
13790: 
13791: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
13792: also removes beginning /home/httpd/html unless /priv/ follows it.
13793: 
13794: =back
13795: 
13796: =head2 Usererfile file routines (/uploaded*)
13797: 
13798: =over 4
13799: 
13800: =item *
13801: 
13802: userfileupload(): main rotine for putting a file in a user or course's
13803:                   filespace, arguments are,
13804: 
13805:  formname - required - this is the name of the element in $env where the
13806:            filename, and the contents of the file to create/modifed exist
13807:            the filename is in $env{'form.'.$formname.'.filename'} and the
13808:            contents of the file is located in $env{'form.'.$formname}
13809:  context - if coursedoc, store the file in the course of the active role
13810:              of the current user; 
13811:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
13812:            if 'canceloverwrite': delete file in tmp/overwrites directory
13813:  subdir - required - subdirectory to put the file in under ../userfiles/
13814:          if undefined, it will be placed in "unknown"
13815: 
13816:  (This routine calls clean_filename() to remove any dangerous
13817:  characters from the filename, and then calls finuserfileupload() to
13818:  complete the transaction)
13819: 
13820:  returns either the url of the uploaded file (/uploaded/....) if successful
13821:  and /adm/notfound.html if unsuccessful
13822: 
13823: =item *
13824: 
13825: clean_filename(): routine for cleaing a filename up for storage in
13826:                  userfile space, argument is:
13827: 
13828:  filename - proposed filename
13829: 
13830: returns: the new clean filename
13831: 
13832: =item *
13833: 
13834: finishuserfileupload(): routine that creates and sends the file to
13835: userspace, probably shouldn't be called directly
13836: 
13837:   docuname: username or courseid of destination for the file
13838:   docudom: domain of user/course of destination for the file
13839:   formname: same as for userfileupload()
13840:   fname: filename (including subdirectories) for the file
13841:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
13842:   allfiles: reference to hash used to store objects found by parser
13843:   codebase: reference to hash used for codebases of java objects found by parser
13844:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
13845:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
13846:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
13847:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
13848:   context: if 'overwrite', will move the uploaded file from its temporary location to
13849:             userfiles to facilitate overwriting a previously uploaded file with same name.
13850:   mimetype: reference to scalar to accommodate mime type determined
13851:             from File::MMagic if $parser = parse.
13852: 
13853:  returns either the url of the uploaded file (/uploaded/....) if successful
13854:  and /adm/notfound.html if unsuccessful (or an error message if context 
13855:  was 'overwrite').
13856:  
13857: 
13858: =item *
13859: 
13860: renameuserfile(): renames an existing userfile to a new name
13861: 
13862:   Args:
13863:    docuname: username or courseid of destination for the file
13864:    docudom: domain of user/course of destination for the file
13865:    old: current file name (including any subdirs under userfiles)
13866:    new: desired file name (including any subdirs under userfiles)
13867: 
13868: =item *
13869: 
13870: mkdiruserfile(): creates a directory is a userfiles dir
13871: 
13872:   Args:
13873:    docuname: username or courseid of destination for the file
13874:    docudom: domain of user/course of destination for the file
13875:    dir: dir to create (including any subdirs under userfiles)
13876: 
13877: =item *
13878: 
13879: removeuserfile(): removes a file that exists in userfiles
13880: 
13881:   Args:
13882:    docuname: username or courseid of destination for the file
13883:    docudom: domain of user/course of destination for the file
13884:    fname: filname to delete (including any subdirs under userfiles)
13885: 
13886: =item *
13887: 
13888: removeuploadedurl(): convience function for removeuserfile()
13889: 
13890:   Args:
13891:    url:  a full /uploaded/... url to delete
13892: 
13893: =item * 
13894: 
13895: get_portfile_permissions():
13896:   Args:
13897:     domain: domain of user or course contain the portfolio files
13898:     user: name of user or num of course contain the portfolio files
13899:   Returns:
13900:     hashref of a dump of the proper file_permissions.db
13901:    
13902: 
13903: =item * 
13904: 
13905: get_access_controls():
13906: 
13907: Args:
13908:   current_permissions: the hash ref returned from get_portfile_permissions()
13909:   group: (optional) the group you want the files associated with
13910:   file: (optional) the file you want access info on
13911: 
13912: Returns:
13913:     a hash (keys are file names) of hashes containing
13914:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
13915:         values are XML containing access control settings (see below) 
13916: 
13917: Internal notes:
13918: 
13919:  access controls are stored in file_permissions.db as key=value pairs.
13920:     key -> path to file/file_name\0uniqueID:scope_end_start
13921:         where scope -> public,guest,course,group,domains or users.
13922:               end -> UNIX time for end of access (0 -> no end date)
13923:               start -> UNIX time for start of access
13924: 
13925:     value -> XML description of access control
13926:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
13927:             <start></start>
13928:             <end></end>
13929: 
13930:             <password></password>  for scope type = guest
13931: 
13932:             <domain></domain>     for scope type = course or group
13933:             <number></number>
13934:             <roles id="">
13935:              <role></role>
13936:              <access></access>
13937:              <section></section>
13938:              <group></group>
13939:             </roles>
13940: 
13941:             <dom></dom>         for scope type = domains
13942: 
13943:             <users>             for scope type = users
13944:              <user>
13945:               <uname></uname>
13946:               <udom></udom>
13947:              </user>
13948:             </users>
13949:            </scope> 
13950:               
13951:  Access data is also aggregated for each file in an additional key=value pair:
13952:  key -> path to file/file_name\0accesscontrol 
13953:  value -> reference to hash
13954:           hash contains key = value pairs
13955:           where key = uniqueID:scope_end_start
13956:                 value = UNIX time record was last updated
13957: 
13958:           Used to improve speed of look-ups of access controls for each file.  
13959:  
13960:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
13961: 
13962: =item *
13963: 
13964: modify_access_controls():
13965: 
13966: Modifies access controls for a portfolio file
13967: Args
13968: 1. file name
13969: 2. reference to hash of required changes,
13970: 3. domain
13971: 4. username
13972:   where domain,username are the domain of the portfolio owner 
13973:   (either a user or a course) 
13974: 
13975: Returns:
13976: 1. result of additions or updates ('ok' or 'error', with error message). 
13977: 2. result of deletions ('ok' or 'error', with error message).
13978: 3. reference to hash of any new or updated access controls.
13979: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
13980:    key = integer (inbound ID)
13981:    value = uniqueID
13982: 
13983: =item *
13984: 
13985: get_timebased_id():
13986: 
13987: Attempts to get a unique timestamp-based suffix for use with items added to a
13988: course via the Course Editor (e.g., folders, composite pages,
13989: group bulletin boards).
13990: 
13991: Args: (first three required; six others optional)
13992: 
13993: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
13994:    docssequence, or name of group
13995: 
13996: 2. keyid (alphanumeric): name of temporary locking key in hash,
13997:    e.g., num, boardids
13998: 
13999: 3. namespace: name of gdbm file used to store suffixes already assigned;
14000:    file will be named nohist_namespace.db
14001: 
14002: 4. cdom: domain of course; default is current course domain from %env
14003: 
14004: 5. cnum: course number; default is current course number from %env
14005: 
14006: 6. idtype: set to concat if an additional digit is to be appended to the
14007:    unix timestamp to form the suffix, if the plain timestamp is already
14008:    in use.  Default is to not do this, but simply increment the unix
14009:    timestamp by 1 until a unique key is obtained.
14010: 
14011: 7. who: holder of locking key; defaults to user:domain for user.
14012: 
14013: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
14014:    retrying); default is 3.
14015: 
14016: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
14017: 
14018: Returns:
14019: 
14020: 1. suffix obtained (numeric)
14021: 
14022: 2. result of deleting locking key (ok if deleted, or lock never obtained)
14023: 
14024: 3. error: contains (localized) error message if an error occurred.
14025: 
14026: 
14027: =back
14028: 
14029: =head2 HTTP Helper Routines
14030: 
14031: =over 4
14032: 
14033: =item *
14034: 
14035: escape() : unpack non-word characters into CGI-compatible hex codes
14036: 
14037: =item *
14038: 
14039: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
14040: 
14041: =back
14042: 
14043: =head1 PRIVATE SUBROUTINES
14044: 
14045: =head2 Underlying communication routines (Shouldn't call)
14046: 
14047: =over 4
14048: 
14049: =item *
14050: 
14051: subreply() : tries to pass a message to lonc, returns con_lost if incapable
14052: 
14053: =item *
14054: 
14055: reply() : uses subreply to send a message to remote machine, logs all failures
14056: 
14057: =item *
14058: 
14059: critical() : passes a critical message to another server; if cannot
14060: get through then place message in connection buffer directory and
14061: returns con_delayed, if incapable of saving message, returns
14062: con_failed
14063: 
14064: =item *
14065: 
14066: reconlonc() : tries to reconnect lonc client processes.
14067: 
14068: =back
14069: 
14070: =head2 Resource Access Logging
14071: 
14072: =over 4
14073: 
14074: =item *
14075: 
14076: flushcourselogs() : flush (save) buffer logs and access logs
14077: 
14078: =item *
14079: 
14080: courselog($what) : save message for course in hash
14081: 
14082: =item *
14083: 
14084: courseacclog($what) : save message for course using &courselog().  Perform
14085: special processing for specific resource types (problems, exams, quizzes, etc).
14086: 
14087: =item *
14088: 
14089: goodbye() : flush course logs and log shutting down; it is called in srm.conf
14090: as a PerlChildExitHandler
14091: 
14092: =back
14093: 
14094: =head2 Other
14095: 
14096: =over 4
14097: 
14098: =item *
14099: 
14100: symblist($mapname,%newhash) : update symbolic storage links
14101: 
14102: =back
14103: 
14104: =cut
14105: 

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