File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1183: download - view: text, annotated - select for diffs
Tue Aug 14 15:45:34 2012 UTC (11 years, 11 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Add ability for users to request creation of an author role in their
  domain, if they do not already have an active author role.
  - Domain defaults can be assigned based on institutional status.
  - Defaults can be overridden for individual users by the DC.
  - Requests can either be processed automatically or queued for DC
    approval.
  - Notification message can be sent to DCs when queued for approval
  - Notification message sent to requester if approved/rejected.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1183 2012/08/14 15:45:34 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: =pod
   31: 
   32: =head1 NAME
   33: 
   34: Apache::lonnet.pm
   35: 
   36: =head1 SYNOPSIS
   37: 
   38: This file is an interface to the lonc processes of
   39: the LON-CAPA network as well as set of elaborated functions for handling information
   40: necessary for navigating through a given cluster of LON-CAPA machines within a
   41: domain. There are over 40 specialized functions in this module which handle the
   42: reading and transmission of metadata, user information (ids, names, environments, roles,
   43: logs), file information (storage, reading, directories, extensions, replication, embedded
   44: styles and descriptors), educational resources (course descriptions, section names and
   45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
   46: and from more descriptive phrases or explanations.
   47: 
   48: This is part of the LearningOnline Network with CAPA project
   49: described at http://www.lon-capa.org.
   50: 
   51: =head1 Package Variables
   52: 
   53: These are largely undocumented, so if you decipher one please note it here.
   54: 
   55: =over 4
   56: 
   57: =item $processmarker
   58: 
   59: Contains the time this process was started and this servers host id.
   60: 
   61: =item $dumpcount
   62: 
   63: Counts the number of times a message log flush has been attempted (regardless
   64: of success) by this process.  Used as part of the filename when messages are
   65: delayed.
   66: 
   67: =back
   68: 
   69: =cut
   70: 
   71: package Apache::lonnet;
   72: 
   73: use strict;
   74: use LWP::UserAgent();
   75: use HTTP::Date;
   76: use Image::Magick;
   77: 
   78: 
   79: use Encode;
   80: 
   81: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
   82:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
   83:             %managerstab);
   84: 
   85: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   86:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   87:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   88:     %courseownerbuf, %coursetypebuf,$locknum);
   89: 
   90: use IO::Socket;
   91: use GDBM_File;
   92: use HTML::LCParser;
   93: use Fcntl qw(:flock);
   94: use Storable qw(thaw nfreeze);
   95: use Time::HiRes qw( gettimeofday tv_interval );
   96: use Cache::Memcached;
   97: use Digest::MD5;
   98: use Math::Random;
   99: use File::MMagic;
  100: use LONCAPA qw(:DEFAULT :match);
  101: use LONCAPA::Configuration;
  102: use LONCAPA::lonmetadata;
  103: use LONCAPA::Lond;
  104: 
  105: use File::Copy;
  106: 
  107: my $readit;
  108: my $max_connection_retries = 10;     # Or some such value.
  109: 
  110: require Exporter;
  111: 
  112: our @ISA = qw (Exporter);
  113: our @EXPORT = qw(%env);
  114: 
  115: 
  116: # --------------------------------------------------------------------- Logging
  117: {
  118:     my $logid;
  119:     sub instructor_log {
  120: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  121:         if (($cnum eq '') || ($cdom eq '')) {
  122:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  123:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  124:         }
  125: 	$logid++;
  126:         my $now = time();
  127: 	my $id=$now.'00000'.$$.'00000'.$logid;
  128: 	return &Apache::lonnet::put('nohist_'.$hash_name,
  129: 				    { $id => {
  130: 					'exe_uname' => $env{'user.name'},
  131: 					'exe_udom'  => $env{'user.domain'},
  132: 					'exe_time'  => $now,
  133: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
  134: 					'delflag'   => $delflag,
  135: 					'logentry'  => $storehash,
  136: 					'uname'     => $uname,
  137: 					'udom'      => $udom,
  138: 				    }
  139: 				  },$cdom,$cnum);
  140:     }
  141: }
  142: 
  143: sub logtouch {
  144:     my $execdir=$perlvar{'lonDaemons'};
  145:     unless (-e "$execdir/logs/lonnet.log") {	
  146: 	open(my $fh,">>$execdir/logs/lonnet.log");
  147: 	close $fh;
  148:     }
  149:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  150:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  151: }
  152: 
  153: sub logthis {
  154:     my $message=shift;
  155:     my $execdir=$perlvar{'lonDaemons'};
  156:     my $now=time;
  157:     my $local=localtime($now);
  158:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  159: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  160: 	print $fh $logstring;
  161: 	close($fh);
  162:     }
  163:     return 1;
  164: }
  165: 
  166: sub logperm {
  167:     my $message=shift;
  168:     my $execdir=$perlvar{'lonDaemons'};
  169:     my $now=time;
  170:     my $local=localtime($now);
  171:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  172: 	print $fh "$now:$message:$local\n";
  173: 	close($fh);
  174:     }
  175:     return 1;
  176: }
  177: 
  178: sub create_connection {
  179:     my ($hostname,$lonid) = @_;
  180:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  181: 				     Type    => SOCK_STREAM,
  182: 				     Timeout => 10);
  183:     return 0 if (!$client);
  184:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  185:     my $result = <$client>;
  186:     chomp($result);
  187:     return 1 if ($result eq 'done');
  188:     return 0;
  189: }
  190: 
  191: sub get_server_timezone {
  192:     my ($cnum,$cdom) = @_;
  193:     my $home=&homeserver($cnum,$cdom);
  194:     if ($home ne 'no_host') {
  195:         my $cachetime = 24*3600;
  196:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  197:         if (defined($cached)) {
  198:             return $timezone;
  199:         } else {
  200:             my $timezone = &reply('servertimezone',$home);
  201:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  202:         }
  203:     }
  204: }
  205: 
  206: sub get_server_distarch {
  207:     my ($lonhost,$ignore_cache) = @_;
  208:     if (defined($lonhost)) {
  209:         if (!defined(&hostname($lonhost))) {
  210:             return;
  211:         }
  212:         my $cachetime = 12*3600;
  213:         if (!$ignore_cache) {
  214:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
  215:             if (defined($cached)) {
  216:                 return $distarch;
  217:             }
  218:         }
  219:         my $rep = &reply('serverdistarch',$lonhost);
  220:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
  221:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
  222:                 $rep eq '') {
  223:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
  224:         }
  225:     }
  226:     return;
  227: }
  228: 
  229: sub get_server_loncaparev {
  230:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  231:     if (defined($lonhost)) {
  232:         if (!defined(&hostname($lonhost))) {
  233:             undef($lonhost);
  234:         }
  235:     }
  236:     if (!defined($lonhost)) {
  237:         if (defined(&domain($dom,'primary'))) {
  238:             $lonhost=&domain($dom,'primary');
  239:             if ($lonhost eq 'no_host') {
  240:                 undef($lonhost);
  241:             }
  242:         }
  243:     }
  244:     if (defined($lonhost)) {
  245:         my $cachetime = 12*3600;
  246:         if (!$ignore_cache) {
  247:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  248:             if (defined($cached)) {
  249:                 return $loncaparev;
  250:             }
  251:         }
  252:         my ($answer,$loncaparev);
  253:         my @ids=&current_machine_ids();
  254:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  255:             $answer = $perlvar{'lonVersion'};
  256:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  257:                 $loncaparev = $1;
  258:             }
  259:         } else {
  260:             $answer = &reply('serverloncaparev',$lonhost);
  261:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  262:                 if ($caller eq 'loncron') {
  263:                     my $ua=new LWP::UserAgent;
  264:                     $ua->timeout(4);
  265:                     my $protocol = $protocol{$lonhost};
  266:                     $protocol = 'http' if ($protocol ne 'https');
  267:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
  268:                     my $request=new HTTP::Request('GET',$url);
  269:                     my $response=$ua->request($request);
  270:                     unless ($response->is_error()) {
  271:                         my $content = $response->content;
  272:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
  273:                             $loncaparev = $1;
  274:                         }
  275:                     }
  276:                 } else {
  277:                     $loncaparev = $loncaparevs{$lonhost};
  278:                 }
  279:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
  280:                 $loncaparev = $1;
  281:             }
  282:         }
  283:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  284:     }
  285: }
  286: 
  287: sub get_server_homeID {
  288:     my ($hostname,$ignore_cache,$caller) = @_;
  289:     unless ($ignore_cache) {
  290:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  291:         if (defined($cached)) {
  292:             return $serverhomeID;
  293:         }
  294:     }
  295:     my $cachetime = 12*3600;
  296:     my $serverhomeID;
  297:     if ($caller eq 'loncron') { 
  298:         my @machine_ids = &machine_ids($hostname);
  299:         foreach my $id (@machine_ids) {
  300:             my $response = &reply('serverhomeID',$id);
  301:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  302:                 $serverhomeID = $response;
  303:                 last;
  304:             }
  305:         }
  306:         if ($serverhomeID eq '') {
  307:             $serverhomeID = $machine_ids[-1];
  308:         }
  309:     } else {
  310:         $serverhomeID = $serverhomeIDs{$hostname};
  311:     }
  312:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  313: }
  314: 
  315: sub get_remote_globals {
  316:     my ($lonhost,$whathash,$ignore_cache) = @_;
  317:     my ($result,%returnhash,%whatneeded);
  318:     if (ref($whathash) eq 'HASH') {
  319:         foreach my $what (sort(keys(%{$whathash}))) {
  320:             my $hashid = $lonhost.'-'.$what;
  321:             my ($response,$cached);
  322:             unless ($ignore_cache) {
  323:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
  324:             }
  325:             if (defined($cached)) {
  326:                 $returnhash{$what} = $response;
  327:             } else {
  328:                 $whatneeded{$what} = 1;
  329:             }
  330:         }
  331:         if (keys(%whatneeded) == 0) {
  332:             $result = 'ok';
  333:         } else {
  334:             my $requested = &freeze_escape(\%whatneeded);
  335:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
  336:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
  337:                 ($rep eq 'unknown_cmd')) {
  338:                 $result = $rep;
  339:             } else {
  340:                 $result = 'ok';
  341:                 my @pairs=split(/\&/,$rep);
  342:                 foreach my $item (@pairs) {
  343:                     my ($key,$value)=split(/=/,$item,2);
  344:                     my $what = &unescape($key);
  345:                     my $hashid = $lonhost.'-'.$what;
  346:                     $returnhash{$what}=&thaw_unescape($value);
  347:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
  348:                 }
  349:             }
  350:         }
  351:     }
  352:     return ($result,\%returnhash);
  353: }
  354: 
  355: sub remote_devalidate_cache {
  356:     my ($lonhost,$name,$id) = @_;
  357:     my $response = &reply('devalidatecache:'.&escape($name).':'.&escape($id),$lonhost);
  358:     return $response;
  359: }
  360: 
  361: # -------------------------------------------------- Non-critical communication
  362: sub subreply {
  363:     my ($cmd,$server)=@_;
  364:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  365:     #
  366:     #  With loncnew process trimming, there's a timing hole between lonc server
  367:     #  process exit and the master server picking up the listen on the AF_UNIX
  368:     #  socket.  In that time interval, a lock file will exist:
  369: 
  370:     my $lockfile=$peerfile.".lock";
  371:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  372: 	sleep(1);
  373:     }
  374:     # At this point, either a loncnew parent is listening or an old lonc
  375:     # or loncnew child is listening so we can connect or everything's dead.
  376:     #
  377:     #   We'll give the connection a few tries before abandoning it.  If
  378:     #   connection is not possible, we'll con_lost back to the client.
  379:     #   
  380:     my $client;
  381:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  382: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  383: 				      Type    => SOCK_STREAM,
  384: 				      Timeout => 10);
  385: 	if ($client) {
  386: 	    last;		# Connected!
  387: 	} else {
  388: 	    &create_connection(&hostname($server),$server);
  389: 	}
  390:         sleep(1);		# Try again later if failed connection.
  391:     }
  392:     my $answer;
  393:     if ($client) {
  394: 	print $client "sethost:$server:$cmd\n";
  395: 	$answer=<$client>;
  396: 	if (!$answer) { $answer="con_lost"; }
  397: 	chomp($answer);
  398:     } else {
  399: 	$answer = 'con_lost';	# Failed connection.
  400:     }
  401:     return $answer;
  402: }
  403: 
  404: sub reply {
  405:     my ($cmd,$server)=@_;
  406:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  407:     my $answer=subreply($cmd,$server);
  408:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  409:        &logthis("<font color=\"blue\">WARNING:".
  410:                 " $cmd to $server returned $answer</font>");
  411:     }
  412:     return $answer;
  413: }
  414: 
  415: # ----------------------------------------------------------- Send USR1 to lonc
  416: 
  417: sub reconlonc {
  418:     my ($lonid) = @_;
  419:     my $hostname = &hostname($lonid);
  420:     if ($lonid) {
  421: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  422: 	if ($hostname && -e $peerfile) {
  423: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  424: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  425: 					     Type    => SOCK_STREAM,
  426: 					     Timeout => 10);
  427: 	    if ($client) {
  428: 		print $client ("reset_retries\n");
  429: 		my $answer=<$client>;
  430: 		#reset just this one.
  431: 	    }
  432: 	}
  433: 	return;
  434:     }
  435: 
  436:     &logthis("Trying to reconnect lonc");
  437:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  438:     if (open(my $fh,"<$loncfile")) {
  439: 	my $loncpid=<$fh>;
  440:         chomp($loncpid);
  441:         if (kill 0 => $loncpid) {
  442: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  443:             kill USR1 => $loncpid;
  444:             sleep 1;
  445:          } else {
  446: 	    &logthis(
  447:                "<font color=\"blue\">WARNING:".
  448:                " lonc at pid $loncpid not responding, giving up</font>");
  449:         }
  450:     } else {
  451: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  452:     }
  453: }
  454: 
  455: # ------------------------------------------------------ Critical communication
  456: 
  457: sub critical {
  458:     my ($cmd,$server)=@_;
  459:     unless (&hostname($server)) {
  460:         &logthis("<font color=\"blue\">WARNING:".
  461:                " Critical message to unknown server ($server)</font>");
  462:         return 'no_such_host';
  463:     }
  464:     my $answer=reply($cmd,$server);
  465:     if ($answer eq 'con_lost') {
  466: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  467: 	my $answer=reply($cmd,$server);
  468:         if ($answer eq 'con_lost') {
  469:             my $now=time;
  470:             my $middlename=$cmd;
  471:             $middlename=substr($middlename,0,16);
  472:             $middlename=~s/\W//g;
  473:             my $dfilename=
  474:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  475:             $dumpcount++;
  476:             {
  477: 		my $dfh;
  478: 		if (open($dfh,">$dfilename")) {
  479: 		    print $dfh "$cmd\n"; 
  480: 		    close($dfh);
  481: 		}
  482:             }
  483:             sleep 2;
  484:             my $wcmd='';
  485:             {
  486: 		my $dfh;
  487: 		if (open($dfh,"<$dfilename")) {
  488: 		    $wcmd=<$dfh>; 
  489: 		    close($dfh);
  490: 		}
  491:             }
  492:             chomp($wcmd);
  493:             if ($wcmd eq $cmd) {
  494: 		&logthis("<font color=\"blue\">WARNING: ".
  495:                          "Connection buffer $dfilename: $cmd</font>");
  496:                 &logperm("D:$server:$cmd");
  497: 	        return 'con_delayed';
  498:             } else {
  499:                 &logthis("<font color=\"red\">CRITICAL:"
  500:                         ." Critical connection failed: $server $cmd</font>");
  501:                 &logperm("F:$server:$cmd");
  502:                 return 'con_failed';
  503:             }
  504:         }
  505:     }
  506:     return $answer;
  507: }
  508: 
  509: # ------------------------------------------- check if return value is an error
  510: 
  511: sub error {
  512:     my ($result) = @_;
  513:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  514: 	if ($2 == 2) { return undef; }
  515: 	return $1;
  516:     }
  517:     return undef;
  518: }
  519: 
  520: sub convert_and_load_session_env {
  521:     my ($lonidsdir,$handle)=@_;
  522:     my @profile;
  523:     {
  524: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  525: 	if (!$opened) {
  526: 	    return 0;
  527: 	}
  528: 	flock($idf,LOCK_SH);
  529: 	@profile=<$idf>;
  530: 	close($idf);
  531:     }
  532:     my %temp_env;
  533:     foreach my $line (@profile) {
  534: 	if ($line !~ m/=/) {
  535: 	    return 0;
  536: 	}
  537: 	chomp($line);
  538: 	my ($envname,$envvalue)=split(/=/,$line,2);
  539: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  540:     }
  541:     unlink("$lonidsdir/$handle.id");
  542:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  543: 	    0640)) {
  544: 	%disk_env = %temp_env;
  545: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  546: 	untie(%disk_env);
  547:     }
  548:     return 1;
  549: }
  550: 
  551: # ------------------------------------------- Transfer profile into environment
  552: my $env_loaded;
  553: sub transfer_profile_to_env {
  554:     my ($lonidsdir,$handle,$force_transfer) = @_;
  555:     if (!$force_transfer && $env_loaded) { return; } 
  556: 
  557:     if (!defined($lonidsdir)) {
  558: 	$lonidsdir = $perlvar{'lonIDsDir'};
  559:     }
  560:     if (!defined($handle)) {
  561:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  562:     }
  563: 
  564:     my $convert;
  565:     {
  566:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  567: 	if (!$opened) {
  568: 	    return;
  569: 	}
  570: 	flock($idf,LOCK_SH);
  571: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  572: 		&GDBM_READER(),0640)) {
  573: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  574: 	    untie(%disk_env);
  575: 	} else {
  576: 	    $convert = 1;
  577: 	}
  578:     }
  579:     if ($convert) {
  580: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  581: 	    &logthis("Failed to load session, or convert session.");
  582: 	}
  583:     }
  584: 
  585:     my %remove;
  586:     while ( my $envname = each(%env) ) {
  587:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  588:             if ($time < time-300) {
  589:                 $remove{$key}++;
  590:             }
  591:         }
  592:     }
  593: 
  594:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  595:     $env_loaded=1;
  596:     foreach my $expired_key (keys(%remove)) {
  597:         &delenv($expired_key);
  598:     }
  599: }
  600: 
  601: # ---------------------------------------------------- Check for valid session 
  602: sub check_for_valid_session {
  603:     my ($r,$name) = @_;
  604:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  605:     if ($name eq '') {
  606:         $name = 'lonID';
  607:     }
  608:     my $lonid=$cookies{$name};
  609:     return undef if (!$lonid);
  610: 
  611:     my $handle=&LONCAPA::clean_handle($lonid->value);
  612:     my $lonidsdir;
  613:     if ($name eq 'lonDAV') {
  614:         $lonidsdir=$r->dir_config('lonDAVsessDir');
  615:     } else {
  616:         $lonidsdir=$r->dir_config('lonIDsDir');
  617:     }
  618:     return undef if (!-e "$lonidsdir/$handle.id");
  619: 
  620:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  621:     return undef if (!$opened);
  622: 
  623:     flock($idf,LOCK_SH);
  624:     my %disk_env;
  625:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  626: 	    &GDBM_READER(),0640)) {
  627: 	return undef;	
  628:     }
  629: 
  630:     if (!defined($disk_env{'user.name'})
  631: 	|| !defined($disk_env{'user.domain'})) {
  632: 	return undef;
  633:     }
  634:     return $handle;
  635: }
  636: 
  637: sub timed_flock {
  638:     my ($file,$lock_type) = @_;
  639:     my $failed=0;
  640:     eval {
  641: 	local $SIG{__DIE__}='DEFAULT';
  642: 	local $SIG{ALRM}=sub {
  643: 	    $failed=1;
  644: 	    die("failed lock");
  645: 	};
  646: 	alarm(13);
  647: 	flock($file,$lock_type);
  648: 	alarm(0);
  649:     };
  650:     if ($failed) {
  651: 	return undef;
  652:     } else {
  653: 	return 1;
  654:     }
  655: }
  656: 
  657: # ---------------------------------------------------------- Append Environment
  658: 
  659: sub appenv {
  660:     my ($newenv,$roles) = @_;
  661:     if (ref($newenv) eq 'HASH') {
  662:         foreach my $key (keys(%{$newenv})) {
  663:             my $refused = 0;
  664: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  665:                 $refused = 1;
  666:                 if (ref($roles) eq 'ARRAY') {
  667:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
  668:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  669:                         $refused = 0;
  670:                     }
  671:                 }
  672:             }
  673:             if ($refused) {
  674:                 &logthis("<font color=\"blue\">WARNING: ".
  675:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  676:                          .'</font>');
  677: 	        delete($newenv->{$key});
  678:             } else {
  679:                 $env{$key}=$newenv->{$key};
  680:             }
  681:         }
  682:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  683:         if ($opened
  684: 	    && &timed_flock($env_file,LOCK_EX)
  685: 	    &&
  686: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  687: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  688: 	    while (my ($key,$value) = each(%{$newenv})) {
  689: 	        $disk_env{$key} = $value;
  690: 	    }
  691: 	    untie(%disk_env);
  692:         }
  693:     }
  694:     return 'ok';
  695: }
  696: # ----------------------------------------------------- Delete from Environment
  697: 
  698: sub delenv {
  699:     my ($delthis,$regexp,$roles) = @_;
  700:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
  701:         my $refused = 1;
  702:         if (ref($roles) eq 'ARRAY') {
  703:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
  704:             if (grep(/^\Q$role\E$/,@{$roles})) {
  705:                 $refused = 0;
  706:             }
  707:         }
  708:         if ($refused) {
  709:             &logthis("<font color=\"blue\">WARNING: ".
  710:                      "Attempt to delete from environment ".$delthis);
  711:             return 'error';
  712:         }
  713:     }
  714:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  715:     if ($opened
  716: 	&& &timed_flock($env_file,LOCK_EX)
  717: 	&&
  718: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  719: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  720: 	foreach my $key (keys(%disk_env)) {
  721: 	    if ($regexp) {
  722:                 if ($key=~/^$delthis/) {
  723:                     delete($env{$key});
  724:                     delete($disk_env{$key});
  725:                 } 
  726:             } else {
  727:                 if ($key=~/^\Q$delthis\E/) {
  728: 		    delete($env{$key});
  729: 		    delete($disk_env{$key});
  730: 	        }
  731:             }
  732: 	}
  733: 	untie(%disk_env);
  734:     }
  735:     return 'ok';
  736: }
  737: 
  738: sub get_env_multiple {
  739:     my ($name) = @_;
  740:     my @values;
  741:     if (defined($env{$name})) {
  742:         # exists is it an array
  743:         if (ref($env{$name})) {
  744:             @values=@{ $env{$name} };
  745:         } else {
  746:             $values[0]=$env{$name};
  747:         }
  748:     }
  749:     return(@values);
  750: }
  751: 
  752: # ------------------------------------------------------------------- Locking
  753: 
  754: sub set_lock {
  755:     my ($text)=@_;
  756:     $locknum++;
  757:     my $id=$$.'-'.$locknum;
  758:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  759:              'session.lock.'.$id => $text});
  760:     return $id;
  761: }
  762: 
  763: sub get_locks {
  764:     my $num=0;
  765:     my %texts=();
  766:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  767:        if ($lock=~/\w/) {
  768:           $num++;
  769:           $texts{$lock}=$env{'session.lock.'.$lock};
  770:        }
  771:    }
  772:    return ($num,%texts);
  773: }
  774: 
  775: sub remove_lock {
  776:     my ($id)=@_;
  777:     my $newlocks='';
  778:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  779:        if (($lock=~/\w/) && ($lock ne $id)) {
  780:           $newlocks.=','.$lock;
  781:        }
  782:     }
  783:     &appenv({'session.locks' => $newlocks});
  784:     &delenv('session.lock.'.$id);
  785: }
  786: 
  787: sub remove_all_locks {
  788:     my $activelocks=$env{'session.locks'};
  789:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  790:        if ($lock=~/\w/) {
  791:           &remove_lock($lock);
  792:        }
  793:     }
  794: }
  795: 
  796: 
  797: # ------------------------------------------ Find out current server userload
  798: sub userload {
  799:     my $numusers=0;
  800:     {
  801: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  802: 	my $filename;
  803: 	my $curtime=time;
  804: 	while ($filename=readdir(LONIDS)) {
  805: 	    next if ($filename eq '.' || $filename eq '..');
  806: 	    next if ($filename =~ /publicuser_\d+\.id/);
  807: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  808: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  809: 	}
  810: 	closedir(LONIDS);
  811:     }
  812:     my $userloadpercent=0;
  813:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  814:     if ($maxuserload) {
  815: 	$userloadpercent=100*$numusers/$maxuserload;
  816:     }
  817:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  818:     return $userloadpercent;
  819: }
  820: 
  821: # ------------------------------ Find server with least workload from spare.tab
  822: 
  823: sub spareserver {
  824:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
  825:     my $spare_server;
  826:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  827:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  828:                                                      :  $userloadpercent;
  829:     my ($uint_dom,$remotesessions);
  830:     if (($udom ne '') && (&domain($udom) ne '')) {
  831:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
  832:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
  833:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
  834:         $remotesessions = $udomdefaults{'remotesessions'};
  835:     }
  836:     my $spareshash = &this_host_spares($udom);
  837:     if (ref($spareshash) eq 'HASH') {
  838:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  839:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  840:                 if ($uint_dom) {
  841:                     next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
  842:                                                  $try_server));
  843:                 }
  844: 	        ($spare_server, $lowest_load) =
  845: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
  846:             }
  847:         }
  848: 
  849:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
  850: 
  851:         if (!$found_server) {
  852:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
  853: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
  854:                     if ($uint_dom) {
  855:                         next unless (&spare_can_host($udom,$uint_dom,
  856:                                                      $remotesessions,$try_server));
  857:                     }
  858: 	            ($spare_server, $lowest_load) =
  859: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
  860:                 }
  861: 	    }
  862:         }
  863:     }
  864: 
  865:     if (!$want_server_name) {
  866:         my $protocol = 'http';
  867:         if ($protocol{$spare_server} eq 'https') {
  868:             $protocol = $protocol{$spare_server};
  869:         }
  870:         if (defined($spare_server)) {
  871:             my $hostname = &hostname($spare_server);
  872:             if (defined($hostname)) {
  873: 	        $spare_server = $protocol.'://'.$hostname;
  874:             }
  875:         }
  876:     }
  877:     return $spare_server;
  878: }
  879: 
  880: sub compare_server_load {
  881:     my ($try_server, $spare_server, $lowest_load) = @_;
  882: 
  883:     my $loadans     = &reply('load',    $try_server);
  884:     my $userloadans = &reply('userload',$try_server);
  885: 
  886:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  887: 	return ($spare_server, $lowest_load); #didn't get a number from the server
  888:     }
  889: 
  890:     my $load;
  891:     if ($loadans =~ /\d/) {
  892: 	if ($userloadans =~ /\d/) {
  893: 	    #both are numbers, pick the bigger one
  894: 	    $load = ($loadans > $userloadans) ? $loadans 
  895: 		                              : $userloadans;
  896: 	} else {
  897: 	    $load = $loadans;
  898: 	}
  899:     } else {
  900: 	$load = $userloadans;
  901:     }
  902: 
  903:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  904: 	$spare_server = $try_server;
  905: 	$lowest_load  = $load;
  906:     }
  907:     return ($spare_server,$lowest_load);
  908: }
  909: 
  910: # --------------------------- ask offload servers if user already has a session
  911: sub find_existing_session {
  912:     my ($udom,$uname) = @_;
  913:     my $spareshash = &this_host_spares($udom);
  914:     if (ref($spareshash) eq 'HASH') {
  915:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
  916:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
  917:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  918:             }
  919:         }
  920:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
  921:             foreach my $try_server (@{ $spareshash->{'default'} }) {
  922:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
  923:             }
  924:         }
  925:     }
  926:     return;
  927: }
  928: 
  929: # -------------------------------- ask if server already has a session for user
  930: sub has_user_session {
  931:     my ($lonid,$udom,$uname) = @_;
  932:     my $result = &reply(join(':','userhassession',
  933: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  934:     return 1 if ($result eq 'ok');
  935: 
  936:     return 0;
  937: }
  938: 
  939: # --------- determine least loaded server in a user's domain which allows login
  940: 
  941: sub choose_server {
  942:     my ($udom,$checkloginvia) = @_;
  943:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
  944:     my %servers = &get_servers($udom);
  945:     my $lowest_load = 30000;
  946:     my ($login_host,$hostname,$portal_path,$isredirect);
  947:     foreach my $lonhost (keys(%servers)) {
  948:         my $loginvia;
  949:         if ($checkloginvia) {
  950:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
  951:             if ($loginvia) {
  952:                 my ($server,$path) = split(/:/,$loginvia);
  953:                 ($login_host, $lowest_load) =
  954:                     &compare_server_load($server, $login_host, $lowest_load);
  955:                 if ($login_host eq $server) {
  956:                     $portal_path = $path;
  957:                     $isredirect = 1;
  958:                 }
  959:             } else {
  960:                 ($login_host, $lowest_load) =
  961:                     &compare_server_load($lonhost, $login_host, $lowest_load);
  962:                 if ($login_host eq $lonhost) {
  963:                     $portal_path = '';
  964:                     $isredirect = ''; 
  965:                 }
  966:             }
  967:         } else {
  968:             ($login_host, $lowest_load) =
  969:                 &compare_server_load($lonhost, $login_host, $lowest_load);
  970:         }
  971:     }
  972:     if ($login_host ne '') {
  973:         $hostname = &hostname($login_host);
  974:     }
  975:     return ($login_host,$hostname,$portal_path,$isredirect);
  976: }
  977: 
  978: # --------------------------------------------- Try to change a user's password
  979: 
  980: sub changepass {
  981:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  982:     $currentpass = &escape($currentpass);
  983:     $newpass     = &escape($newpass);
  984:     my $lonhost = $perlvar{'lonHostID'};
  985:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
  986: 		       $server);
  987:     if (! $answer) {
  988: 	&logthis("No reply on password change request to $server ".
  989: 		 "by $uname in domain $udom.");
  990:     } elsif ($answer =~ "^ok") {
  991:         &logthis("$uname in $udom successfully changed their password ".
  992: 		 "on $server.");
  993:     } elsif ($answer =~ "^pwchange_failure") {
  994: 	&logthis("$uname in $udom was unable to change their password ".
  995: 		 "on $server.  The action was blocked by either lcpasswd ".
  996: 		 "or pwchange");
  997:     } elsif ($answer =~ "^non_authorized") {
  998:         &logthis("$uname in $udom did not get their password correct when ".
  999: 		 "attempting to change it on $server.");
 1000:     } elsif ($answer =~ "^auth_mode_error") {
 1001:         &logthis("$uname in $udom attempted to change their password despite ".
 1002: 		 "not being locally or internally authenticated on $server.");
 1003:     } elsif ($answer =~ "^unknown_user") {
 1004:         &logthis("$uname in $udom attempted to change their password ".
 1005: 		 "on $server but were unable to because $server is not ".
 1006: 		 "their home server.");
 1007:     } elsif ($answer =~ "^refused") {
 1008: 	&logthis("$server refused to change $uname in $udom password because ".
 1009: 		 "it was sent an unencrypted request to change the password.");
 1010:     } elsif ($answer =~ "invalid_client") {
 1011:         &logthis("$server refused to change $uname in $udom password because ".
 1012:                  "it was a reset by e-mail originating from an invalid server.");
 1013:     }
 1014:     return $answer;
 1015: }
 1016: 
 1017: # ----------------------- Try to determine user's current authentication scheme
 1018: 
 1019: sub queryauthenticate {
 1020:     my ($uname,$udom)=@_;
 1021:     my $uhome=&homeserver($uname,$udom);
 1022:     if (!$uhome) {
 1023: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
 1024: 	return 'no_host';
 1025:     }
 1026:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
 1027:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
 1028: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1029:     }
 1030:     return $answer;
 1031: }
 1032: 
 1033: # --------- Try to authenticate user from domain's lib servers (first this one)
 1034: 
 1035: sub authenticate {
 1036:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
 1037:     $upass=&escape($upass);
 1038:     $uname= &LONCAPA::clean_username($uname);
 1039:     my $uhome=&homeserver($uname,$udom,1);
 1040:     my $newhome;
 1041:     if ((!$uhome) || ($uhome eq 'no_host')) {
 1042: # Maybe the machine was offline and only re-appeared again recently?
 1043:         &reconlonc();
 1044: # One more
 1045: 	$uhome=&homeserver($uname,$udom,1);
 1046:         if (($uhome eq 'no_host') && $checkdefauth) {
 1047:             if (defined(&domain($udom,'primary'))) {
 1048:                 $newhome=&domain($udom,'primary');
 1049:             }
 1050:             if ($newhome ne '') {
 1051:                 $uhome = $newhome;
 1052:             }
 1053:         }
 1054: 	if ((!$uhome) || ($uhome eq 'no_host')) {
 1055: 	    &logthis("User $uname at $udom is unknown in authenticate");
 1056: 	    return 'no_host';
 1057:         }
 1058:     }
 1059:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
 1060:     if ($answer eq 'authorized') {
 1061:         if ($newhome) {
 1062:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
 1063:             return 'no_account_on_host'; 
 1064:         } else {
 1065:             &logthis("User $uname at $udom authorized by $uhome");
 1066:             return $uhome;
 1067:         }
 1068:     }
 1069:     if ($answer eq 'non_authorized') {
 1070: 	&logthis("User $uname at $udom rejected by $uhome");
 1071: 	return 'no_host'; 
 1072:     }
 1073:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
 1074:     return 'no_host';
 1075: }
 1076: 
 1077: sub can_host_session {
 1078:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
 1079:     my $canhost = 1;
 1080:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
 1081:     if (ref($remotesessions) eq 'HASH') {
 1082:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
 1083:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
 1084:                 $canhost = 0;
 1085:             } else {
 1086:                 $canhost = 1;
 1087:             }
 1088:         }
 1089:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
 1090:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
 1091:                 $canhost = 1;
 1092:             } else {
 1093:                 $canhost = 0;
 1094:             }
 1095:         }
 1096:         if ($canhost) {
 1097:             if ($remotesessions->{'version'} ne '') {
 1098:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
 1099:                 if ($reqmajor ne '' && $reqminor ne '') {
 1100:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
 1101:                         my $major = $1;
 1102:                         my $minor = $2;
 1103:                         if (($major < $reqmajor ) ||
 1104:                             (($major == $reqmajor) && ($minor < $reqminor))) {
 1105:                             $canhost = 0;
 1106:                         }
 1107:                     } else {
 1108:                         $canhost = 0;
 1109:                     }
 1110:                 }
 1111:             }
 1112:         }
 1113:     }
 1114:     if ($canhost) {
 1115:         if (ref($hostedsessions) eq 'HASH') {
 1116:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1117:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
 1118:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
 1119:                 if (($uint_dom ne '') && 
 1120:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
 1121:                     $canhost = 0;
 1122:                 } else {
 1123:                     $canhost = 1;
 1124:                 }
 1125:             }
 1126:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
 1127:                 if (($uint_dom ne '') && 
 1128:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
 1129:                     $canhost = 1;
 1130:                 } else {
 1131:                     $canhost = 0;
 1132:                 }
 1133:             }
 1134:         }
 1135:     }
 1136:     return $canhost;
 1137: }
 1138: 
 1139: sub spare_can_host {
 1140:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
 1141:     my $canhost=1;
 1142:     my @intdoms;
 1143:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
 1144:     if (ref($internet_names) eq 'ARRAY') {
 1145:         @intdoms = @{$internet_names};
 1146:     }
 1147:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
 1148:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
 1149:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
 1150:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
 1151:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
 1152:         $canhost = &can_host_session($udom,$try_server,$remoterev,
 1153:                                      $remotesessions,
 1154:                                      $defdomdefaults{'hostedsessions'});
 1155:     }
 1156:     return $canhost;
 1157: }
 1158: 
 1159: sub this_host_spares {
 1160:     my ($dom) = @_;
 1161:     my ($dom_in_use,$lonhost_in_use,$result);
 1162:     my @hosts = &current_machine_ids();
 1163:     foreach my $lonhost (@hosts) {
 1164:         if (&host_domain($lonhost) eq $dom) {
 1165:             $dom_in_use = $dom;
 1166:             $lonhost_in_use = $lonhost;
 1167:             last;
 1168:         }
 1169:     }
 1170:     if ($dom_in_use ne '') {
 1171:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1172:     }
 1173:     if (ref($result) ne 'HASH') {
 1174:         $lonhost_in_use = $perlvar{'lonHostID'};
 1175:         $dom_in_use = &host_domain($lonhost_in_use);
 1176:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
 1177:         if (ref($result) ne 'HASH') {
 1178:             $result = \%spareid;
 1179:         }
 1180:     }
 1181:     return $result;
 1182: }
 1183: 
 1184: sub spares_for_offload  {
 1185:     my ($dom_in_use,$lonhost_in_use) = @_;
 1186:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
 1187:     if (defined($cached)) {
 1188:         return $result;
 1189:     } else {
 1190:         my $cachetime = 60*60*24;
 1191:         my %domconfig =
 1192:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
 1193:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1194:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
 1195:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
 1196:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
 1197:                 }
 1198:             }
 1199:         }
 1200:     }
 1201:     return;
 1202: }
 1203: 
 1204: sub get_lonbalancer_config {
 1205:     my ($servers) = @_;
 1206:     my ($currbalancer,$currtargets);
 1207:     if (ref($servers) eq 'HASH') {
 1208:         foreach my $server (keys(%{$servers})) {
 1209:             my %what = (
 1210:                          spareid => 1,
 1211:                          perlvar => 1,
 1212:                        );
 1213:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
 1214:             if ($result eq 'ok') {
 1215:                 if (ref($returnhash) eq 'HASH') {
 1216:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
 1217:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
 1218:                             $currbalancer = $server;
 1219:                             $currtargets = {};
 1220:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
 1221:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
 1222:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
 1223:                                 }
 1224:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
 1225:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
 1226:                                 }
 1227:                             }
 1228:                             last;
 1229:                         }
 1230:                     }
 1231:                 }
 1232:             }
 1233:         }
 1234:     }
 1235:     return ($currbalancer,$currtargets);
 1236: }
 1237: 
 1238: sub check_loadbalancing {
 1239:     my ($uname,$udom) = @_;
 1240:     my ($is_balancer,$dom_in_use,$homeintdom,$rule_in_effect,
 1241:         $offloadto,$otherserver);
 1242:     my $lonhost = $perlvar{'lonHostID'};
 1243:     my @hosts = &current_machine_ids();
 1244:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
 1245:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
 1246:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
 1247:     my $serverhomedom = &host_domain($lonhost);
 1248: 
 1249:     my $cachetime = 60*60*24;
 1250: 
 1251:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
 1252:         $dom_in_use = $udom;
 1253:         $homeintdom = 1;
 1254:     } else {
 1255:         $dom_in_use = $serverhomedom;
 1256:     }
 1257:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
 1258:     unless (defined($cached)) {
 1259:         my %domconfig =
 1260:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
 1261:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1262:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1263:         }
 1264:     }
 1265:     if (ref($result) eq 'HASH') {
 1266:         my $currbalancer = $result->{'lonhost'};
 1267:         my $currtargets = $result->{'targets'};
 1268:         my $currrules = $result->{'rules'};
 1269:         if ($currbalancer ne '') {
 1270:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
 1271:                 $is_balancer = 1;
 1272:             }
 1273:         }
 1274:         if ($is_balancer) {
 1275:             if (ref($currrules) eq 'HASH') {
 1276:                 if ($homeintdom) {
 1277:                     if ($uname ne '') {
 1278:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
 1279:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
 1280:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
 1281:                                 $rule_in_effect = $currrules->{'_LC_author'};
 1282:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
 1283:                                 $rule_in_effect = $currrules->{'_LC_adv'}
 1284:                             }
 1285:                         }
 1286:                         if ($rule_in_effect eq '') {
 1287:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
 1288:                             if ($userenv{'inststatus'} ne '') {
 1289:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
 1290:                                 my ($othertitle,$usertypes,$types) =
 1291:                                     &Apache::loncommon::sorted_inst_types($udom);
 1292:                                 if (ref($types) eq 'ARRAY') {
 1293:                                     foreach my $type (@{$types}) {
 1294:                                         if (grep(/^\Q$type\E$/,@statuses)) {
 1295:                                             if (exists($currrules->{$type})) {
 1296:                                                 $rule_in_effect = $currrules->{$type};
 1297:                                             }
 1298:                                         }
 1299:                                     }
 1300:                                 }
 1301:                             } else {
 1302:                                 if (exists($currrules->{'default'})) {
 1303:                                     $rule_in_effect = $currrules->{'default'};
 1304:                                 }
 1305:                             }
 1306:                         }
 1307:                     } else {
 1308:                         if (exists($currrules->{'default'})) {
 1309:                             $rule_in_effect = $currrules->{'default'};
 1310:                         }
 1311:                     }
 1312:                 } else {
 1313:                     if ($currrules->{'_LC_external'} ne '') {
 1314:                         $rule_in_effect = $currrules->{'_LC_external'};
 1315:                     }
 1316:                 }
 1317:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1318:                                                        $uname,$udom);
 1319:             }
 1320:         }
 1321:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
 1322:         my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
 1323:         unless (defined($cached)) {
 1324:             my %domconfig =
 1325:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
 1326:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1327:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
 1328:             }
 1329:         }
 1330:         if (ref($result) eq 'HASH') {
 1331:             my $currbalancer = $result->{'lonhost'};
 1332:             my $currtargets = $result->{'targets'};
 1333:             my $currrules = $result->{'rules'};
 1334: 
 1335:             if ($currbalancer eq $lonhost) {
 1336:                 $is_balancer = 1;
 1337:                 if (ref($currrules) eq 'HASH') {
 1338:                     if ($currrules->{'_LC_internetdom'} ne '') {
 1339:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
 1340:                     }
 1341:                 }
 1342:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
 1343:                                                        $uname,$udom);
 1344:             }
 1345:         } else {
 1346:             if ($perlvar{'lonBalancer'} eq 'yes') {
 1347:                 $is_balancer = 1;
 1348:                 $offloadto = &this_host_spares($dom_in_use);
 1349:             }
 1350:         }
 1351:     } else {
 1352:         if ($perlvar{'lonBalancer'} eq 'yes') {
 1353:             $is_balancer = 1;
 1354:             $offloadto = &this_host_spares($dom_in_use);
 1355:         }
 1356:     }
 1357:     if ($is_balancer) {
 1358:         my $lowest_load = 30000;
 1359:         if (ref($offloadto) eq 'HASH') {
 1360:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
 1361:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
 1362:                     ($otherserver,$lowest_load) =
 1363:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1364:                 }
 1365:             }
 1366:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
 1367: 
 1368:             if (!$found_server) {
 1369:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
 1370:                     foreach my $try_server (@{$offloadto->{'default'}}) {
 1371:                         ($otherserver,$lowest_load) =
 1372:                             &compare_server_load($try_server,$otherserver,$lowest_load);
 1373:                     }
 1374:                 }
 1375:             }
 1376:         } elsif (ref($offloadto) eq 'ARRAY') {
 1377:             if (@{$offloadto} == 1) {
 1378:                 $otherserver = $offloadto->[0];
 1379:             } elsif (@{$offloadto} > 1) {
 1380:                 foreach my $try_server (@{$offloadto}) {
 1381:                     ($otherserver,$lowest_load) =
 1382:                         &compare_server_load($try_server,$otherserver,$lowest_load);
 1383:                 }
 1384:             }
 1385:         }
 1386:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
 1387:             $is_balancer = 0;
 1388:             if ($uname ne '' && $udom ne '') {
 1389:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
 1390:                     
 1391:                     &appenv({'user.loadbalexempt'     => $lonhost,  
 1392:                              'user.loadbalcheck.time' => time});
 1393:                 }
 1394:             }
 1395:         }
 1396:     }
 1397:     return ($is_balancer,$otherserver);
 1398: }
 1399: 
 1400: sub get_loadbalancer_targets {
 1401:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
 1402:     my $offloadto;
 1403:     if ($rule_in_effect eq 'none') {
 1404:         return [$perlvar{'lonHostID'}];
 1405:     } elsif ($rule_in_effect eq '') {
 1406:         $offloadto = $currtargets;
 1407:     } else {
 1408:         if ($rule_in_effect eq 'homeserver') {
 1409:             my $homeserver = &homeserver($uname,$udom);
 1410:             if ($homeserver ne 'no_host') {
 1411:                 $offloadto = [$homeserver];
 1412:             }
 1413:         } elsif ($rule_in_effect eq 'externalbalancer') {
 1414:             my %domconfig =
 1415:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
 1416:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
 1417:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
 1418:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
 1419:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
 1420:                     }
 1421:                 }
 1422:             } else {
 1423:                 my %servers = &internet_dom_servers($udom);
 1424:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
 1425:                 if (&hostname($remotebalancer) ne '') {
 1426:                     $offloadto = [$remotebalancer];
 1427:                 }
 1428:             }
 1429:         } elsif (&hostname($rule_in_effect) ne '') {
 1430:             $offloadto = [$rule_in_effect];
 1431:         }
 1432:     }
 1433:     return $offloadto;
 1434: }
 1435: 
 1436: sub internet_dom_servers {
 1437:     my ($dom) = @_;
 1438:     my (%uniqservers,%servers);
 1439:     my $primaryserver = &hostname(&domain($dom,'primary'));
 1440:     my @machinedoms = &machine_domains($primaryserver);
 1441:     foreach my $mdom (@machinedoms) {
 1442:         my %currservers = %servers;
 1443:         my %server = &get_servers($mdom);
 1444:         %servers = (%currservers,%server);
 1445:     }
 1446:     my %by_hostname;
 1447:     foreach my $id (keys(%servers)) {
 1448:         push(@{$by_hostname{$servers{$id}}},$id);
 1449:     }
 1450:     foreach my $hostname (sort(keys(%by_hostname))) {
 1451:         if (@{$by_hostname{$hostname}} > 1) {
 1452:             my $match = 0;
 1453:             foreach my $id (@{$by_hostname{$hostname}}) {
 1454:                 if (&host_domain($id) eq $dom) {
 1455:                     $uniqservers{$id} = $hostname;
 1456:                     $match = 1;
 1457:                 }
 1458:             }
 1459:             unless ($match) {
 1460:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1461:             }
 1462:         } else {
 1463:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
 1464:         }
 1465:     }
 1466:     return %uniqservers;
 1467: }
 1468: 
 1469: # ---------------------- Find the homebase for a user from domain's lib servers
 1470: 
 1471: my %homecache;
 1472: sub homeserver {
 1473:     my ($uname,$udom,$ignoreBadCache)=@_;
 1474:     my $index="$uname:$udom";
 1475: 
 1476:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1477: 
 1478:     my %servers = &get_servers($udom,'library');
 1479:     foreach my $tryserver (keys(%servers)) {
 1480:         next if ($ignoreBadCache ne 'true' && 
 1481: 		 exists($badServerCache{$tryserver}));
 1482: 
 1483: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1484: 	if ($answer eq 'found') {
 1485: 	    delete($badServerCache{$tryserver}); 
 1486: 	    return $homecache{$index}=$tryserver;
 1487: 	} elsif ($answer eq 'no_host') {
 1488: 	    $badServerCache{$tryserver}=1;
 1489: 	}
 1490:     }    
 1491:     return 'no_host';
 1492: }
 1493: 
 1494: # ------------------------------------- Find the usernames behind a list of IDs
 1495: 
 1496: sub idget {
 1497:     my ($udom,@ids)=@_;
 1498:     my %returnhash=();
 1499:     
 1500:     my %servers = &get_servers($udom,'library');
 1501:     foreach my $tryserver (keys(%servers)) {
 1502: 	my $idlist=join('&',@ids);
 1503: 	$idlist=~tr/A-Z/a-z/; 
 1504: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1505: 	my @answer=();
 1506: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1507: 	    @answer=split(/\&/,$reply);
 1508: 	}                    ;
 1509: 	my $i;
 1510: 	for ($i=0;$i<=$#ids;$i++) {
 1511: 	    if ($answer[$i]) {
 1512: 		$returnhash{$ids[$i]}=$answer[$i];
 1513: 	    } 
 1514: 	}
 1515:     } 
 1516:     return %returnhash;
 1517: }
 1518: 
 1519: # ------------------------------------- Find the IDs behind a list of usernames
 1520: 
 1521: sub idrget {
 1522:     my ($udom,@unames)=@_;
 1523:     my %returnhash=();
 1524:     foreach my $uname (@unames) {
 1525:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1526:     }
 1527:     return %returnhash;
 1528: }
 1529: 
 1530: # ------------------------------- Store away a list of names and associated IDs
 1531: 
 1532: sub idput {
 1533:     my ($udom,%ids)=@_;
 1534:     my %servers=();
 1535:     foreach my $uname (keys(%ids)) {
 1536: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1537:         my $uhom=&homeserver($uname,$udom);
 1538:         if ($uhom ne 'no_host') {
 1539:             my $id=&escape($ids{$uname});
 1540:             $id=~tr/A-Z/a-z/;
 1541:             my $esc_unam=&escape($uname);
 1542: 	    if ($servers{$uhom}) {
 1543: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
 1544:             } else {
 1545:                 $servers{$uhom}=$id.'='.$esc_unam;
 1546:             }
 1547:         }
 1548:     }
 1549:     foreach my $server (keys(%servers)) {
 1550:         &critical('idput:'.$udom.':'.$servers{$server},$server);
 1551:     }
 1552: }
 1553: 
 1554: # ------------------------------dump from db file owned by domainconfig user
 1555: sub dump_dom {
 1556:     my ($namespace, $udom, $regexp) = @_;
 1557: 
 1558:     $udom ||= $env{'user.domain'};
 1559: 
 1560:     return () unless $udom;
 1561: 
 1562:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
 1563: }
 1564: 
 1565: # ------------------------------------------ get items from domain db files   
 1566: 
 1567: sub get_dom {
 1568:     my ($namespace,$storearr,$udom,$uhome)=@_;
 1569:     my $items='';
 1570:     foreach my $item (@$storearr) {
 1571:         $items.=&escape($item).'&';
 1572:     }
 1573:     $items=~s/\&$//;
 1574:     if (!$udom) {
 1575:         $udom=$env{'user.domain'};
 1576:         if (defined(&domain($udom,'primary'))) {
 1577:             $uhome=&domain($udom,'primary');
 1578:         } else {
 1579:             undef($uhome);
 1580:         }
 1581:     } else {
 1582:         if (!$uhome) {
 1583:             if (defined(&domain($udom,'primary'))) {
 1584:                 $uhome=&domain($udom,'primary');
 1585:             }
 1586:         }
 1587:     }
 1588:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1589:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 1590:         my %returnhash;
 1591:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 1592:             return %returnhash;
 1593:         }
 1594:         my @pairs=split(/\&/,$rep);
 1595:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1596:             return @pairs;
 1597:         }
 1598:         my $i=0;
 1599:         foreach my $item (@$storearr) {
 1600:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 1601:             $i++;
 1602:         }
 1603:         return %returnhash;
 1604:     } else {
 1605:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1606:     }
 1607: }
 1608: 
 1609: # -------------------------------------------- put items in domain db files 
 1610: 
 1611: sub put_dom {
 1612:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1613:     if (!$udom) {
 1614:         $udom=$env{'user.domain'};
 1615:         if (defined(&domain($udom,'primary'))) {
 1616:             $uhome=&domain($udom,'primary');
 1617:         } else {
 1618:             undef($uhome);
 1619:         }
 1620:     } else {
 1621:         if (!$uhome) {
 1622:             if (defined(&domain($udom,'primary'))) {
 1623:                 $uhome=&domain($udom,'primary');
 1624:             }
 1625:         }
 1626:     } 
 1627:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1628:         my $items='';
 1629:         foreach my $item (keys(%$storehash)) {
 1630:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 1631:         }
 1632:         $items=~s/\&$//;
 1633:         return &reply("putdom:$udom:$namespace:$items",$uhome);
 1634:     } else {
 1635:         &logthis("put_dom failed - no homeserver and/or domain");
 1636:     }
 1637: }
 1638: 
 1639: # --------------------- newput for items in db file owned by domainconfig user
 1640: sub newput_dom {
 1641:     my ($namespace,$storehash,$udom) = @_;
 1642:     my $result;
 1643:     if (!$udom) {
 1644:         $udom=$env{'user.domain'};
 1645:     }
 1646:     if ($udom) {
 1647:         my $uname = &get_domainconfiguser($udom);
 1648:         $result = &newput($namespace,$storehash,$udom,$uname);
 1649:     }
 1650:     return $result;
 1651: }
 1652: 
 1653: # --------------------- delete for items in db file owned by domainconfig user
 1654: sub del_dom {
 1655:     my ($namespace,$storearr,$udom)=@_;
 1656:     if (ref($storearr) eq 'ARRAY') {
 1657:         if (!$udom) {
 1658:             $udom=$env{'user.domain'};
 1659:         }
 1660:         if ($udom) {
 1661:             my $uname = &get_domainconfiguser($udom); 
 1662:             return &del($namespace,$storearr,$udom,$uname);
 1663:         }
 1664:     }
 1665: }
 1666: 
 1667: # ----------------------------------construct domainconfig user for a domain 
 1668: sub get_domainconfiguser {
 1669:     my ($udom) = @_;
 1670:     return $udom.'-domainconfig';
 1671: }
 1672: 
 1673: sub retrieve_inst_usertypes {
 1674:     my ($udom) = @_;
 1675:     my (%returnhash,@order);
 1676:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 1677:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 1678:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 1679:         %returnhash = %{$domdefs{'inststatustypes'}};
 1680:         @order = @{$domdefs{'inststatusorder'}};
 1681:     } else {
 1682:         if (defined(&domain($udom,'primary'))) {
 1683:             my $uhome=&domain($udom,'primary');
 1684:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 1685:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 1686:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
 1687:                 return (\%returnhash,\@order);
 1688:             }
 1689:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 1690:             my @pairs=split(/\&/,$hashitems);
 1691:             foreach my $item (@pairs) {
 1692:                 my ($key,$value)=split(/=/,$item,2);
 1693:                 $key = &unescape($key);
 1694:                 next if ($key =~ /^error: 2 /);
 1695:                 $returnhash{$key}=&thaw_unescape($value);
 1696:             }
 1697:             my @esc_order = split(/\&/,$orderitems);
 1698:             foreach my $item (@esc_order) {
 1699:                 push(@order,&unescape($item));
 1700:             }
 1701:         } else {
 1702:             &logthis("get_dom failed - no primary domain server for $udom");
 1703:         }
 1704:     }
 1705:     return (\%returnhash,\@order);
 1706: }
 1707: 
 1708: sub is_domainimage {
 1709:     my ($url) = @_;
 1710:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1711:         if (&domain($1) ne '') {
 1712:             return '1';
 1713:         }
 1714:     }
 1715:     return;
 1716: }
 1717: 
 1718: sub inst_directory_query {
 1719:     my ($srch) = @_;
 1720:     my $udom = $srch->{'srchdomain'};
 1721:     my %results;
 1722:     my $homeserver = &domain($udom,'primary');
 1723:     my $outcome;
 1724:     if ($homeserver ne '') {
 1725: 	my $queryid=&reply("querysend:instdirsearch:".
 1726: 			   &escape($srch->{'srchby'}).':'.
 1727: 			   &escape($srch->{'srchterm'}).':'.
 1728: 			   &escape($srch->{'srchtype'}),$homeserver);
 1729: 	my $host=&hostname($homeserver);
 1730: 	if ($queryid !~/^\Q$host\E\_/) {
 1731: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1732: 	    return;
 1733: 	}
 1734: 	my $response = &get_query_reply($queryid);
 1735: 	my $maxtries = 5;
 1736: 	my $tries = 1;
 1737: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1738: 	    $response = &get_query_reply($queryid);
 1739: 	    $tries ++;
 1740: 	}
 1741: 
 1742:         if (!&error($response) && $response ne 'refused') {
 1743:             if ($response eq 'unavailable') {
 1744:                 $outcome = $response;
 1745:             } else {
 1746:                 $outcome = 'ok';
 1747:                 my @matches = split(/\n/,$response);
 1748:                 foreach my $match (@matches) {
 1749:                     my ($key,$value) = split(/=/,$match);
 1750:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1751:                 }
 1752:             }
 1753:         }
 1754:     }
 1755:     return ($outcome,%results);
 1756: }
 1757: 
 1758: sub usersearch {
 1759:     my ($srch) = @_;
 1760:     my $dom = $srch->{'srchdomain'};
 1761:     my %results;
 1762:     my %libserv = &all_library();
 1763:     my $query = 'usersearch';
 1764:     foreach my $tryserver (keys(%libserv)) {
 1765:         if (&host_domain($tryserver) eq $dom) {
 1766:             my $host=&hostname($tryserver);
 1767:             my $queryid=
 1768:                 &reply("querysend:".&escape($query).':'.
 1769:                        &escape($srch->{'srchby'}).':'.
 1770:                        &escape($srch->{'srchtype'}).':'.
 1771:                        &escape($srch->{'srchterm'}),$tryserver);
 1772:             if ($queryid !~/^\Q$host\E\_/) {
 1773:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1774:                 next;
 1775:             }
 1776:             my $reply = &get_query_reply($queryid);
 1777:             my $maxtries = 1;
 1778:             my $tries = 1;
 1779:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1780:                 $reply = &get_query_reply($queryid);
 1781:                 $tries ++;
 1782:             }
 1783:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1784:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1785:             } else {
 1786:                 my @matches;
 1787:                 if ($reply =~ /\n/) {
 1788:                     @matches = split(/\n/,$reply);
 1789:                 } else {
 1790:                     @matches = split(/\&/,$reply);
 1791:                 }
 1792:                 foreach my $match (@matches) {
 1793:                     my ($uname,$udom,%userhash);
 1794:                     foreach my $entry (split(/:/,$match)) {
 1795:                         my ($key,$value) =
 1796:                             map {&unescape($_);} split(/=/,$entry);
 1797:                         $userhash{$key} = $value;
 1798:                         if ($key eq 'username') {
 1799:                             $uname = $value;
 1800:                         } elsif ($key eq 'domain') {
 1801:                             $udom = $value;
 1802:                         }
 1803:                     }
 1804:                     $results{$uname.':'.$udom} = \%userhash;
 1805:                 }
 1806:             }
 1807:         }
 1808:     }
 1809:     return %results;
 1810: }
 1811: 
 1812: sub get_instuser {
 1813:     my ($udom,$uname,$id) = @_;
 1814:     my $homeserver = &domain($udom,'primary');
 1815:     my ($outcome,%results);
 1816:     if ($homeserver ne '') {
 1817:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1818:                            &escape($id).':'.&escape($udom),$homeserver);
 1819:         my $host=&hostname($homeserver);
 1820:         if ($queryid !~/^\Q$host\E\_/) {
 1821:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1822:             return;
 1823:         }
 1824:         my $response = &get_query_reply($queryid);
 1825:         my $maxtries = 5;
 1826:         my $tries = 1;
 1827:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1828:             $response = &get_query_reply($queryid);
 1829:             $tries ++;
 1830:         }
 1831:         if (!&error($response) && $response ne 'refused') {
 1832:             if ($response eq 'unavailable') {
 1833:                 $outcome = $response;
 1834:             } else {
 1835:                 $outcome = 'ok';
 1836:                 my @matches = split(/\n/,$response);
 1837:                 foreach my $match (@matches) {
 1838:                     my ($key,$value) = split(/=/,$match);
 1839:                     $results{&unescape($key)} = &thaw_unescape($value);
 1840:                 }
 1841:             }
 1842:         }
 1843:     }
 1844:     my %userinfo;
 1845:     if (ref($results{$uname}) eq 'HASH') {
 1846:         %userinfo = %{$results{$uname}};
 1847:     } 
 1848:     return ($outcome,%userinfo);
 1849: }
 1850: 
 1851: sub inst_rulecheck {
 1852:     my ($udom,$uname,$id,$item,$rules) = @_;
 1853:     my %returnhash;
 1854:     if ($udom ne '') {
 1855:         if (ref($rules) eq 'ARRAY') {
 1856:             @{$rules} = map {&escape($_);} (@{$rules});
 1857:             my $rulestr = join(':',@{$rules});
 1858:             my $homeserver=&domain($udom,'primary');
 1859:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1860:                 my $response;
 1861:                 if ($item eq 'username') {                
 1862:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1863:                                               ':'.&escape($uname).':'.$rulestr,
 1864:                                               $homeserver));
 1865:                 } elsif ($item eq 'id') {
 1866:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1867:                                               ':'.&escape($id).':'.$rulestr,
 1868:                                               $homeserver));
 1869:                 } elsif ($item eq 'selfcreate') {
 1870:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1871:                                                &escape($udom).':'.&escape($uname).
 1872:                                               ':'.$rulestr,$homeserver));
 1873:                 }
 1874:                 if ($response ne 'refused') {
 1875:                     my @pairs=split(/\&/,$response);
 1876:                     foreach my $item (@pairs) {
 1877:                         my ($key,$value)=split(/=/,$item,2);
 1878:                         $key = &unescape($key);
 1879:                         next if ($key =~ /^error: 2 /);
 1880:                         $returnhash{$key}=&thaw_unescape($value);
 1881:                     }
 1882:                 }
 1883:             }
 1884:         }
 1885:     }
 1886:     return %returnhash;
 1887: }
 1888: 
 1889: sub inst_userrules {
 1890:     my ($udom,$check) = @_;
 1891:     my (%ruleshash,@ruleorder);
 1892:     if ($udom ne '') {
 1893:         my $homeserver=&domain($udom,'primary');
 1894:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1895:             my $response;
 1896:             if ($check eq 'id') {
 1897:                 $response=&reply('instidrules:'.&escape($udom),
 1898:                                  $homeserver);
 1899:             } elsif ($check eq 'email') {
 1900:                 $response=&reply('instemailrules:'.&escape($udom),
 1901:                                  $homeserver);
 1902:             } else {
 1903:                 $response=&reply('instuserrules:'.&escape($udom),
 1904:                                  $homeserver);
 1905:             }
 1906:             if (($response ne 'refused') && ($response ne 'error') && 
 1907:                 ($response ne 'unknown_cmd') && 
 1908:                 ($response ne 'no_such_host')) {
 1909:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1910:                 my @pairs=split(/\&/,$hashitems);
 1911:                 foreach my $item (@pairs) {
 1912:                     my ($key,$value)=split(/=/,$item,2);
 1913:                     $key = &unescape($key);
 1914:                     next if ($key =~ /^error: 2 /);
 1915:                     $ruleshash{$key}=&thaw_unescape($value);
 1916:                 }
 1917:                 my @esc_order = split(/\&/,$orderitems);
 1918:                 foreach my $item (@esc_order) {
 1919:                     push(@ruleorder,&unescape($item));
 1920:                 }
 1921:             }
 1922:         }
 1923:     }
 1924:     return (\%ruleshash,\@ruleorder);
 1925: }
 1926: 
 1927: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 1928: 
 1929: sub get_domain_defaults {
 1930:     my ($domain) = @_;
 1931:     my $cachetime = 60*60*24;
 1932:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 1933:     if (defined($cached)) {
 1934:         if (ref($result) eq 'HASH') {
 1935:             return %{$result};
 1936:         }
 1937:     }
 1938:     my %domdefaults;
 1939:     my %domconfig =
 1940:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 1941:                                   'requestcourses','inststatus',
 1942:                                   'coursedefaults','usersessions',
 1943:                                   'requestauthor'],$domain);
 1944:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 1945:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 1946:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 1947:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 1948:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 1949:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 1950:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
 1951:     } else {
 1952:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 1953:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 1954:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 1955:     }
 1956:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 1957:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 1958:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 1959:         } else {
 1960:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 1961:         } 
 1962:         my @usertools = ('aboutme','blog','webdav','portfolio');
 1963:         foreach my $item (@usertools) {
 1964:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 1965:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 1966:             }
 1967:         }
 1968:     }
 1969:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 1970:         foreach my $item ('official','unofficial','community') {
 1971:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 1972:         }
 1973:     }
 1974:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
 1975:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
 1976:     }
 1977:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 1978:         foreach my $item ('inststatustypes','inststatusorder') {
 1979:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 1980:         }
 1981:     }
 1982:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 1983:         foreach my $item ('canuse_pdfforms') {
 1984:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
 1985:         }
 1986:     }
 1987:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1988:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 1989:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 1990:         }
 1991:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 1992:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 1993:         }
 1994:     }
 1995:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
 1996:                                   $cachetime);
 1997:     return %domdefaults;
 1998: }
 1999: 
 2000: # --------------------------------------------------- Assign a key to a student
 2001: 
 2002: sub assign_access_key {
 2003: #
 2004: # a valid key looks like uname:udom#comments
 2005: # comments are being appended
 2006: #
 2007:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 2008:     $kdom=
 2009:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 2010:     $knum=
 2011:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 2012:     $cdom=
 2013:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2014:     $cnum=
 2015:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2016:     $udom=$env{'user.name'} unless (defined($udom));
 2017:     $uname=$env{'user.domain'} unless (defined($uname));
 2018:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 2019:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 2020:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 2021:                                                   # assigned to this person
 2022:                                                   # - this should not happen,
 2023:                                                   # unless something went wrong
 2024:                                                   # the first time around
 2025: # ready to assign
 2026:         $logentry=$1.'; '.$logentry;
 2027:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 2028:                                                  $kdom,$knum) eq 'ok') {
 2029: # key now belongs to user
 2030: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 2031:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 2032:                 &appenv({'environment.'.$envkey => $ckey});
 2033:                 return 'ok';
 2034:             } else {
 2035:                 return 
 2036:   'error: Count not permanently assign key, will need to be re-entered later.';
 2037: 	    }
 2038:         } else {
 2039:             return 'error: Could not assign key, try again later.';
 2040:         }
 2041:     } elsif (!$existing{$ckey}) {
 2042: # the key does not exist
 2043: 	return 'error: The key does not exist';
 2044:     } else {
 2045: # the key is somebody else's
 2046: 	return 'error: The key is already in use';
 2047:     }
 2048: }
 2049: 
 2050: # ------------------------------------------ put an additional comment on a key
 2051: 
 2052: sub comment_access_key {
 2053: #
 2054: # a valid key looks like uname:udom#comments
 2055: # comments are being appended
 2056: #
 2057:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 2058:     $cdom=
 2059:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2060:     $cnum=
 2061:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2062:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2063:     if ($existing{$ckey}) {
 2064:         $existing{$ckey}.='; '.$logentry;
 2065: # ready to assign
 2066:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 2067:                                                  $cdom,$cnum) eq 'ok') {
 2068: 	    return 'ok';
 2069:         } else {
 2070: 	    return 'error: Count not store comment.';
 2071:         }
 2072:     } else {
 2073: # the key does not exist
 2074: 	return 'error: The key does not exist';
 2075:     }
 2076: }
 2077: 
 2078: # ------------------------------------------------------ Generate a set of keys
 2079: 
 2080: sub generate_access_keys {
 2081:     my ($number,$cdom,$cnum,$logentry)=@_;
 2082:     $cdom=
 2083:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2084:     $cnum=
 2085:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2086:     unless (&allowed('mky',$cdom)) { return 0; }
 2087:     unless (($cdom) && ($cnum)) { return 0; }
 2088:     if ($number>10000) { return 0; }
 2089:     sleep(2); # make sure don't get same seed twice
 2090:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 2091:     my $total=0;
 2092:     for (my $i=1;$i<=$number;$i++) {
 2093:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 2094:                   sprintf("%lx",int(100000*rand)).'-'.
 2095:                   sprintf("%lx",int(100000*rand));
 2096:        $newkey=~s/1/g/g; # folks mix up 1 and l
 2097:        $newkey=~s/0/h/g; # and also 0 and O
 2098:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 2099:        if ($existing{$newkey}) {
 2100:            $i--;
 2101:        } else {
 2102: 	  if (&put('accesskeys',
 2103:               { $newkey => '# generated '.localtime().
 2104:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 2105:                            '; '.$logentry },
 2106: 		   $cdom,$cnum) eq 'ok') {
 2107:               $total++;
 2108: 	  }
 2109:        }
 2110:     }
 2111:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 2112:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 2113:     return $total;
 2114: }
 2115: 
 2116: # ------------------------------------------------------- Validate an accesskey
 2117: 
 2118: sub validate_access_key {
 2119:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 2120:     $cdom=
 2121:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 2122:     $cnum=
 2123:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 2124:     $udom=$env{'user.domain'} unless (defined($udom));
 2125:     $uname=$env{'user.name'} unless (defined($uname));
 2126:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 2127:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 2128: }
 2129: 
 2130: # ------------------------------------- Find the section of student in a course
 2131: sub devalidate_getsection_cache {
 2132:     my ($udom,$unam,$courseid)=@_;
 2133:     my $hashid="$udom:$unam:$courseid";
 2134:     &devalidate_cache_new('getsection',$hashid);
 2135: }
 2136: 
 2137: sub courseid_to_courseurl {
 2138:     my ($courseid) = @_;
 2139:     #already url style courseid
 2140:     return $courseid if ($courseid =~ m{^/});
 2141: 
 2142:     if (exists($env{'course.'.$courseid.'.num'})) {
 2143: 	my $cnum = $env{'course.'.$courseid.'.num'};
 2144: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 2145: 	return "/$cdom/$cnum";
 2146:     }
 2147: 
 2148:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 2149:     if (exists($courseinfo{'num'})) {
 2150: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 2151:     }
 2152: 
 2153:     return undef;
 2154: }
 2155: 
 2156: sub getsection {
 2157:     my ($udom,$unam,$courseid)=@_;
 2158:     my $cachetime=1800;
 2159: 
 2160:     my $hashid="$udom:$unam:$courseid";
 2161:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 2162:     if (defined($cached)) { return $result; }
 2163: 
 2164:     my %Pending; 
 2165:     my %Expired;
 2166:     #
 2167:     # Each role can either have not started yet (pending), be active, 
 2168:     #    or have expired.
 2169:     #
 2170:     # If there is an active role, we are done.
 2171:     #
 2172:     # If there is more than one role which has not started yet, 
 2173:     #     choose the one which will start sooner
 2174:     # If there is one role which has not started yet, return it.
 2175:     #
 2176:     # If there is more than one expired role, choose the one which ended last.
 2177:     # If there is a role which has expired, return it.
 2178:     #
 2179:     $courseid = &courseid_to_courseurl($courseid);
 2180:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 2181:     foreach my $key (keys(%roleshash)) {
 2182:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 2183:         my $section=$1;
 2184:         if ($key eq $courseid.'_st') { $section=''; }
 2185:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 2186:         my $now=time;
 2187:         if (defined($end) && $end && ($now > $end)) {
 2188:             $Expired{$end}=$section;
 2189:             next;
 2190:         }
 2191:         if (defined($start) && $start && ($now < $start)) {
 2192:             $Pending{$start}=$section;
 2193:             next;
 2194:         }
 2195:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 2196:     }
 2197:     #
 2198:     # Presumedly there will be few matching roles from the above
 2199:     # loop and the sorting time will be negligible.
 2200:     if (scalar(keys(%Pending))) {
 2201:         my ($time) = sort {$a <=> $b} keys(%Pending);
 2202:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 2203:     } 
 2204:     if (scalar(keys(%Expired))) {
 2205:         my @sorted = sort {$a <=> $b} keys(%Expired);
 2206:         my $time = pop(@sorted);
 2207:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 2208:     }
 2209:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 2210: }
 2211: 
 2212: sub save_cache {
 2213:     &purge_remembered();
 2214:     #&Apache::loncommon::validate_page();
 2215:     undef(%env);
 2216:     undef($env_loaded);
 2217: }
 2218: 
 2219: my $to_remember=-1;
 2220: my %remembered;
 2221: my %accessed;
 2222: my $kicks=0;
 2223: my $hits=0;
 2224: sub make_key {
 2225:     my ($name,$id) = @_;
 2226:     if (length($id) > 65 
 2227: 	&& length(&escape($id)) > 200) {
 2228: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 2229:     }
 2230:     return &escape($name.':'.$id);
 2231: }
 2232: 
 2233: sub devalidate_cache_new {
 2234:     my ($name,$id,$debug) = @_;
 2235:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 2236:     $id=&make_key($name,$id);
 2237:     $memcache->delete($id);
 2238:     delete($remembered{$id});
 2239:     delete($accessed{$id});
 2240: }
 2241: 
 2242: sub is_cached_new {
 2243:     my ($name,$id,$debug) = @_;
 2244:     $id=&make_key($name,$id);
 2245:     if (exists($remembered{$id})) {
 2246: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
 2247: 	$accessed{$id}=[&gettimeofday()];
 2248: 	$hits++;
 2249: 	return ($remembered{$id},1);
 2250:     }
 2251:     my $value = $memcache->get($id);
 2252:     if (!(defined($value))) {
 2253: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 2254: 	return (undef,undef);
 2255:     }
 2256:     if ($value eq '__undef__') {
 2257: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 2258: 	$value=undef;
 2259:     }
 2260:     &make_room($id,$value,$debug);
 2261:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 2262:     return ($value,1);
 2263: }
 2264: 
 2265: sub do_cache_new {
 2266:     my ($name,$id,$value,$time,$debug) = @_;
 2267:     $id=&make_key($name,$id);
 2268:     my $setvalue=$value;
 2269:     if (!defined($setvalue)) {
 2270: 	$setvalue='__undef__';
 2271:     }
 2272:     if (!defined($time) ) {
 2273: 	$time=600;
 2274:     }
 2275:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 2276:     my $result = $memcache->set($id,$setvalue,$time);
 2277:     if (! $result) {
 2278: 	&logthis("caching of id -> $id  failed");
 2279: 	$memcache->disconnect_all();
 2280:     }
 2281:     # need to make a copy of $value
 2282:     &make_room($id,$value,$debug);
 2283:     return $value;
 2284: }
 2285: 
 2286: sub make_room {
 2287:     my ($id,$value,$debug)=@_;
 2288: 
 2289:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 2290:                                     : $value;
 2291:     if ($to_remember<0) { return; }
 2292:     $accessed{$id}=[&gettimeofday()];
 2293:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 2294:     my $to_kick;
 2295:     my $max_time=0;
 2296:     foreach my $other (keys(%accessed)) {
 2297: 	if (&tv_interval($accessed{$other}) > $max_time) {
 2298: 	    $to_kick=$other;
 2299: 	    $max_time=&tv_interval($accessed{$other});
 2300: 	}
 2301:     }
 2302:     delete($remembered{$to_kick});
 2303:     delete($accessed{$to_kick});
 2304:     $kicks++;
 2305:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 2306:     return;
 2307: }
 2308: 
 2309: sub purge_remembered {
 2310:     #&logthis("Tossing ".scalar(keys(%remembered)));
 2311:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 2312:     undef(%remembered);
 2313:     undef(%accessed);
 2314: }
 2315: # ------------------------------------- Read an entry from a user's environment
 2316: 
 2317: sub userenvironment {
 2318:     my ($udom,$unam,@what)=@_;
 2319:     my $items;
 2320:     foreach my $item (@what) {
 2321:         $items.=&escape($item).'&';
 2322:     }
 2323:     $items=~s/\&$//;
 2324:     my %returnhash=();
 2325:     my $uhome = &homeserver($unam,$udom);
 2326:     unless ($uhome eq 'no_host') {
 2327:         my @answer=split(/\&/, 
 2328:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 2329:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 2330:             return %returnhash;
 2331:         }
 2332:         my $i;
 2333:         for ($i=0;$i<=$#what;$i++) {
 2334: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 2335:         }
 2336:     }
 2337:     return %returnhash;
 2338: }
 2339: 
 2340: # ---------------------------------------------------------- Get a studentphoto
 2341: sub studentphoto {
 2342:     my ($udom,$unam,$ext) = @_;
 2343:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2344:     if (defined($env{'request.course.id'})) {
 2345:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 2346:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 2347:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 2348:             } else {
 2349:                 my ($result,$perm_reqd)=
 2350: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2351:                 if ($result eq 'ok') {
 2352:                     if (!($perm_reqd eq 'yes')) {
 2353:                         return(&retrievestudentphoto($udom,$unam,$ext));
 2354:                     }
 2355:                 }
 2356:             }
 2357:         }
 2358:     } else {
 2359:         my ($result,$perm_reqd) = 
 2360: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 2361:         if ($result eq 'ok') {
 2362:             if (!($perm_reqd eq 'yes')) {
 2363:                 return(&retrievestudentphoto($udom,$unam,$ext));
 2364:             }
 2365:         }
 2366:     }
 2367:     return '/adm/lonKaputt/lonlogo_broken.gif';
 2368: }
 2369: 
 2370: sub retrievestudentphoto {
 2371:     my ($udom,$unam,$ext,$type) = @_;
 2372:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 2373:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 2374:     if ($ret eq 'ok') {
 2375:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 2376:         if ($type eq 'thumbnail') {
 2377:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 2378:         }
 2379:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 2380:         return $tokenurl;
 2381:     } else {
 2382:         if ($type eq 'thumbnail') {
 2383:             return '/adm/lonKaputt/genericstudent_tn.gif';
 2384:         } else { 
 2385:             return '/adm/lonKaputt/lonlogo_broken.gif';
 2386:         }
 2387:     }
 2388: }
 2389: 
 2390: # -------------------------------------------------------------------- New chat
 2391: 
 2392: sub chatsend {
 2393:     my ($newentry,$anon,$group)=@_;
 2394:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 2395:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2396:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 2397:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 2398: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 2399: 		   &escape($newentry)).':'.$group,$chome);
 2400: }
 2401: 
 2402: # ------------------------------------------ Find current version of a resource
 2403: 
 2404: sub getversion {
 2405:     my $fname=&clutter(shift);
 2406:     unless ($fname=~/^\/res\//) { return -1; }
 2407:     return &currentversion(&filelocation('',$fname));
 2408: }
 2409: 
 2410: sub currentversion {
 2411:     my $fname=shift;
 2412:     my $author=$fname;
 2413:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2414:     my ($udom,$uname)=split(/\//,$author);
 2415:     my $home=&homeserver($uname,$udom);
 2416:     if ($home eq 'no_host') { 
 2417:         return -1; 
 2418:     }
 2419:     my $answer=&reply("currentversion:$fname",$home);
 2420:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2421: 	return -1;
 2422:     }
 2423:     return $answer;
 2424: }
 2425: 
 2426: #
 2427: # Return special version number of resource if set by override, empty otherwise
 2428: #
 2429: sub usedversion {
 2430:     my $fname=shift;
 2431:     unless ($fname) { $fname=$env{'request.uri'}; }
 2432:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
 2433:     if ($urlversion) { return $urlversion; }
 2434:     return '';
 2435: }
 2436: 
 2437: # ----------------------------- Subscribe to a resource, return URL if possible
 2438: 
 2439: sub subscribe {
 2440:     my $fname=shift;
 2441:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 2442:     $fname=~s/[\n\r]//g;
 2443:     my $author=$fname;
 2444:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2445:     my ($udom,$uname)=split(/\//,$author);
 2446:     my $home=homeserver($uname,$udom);
 2447:     if ($home eq 'no_host') {
 2448:         return 'not_found';
 2449:     }
 2450:     my $answer=reply("sub:$fname",$home);
 2451:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 2452: 	$answer.=' by '.$home;
 2453:     }
 2454:     return $answer;
 2455: }
 2456:     
 2457: # -------------------------------------------------------------- Replicate file
 2458: 
 2459: sub repcopy {
 2460:     my $filename=shift;
 2461:     $filename=~s/\/+/\//g;
 2462:     my $londocroot = $perlvar{'lonDocRoot'};
 2463:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
 2464:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
 2465:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
 2466: 	$filename=~m{^/*(uploaded|editupload)/}) {
 2467: 	return &repcopy_userfile($filename);
 2468:     }
 2469:     $filename=~s/[\n\r]//g;
 2470:     my $transname="$filename.in.transfer";
 2471: # FIXME: this should flock
 2472:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 2473:     my $remoteurl=subscribe($filename);
 2474:     if ($remoteurl =~ /^con_lost by/) {
 2475: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2476:            return 'unavailable';
 2477:     } elsif ($remoteurl eq 'not_found') {
 2478: 	   #&logthis("Subscribe returned not_found: $filename");
 2479: 	   return 'not_found';
 2480:     } elsif ($remoteurl =~ /^rejected by/) {
 2481: 	   &logthis("Subscribe returned $remoteurl: $filename");
 2482:            return 'forbidden';
 2483:     } elsif ($remoteurl eq 'directory') {
 2484:            return 'ok';
 2485:     } else {
 2486:         my $author=$filename;
 2487:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2488:         my ($udom,$uname)=split(/\//,$author);
 2489:         my $home=homeserver($uname,$udom);
 2490:         unless ($home eq $perlvar{'lonHostID'}) {
 2491:            my @parts=split(/\//,$filename);
 2492:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 2493:            if ($path ne "$londocroot/res") {
 2494:                &logthis("Malconfiguration for replication: $filename");
 2495: 	       return 'bad_request';
 2496:            }
 2497:            my $count;
 2498:            for ($count=5;$count<$#parts;$count++) {
 2499:                $path.="/$parts[$count]";
 2500:                if ((-e $path)!=1) {
 2501: 		   mkdir($path,0777);
 2502:                }
 2503:            }
 2504:            my $ua=new LWP::UserAgent;
 2505:            my $request=new HTTP::Request('GET',"$remoteurl");
 2506:            my $response=$ua->request($request,$transname);
 2507:            if ($response->is_error()) {
 2508: 	       unlink($transname);
 2509:                my $message=$response->status_line;
 2510:                &logthis("<font color=\"blue\">WARNING:"
 2511:                        ." LWP get: $message: $filename</font>");
 2512:                return 'unavailable';
 2513:            } else {
 2514: 	       if ($remoteurl!~/\.meta$/) {
 2515:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 2516:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 2517:                   if ($mresponse->is_error()) {
 2518: 		      unlink($filename.'.meta');
 2519:                       &logthis(
 2520:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 2521:                   }
 2522: 	       }
 2523:                rename($transname,$filename);
 2524:                return 'ok';
 2525:            }
 2526:        }
 2527:     }
 2528: }
 2529: 
 2530: # ------------------------------------------------ Get server side include body
 2531: sub ssi_body {
 2532:     my ($filelink,%form)=@_;
 2533:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 2534:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 2535:     }
 2536:     my $output='';
 2537:     my $response;
 2538:     if ($filelink=~/^https?\:/) {
 2539:        ($output,$response)=&externalssi($filelink);
 2540:     } else {
 2541:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 2542:        $filelink .= 'inhibitmenu=yes';
 2543:        ($output,$response)=&ssi($filelink,%form);
 2544:     }
 2545:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 2546:     $output=~s/^.*?\<body[^\>]*\>//si;
 2547:     $output=~s/\<\/body\s*\>.*?$//si;
 2548:     if (wantarray) {
 2549:         return ($output, $response);
 2550:     } else {
 2551:         return $output;
 2552:     }
 2553: }
 2554: 
 2555: # --------------------------------------------------------- Server Side Include
 2556: 
 2557: sub absolute_url {
 2558:     my ($host_name) = @_;
 2559:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 2560:     if ($host_name eq '') {
 2561: 	$host_name = $ENV{'SERVER_NAME'};
 2562:     }
 2563:     return $protocol.$host_name;
 2564: }
 2565: 
 2566: #
 2567: #   Server side include.
 2568: # Parameters:
 2569: #  fn     Possibly encrypted resource name/id.
 2570: #  form   Hash that describes how the rendering should be done
 2571: #         and other things.
 2572: # Returns:
 2573: #   Scalar context: The content of the response.
 2574: #   Array context:  2 element list of the content and the full response object.
 2575: #     
 2576: sub ssi {
 2577: 
 2578:     my ($fn,%form)=@_;
 2579:     my $ua=new LWP::UserAgent;
 2580:     my $request;
 2581: 
 2582:     $form{'no_update_last_known'}=1;
 2583:     &Apache::lonenc::check_encrypt(\$fn);
 2584:     if (%form) {
 2585:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 2586:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
 2587:     } else {
 2588:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 2589:     }
 2590: 
 2591:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 2592:     my $response= $ua->request($request);
 2593:     my $content = $response->content;
 2594: 
 2595: 
 2596:     if (wantarray) {
 2597: 	return ($content, $response);
 2598:     } else {
 2599: 	return $content;
 2600:     }
 2601: }
 2602: 
 2603: sub externalssi {
 2604:     my ($url)=@_;
 2605:     my $ua=new LWP::UserAgent;
 2606:     my $request=new HTTP::Request('GET',$url);
 2607:     my $response=$ua->request($request);
 2608:     if (wantarray) {
 2609:         return ($response->content, $response);
 2610:     } else {
 2611:         return $response->content;
 2612:     }
 2613: }
 2614: 
 2615: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 2616: 
 2617: sub allowuploaded {
 2618:     my ($srcurl,$url)=@_;
 2619:     $url=&clutter(&declutter($url));
 2620:     my $dir=$url;
 2621:     $dir=~s/\/[^\/]+$//;
 2622:     my %httpref=();
 2623:     my $httpurl=&hreflocation('',$url);
 2624:     $httpref{'httpref.'.$httpurl}=$srcurl;
 2625:     &Apache::lonnet::appenv(\%httpref);
 2626: }
 2627: 
 2628: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 2629: # input: action, courseID, current domain, intended
 2630: #        path to file, source of file, instruction to parse file for objects,
 2631: #        ref to hash for embedded objects,
 2632: #        ref to hash for codebase of java objects.
 2633: #        reference to scalar to accommodate mime type determined
 2634: #          from File::MMagic if $parser = parse.
 2635: #
 2636: # output: url to file (if action was uploaddoc), 
 2637: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 2638: #
 2639: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 2640: # course.
 2641: #
 2642: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2643: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 2644: #          course's home server.
 2645: #
 2646: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 2647: #          be copied from $source (current location) to 
 2648: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2649: #         and will then be copied to
 2650: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 2651: #         course's home server.
 2652: #
 2653: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2654: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 2655: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2656: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 2657: #         in course's home server.
 2658: #
 2659: 
 2660: sub process_coursefile {
 2661:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
 2662:         $mimetype)=@_;
 2663:     my $fetchresult;
 2664:     my $home=&homeserver($docuname,$docudom);
 2665:     if ($action eq 'propagate') {
 2666:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2667: 			     $home);
 2668:     } else {
 2669:         my $fpath = '';
 2670:         my $fname = $file;
 2671:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2672:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2673:         my $filepath = &build_filepath($fpath);
 2674:         if ($action eq 'copy') {
 2675:             if ($source eq '') {
 2676:                 $fetchresult = 'no source file';
 2677:                 return $fetchresult;
 2678:             } else {
 2679:                 my $destination = $filepath.'/'.$fname;
 2680:                 rename($source,$destination);
 2681:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2682:                                  $home);
 2683:             }
 2684:         } elsif ($action eq 'uploaddoc') {
 2685:             open(my $fh,'>'.$filepath.'/'.$fname);
 2686:             print $fh $env{'form.'.$source};
 2687:             close($fh);
 2688:             if ($parser eq 'parse') {
 2689:                 my $mm = new File::MMagic;
 2690:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
 2691:                 if ($type eq 'text/html') {
 2692:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 2693:                     unless ($parse_result eq 'ok') {
 2694:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 2695:                     }
 2696:                 }
 2697:                 if (ref($mimetype)) {
 2698:                     $$mimetype = $type;
 2699:                 } 
 2700:             }
 2701:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2702:                                  $home);
 2703:             if ($fetchresult eq 'ok') {
 2704:                 return '/uploaded/'.$fpath.'/'.$fname;
 2705:             } else {
 2706:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2707:                         ' to host '.$home.': '.$fetchresult);
 2708:                 return '/adm/notfound.html';
 2709:             }
 2710:         }
 2711:     }
 2712:     unless ( $fetchresult eq 'ok') {
 2713:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2714:              ' to host '.$home.': '.$fetchresult);
 2715:     }
 2716:     return $fetchresult;
 2717: }
 2718: 
 2719: sub build_filepath {
 2720:     my ($fpath) = @_;
 2721:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 2722:     unless ($fpath eq '') {
 2723:         my @parts=split('/',$fpath);
 2724:         foreach my $part (@parts) {
 2725:             $filepath.= '/'.$part;
 2726:             if ((-e $filepath)!=1) {
 2727:                 mkdir($filepath,0777);
 2728:             }
 2729:         }
 2730:     }
 2731:     return $filepath;
 2732: }
 2733: 
 2734: sub store_edited_file {
 2735:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 2736:     my $file = $primary_url;
 2737:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 2738:     my $fpath = '';
 2739:     my $fname = $file;
 2740:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2741:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2742:     my $filepath = &build_filepath($fpath);
 2743:     open(my $fh,'>'.$filepath.'/'.$fname);
 2744:     print $fh $content;
 2745:     close($fh);
 2746:     my $home=&homeserver($docuname,$docudom);
 2747:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2748: 			  $home);
 2749:     if ($$fetchresult eq 'ok') {
 2750:         return '/uploaded/'.$fpath.'/'.$fname;
 2751:     } else {
 2752:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2753: 		 ' to host '.$home.': '.$$fetchresult);
 2754:         return '/adm/notfound.html';
 2755:     }
 2756: }
 2757: 
 2758: sub clean_filename {
 2759:     my ($fname,$args)=@_;
 2760: # Replace Windows backslashes by forward slashes
 2761:     $fname=~s/\\/\//g;
 2762:     if (!$args->{'keep_path'}) {
 2763:         # Get rid of everything but the actual filename
 2764: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 2765:     }
 2766: # Replace spaces by underscores
 2767:     $fname=~s/\s+/\_/g;
 2768: # Replace all other weird characters by nothing
 2769:     $fname=~s{[^/\w\.\-]}{}g;
 2770: # Replace all .\d. sequences with _\d. so they no longer look like version
 2771: # numbers
 2772:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 2773:     return $fname;
 2774: }
 2775: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 2776: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 2777: # image with the same aspect ratio as the original, but with dimensions which do 
 2778: # not exceed $resizewidth and $resizeheight.
 2779:  
 2780: sub resizeImage {
 2781:     my ($img_path,$resizewidth,$resizeheight) = @_;
 2782:     my $ima = Image::Magick->new;
 2783:     my $resized;
 2784:     if (-e $img_path) {
 2785:         $ima->Read($img_path);
 2786:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 2787:             my $width = $ima->Get('width');
 2788:             my $height = $ima->Get('height');
 2789:             if ($width > $resizewidth) {
 2790: 	        my $factor = $width/$resizewidth;
 2791:                 my $newheight = $height/$factor;
 2792:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 2793:                 $resized = 1;
 2794:             }
 2795:         }
 2796:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 2797:             my $width = $ima->Get('width');
 2798:             my $height = $ima->Get('height');
 2799:             if ($height > $resizeheight) {
 2800:                 my $factor = $height/$resizeheight;
 2801:                 my $newwidth = $width/$factor;
 2802:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 2803:                 $resized = 1;
 2804:             }
 2805:         }
 2806:         if ($resized) {
 2807:             $ima->Write($img_path);
 2808:         }
 2809:     }
 2810:     return;
 2811: }
 2812: 
 2813: # --------------- Take an uploaded file and put it into the userfiles directory
 2814: # input: $formname - the contents of the file are in $env{"form.$formname"}
 2815: #                    the desired filename is in $env{"form.$formname.filename"}
 2816: #        $context - possible values: coursedoc, existingfile, overwrite, 
 2817: #                                    canceloverwrite, or ''. 
 2818: #                   if 'coursedoc': upload to the current course
 2819: #                   if 'existingfile': write file to tmp/overwrites directory 
 2820: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
 2821: #                   $context is passed as argument to &finishuserfileupload
 2822: #        $subdir - directory in userfile to store the file into
 2823: #        $parser - instruction to parse file for objects ($parser = parse)    
 2824: #        $allfiles - reference to hash for embedded objects
 2825: #        $codebase - reference to hash for codebase of java objects
 2826: #        $desuname - username for permanent storage of uploaded file
 2827: #        $dsetudom - domain for permanaent storage of uploaded file
 2828: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 2829: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 2830: #        $resizewidth - width (pixels) to which to resize uploaded image
 2831: #        $resizeheight - height (pixels) to which to resize uploaded image
 2832: #        $mimetype - reference to scalar to accommodate mime type determined
 2833: #                    from File::MMagic.
 2834: # 
 2835: # output: url of file in userspace, or error: <message> 
 2836: #             or /adm/notfound.html if failure to upload occurse
 2837: 
 2838: sub userfileupload {
 2839:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
 2840:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
 2841:     if (!defined($subdir)) { $subdir='unknown'; }
 2842:     my $fname=$env{'form.'.$formname.'.filename'};
 2843:     $fname=&clean_filename($fname);
 2844:     # See if there is anything left
 2845:     unless ($fname) { return 'error: no uploaded file'; }
 2846:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
 2847:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
 2848:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
 2849:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 2850:         my $now = time;
 2851:         my $filepath;
 2852:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
 2853:              $filepath = 'tmp/helprequests/'.$now;
 2854:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
 2855:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 2856:                          '_'.$env{'user.domain'}.'/pending';
 2857:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
 2858:             my ($docuname,$docudom);
 2859:             if ($destudom) {
 2860:                 $docudom = $destudom;
 2861:             } else {
 2862:                 $docudom = $env{'user.domain'};
 2863:             }
 2864:             if ($destuname) {
 2865:                 $docuname = $destuname;
 2866:             } else {
 2867:                 $docuname = $env{'user.name'};
 2868:             }
 2869:             if (exists($env{'form.group'})) {
 2870:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2871:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2872:             }
 2873:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
 2874:             if ($context eq 'canceloverwrite') {
 2875:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
 2876:                 if (-e  $tempfile) {
 2877:                     my @info = stat($tempfile);
 2878:                     if ($info[9] eq $env{'form.timestamp'}) {
 2879:                         unlink($tempfile);
 2880:                     }
 2881:                 }
 2882:                 return;
 2883:             }
 2884:         }
 2885:         # Create the directory if not present
 2886:         my @parts=split(/\//,$filepath);
 2887:         my $fullpath = $perlvar{'lonDaemons'};
 2888:         for (my $i=0;$i<@parts;$i++) {
 2889:             $fullpath .= '/'.$parts[$i];
 2890:             if ((-e $fullpath)!=1) {
 2891:                 mkdir($fullpath,0777);
 2892:             }
 2893:         }
 2894:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2895:         print $fh $env{'form.'.$formname};
 2896:         close($fh);
 2897:         if ($context eq 'existingfile') {
 2898:             my @info = stat($fullpath.'/'.$fname);
 2899:             return ($fullpath.'/'.$fname,$info[9]);
 2900:         } else {
 2901:             return $fullpath.'/'.$fname;
 2902:         }
 2903:     }
 2904:     if ($subdir eq 'scantron') {
 2905:         $fname = 'scantron_orig_'.$fname;
 2906:     } else {
 2907:         $fname="$subdir/$fname";
 2908:     }
 2909:     if ($context eq 'coursedoc') {
 2910: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2911: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2912:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 2913:             return &finishuserfileupload($docuname,$docudom,
 2914: 					 $formname,$fname,$parser,$allfiles,
 2915: 					 $codebase,$thumbwidth,$thumbheight,
 2916:                                          $resizewidth,$resizeheight,$context,$mimetype);
 2917:         } else {
 2918:             $fname=$env{'form.folder'}.'/'.$fname;
 2919:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 2920: 				       $fname,$formname,$parser,
 2921: 				       $allfiles,$codebase,$mimetype);
 2922:         }
 2923:     } elsif (defined($destuname)) {
 2924:         my $docuname=$destuname;
 2925:         my $docudom=$destudom;
 2926: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2927: 				     $parser,$allfiles,$codebase,
 2928:                                      $thumbwidth,$thumbheight,
 2929:                                      $resizewidth,$resizeheight,$context,$mimetype);
 2930:     } else {
 2931:         my $docuname=$env{'user.name'};
 2932:         my $docudom=$env{'user.domain'};
 2933:         if (exists($env{'form.group'})) {
 2934:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2935:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2936:         }
 2937: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2938: 				     $parser,$allfiles,$codebase,
 2939:                                      $thumbwidth,$thumbheight,
 2940:                                      $resizewidth,$resizeheight,$context,$mimetype);
 2941:     }
 2942: }
 2943: 
 2944: sub finishuserfileupload {
 2945:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 2946:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
 2947:     my $path=$docudom.'/'.$docuname.'/';
 2948:     my $filepath=$perlvar{'lonDocRoot'};
 2949:   
 2950:     my ($fnamepath,$file,$fetchthumb);
 2951:     $file=$fname;
 2952:     if ($fname=~m|/|) {
 2953:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 2954: 	$path.=$fnamepath.'/';
 2955:     }
 2956:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 2957:     my $count;
 2958:     for ($count=4;$count<=$#parts;$count++) {
 2959:         $filepath.="/$parts[$count]";
 2960:         if ((-e $filepath)!=1) {
 2961: 	    mkdir($filepath,0777);
 2962:         }
 2963:     }
 2964: 
 2965: # Save the file
 2966:     {
 2967: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 2968: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 2969: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 2970: 	    return '/adm/notfound.html';
 2971: 	}
 2972:         if ($context eq 'overwrite') {
 2973:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
 2974:             my $target = $filepath.'/'.$file;
 2975:             if (-e $source) {
 2976:                 my @info = stat($source);
 2977:                 if ($info[9] eq $env{'form.timestamp'}) {   
 2978:                     unless (&File::Copy::move($source,$target)) {
 2979:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
 2980:                         return "Moving from $source failed";
 2981:                     }
 2982:                 } else {
 2983:                     return "Temporary file: $source had unexpected date/time for last modification";
 2984:                 }
 2985:             } else {
 2986:                 return "Temporary file: $source missing";
 2987:             }
 2988:         } elsif (!print FH ($env{'form.'.$formname})) {
 2989: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 2990: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 2991: 	    return '/adm/notfound.html';
 2992: 	}
 2993: 	close(FH);
 2994:         if ($resizewidth && $resizeheight) {
 2995:             my $mm = new File::MMagic;
 2996:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 2997:             if ($mime_type =~ m{^image/}) {
 2998: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 2999:             }  
 3000: 	}
 3001:     }
 3002:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
 3003:         if (ref($mimetype)) {
 3004:             if ($$mimetype eq '') {
 3005:                 my $mm = new File::MMagic;
 3006:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
 3007:                 $$mimetype = $type;
 3008:             }
 3009:         }
 3010:     }
 3011:     if ($parser eq 'parse') {
 3012:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
 3013:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 3014:                                                        $allfiles,$codebase);
 3015:             unless ($parse_result eq 'ok') {
 3016:                 &logthis('Failed to parse '.$filepath.$file.
 3017: 	   	         ' for embedded media: '.$parse_result); 
 3018:             }
 3019:         }
 3020:     }
 3021:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 3022:         my $input = $filepath.'/'.$file;
 3023:         my $output = $filepath.'/'.'tn-'.$file;
 3024:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 3025:         system("convert -sample $thumbsize $input $output");
 3026:         if (-e $filepath.'/'.'tn-'.$file) {
 3027:             $fetchthumb  = 1; 
 3028:         }
 3029:     }
 3030:  
 3031: # Notify homeserver to grep it
 3032: #
 3033:     my $docuhome=&homeserver($docuname,$docudom);	
 3034:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 3035:     if ($fetchresult eq 'ok') {
 3036:         if ($fetchthumb) {
 3037:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 3038:             if ($thumbresult ne 'ok') {
 3039:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 3040:                          $docuhome.': '.$thumbresult);
 3041:             }
 3042:         }
 3043: #
 3044: # Return the URL to it
 3045:         return '/uploaded/'.$path.$file;
 3046:     } else {
 3047:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 3048: 		 ': '.$fetchresult);
 3049:         return '/adm/notfound.html';
 3050:     }
 3051: }
 3052: 
 3053: sub extract_embedded_items {
 3054:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 3055:     my @state = ();
 3056:     my (%lastids,%related,%shockwave,%flashvars);
 3057:     my %javafiles = (
 3058:                       codebase => '',
 3059:                       code => '',
 3060:                       archive => ''
 3061:                     );
 3062:     my %mediafiles = (
 3063:                       src => '',
 3064:                       movie => '',
 3065:                      );
 3066:     my $p;
 3067:     if ($content) {
 3068:         $p = HTML::LCParser->new($content);
 3069:     } else {
 3070:         $p = HTML::LCParser->new($fullpath);
 3071:     }
 3072:     while (my $t=$p->get_token()) {
 3073: 	if ($t->[0] eq 'S') {
 3074: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 3075: 	    push(@state, $tagname);
 3076:             if (lc($tagname) eq 'allow') {
 3077:                 &add_filetype($allfiles,$attr->{'src'},'src');
 3078:             }
 3079: 	    if (lc($tagname) eq 'img') {
 3080: 		&add_filetype($allfiles,$attr->{'src'},'src');
 3081: 	    }
 3082: 	    if (lc($tagname) eq 'a') {
 3083: 		&add_filetype($allfiles,$attr->{'href'},'href');
 3084: 	    }
 3085:             if (lc($tagname) eq 'script') {
 3086:                 my $src;
 3087:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 3088:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 3089:                 } else {
 3090:                     if ($attr->{'src'} ne '') {
 3091:                         $src = $attr->{'src'};
 3092:                         &add_filetype($allfiles,$src,'src');
 3093:                     }
 3094:                 }
 3095:                 my $text = $p->get_trimmed_text();
 3096:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
 3097:                     my @swfargs = split(/,/,$1);
 3098:                     foreach my $item (@swfargs) {
 3099:                         $item =~ s/["']//g;
 3100:                         $item =~ s/^\s+//;
 3101:                         $item =~ s/\s+$//;
 3102:                     }
 3103:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
 3104:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
 3105:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
 3106:                         } else {
 3107:                             $related{$swfargs[0]} = [$swfargs[2]];
 3108:                         }
 3109:                     }
 3110:                 }
 3111:             }
 3112:             if (lc($tagname) eq 'link') {
 3113:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 3114:                     &add_filetype($allfiles,$attr->{'href'},'href');
 3115:                 }
 3116:             }
 3117: 	    if (lc($tagname) eq 'object' ||
 3118: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 3119: 		foreach my $item (keys(%javafiles)) {
 3120: 		    $javafiles{$item} = '';
 3121: 		}
 3122:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
 3123:                     $lastids{lc($tagname)} = $attr->{'id'};
 3124:                 }
 3125: 	    }
 3126: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 3127: 		my $name = lc($attr->{'name'});
 3128: 		foreach my $item (keys(%javafiles)) {
 3129: 		    if ($name eq $item) {
 3130: 			$javafiles{$item} = $attr->{'value'};
 3131: 			last;
 3132: 		    }
 3133: 		}
 3134:                 my $pathfrom;
 3135: 		foreach my $item (keys(%mediafiles)) {
 3136: 		    if ($name eq $item) {
 3137:                         $pathfrom = $attr->{'value'};
 3138:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
 3139: 			&add_filetype($allfiles,$pathfrom,$name);
 3140: 			last;
 3141: 		    }
 3142: 		}
 3143:                 if ($name eq 'flashvars') {
 3144:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
 3145:                 }
 3146:                 if ($pathfrom ne '') {
 3147:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
 3148:                                          $pathfrom);
 3149:                 }
 3150: 	    }
 3151: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 3152: 		foreach my $item (keys(%javafiles)) {
 3153: 		    if ($attr->{$item}) {
 3154: 			$javafiles{$item} = $attr->{$item};
 3155: 			last;
 3156: 		    }
 3157: 		}
 3158: 		foreach my $item (keys(%mediafiles)) {
 3159: 		    if ($attr->{$item}) {
 3160: 			&add_filetype($allfiles,$attr->{$item},$item);
 3161: 			last;
 3162: 		    }
 3163: 		}
 3164:                 if (lc($tagname) eq 'embed') {
 3165:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
 3166:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
 3167:                                              $attr->{'src'});
 3168:                     }
 3169:                 }
 3170: 	    }
 3171:             if ($t->[4] =~ m{/>$}) {
 3172:                 pop(@state);  
 3173:             }
 3174: 	} elsif ($t->[0] eq 'E') {
 3175: 	    my ($tagname) = ($t->[1]);
 3176: 	    if ($javafiles{'codebase'} ne '') {
 3177: 		$javafiles{'codebase'} .= '/';
 3178: 	    }  
 3179: 	    if (lc($tagname) eq 'applet' ||
 3180: 		lc($tagname) eq 'object' ||
 3181: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 3182: 		) {
 3183: 		foreach my $item (keys(%javafiles)) {
 3184: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 3185: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 3186: 			&add_filetype($allfiles,$file,$item);
 3187: 		    }
 3188: 		}
 3189: 	    } 
 3190: 	    pop @state;
 3191: 	}
 3192:     }
 3193:     foreach my $id (sort(keys(%flashvars))) {
 3194:         if ($shockwave{$id} ne '') {
 3195:             my @pairs = split(/\&/,$flashvars{$id});
 3196:             foreach my $pair (@pairs) {
 3197:                 my ($key,$value) = split(/\=/,$pair);
 3198:                 if ($key eq 'thumb') {
 3199:                     &add_filetype($allfiles,$value,$key);
 3200:                 } elsif ($key eq 'content') {
 3201:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
 3202:                     my ($ext) = ($value =~ /\.([^.]+)$/);
 3203:                     if ($ext ne '') {
 3204:                         &add_filetype($allfiles,$path.$value,$ext);
 3205:                     }
 3206:                 }
 3207:             }
 3208:         }
 3209:     }
 3210:     return 'ok';
 3211: }
 3212: 
 3213: sub add_filetype {
 3214:     my ($allfiles,$file,$type)=@_;
 3215:     if (exists($allfiles->{$file})) {
 3216: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 3217: 	    push(@{$allfiles->{$file}}, &escape($type));
 3218: 	}
 3219:     } else {
 3220: 	@{$allfiles->{$file}} = (&escape($type));
 3221:     }
 3222: }
 3223: 
 3224: sub embedded_dependency {
 3225:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
 3226:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
 3227:         if (($identifier ne '') &&
 3228:             (ref($related->{$identifier}) eq 'ARRAY') &&
 3229:             ($pathfrom ne '')) {
 3230:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
 3231:             foreach my $dep (@{$related->{$identifier}}) {
 3232:                 &add_filetype($allfiles,$path.$dep,'object');
 3233:             }
 3234:         }
 3235:     }
 3236:     return;
 3237: }
 3238: 
 3239: sub removeuploadedurl {
 3240:     my ($url)=@_;	
 3241:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 3242:     return &removeuserfile($uname,$udom,$fname);
 3243: }
 3244: 
 3245: sub removeuserfile {
 3246:     my ($docuname,$docudom,$fname)=@_;
 3247:     my $home=&homeserver($docuname,$docudom);    
 3248:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 3249:     if ($result eq 'ok') {	
 3250:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 3251:             my $metafile = $fname.'.meta';
 3252:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 3253: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 3254:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 3255:             my $sqlresult = 
 3256:                 &update_portfolio_table($docuname,$docudom,$file,
 3257:                                         'portfolio_metadata',$group,
 3258:                                         'delete');
 3259:         }
 3260:     }
 3261:     return $result;
 3262: }
 3263: 
 3264: sub mkdiruserfile {
 3265:     my ($docuname,$docudom,$dir)=@_;
 3266:     my $home=&homeserver($docuname,$docudom);
 3267:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 3268: }
 3269: 
 3270: sub renameuserfile {
 3271:     my ($docuname,$docudom,$old,$new)=@_;
 3272:     my $home=&homeserver($docuname,$docudom);
 3273:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 3274:                         &escape("$old").':'.&escape("$new"),$home);
 3275:     if ($result eq 'ok') {
 3276:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 3277:             my $oldmeta = $old.'.meta';
 3278:             my $newmeta = $new.'.meta';
 3279:             my $metaresult = 
 3280:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 3281: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 3282:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 3283:             my $sqlresult = 
 3284:                 &update_portfolio_table($docuname,$docudom,$file,
 3285:                                         'portfolio_metadata',$group,
 3286:                                         'delete');
 3287:         }
 3288:     }
 3289:     return $result;
 3290: }
 3291: 
 3292: # ------------------------------------------------------------------------- Log
 3293: 
 3294: sub log {
 3295:     my ($dom,$nam,$hom,$what)=@_;
 3296:     return critical("log:$dom:$nam:$what",$hom);
 3297: }
 3298: 
 3299: # ------------------------------------------------------------------ Course Log
 3300: #
 3301: # This routine flushes several buffers of non-mission-critical nature
 3302: #
 3303: 
 3304: sub flushcourselogs {
 3305:     &logthis('Flushing log buffers');
 3306: #
 3307: # course logs
 3308: # This is a log of all transactions in a course, which can be used
 3309: # for data mining purposes
 3310: #
 3311: # It also collects the courseid database, which lists last transaction
 3312: # times and course titles for all courseids
 3313: #
 3314:     my %courseidbuffer=();
 3315:     foreach my $crsid (keys(%courselogs)) {
 3316:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 3317: 		          &escape($courselogs{$crsid}),
 3318: 		          $coursehombuf{$crsid}) eq 'ok') {
 3319: 	    delete $courselogs{$crsid};
 3320:         } else {
 3321:             &logthis('Failed to flush log buffer for '.$crsid);
 3322:             if (length($courselogs{$crsid})>40000) {
 3323:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 3324:                         " exceeded maximum size, deleting.</font>");
 3325:                delete $courselogs{$crsid};
 3326:             }
 3327:         }
 3328:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 3329:             'description' => $coursedescrbuf{$crsid},
 3330:             'inst_code'    => $courseinstcodebuf{$crsid},
 3331:             'type'        => $coursetypebuf{$crsid},
 3332:             'owner'       => $courseownerbuf{$crsid},
 3333:         };
 3334:     }
 3335: #
 3336: # Write course id database (reverse lookup) to homeserver of courses 
 3337: # Is used in pickcourse
 3338: #
 3339:     foreach my $crs_home (keys(%courseidbuffer)) {
 3340:         my $response = &courseidput(&host_domain($crs_home),
 3341:                                     $courseidbuffer{$crs_home},
 3342:                                     $crs_home,'timeonly');
 3343:     }
 3344: #
 3345: # File accesses
 3346: # Writes to the dynamic metadata of resources to get hit counts, etc.
 3347: #
 3348:     foreach my $entry (keys(%accesshash)) {
 3349:         if ($entry =~ /___count$/) {
 3350:             my ($dom,$name);
 3351:             ($dom,$name,undef)=
 3352: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 3353:             if (! defined($dom) || $dom eq '' || 
 3354:                 ! defined($name) || $name eq '') {
 3355:                 my $cid = $env{'request.course.id'};
 3356:                 $dom  = $env{'request.'.$cid.'.domain'};
 3357:                 $name = $env{'request.'.$cid.'.num'};
 3358:             }
 3359:             my $value = $accesshash{$entry};
 3360:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 3361:             my %temphash=($url => $value);
 3362:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 3363:             if ($result eq 'ok') {
 3364:                 delete $accesshash{$entry};
 3365:             }
 3366:         } else {
 3367:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 3368:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
 3369:             my %temphash=($entry => $accesshash{$entry});
 3370:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 3371:                 delete $accesshash{$entry};
 3372:             }
 3373:         }
 3374:     }
 3375: #
 3376: # Roles
 3377: # Reverse lookup of user roles for course faculty/staff and co-authorship
 3378: #
 3379:     foreach my $entry (keys(%userrolehash)) {
 3380:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 3381: 	    split(/\:/,$entry);
 3382:         if (&Apache::lonnet::put('nohist_userroles',
 3383:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 3384:                 $rudom,$runame) eq 'ok') {
 3385: 	    delete $userrolehash{$entry};
 3386:         }
 3387:     }
 3388: #
 3389: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 3390: #
 3391:     my %domrolebuffer = ();
 3392:     foreach my $entry (keys(%domainrolehash)) {
 3393:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 3394:         if ($domrolebuffer{$rudom}) {
 3395:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 3396:                       '='.&escape($domainrolehash{$entry});
 3397:         } else {
 3398:             $domrolebuffer{$rudom}.=&escape($entry).
 3399:                       '='.&escape($domainrolehash{$entry});
 3400:         }
 3401:         delete $domainrolehash{$entry};
 3402:     }
 3403:     foreach my $dom (keys(%domrolebuffer)) {
 3404: 	my %servers = &get_servers($dom,'library');
 3405: 	foreach my $tryserver (keys(%servers)) {
 3406: 	    unless (&reply('domroleput:'.$dom.':'.
 3407: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 3408: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 3409: 	    }
 3410:         }
 3411:     }
 3412:     $dumpcount++;
 3413: }
 3414: 
 3415: sub courselog {
 3416:     my $what=shift;
 3417:     $what=time.':'.$what;
 3418:     unless ($env{'request.course.id'}) { return ''; }
 3419:     $coursedombuf{$env{'request.course.id'}}=
 3420:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 3421:     $coursenumbuf{$env{'request.course.id'}}=
 3422:        $env{'course.'.$env{'request.course.id'}.'.num'};
 3423:     $coursehombuf{$env{'request.course.id'}}=
 3424:        $env{'course.'.$env{'request.course.id'}.'.home'};
 3425:     $coursedescrbuf{$env{'request.course.id'}}=
 3426:        $env{'course.'.$env{'request.course.id'}.'.description'};
 3427:     $courseinstcodebuf{$env{'request.course.id'}}=
 3428:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 3429:     $courseownerbuf{$env{'request.course.id'}}=
 3430:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 3431:     $coursetypebuf{$env{'request.course.id'}}=
 3432:        $env{'course.'.$env{'request.course.id'}.'.type'};
 3433:     if (defined $courselogs{$env{'request.course.id'}}) {
 3434: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 3435:     } else {
 3436: 	$courselogs{$env{'request.course.id'}}.=$what;
 3437:     }
 3438:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 3439: 	&flushcourselogs();
 3440:     }
 3441: }
 3442: 
 3443: sub courseacclog {
 3444:     my $fnsymb=shift;
 3445:     unless ($env{'request.course.id'}) { return ''; }
 3446:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 3447:     if ($fnsymb=~/$LONCAPA::assess_re/) {
 3448:         $what.=':POST';
 3449:         # FIXME: Probably ought to escape things....
 3450: 	foreach my $key (keys(%env)) {
 3451:             if ($key=~/^form\.(.*)/) {
 3452:                 my $formitem = $1;
 3453:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 3454:                     $what.=':'.$formitem.'='.$env{$key};
 3455:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 3456:                     $what.=':'.$formitem.'='.$env{$key};
 3457:                 }
 3458:             }
 3459:         }
 3460:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 3461:         # FIXME: We should not be depending on a form parameter that someone
 3462:         # editing lonsearchcat.pm might change in the future.
 3463:         if ($env{'form.phase'} eq 'course_search') {
 3464:             $what.= ':POST';
 3465:             # FIXME: Probably ought to escape things....
 3466:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 3467:                                  'crsdiscuss') {
 3468:                 $what.=':'.$element.'='.$env{'form.'.$element};
 3469:             }
 3470:         }
 3471:     }
 3472:     &courselog($what);
 3473: }
 3474: 
 3475: sub countacc {
 3476:     my $url=&declutter(shift);
 3477:     return if (! defined($url) || $url eq '');
 3478:     unless ($env{'request.course.id'}) { return ''; }
 3479: #
 3480: # Mark that this url was used in this course
 3481: #
 3482:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 3483: #
 3484: # Increase the access count for this resource in this child process
 3485: #
 3486:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 3487:     $accesshash{$key}++;
 3488: }
 3489: 
 3490: sub linklog {
 3491:     my ($from,$to)=@_;
 3492:     $from=&declutter($from);
 3493:     $to=&declutter($to);
 3494:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 3495:     $accesshash{$to.'___'.$from.'___goto'}=1;
 3496: }
 3497: 
 3498: sub statslog {
 3499:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
 3500:     if ($users<2) { return; }
 3501:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
 3502:             'course'       => $env{'request.course.id'},
 3503:             'sections'     => '"all"',
 3504:             'num_students' => $users,
 3505:             'part'         => $part,
 3506:             'symb'         => $symb,
 3507:             'mean_tries'   => $av_attempts,
 3508:             'deg_of_diff'  => $degdiff});
 3509:     foreach my $key (keys(%dynstore)) {
 3510:         $accesshash{$key}=$dynstore{$key};
 3511:     }
 3512: }
 3513:   
 3514: sub userrolelog {
 3515:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 3516:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
 3517:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3518:        $userrolehash
 3519:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3520:                     =$tend.':'.$tstart;
 3521:     }
 3522:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
 3523:        $userrolehash
 3524:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 3525:                     =$tend.':'.$tstart;
 3526:     }
 3527:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
 3528:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 3529:        $domainrolehash
 3530:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 3531:                     = $tend.':'.$tstart;
 3532:     }
 3533: }
 3534: 
 3535: sub courserolelog {
 3536:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 3537:     if (($trole eq 'cc') || ($trole eq 'in') ||
 3538:         ($trole eq 'ep') || ($trole eq 'ad') ||
 3539:         ($trole eq 'ta') || ($trole eq 'st') ||
 3540:         ($trole=~/^cr/) || ($trole eq 'gr') ||
 3541:         ($trole eq 'co')) {
 3542:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 3543:             my $cdom = $1;
 3544:             my $cnum = $2;
 3545:             my $sec = $3;
 3546:             my $namespace = 'rolelog';
 3547:             my %storehash = (
 3548:                                role    => $trole,
 3549:                                start   => $tstart,
 3550:                                end     => $tend,
 3551:                                selfenroll => $selfenroll,
 3552:                                context    => $context,
 3553:                             );
 3554:             if ($trole eq 'gr') {
 3555:                 $namespace = 'groupslog';
 3556:                 $storehash{'group'} = $sec;
 3557:             } else {
 3558:                 $storehash{'section'} = $sec;
 3559:             }
 3560:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
 3561:             if (($trole ne 'st') || ($sec ne '')) {
 3562:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 3563:             }
 3564:         }
 3565:     }
 3566:     return;
 3567: }
 3568: 
 3569: sub get_course_adv_roles {
 3570:     my ($cid,$codes) = @_;
 3571:     $cid=$env{'request.course.id'} unless (defined($cid));
 3572:     my %coursehash=&coursedescription($cid);
 3573:     my $crstype = &Apache::loncommon::course_type($cid);
 3574:     my %nothide=();
 3575:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3576:         if ($user !~ /:/) {
 3577: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 3578:         } else {
 3579:             $nothide{$user}=1;
 3580:         }
 3581:     }
 3582:     my %returnhash=();
 3583:     my %dumphash=
 3584:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 3585:     my $now=time;
 3586:     my %privileged;
 3587:     foreach my $entry (keys(%dumphash)) {
 3588: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 3589:         if (($tstart) && ($tstart<0)) { next; }
 3590:         if (($tend) && ($tend<$now)) { next; }
 3591:         if (($tstart) && ($now<$tstart)) { next; }
 3592:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 3593: 	if ($username eq '' || $domain eq '') { next; }
 3594:         unless (ref($privileged{$domain}) eq 'HASH') {
 3595:             my %dompersonnel =
 3596:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 3597:             $privileged{$domain} = {};
 3598:             foreach my $server (keys(%dompersonnel)) {
 3599:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 3600:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
 3601:                         my ($trole,$uname,$udom) = split(/:/,$user);
 3602:                         $privileged{$udom}{$uname} = 1;
 3603:                     }
 3604:                 }
 3605:             }
 3606:         }
 3607:         if ((exists($privileged{$domain}{$username})) && 
 3608:             (!$nothide{$username.':'.$domain})) { next; }
 3609: 	if ($role eq 'cr') { next; }
 3610:         if ($codes) {
 3611:             if ($section) { $role .= ':'.$section; }
 3612:             if ($returnhash{$role}) {
 3613:                 $returnhash{$role}.=','.$username.':'.$domain;
 3614:             } else {
 3615:                 $returnhash{$role}=$username.':'.$domain;
 3616:             }
 3617:         } else {
 3618:             my $key=&plaintext($role,$crstype);
 3619:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 3620:             if ($returnhash{$key}) {
 3621: 	        $returnhash{$key}.=','.$username.':'.$domain;
 3622:             } else {
 3623:                 $returnhash{$key}=$username.':'.$domain;
 3624:             }
 3625:         }
 3626:     }
 3627:     return %returnhash;
 3628: }
 3629: 
 3630: sub get_my_roles {
 3631:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 3632:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 3633:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 3634:     my (%dumphash,%nothide);
 3635:     if ($context eq 'userroles') {
 3636:         %dumphash = &dump('roles',$udom,$uname);
 3637:     } else {
 3638:         %dumphash=
 3639:             &dump('nohist_userroles',$udom,$uname);
 3640:         if ($hidepriv) {
 3641:             my %coursehash=&coursedescription($udom.'_'.$uname);
 3642:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3643:                 if ($user !~ /:/) {
 3644:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 3645:                 } else {
 3646:                     $nothide{$user} = 1;
 3647:                 }
 3648:             }
 3649:         }
 3650:     }
 3651:     my %returnhash=();
 3652:     my $now=time;
 3653:     my %privileged;
 3654:     foreach my $entry (keys(%dumphash)) {
 3655:         my ($role,$tend,$tstart);
 3656:         if ($context eq 'userroles') {
 3657:             next if ($entry =~ /^rolesdef/);
 3658: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 3659:         } else {
 3660:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 3661:         }
 3662:         if (($tstart) && ($tstart<0)) { next; }
 3663:         my $status = 'active';
 3664:         if (($tend) && ($tend<=$now)) {
 3665:             $status = 'previous';
 3666:         } 
 3667:         if (($tstart) && ($now<$tstart)) {
 3668:             $status = 'future';
 3669:         }
 3670:         if (ref($types) eq 'ARRAY') {
 3671:             if (!grep(/^\Q$status\E$/,@{$types})) {
 3672:                 next;
 3673:             } 
 3674:         } else {
 3675:             if ($status ne 'active') {
 3676:                 next;
 3677:             }
 3678:         }
 3679:         my ($rolecode,$username,$domain,$section,$area);
 3680:         if ($context eq 'userroles') {
 3681:             ($area,$rolecode) = split(/_/,$entry);
 3682:             (undef,$domain,$username,$section) = split(/\//,$area);
 3683:         } else {
 3684:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 3685:         }
 3686:         if (ref($roledoms) eq 'ARRAY') {
 3687:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 3688:                 next;
 3689:             }
 3690:         }
 3691:         if (ref($roles) eq 'ARRAY') {
 3692:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 3693:                 if ($role =~ /^cr\//) {
 3694:                     if (!grep(/^cr$/,@{$roles})) {
 3695:                         next;
 3696:                     }
 3697:                 } elsif ($role =~ /^gr\//) {
 3698:                     if (!grep(/^gr$/,@{$roles})) {
 3699:                         next;
 3700:                     }
 3701:                 } else {
 3702:                     next;
 3703:                 }
 3704:             }
 3705:         }
 3706:         if ($hidepriv) {
 3707:             if ($context eq 'userroles') {
 3708:                 if ((&privileged($username,$domain)) &&
 3709:                     (!$nothide{$username.':'.$domain})) {
 3710:                     next;
 3711:                 }
 3712:             } else {
 3713:                 unless (ref($privileged{$domain}) eq 'HASH') {
 3714:                     my %dompersonnel =
 3715:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 3716:                     $privileged{$domain} = {};
 3717:                     if (keys(%dompersonnel)) {
 3718:                         foreach my $server (keys(%dompersonnel)) {
 3719:                             if (ref($dompersonnel{$server}) eq 'HASH') {
 3720:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
 3721:                                     my ($trole,$uname,$udom) = split(/:/,$user);
 3722:                                     $privileged{$udom}{$uname} = $trole;
 3723:                                 }
 3724:                             }
 3725:                         }
 3726:                     }
 3727:                 }
 3728:                 if (exists($privileged{$domain}{$username})) {
 3729:                     if (!$nothide{$username.':'.$domain}) {
 3730:                         next;
 3731:                     }
 3732:                 }
 3733:             }
 3734:         }
 3735:         if ($withsec) {
 3736:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 3737:                 $tstart.':'.$tend;
 3738:         } else {
 3739:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 3740:         }
 3741:     }
 3742:     return %returnhash;
 3743: }
 3744: 
 3745: # ----------------------------------------------------- Frontpage Announcements
 3746: #
 3747: #
 3748: 
 3749: sub postannounce {
 3750:     my ($server,$text)=@_;
 3751:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 3752:     unless ($text=~/\w/) { $text=''; }
 3753:     return &reply('setannounce:'.&escape($text),$server);
 3754: }
 3755: 
 3756: sub getannounce {
 3757: 
 3758:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 3759: 	my $announcement='';
 3760: 	while (my $line = <$fh>) { $announcement .= $line; }
 3761: 	close($fh);
 3762: 	if ($announcement=~/\w/) { 
 3763: 	    return 
 3764:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 3765:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 3766: 	} else {
 3767: 	    return '';
 3768: 	}
 3769:     } else {
 3770: 	return '';
 3771:     }
 3772: }
 3773: 
 3774: # ---------------------------------------------------------- Course ID routines
 3775: # Deal with domain's nohist_courseid.db files
 3776: #
 3777: 
 3778: sub courseidput {
 3779:     my ($domain,$storehash,$coursehome,$caller) = @_;
 3780:     return unless (ref($storehash) eq 'HASH');
 3781:     my $outcome;
 3782:     if ($caller eq 'timeonly') {
 3783:         my $cids = '';
 3784:         foreach my $item (keys(%$storehash)) {
 3785:             $cids.=&escape($item).'&';
 3786:         }
 3787:         $cids=~s/\&$//;
 3788:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 3789:                           $coursehome);       
 3790:     } else {
 3791:         my $items = '';
 3792:         foreach my $item (keys(%$storehash)) {
 3793:             $items.= &escape($item).'='.
 3794:                      &freeze_escape($$storehash{$item}).'&';
 3795:         }
 3796:         $items=~s/\&$//;
 3797:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 3798:                           $coursehome);
 3799:     }
 3800:     if ($outcome eq 'unknown_cmd') {
 3801:         my $what;
 3802:         foreach my $cid (keys(%$storehash)) {
 3803:             $what .= &escape($cid).'=';
 3804:             foreach my $item ('description','inst_code','owner','type') {
 3805:                 $what .= &escape($storehash->{$cid}{$item}).':';
 3806:             }
 3807:             $what =~ s/\:$/&/;
 3808:         }
 3809:         $what =~ s/\&$//;  
 3810:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 3811:     } else {
 3812:         return $outcome;
 3813:     }
 3814: }
 3815: 
 3816: sub courseiddump {
 3817:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 3818:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 3819:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 3820:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
 3821:     my $as_hash = 1;
 3822:     my %returnhash;
 3823:     if (!$domfilter) { $domfilter=''; }
 3824:     my %libserv = &all_library();
 3825:     foreach my $tryserver (keys(%libserv)) {
 3826:         if ( (  $hostidflag == 1 
 3827: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 3828: 	     || (!defined($hostidflag)) ) {
 3829: 
 3830: 	    if (($domfilter eq '') ||
 3831: 		(&host_domain($tryserver) eq $domfilter)) {
 3832:                 my $rep;
 3833:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
 3834:                     $rep = LONCAPA::Lond::dump_course_id_handler(
 3835:                         join(":", (&host_domain($tryserver), $sincefilter, 
 3836:                                 &escape($descfilter), &escape($instcodefilter), 
 3837:                                 &escape($ownerfilter), &escape($coursefilter),
 3838:                                 &escape($typefilter), &escape($regexp_ok), 
 3839:                                 $as_hash, &escape($selfenrollonly), 
 3840:                                 &escape($catfilter), $showhidden, $caller, 
 3841:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
 3842:                                 &escape($createdbefore), &escape($createdafter), 
 3843:                                 &escape($creationcontext), $domcloner)));
 3844:                 } else {
 3845:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
 3846:                              $sincefilter.':'.&escape($descfilter).':'.
 3847:                              &escape($instcodefilter).':'.&escape($ownerfilter).
 3848:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
 3849:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
 3850:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
 3851:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
 3852:                              &escape($cc_clone).':'.$cloneonly.':'.
 3853:                              &escape($createdbefore).':'.&escape($createdafter).':'.
 3854:                              &escape($creationcontext).':'.$domcloner,
 3855:                              $tryserver);
 3856:                 }
 3857:                      
 3858:                 my @pairs=split(/\&/,$rep);
 3859:                 foreach my $item (@pairs) {
 3860:                     my ($key,$value)=split(/\=/,$item,2);
 3861:                     $key = &unescape($key);
 3862:                     next if ($key =~ /^error: 2 /);
 3863:                     my $result = &thaw_unescape($value);
 3864:                     if (ref($result) eq 'HASH') {
 3865:                         $returnhash{$key}=$result;
 3866:                     } else {
 3867:                         my @responses = split(/:/,$value);
 3868:                         my @items = ('description','inst_code','owner','type');
 3869:                         for (my $i=0; $i<@responses; $i++) {
 3870:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 3871:                         }
 3872:                     }
 3873:                 }
 3874:             }
 3875:         }
 3876:     }
 3877:     return %returnhash;
 3878: }
 3879: 
 3880: sub courselastaccess {
 3881:     my ($cdom,$cnum,$hostidref) = @_;
 3882:     my %returnhash;
 3883:     if ($cdom && $cnum) {
 3884:         my $chome = &homeserver($cnum,$cdom);
 3885:         if ($chome ne 'no_host') {
 3886:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 3887:             &extract_lastaccess(\%returnhash,$rep);
 3888:         }
 3889:     } else {
 3890:         if (!$cdom) { $cdom=''; }
 3891:         my %libserv = &all_library();
 3892:         foreach my $tryserver (keys(%libserv)) {
 3893:             if (ref($hostidref) eq 'ARRAY') {
 3894:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 3895:             } 
 3896:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 3897:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 3898:                 &extract_lastaccess(\%returnhash,$rep);
 3899:             }
 3900:         }
 3901:     }
 3902:     return %returnhash;
 3903: }
 3904: 
 3905: sub extract_lastaccess {
 3906:     my ($returnhash,$rep) = @_;
 3907:     if (ref($returnhash) eq 'HASH') {
 3908:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 3909:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 3910:                  $rep eq '') {
 3911:             my @pairs=split(/\&/,$rep);
 3912:             foreach my $item (@pairs) {
 3913:                 my ($key,$value)=split(/\=/,$item,2);
 3914:                 $key = &unescape($key);
 3915:                 next if ($key =~ /^error: 2 /);
 3916:                 $returnhash->{$key} = &thaw_unescape($value);
 3917:             }
 3918:         }
 3919:     }
 3920:     return;
 3921: }
 3922: 
 3923: # ---------------------------------------------------------- DC e-mail
 3924: 
 3925: sub dcmailput {
 3926:     my ($domain,$msgid,$message,$server)=@_;
 3927:     my $status = &Apache::lonnet::critical(
 3928:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 3929:        &escape($message),$server);
 3930:     return $status;
 3931: }
 3932: 
 3933: sub dcmaildump {
 3934:     my ($dom,$startdate,$enddate,$senders) = @_;
 3935:     my %returnhash=();
 3936: 
 3937:     if (defined(&domain($dom,'primary'))) {
 3938:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 3939:                                                          &escape($enddate).':';
 3940: 	my @esc_senders=map { &escape($_)} @$senders;
 3941: 	$cmd.=&escape(join('&',@esc_senders));
 3942: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 3943:             my ($key,$value) = split(/\=/,$line,2);
 3944:             if (($key) && ($value)) {
 3945:                 $returnhash{&unescape($key)} = &unescape($value);
 3946:             }
 3947:         }
 3948:     }
 3949:     return %returnhash;
 3950: }
 3951: # ---------------------------------------------------------- Domain roles
 3952: 
 3953: sub get_domain_roles {
 3954:     my ($dom,$roles,$startdate,$enddate)=@_;
 3955:     if ((!defined($startdate)) || ($startdate eq '')) {
 3956:         $startdate = '.';
 3957:     }
 3958:     if ((!defined($enddate)) || ($enddate eq '')) {
 3959:         $enddate = '.';
 3960:     }
 3961:     my $rolelist;
 3962:     if (ref($roles) eq 'ARRAY') {
 3963:         $rolelist = join(':',@{$roles});
 3964:     }
 3965:     my %personnel = ();
 3966: 
 3967:     my %servers = &get_servers($dom,'library');
 3968:     foreach my $tryserver (keys(%servers)) {
 3969: 	%{$personnel{$tryserver}}=();
 3970: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 3971: 					    &escape($startdate).':'.
 3972: 					    &escape($enddate).':'.
 3973: 					    &escape($rolelist), $tryserver))) {
 3974: 	    my ($key,$value) = split(/\=/,$line,2);
 3975: 	    if (($key) && ($value)) {
 3976: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 3977: 	    }
 3978: 	}
 3979:     }
 3980:     return %personnel;
 3981: }
 3982: 
 3983: # ----------------------------------------------------------- Interval timing 
 3984: 
 3985: {
 3986: # Caches needed for speedup of navmaps
 3987: # We don't want to cache this for very long at all (5 seconds at most)
 3988: # 
 3989: # The user for whom we cache
 3990: my $cachedkey='';
 3991: # The cached times for this user
 3992: my %cachedtimes=();
 3993: # When this was last done
 3994: my $cachedtime=();
 3995: 
 3996: sub load_all_first_access {
 3997:     my ($uname,$udom)=@_;
 3998:     if (($cachedkey eq $uname.':'.$udom) &&
 3999:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
 4000:         return;
 4001:     }
 4002:     $cachedtime=time;
 4003:     $cachedkey=$uname.':'.$udom;
 4004:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
 4005: }
 4006: 
 4007: sub get_first_access {
 4008:     my ($type,$argsymb,$argmap)=@_;
 4009:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4010:     if ($argsymb) { $symb=$argsymb; }
 4011:     my ($map,$id,$res)=&decode_symb($symb);
 4012:     if ($argmap) { $map = $argmap; }
 4013:     if ($type eq 'course') {
 4014: 	$res='course';
 4015:     } elsif ($type eq 'map') {
 4016: 	$res=&symbread($map);
 4017:     } else {
 4018: 	$res=$symb;
 4019:     }
 4020:     &load_all_first_access($uname,$udom);
 4021:     return $cachedtimes{"$courseid\0$res"};
 4022: }
 4023: 
 4024: sub set_first_access {
 4025:     my ($type,$interval)=@_;
 4026:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 4027:     my ($map,$id,$res)=&decode_symb($symb);
 4028:     if ($type eq 'course') {
 4029: 	$res='course';
 4030:     } elsif ($type eq 'map') {
 4031: 	$res=&symbread($map);
 4032:     } else {
 4033: 	$res=$symb;
 4034:     }
 4035:     $cachedkey='';
 4036:     my $firstaccess=&get_first_access($type,$symb,$map);
 4037:     if (!$firstaccess) {
 4038:         my $start = time;
 4039: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
 4040:                           $udom,$uname);
 4041:         if ($putres eq 'ok') {
 4042:             &put('timerinterval',{"$courseid\0$res"=>$interval},
 4043:                  $udom,$uname); 
 4044:             &appenv(
 4045:                      {
 4046:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
 4047:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
 4048:                      }
 4049:                   );
 4050:         }
 4051:         return $putres;
 4052:     }
 4053:     return 'already_set';
 4054: }
 4055: }
 4056: # --------------------------------------------- Set Expire Date for Spreadsheet
 4057: 
 4058: sub expirespread {
 4059:     my ($uname,$udom,$stype,$usymb)=@_;
 4060:     my $cid=$env{'request.course.id'}; 
 4061:     if ($cid) {
 4062:        my $now=time;
 4063:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 4064:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 4065:                             $env{'course.'.$cid.'.num'}.
 4066: 	        	    ':nohist_expirationdates:'.
 4067:                             &escape($key).'='.$now,
 4068:                             $env{'course.'.$cid.'.home'})
 4069:     }
 4070:     return 'ok';
 4071: }
 4072: 
 4073: # ----------------------------------------------------- Devalidate Spreadsheets
 4074: 
 4075: sub devalidate {
 4076:     my ($symb,$uname,$udom)=@_;
 4077:     my $cid=$env{'request.course.id'}; 
 4078:     if ($cid) {
 4079:         # delete the stored spreadsheets for
 4080:         # - the student level sheet of this user in course's homespace
 4081:         # - the assessment level sheet for this resource 
 4082:         #   for this user in user's homespace
 4083: 	# - current conditional state info
 4084: 	my $key=$uname.':'.$udom.':';
 4085:         my $status=
 4086: 	    &del('nohist_calculatedsheets',
 4087: 		 [$key.'studentcalc:'],
 4088: 		 $env{'course.'.$cid.'.domain'},
 4089: 		 $env{'course.'.$cid.'.num'})
 4090: 		.' '.
 4091: 	    &del('nohist_calculatedsheets_'.$cid,
 4092: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 4093:         unless ($status eq 'ok ok') {
 4094:            &logthis('Could not devalidate spreadsheet '.
 4095:                     $uname.' at '.$udom.' for '.
 4096: 		    $symb.': '.$status);
 4097:         }
 4098: 	&delenv('user.state.'.$cid);
 4099:     }
 4100: }
 4101: 
 4102: sub get_scalar {
 4103:     my ($string,$end) = @_;
 4104:     my $value;
 4105:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 4106: 	$value = $1;
 4107:     } elsif ($$string =~ s/^([^&]*?)&//) {
 4108: 	$value = $1;
 4109:     }
 4110:     return &unescape($value);
 4111: }
 4112: 
 4113: sub array2str {
 4114:   my (@array) = @_;
 4115:   my $result=&arrayref2str(\@array);
 4116:   $result=~s/^__ARRAY_REF__//;
 4117:   $result=~s/__END_ARRAY_REF__$//;
 4118:   return $result;
 4119: }
 4120: 
 4121: sub arrayref2str {
 4122:   my ($arrayref) = @_;
 4123:   my $result='__ARRAY_REF__';
 4124:   foreach my $elem (@$arrayref) {
 4125:     if(ref($elem) eq 'ARRAY') {
 4126:       $result.=&arrayref2str($elem).'&';
 4127:     } elsif(ref($elem) eq 'HASH') {
 4128:       $result.=&hashref2str($elem).'&';
 4129:     } elsif(ref($elem)) {
 4130:       #print("Got a ref of ".(ref($elem))." skipping.");
 4131:     } else {
 4132:       $result.=&escape($elem).'&';
 4133:     }
 4134:   }
 4135:   $result=~s/\&$//;
 4136:   $result .= '__END_ARRAY_REF__';
 4137:   return $result;
 4138: }
 4139: 
 4140: sub hash2str {
 4141:   my (%hash) = @_;
 4142:   my $result=&hashref2str(\%hash);
 4143:   $result=~s/^__HASH_REF__//;
 4144:   $result=~s/__END_HASH_REF__$//;
 4145:   return $result;
 4146: }
 4147: 
 4148: sub hashref2str {
 4149:   my ($hashref)=@_;
 4150:   my $result='__HASH_REF__';
 4151:   foreach my $key (sort(keys(%$hashref))) {
 4152:     if (ref($key) eq 'ARRAY') {
 4153:       $result.=&arrayref2str($key).'=';
 4154:     } elsif (ref($key) eq 'HASH') {
 4155:       $result.=&hashref2str($key).'=';
 4156:     } elsif (ref($key)) {
 4157:       $result.='=';
 4158:       #print("Got a ref of ".(ref($key))." skipping.");
 4159:     } else {
 4160: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
 4161:     }
 4162: 
 4163:     if(ref($hashref->{$key}) eq 'ARRAY') {
 4164:       $result.=&arrayref2str($hashref->{$key}).'&';
 4165:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 4166:       $result.=&hashref2str($hashref->{$key}).'&';
 4167:     } elsif(ref($hashref->{$key})) {
 4168:        $result.='&';
 4169:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 4170:     } else {
 4171:       $result.=&escape($hashref->{$key}).'&';
 4172:     }
 4173:   }
 4174:   $result=~s/\&$//;
 4175:   $result .= '__END_HASH_REF__';
 4176:   return $result;
 4177: }
 4178: 
 4179: sub str2hash {
 4180:     my ($string)=@_;
 4181:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 4182:     return %$hash;
 4183: }
 4184: 
 4185: sub str2hashref {
 4186:   my ($string) = @_;
 4187: 
 4188:   my %hash;
 4189: 
 4190:   if($string !~ /^__HASH_REF__/) {
 4191:       if (! ($string eq '' || !defined($string))) {
 4192: 	  $hash{'error'}='Not hash reference';
 4193:       }
 4194:       return (\%hash, $string);
 4195:   }
 4196: 
 4197:   $string =~ s/^__HASH_REF__//;
 4198: 
 4199:   while($string !~ /^__END_HASH_REF__/) {
 4200:       #key
 4201:       my $key='';
 4202:       if($string =~ /^__HASH_REF__/) {
 4203:           ($key, $string)=&str2hashref($string);
 4204:           if(defined($key->{'error'})) {
 4205:               $hash{'error'}='Bad data';
 4206:               return (\%hash, $string);
 4207:           }
 4208:       } elsif($string =~ /^__ARRAY_REF__/) {
 4209:           ($key, $string)=&str2arrayref($string);
 4210:           if($key->[0] eq 'Array reference error') {
 4211:               $hash{'error'}='Bad data';
 4212:               return (\%hash, $string);
 4213:           }
 4214:       } else {
 4215:           $string =~ s/^(.*?)=//;
 4216: 	  $key=&unescape($1);
 4217:       }
 4218:       $string =~ s/^=//;
 4219: 
 4220:       #value
 4221:       my $value='';
 4222:       if($string =~ /^__HASH_REF__/) {
 4223:           ($value, $string)=&str2hashref($string);
 4224:           if(defined($value->{'error'})) {
 4225:               $hash{'error'}='Bad data';
 4226:               return (\%hash, $string);
 4227:           }
 4228:       } elsif($string =~ /^__ARRAY_REF__/) {
 4229:           ($value, $string)=&str2arrayref($string);
 4230:           if($value->[0] eq 'Array reference error') {
 4231:               $hash{'error'}='Bad data';
 4232:               return (\%hash, $string);
 4233:           }
 4234:       } else {
 4235: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 4236:       }
 4237:       $string =~ s/^&//;
 4238: 
 4239:       $hash{$key}=$value;
 4240:   }
 4241: 
 4242:   $string =~ s/^__END_HASH_REF__//;
 4243: 
 4244:   return (\%hash, $string);
 4245: }
 4246: 
 4247: sub str2array {
 4248:     my ($string)=@_;
 4249:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 4250:     return @$array;
 4251: }
 4252: 
 4253: sub str2arrayref {
 4254:   my ($string) = @_;
 4255:   my @array;
 4256: 
 4257:   if($string !~ /^__ARRAY_REF__/) {
 4258:       if (! ($string eq '' || !defined($string))) {
 4259: 	  $array[0]='Array reference error';
 4260:       }
 4261:       return (\@array, $string);
 4262:   }
 4263: 
 4264:   $string =~ s/^__ARRAY_REF__//;
 4265: 
 4266:   while($string !~ /^__END_ARRAY_REF__/) {
 4267:       my $value='';
 4268:       if($string =~ /^__HASH_REF__/) {
 4269:           ($value, $string)=&str2hashref($string);
 4270:           if(defined($value->{'error'})) {
 4271:               $array[0] ='Array reference error';
 4272:               return (\@array, $string);
 4273:           }
 4274:       } elsif($string =~ /^__ARRAY_REF__/) {
 4275:           ($value, $string)=&str2arrayref($string);
 4276:           if($value->[0] eq 'Array reference error') {
 4277:               $array[0] ='Array reference error';
 4278:               return (\@array, $string);
 4279:           }
 4280:       } else {
 4281: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 4282:       }
 4283:       $string =~ s/^&//;
 4284: 
 4285:       push(@array, $value);
 4286:   }
 4287: 
 4288:   $string =~ s/^__END_ARRAY_REF__//;
 4289: 
 4290:   return (\@array, $string);
 4291: }
 4292: 
 4293: # -------------------------------------------------------------------Temp Store
 4294: 
 4295: sub tmpreset {
 4296:   my ($symb,$namespace,$domain,$stuname) = @_;
 4297:   if (!$symb) {
 4298:     $symb=&symbread();
 4299:     if (!$symb) { $symb= $env{'request.url'}; }
 4300:   }
 4301:   $symb=escape($symb);
 4302: 
 4303:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4304:   $namespace=~s/\//\_/g;
 4305:   $namespace=~s/\W//g;
 4306: 
 4307:   if (!$domain) { $domain=$env{'user.domain'}; }
 4308:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4309:   if ($domain eq 'public' && $stuname eq 'public') {
 4310:       $stuname=$ENV{'REMOTE_ADDR'};
 4311:   }
 4312:   my $path=LONCAPA::tempdir();
 4313:   my %hash;
 4314:   if (tie(%hash,'GDBM_File',
 4315: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4316: 	  &GDBM_WRCREAT(),0640)) {
 4317:     foreach my $key (keys(%hash)) {
 4318:       if ($key=~ /:$symb/) {
 4319: 	delete($hash{$key});
 4320:       }
 4321:     }
 4322:   }
 4323: }
 4324: 
 4325: sub tmpstore {
 4326:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4327: 
 4328:   if (!$symb) {
 4329:     $symb=&symbread();
 4330:     if (!$symb) { $symb= $env{'request.url'}; }
 4331:   }
 4332:   $symb=escape($symb);
 4333: 
 4334:   if (!$namespace) {
 4335:     # I don't think we would ever want to store this for a course.
 4336:     # it seems this will only be used if we don't have a course.
 4337:     #$namespace=$env{'request.course.id'};
 4338:     #if (!$namespace) {
 4339:       $namespace=$env{'request.state'};
 4340:     #}
 4341:   }
 4342:   $namespace=~s/\//\_/g;
 4343:   $namespace=~s/\W//g;
 4344:   if (!$domain) { $domain=$env{'user.domain'}; }
 4345:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4346:   if ($domain eq 'public' && $stuname eq 'public') {
 4347:       $stuname=$ENV{'REMOTE_ADDR'};
 4348:   }
 4349:   my $now=time;
 4350:   my %hash;
 4351:   my $path=LONCAPA::tempdir();
 4352:   if (tie(%hash,'GDBM_File',
 4353: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4354: 	  &GDBM_WRCREAT(),0640)) {
 4355:     $hash{"version:$symb"}++;
 4356:     my $version=$hash{"version:$symb"};
 4357:     my $allkeys=''; 
 4358:     foreach my $key (keys(%$storehash)) {
 4359:       $allkeys.=$key.':';
 4360:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 4361:     }
 4362:     $hash{"$version:$symb:timestamp"}=$now;
 4363:     $allkeys.='timestamp';
 4364:     $hash{"$version:keys:$symb"}=$allkeys;
 4365:     if (untie(%hash)) {
 4366:       return 'ok';
 4367:     } else {
 4368:       return "error:$!";
 4369:     }
 4370:   } else {
 4371:     return "error:$!";
 4372:   }
 4373: }
 4374: 
 4375: # -----------------------------------------------------------------Temp Restore
 4376: 
 4377: sub tmprestore {
 4378:   my ($symb,$namespace,$domain,$stuname) = @_;
 4379: 
 4380:   if (!$symb) {
 4381:     $symb=&symbread();
 4382:     if (!$symb) { $symb= $env{'request.url'}; }
 4383:   }
 4384:   $symb=escape($symb);
 4385: 
 4386:   if (!$namespace) { $namespace=$env{'request.state'}; }
 4387: 
 4388:   if (!$domain) { $domain=$env{'user.domain'}; }
 4389:   if (!$stuname) { $stuname=$env{'user.name'}; }
 4390:   if ($domain eq 'public' && $stuname eq 'public') {
 4391:       $stuname=$ENV{'REMOTE_ADDR'};
 4392:   }
 4393:   my %returnhash;
 4394:   $namespace=~s/\//\_/g;
 4395:   $namespace=~s/\W//g;
 4396:   my %hash;
 4397:   my $path=LONCAPA::tempdir();
 4398:   if (tie(%hash,'GDBM_File',
 4399: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 4400: 	  &GDBM_READER(),0640)) {
 4401:     my $version=$hash{"version:$symb"};
 4402:     $returnhash{'version'}=$version;
 4403:     my $scope;
 4404:     for ($scope=1;$scope<=$version;$scope++) {
 4405:       my $vkeys=$hash{"$scope:keys:$symb"};
 4406:       my @keys=split(/:/,$vkeys);
 4407:       my $key;
 4408:       $returnhash{"$scope:keys"}=$vkeys;
 4409:       foreach $key (@keys) {
 4410: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4411: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 4412:       }
 4413:     }
 4414:     if (!(untie(%hash))) {
 4415:       return "error:$!";
 4416:     }
 4417:   } else {
 4418:     return "error:$!";
 4419:   }
 4420:   return %returnhash;
 4421: }
 4422: 
 4423: # ----------------------------------------------------------------------- Store
 4424: 
 4425: sub store {
 4426:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4427:     my $home='';
 4428: 
 4429:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4430: 
 4431:     $symb=&symbclean($symb);
 4432:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4433: 
 4434:     if (!$domain) { $domain=$env{'user.domain'}; }
 4435:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4436: 
 4437:     &devalidate($symb,$stuname,$domain);
 4438: 
 4439:     $symb=escape($symb);
 4440:     if (!$namespace) { 
 4441:        unless ($namespace=$env{'request.course.id'}) { 
 4442:           return ''; 
 4443:        } 
 4444:     }
 4445:     if (!$home) { $home=$env{'user.home'}; }
 4446: 
 4447:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4448:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4449: 
 4450:     my $namevalue='';
 4451:     foreach my $key (keys(%$storehash)) {
 4452:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4453:     }
 4454:     $namevalue=~s/\&$//;
 4455:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 4456:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4457: }
 4458: 
 4459: # -------------------------------------------------------------- Critical Store
 4460: 
 4461: sub cstore {
 4462:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 4463:     my $home='';
 4464: 
 4465:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4466: 
 4467:     $symb=&symbclean($symb);
 4468:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 4469: 
 4470:     if (!$domain) { $domain=$env{'user.domain'}; }
 4471:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4472: 
 4473:     &devalidate($symb,$stuname,$domain);
 4474: 
 4475:     $symb=escape($symb);
 4476:     if (!$namespace) { 
 4477:        unless ($namespace=$env{'request.course.id'}) { 
 4478:           return ''; 
 4479:        } 
 4480:     }
 4481:     if (!$home) { $home=$env{'user.home'}; }
 4482: 
 4483:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 4484:     $$storehash{'host'}=$perlvar{'lonHostID'};
 4485: 
 4486:     my $namevalue='';
 4487:     foreach my $key (keys(%$storehash)) {
 4488:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4489:     }
 4490:     $namevalue=~s/\&$//;
 4491:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 4492:     return critical
 4493:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 4494: }
 4495: 
 4496: # --------------------------------------------------------------------- Restore
 4497: 
 4498: sub restore {
 4499:     my ($symb,$namespace,$domain,$stuname) = @_;
 4500:     my $home='';
 4501: 
 4502:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 4503: 
 4504:     if (!$symb) {
 4505:       unless ($symb=escape(&symbread())) { return ''; }
 4506:     } else {
 4507:       $symb=&escape(&symbclean($symb));
 4508:     }
 4509:     if (!$namespace) { 
 4510:        unless ($namespace=$env{'request.course.id'}) { 
 4511:           return ''; 
 4512:        } 
 4513:     }
 4514:     if (!$domain) { $domain=$env{'user.domain'}; }
 4515:     if (!$stuname) { $stuname=$env{'user.name'}; }
 4516:     if (!$home) { $home=$env{'user.home'}; }
 4517:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 4518: 
 4519:     my %returnhash=();
 4520:     foreach my $line (split(/\&/,$answer)) {
 4521: 	my ($name,$value)=split(/\=/,$line);
 4522:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 4523:     }
 4524:     my $version;
 4525:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 4526:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 4527:           $returnhash{$item}=$returnhash{$version.':'.$item};
 4528:        }
 4529:     }
 4530:     return %returnhash;
 4531: }
 4532: 
 4533: # ---------------------------------------------------------- Course Description
 4534: #
 4535: #  
 4536: 
 4537: sub coursedescription {
 4538:     my ($courseid,$args)=@_;
 4539:     $courseid=~s/^\///;
 4540:     $courseid=~s/\_/\//g;
 4541:     my ($cdomain,$cnum)=split(/\//,$courseid);
 4542:     my $chome=&homeserver($cnum,$cdomain);
 4543:     my $normalid=$cdomain.'_'.$cnum;
 4544:     # need to always cache even if we get errors otherwise we keep 
 4545:     # trying and trying and trying to get the course description.
 4546:     my %envhash=();
 4547:     my %returnhash=();
 4548:     
 4549:     my $expiretime=600;
 4550:     if ($env{'request.course.id'} eq $normalid) {
 4551: 	$expiretime=120;
 4552:     }
 4553: 
 4554:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 4555:     if (!$args->{'freshen_cache'}
 4556: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 4557: 	foreach my $key (keys(%env)) {
 4558: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 4559: 	    my ($setting) = $1;
 4560: 	    $returnhash{$setting} = $env{$key};
 4561: 	}
 4562: 	return %returnhash;
 4563:     }
 4564: 
 4565:     # get the data again
 4566: 
 4567:     if (!$args->{'one_time'}) {
 4568: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 4569:     }
 4570: 
 4571:     if ($chome ne 'no_host') {
 4572:        %returnhash=&dump('environment',$cdomain,$cnum);
 4573:        if (!exists($returnhash{'con_lost'})) {
 4574: 	   my $username = $env{'user.name'}; # Defult username
 4575: 	   if(defined $args->{'user'}) {
 4576: 	       $username = $args->{'user'};
 4577: 	   }
 4578:            $returnhash{'home'}= $chome;
 4579: 	   $returnhash{'domain'} = $cdomain;
 4580: 	   $returnhash{'num'} = $cnum;
 4581:            if (!defined($returnhash{'type'})) {
 4582:                $returnhash{'type'} = 'Course';
 4583:            }
 4584:            while (my ($name,$value) = each %returnhash) {
 4585:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 4586:            }
 4587:            $returnhash{'url'}=&clutter($returnhash{'url'});
 4588:            $returnhash{'fn'}=LONCAPA::tempdir() .
 4589: 	       $username.'_'.$cdomain.'_'.$cnum;
 4590:            $envhash{'course.'.$normalid.'.home'}=$chome;
 4591:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 4592:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 4593:        }
 4594:     }
 4595:     if (!$args->{'one_time'}) {
 4596: 	&appenv(\%envhash);
 4597:     }
 4598:     return %returnhash;
 4599: }
 4600: 
 4601: sub update_released_required {
 4602:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
 4603:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
 4604:         $cid = $env{'request.course.id'};
 4605:         $cdom = $env{'course.'.$cid.'.domain'};
 4606:         $cnum = $env{'course.'.$cid.'.num'};
 4607:         $chome = $env{'course.'.$cid.'.home'};
 4608:     }
 4609:     if ($needsrelease) {
 4610:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
 4611:         my $needsupdate;
 4612:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
 4613:             $needsupdate = 1;
 4614:         } else {
 4615:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
 4616:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
 4617:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
 4618:                 $needsupdate = 1;
 4619:             }
 4620:         }
 4621:         if ($needsupdate) {
 4622:             my %needshash = (
 4623:                              'internal.releaserequired' => $needsrelease,
 4624:                             );
 4625:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
 4626:             if ($putresult eq 'ok') {
 4627:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
 4628:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 4629:                 if (ref($crsinfo{$cid}) eq 'HASH') {
 4630:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
 4631:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
 4632:                 }
 4633:             }
 4634:         }
 4635:     }
 4636:     return;
 4637: }
 4638: 
 4639: # -------------------------------------------------See if a user is privileged
 4640: 
 4641: sub privileged {
 4642:     my ($username,$domain)=@_;
 4643: 
 4644:     my %rolesdump = &dump("roles", $domain, $username) or return 0;
 4645:     my $now = time;
 4646: 
 4647:     for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
 4648:             my ($trole, $tend, $tstart) = split(/_/, $role);
 4649:             if (($trole eq 'dc') || ($trole eq 'su')) {
 4650:                 return 1 unless ($tend && $tend < $now) 
 4651:                     or ($tstart && $tstart > $now);
 4652:             }
 4653: 	}
 4654: 
 4655:     return 0;
 4656: }
 4657: 
 4658: # -------------------------------------------------------- Get user privileges
 4659: 
 4660: sub rolesinit {
 4661:     my ($domain, $username) = @_;
 4662:     my %userroles = ('user.login.time' => time);
 4663:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
 4664: 
 4665:     # firstaccess and timerinterval are related to timed maps/resources. 
 4666:     # also, blocking can be triggered by an activating timer
 4667:     # it's saved in the user's %env.
 4668:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
 4669:     my %timerinterval = &dump('timerinterval', $domain, $username);
 4670:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
 4671:         %timerintchk, %timerintenv);
 4672: 
 4673:     foreach my $key (keys(%firstaccess)) {
 4674:         my ($cid, $rest) = split(/\0/, $key);
 4675:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
 4676:     }
 4677: 
 4678:     foreach my $key (keys(%timerinterval)) {
 4679:         my ($cid,$rest) = split(/\0/,$key);
 4680:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
 4681:     }
 4682: 
 4683:     my %allroles=();
 4684:     my %allgroups=();
 4685: 
 4686:     for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
 4687:         my $role = $rolesdump{$area};
 4688:         $area =~ s/\_\w\w$//;
 4689: 
 4690:         my ($trole, $tend, $tstart, $group_privs);
 4691: 
 4692:         if ($role =~ /^cr/) {
 4693:         # Custom role, defined by a user 
 4694:         # e.g., user.role.cr/msu/smith/mynewrole
 4695:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 4696:                 $trole = $1;
 4697:                 ($tend, $tstart) = split('_', $2);
 4698:             } else {
 4699:                 $trole = $role;
 4700:             }
 4701:         } elsif ($role =~ m|^gr/|) {
 4702:         # Role of member in a group, defined within a course/community
 4703:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
 4704:             ($trole, $tend, $tstart) = split(/_/, $role);
 4705:             next if $tstart eq '-1';
 4706:             ($trole, $group_privs) = split(/\//, $trole);
 4707:             $group_privs = &unescape($group_privs);
 4708:         } else {
 4709:         # Just a normal role, defined in roles.tab
 4710:             ($trole, $tend, $tstart) = split(/_/,$role);
 4711:         }
 4712: 
 4713:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 4714:                  $username);
 4715:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 4716: 
 4717:         # role expired or not available yet?
 4718:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
 4719:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
 4720: 
 4721:         next if $area eq '' or $trole eq '';
 4722: 
 4723:         my $spec = "$trole.$area";
 4724:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
 4725: 
 4726:         if ($trole =~ /^cr\//) {
 4727:         # Custom role, defined by a user
 4728:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 4729:         } elsif ($trole eq 'gr') {
 4730:         # Role of a member in a group, defined within a course/community
 4731:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 4732:             next;
 4733:         } else {
 4734:         # Normal role, defined in roles.tab
 4735:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 4736:         }
 4737: 
 4738:         my $cid = $tdomain.'_'.$trest;
 4739:         unless ($firstaccchk{$cid}) {
 4740:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
 4741:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
 4742:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
 4743:                         $coursetimerstarts{$cid}{$item}; 
 4744:                 }
 4745:             }
 4746:             $firstaccchk{$cid} = 1;
 4747:         }
 4748:         unless ($timerintchk{$cid}) {
 4749:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
 4750:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
 4751:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
 4752:                        $coursetimerintervals{$cid}{$item};
 4753:                 }
 4754:             }
 4755:             $timerintchk{$cid} = 1;
 4756:         }
 4757:     }
 4758: 
 4759:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
 4760:         \%allroles, \%allgroups);
 4761:     $env{'user.adv'} = $userroles{'user.adv'};
 4762: 
 4763:     return (\%userroles,\%firstaccenv,\%timerintenv);
 4764: }
 4765: 
 4766: sub set_arearole {
 4767:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 4768: # log the associated role with the area
 4769:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 4770:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 4771: }
 4772: 
 4773: sub custom_roleprivs {
 4774:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 4775:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 4776:     my $homsvr=homeserver($rauthor,$rdomain);
 4777:     if (&hostname($homsvr) ne '') {
 4778:         my ($rdummy,$roledef)=
 4779:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 4780:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4781:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 4782:             if (defined($syspriv)) {
 4783:                 if ($trest =~ /^$match_community$/) {
 4784:                     $syspriv =~ s/bre\&S//; 
 4785:                 }
 4786:                 $$allroles{'cm./'}.=':'.$syspriv;
 4787:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 4788:             }
 4789:             if ($tdomain ne '') {
 4790:                 if (defined($dompriv)) {
 4791:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 4792:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 4793:                 }
 4794:                 if (($trest ne '') && (defined($coursepriv))) {
 4795:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 4796:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 4797:                 }
 4798:             }
 4799:         }
 4800:     }
 4801: }
 4802: 
 4803: sub group_roleprivs {
 4804:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 4805:     my $access = 1;
 4806:     my $now = time;
 4807:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 4808:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 4809:     if ($access) {
 4810:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 4811:         $$allgroups{$course}{$group} .=':'.$group_privs;
 4812:     }
 4813: }
 4814: 
 4815: sub standard_roleprivs {
 4816:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 4817:     if (defined($pr{$trole.':s'})) {
 4818:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 4819:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 4820:     }
 4821:     if ($tdomain ne '') {
 4822:         if (defined($pr{$trole.':d'})) {
 4823:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 4824:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 4825:         }
 4826:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 4827:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 4828:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 4829:         }
 4830:     }
 4831: }
 4832: 
 4833: sub set_userprivs {
 4834:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 4835:     my $author=0;
 4836:     my $adv=0;
 4837:     my %grouproles = ();
 4838:     if (keys(%{$allgroups}) > 0) {
 4839:         my @groupkeys; 
 4840:         foreach my $role (keys(%{$allroles})) {
 4841:             push(@groupkeys,$role);
 4842:         }
 4843:         if (ref($groups_roles) eq 'HASH') {
 4844:             foreach my $key (keys(%{$groups_roles})) {
 4845:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 4846:                     push(@groupkeys,$key);
 4847:                 }
 4848:             }
 4849:         }
 4850:         if (@groupkeys > 0) {
 4851:             foreach my $role (@groupkeys) {
 4852:                 my ($trole,$area,$sec,$extendedarea);
 4853:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 4854:                     $trole = $1;
 4855:                     $area = $2;
 4856:                     $sec = $3;
 4857:                     $extendedarea = $area.$sec;
 4858:                     if (exists($$allgroups{$area})) {
 4859:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 4860:                             my $spec = $trole.'.'.$extendedarea;
 4861:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 4862:                                                 $$allgroups{$area}{$group};
 4863:                         }
 4864:                     }
 4865:                 }
 4866:             }
 4867:         }
 4868:     }
 4869:     foreach my $group (keys(%grouproles)) {
 4870:         $$allroles{$group} = $grouproles{$group};
 4871:     }
 4872:     foreach my $role (keys(%{$allroles})) {
 4873:         my %thesepriv;
 4874:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 4875:         foreach my $item (split(/:/,$$allroles{$role})) {
 4876:             if ($item ne '') {
 4877:                 my ($privilege,$restrictions)=split(/&/,$item);
 4878:                 if ($restrictions eq '') {
 4879:                     $thesepriv{$privilege}='F';
 4880:                 } elsif ($thesepriv{$privilege} ne 'F') {
 4881:                     $thesepriv{$privilege}.=$restrictions;
 4882:                 }
 4883:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 4884:             }
 4885:         }
 4886:         my $thesestr='';
 4887:         foreach my $priv (sort(keys(%thesepriv))) {
 4888: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 4889: 	}
 4890:         $userroles->{'user.priv.'.$role} = $thesestr;
 4891:     }
 4892:     return ($author,$adv);
 4893: }
 4894: 
 4895: sub role_status {
 4896:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 4897:     my @pwhere = ();
 4898:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 4899:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
 4900:         unless (!defined($$role) || $$role eq '') {
 4901:             $$where=join('.',@pwhere);
 4902:             $$trolecode=$$role.'.'.$$where;
 4903:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 4904:             $$tstatus='is';
 4905:             if ($$tstart && $$tstart>$update) {
 4906:                 $$tstatus='future';
 4907:                 if ($$tstart<$now) {
 4908:                     if ($$tstart && $$tstart>$refresh) {
 4909:                         if (($$where ne '') && ($$role ne '')) {
 4910:                             my (%allroles,%allgroups,$group_privs,
 4911:                                 %groups_roles,@rolecodes);
 4912:                             my %userroles = (
 4913:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 4914:                             );
 4915:                             @rolecodes = ('cm'); 
 4916:                             my $spec=$$role.'.'.$$where;
 4917:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 4918:                             if ($$role =~ /^cr\//) {
 4919:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 4920:                                 push(@rolecodes,'cr');
 4921:                             } elsif ($$role eq 'gr') {
 4922:                                 push(@rolecodes,$$role);
 4923:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 4924:                                                     $env{'user.name'});
 4925:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 4926:                                 (undef,my $group_privs) = split(/\//,$trole);
 4927:                                 $group_privs = &unescape($group_privs);
 4928:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 4929:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 4930:                                 &get_groups_roles($tdomain,$trest,
 4931:                                                   \%course_roles,\@rolecodes,
 4932:                                                   \%groups_roles);
 4933:                             } else {
 4934:                                 push(@rolecodes,$$role);
 4935:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 4936:                             }
 4937:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
 4938:                             &appenv(\%userroles,\@rolecodes);
 4939:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 4940:                         }
 4941:                     }
 4942:                     $$tstatus = 'is';
 4943:                 }
 4944:             }
 4945:             if ($$tend) {
 4946:                 if ($$tend<$update) {
 4947:                     $$tstatus='expired';
 4948:                 } elsif ($$tend<$now) {
 4949:                     $$tstatus='will_not';
 4950:                 }
 4951:             }
 4952:         }
 4953:     }
 4954: }
 4955: 
 4956: sub get_groups_roles {
 4957:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
 4958:     return unless((ref($cdom_courseroles) eq 'HASH') && 
 4959:                   (ref($rolecodes) eq 'ARRAY') && 
 4960:                   (ref($groups_roles) eq 'HASH')); 
 4961:     if (keys(%{$cdom_courseroles}) > 0) {
 4962:         my ($cnum) = ($rest =~ /^($match_courseid)/);
 4963:         if ($cdom ne '' && $cnum ne '') {
 4964:             foreach my $key (keys(%{$cdom_courseroles})) {
 4965:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
 4966:                     my $crsrole = $1;
 4967:                     my $crssec = $2;
 4968:                     if ($crsrole =~ /^cr/) {
 4969:                         unless (grep(/^cr$/,@{$rolecodes})) {
 4970:                             push(@{$rolecodes},'cr');
 4971:                         }
 4972:                     } else {
 4973:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
 4974:                             push(@{$rolecodes},$crsrole);
 4975:                         }
 4976:                     }
 4977:                     my $rolekey = "$crsrole./$cdom/$cnum";
 4978:                     if ($crssec ne '') {
 4979:                         $rolekey .= "/$crssec";
 4980:                     }
 4981:                     $rolekey .= './';
 4982:                     $groups_roles->{$rolekey} = $rolecodes;
 4983:                 }
 4984:             }
 4985:         }
 4986:     }
 4987:     return;
 4988: }
 4989: 
 4990: sub delete_env_groupprivs {
 4991:     my ($where,$courseroles,$possroles) = @_;
 4992:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
 4993:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
 4994:     unless (ref($courseroles->{$udom}) eq 'HASH') {
 4995:         %{$courseroles->{$udom}} =
 4996:             &get_my_roles('','','userroles',['active'],
 4997:                           $possroles,[$udom],1);
 4998:     }
 4999:     if (ref($courseroles->{$udom}) eq 'HASH') {
 5000:         foreach my $item (keys(%{$courseroles->{$udom}})) {
 5001:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
 5002:             my $area = '/'.$cdom.'/'.$cnum;
 5003:             my $privkey = "user.priv.$crsrole.$area";
 5004:             if ($crssec ne '') {
 5005:                 $privkey .= '/'.$crssec;
 5006:             }
 5007:             $privkey .= ".$area/$group";
 5008:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
 5009:         }
 5010:     }
 5011:     return;
 5012: }
 5013: 
 5014: sub check_adhoc_privs {
 5015:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
 5016:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 5017:     if ($env{$cckey}) {
 5018:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 5019:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 5020:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 5021:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5022:         }
 5023:     } else {
 5024:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
 5025:     }
 5026: }
 5027: 
 5028: sub set_adhoc_privileges {
 5029: # role can be cc or ca
 5030:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
 5031:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 5032:     my $spec = $role.'.'.$area;
 5033:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 5034:                                   $env{'user.name'});
 5035:     my %ccrole = ();
 5036:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
 5037:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
 5038:     &appenv(\%userroles,[$role,'cm']);
 5039:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 5040:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
 5041:         &appenv( {'request.role'        => $spec,
 5042:                   'request.role.domain' => $dcdom,
 5043:                   'request.course.sec'  => ''
 5044:                  }
 5045:                );
 5046:         my $tadv=0;
 5047:         if (&allowed('adv') eq 'F') { $tadv=1; }
 5048:         &appenv({'request.role.adv'    => $tadv});
 5049:     }
 5050: }
 5051: 
 5052: # --------------------------------------------------------------- get interface
 5053: 
 5054: sub get {
 5055:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5056:    my $items='';
 5057:    foreach my $item (@$storearr) {
 5058:        $items.=&escape($item).'&';
 5059:    }
 5060:    $items=~s/\&$//;
 5061:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5062:    if (!$uname) { $uname=$env{'user.name'}; }
 5063:    my $uhome=&homeserver($uname,$udomain);
 5064: 
 5065:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 5066:    my @pairs=split(/\&/,$rep);
 5067:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 5068:      return @pairs;
 5069:    }
 5070:    my %returnhash=();
 5071:    my $i=0;
 5072:    foreach my $item (@$storearr) {
 5073:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5074:       $i++;
 5075:    }
 5076:    return %returnhash;
 5077: }
 5078: 
 5079: # --------------------------------------------------------------- del interface
 5080: 
 5081: sub del {
 5082:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5083:    my $items='';
 5084:    foreach my $item (@$storearr) {
 5085:        $items.=&escape($item).'&';
 5086:    }
 5087: 
 5088:    $items=~s/\&$//;
 5089:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5090:    if (!$uname) { $uname=$env{'user.name'}; }
 5091:    my $uhome=&homeserver($uname,$udomain);
 5092:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 5093: }
 5094: 
 5095: # -------------------------------------------------------------- dump interface
 5096: 
 5097: sub unserialize {
 5098:     my ($rep, $escapedkeys) = @_;
 5099: 
 5100:     return {} if $rep =~ /^error/;
 5101: 
 5102:     my %returnhash=();
 5103: 	foreach my $item (split /\&/, $rep) {
 5104: 	    my ($key, $value) = split(/=/, $item, 2);
 5105: 	    $key = unescape($key) unless $escapedkeys;
 5106: 	    next if $key =~ /^error: 2 /;
 5107: 	    $returnhash{$key} = Apache::lonnet::thaw_unescape($value);
 5108: 	}
 5109:     #return %returnhash;
 5110:     return \%returnhash;
 5111: }        
 5112: 
 5113: # see Lond::dump_with_regexp
 5114: # if $escapedkeys hash keys won't get unescaped.
 5115: sub dump {
 5116:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
 5117:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5118:     if (!$uname) { $uname=$env{'user.name'}; }
 5119:     my $uhome=&homeserver($uname,$udomain);
 5120: 
 5121:     my $reply;
 5122:     if (grep { $_ eq $uhome } current_machine_ids()) {
 5123:         # user is hosted on this machine
 5124:         $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
 5125:                     $uname, $namespace, $regexp, $range)), $loncaparevs{$uhome});
 5126:         return %{unserialize($reply, $escapedkeys)};
 5127:     }
 5128:     if ($regexp) {
 5129: 	$regexp=&escape($regexp);
 5130:     } else {
 5131: 	$regexp='.';
 5132:     }
 5133:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 5134:     my @pairs=split(/\&/,$rep);
 5135:     my %returnhash=();
 5136:     if (!($rep =~ /^error/ )) {
 5137: 	foreach my $item (@pairs) {
 5138: 	    my ($key,$value)=split(/=/,$item,2);
 5139:         $key = unescape($key) unless $escapedkeys;
 5140:         #$key = &unescape($key);
 5141: 	    next if ($key =~ /^error: 2 /);
 5142: 	    $returnhash{$key}=&thaw_unescape($value);
 5143: 	}
 5144:     }
 5145:     return %returnhash;
 5146: }
 5147: 
 5148: 
 5149: # --------------------------------------------------------- dumpstore interface
 5150: 
 5151: sub dumpstore {
 5152:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 5153:    # same as dump but keys must be escaped. They may contain colon separated
 5154:    # lists of values that may themself contain colons (e.g. symbs).
 5155:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
 5156: }
 5157: 
 5158: # -------------------------------------------------------------- keys interface
 5159: 
 5160: sub getkeys {
 5161:    my ($namespace,$udomain,$uname)=@_;
 5162:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5163:    if (!$uname) { $uname=$env{'user.name'}; }
 5164:    my $uhome=&homeserver($uname,$udomain);
 5165:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 5166:    my @keyarray=();
 5167:    foreach my $key (split(/\&/,$rep)) {
 5168:       next if ($key =~ /^error: 2 /);
 5169:       push(@keyarray,&unescape($key));
 5170:    }
 5171:    return @keyarray;
 5172: }
 5173: 
 5174: # --------------------------------------------------------------- currentdump
 5175: sub currentdump {
 5176:    my ($courseid,$sdom,$sname)=@_;
 5177:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 5178:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 5179:    $sname    = $env{'user.name'}         if (! defined($sname));
 5180:    my $uhome = &homeserver($sname,$sdom);
 5181:    my $rep;
 5182: 
 5183:    if (grep { $_ eq $uhome } current_machine_ids()) {
 5184:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
 5185:                    $courseid)));
 5186:    } else {
 5187:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 5188:    }
 5189: 
 5190:    return if ($rep =~ /^(error:|no_such_host)/);
 5191:    #
 5192:    my %returnhash=();
 5193:    #
 5194:    if ($rep eq "unknown_cmd") { 
 5195:        # an old lond will not know currentdump
 5196:        # Do a dump and make it look like a currentdump
 5197:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 5198:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 5199:        my %hash = @tmp;
 5200:        @tmp=();
 5201:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 5202:    } else {
 5203:        my @pairs=split(/\&/,$rep);
 5204:        foreach my $pair (@pairs) {
 5205:            my ($key,$value)=split(/=/,$pair,2);
 5206:            my ($symb,$param) = split(/:/,$key);
 5207:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 5208:                                                         &thaw_unescape($value);
 5209:        }
 5210:    }
 5211:    return %returnhash;
 5212: }
 5213: 
 5214: sub convert_dump_to_currentdump{
 5215:     my %hash = %{shift()};
 5216:     my %returnhash;
 5217:     # Code ripped from lond, essentially.  The only difference
 5218:     # here is the unescaping done by lonnet::dump().  Conceivably
 5219:     # we might run in to problems with parameter names =~ /^v\./
 5220:     while (my ($key,$value) = each(%hash)) {
 5221:         my ($v,$symb,$param) = split(/:/,$key);
 5222: 	$symb  = &unescape($symb);
 5223: 	$param = &unescape($param);
 5224:         next if ($v eq 'version' || $symb eq 'keys');
 5225:         next if (exists($returnhash{$symb}) &&
 5226:                  exists($returnhash{$symb}->{$param}) &&
 5227:                  $returnhash{$symb}->{'v.'.$param} > $v);
 5228:         $returnhash{$symb}->{$param}=$value;
 5229:         $returnhash{$symb}->{'v.'.$param}=$v;
 5230:     }
 5231:     #
 5232:     # Remove all of the keys in the hashes which keep track of
 5233:     # the version of the parameter.
 5234:     while (my ($symb,$param_hash) = each(%returnhash)) {
 5235:         # use a foreach because we are going to delete from the hash.
 5236:         foreach my $key (keys(%$param_hash)) {
 5237:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 5238:         }
 5239:     }
 5240:     return \%returnhash;
 5241: }
 5242: 
 5243: # ------------------------------------------------------ critical inc interface
 5244: 
 5245: sub cinc {
 5246:     return &inc(@_,'critical');
 5247: }
 5248: 
 5249: # --------------------------------------------------------------- inc interface
 5250: 
 5251: sub inc {
 5252:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 5253:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5254:     if (!$uname) { $uname=$env{'user.name'}; }
 5255:     my $uhome=&homeserver($uname,$udomain);
 5256:     my $items='';
 5257:     if (! ref($store)) {
 5258:         # got a single value, so use that instead
 5259:         $items = &escape($store).'=&';
 5260:     } elsif (ref($store) eq 'SCALAR') {
 5261:         $items = &escape($$store).'=&';        
 5262:     } elsif (ref($store) eq 'ARRAY') {
 5263:         $items = join('=&',map {&escape($_);} @{$store});
 5264:     } elsif (ref($store) eq 'HASH') {
 5265:         while (my($key,$value) = each(%{$store})) {
 5266:             $items.= &escape($key).'='.&escape($value).'&';
 5267:         }
 5268:     }
 5269:     $items=~s/\&$//;
 5270:     if ($critical) {
 5271: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 5272:     } else {
 5273: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 5274:     }
 5275: }
 5276: 
 5277: # --------------------------------------------------------------- put interface
 5278: 
 5279: sub put {
 5280:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5281:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5282:    if (!$uname) { $uname=$env{'user.name'}; }
 5283:    my $uhome=&homeserver($uname,$udomain);
 5284:    my $items='';
 5285:    foreach my $item (keys(%$storehash)) {
 5286:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5287:    }
 5288:    $items=~s/\&$//;
 5289:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5290: }
 5291: 
 5292: # ------------------------------------------------------------ newput interface
 5293: 
 5294: sub newput {
 5295:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5296:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5297:    if (!$uname) { $uname=$env{'user.name'}; }
 5298:    my $uhome=&homeserver($uname,$udomain);
 5299:    my $items='';
 5300:    foreach my $key (keys(%$storehash)) {
 5301:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 5302:    }
 5303:    $items=~s/\&$//;
 5304:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 5305: }
 5306: 
 5307: # ---------------------------------------------------------  putstore interface
 5308: 
 5309: sub putstore {
 5310:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5311:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5312:    if (!$uname) { $uname=$env{'user.name'}; }
 5313:    my $uhome=&homeserver($uname,$udomain);
 5314:    my $items='';
 5315:    foreach my $key (keys(%$storehash)) {
 5316:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 5317:    }
 5318:    $items=~s/\&$//;
 5319:    my $esc_symb=&escape($symb);
 5320:    my $esc_v=&escape($version);
 5321:    my $reply =
 5322:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 5323: 	      $uhome);
 5324:    if ($reply eq 'unknown_cmd') {
 5325:        # gfall back to way things use to be done
 5326:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 5327: 			    $uname);
 5328:    }
 5329:    return $reply;
 5330: }
 5331: 
 5332: sub old_putstore {
 5333:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 5334:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 5335:     if (!$uname) { $uname=$env{'user.name'}; }
 5336:     my $uhome=&homeserver($uname,$udomain);
 5337:     my %newstorehash;
 5338:     foreach my $item (keys(%$storehash)) {
 5339: 	my $key = $version.':'.&escape($symb).':'.$item;
 5340: 	$newstorehash{$key} = $storehash->{$item};
 5341:     }
 5342:     my $items='';
 5343:     my %allitems = ();
 5344:     foreach my $item (keys(%newstorehash)) {
 5345: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 5346: 	    my $key = $1.':keys:'.$2;
 5347: 	    $allitems{$key} .= $3.':';
 5348: 	}
 5349: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 5350:     }
 5351:     foreach my $item (keys(%allitems)) {
 5352: 	$allitems{$item} =~ s/\:$//;
 5353: 	$items.= $item.'='.$allitems{$item}.'&';
 5354:     }
 5355:     $items=~s/\&$//;
 5356:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 5357: }
 5358: 
 5359: # ------------------------------------------------------ critical put interface
 5360: 
 5361: sub cput {
 5362:    my ($namespace,$storehash,$udomain,$uname)=@_;
 5363:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5364:    if (!$uname) { $uname=$env{'user.name'}; }
 5365:    my $uhome=&homeserver($uname,$udomain);
 5366:    my $items='';
 5367:    foreach my $item (keys(%$storehash)) {
 5368:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5369:    }
 5370:    $items=~s/\&$//;
 5371:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 5372: }
 5373: 
 5374: # -------------------------------------------------------------- eget interface
 5375: 
 5376: sub eget {
 5377:    my ($namespace,$storearr,$udomain,$uname)=@_;
 5378:    my $items='';
 5379:    foreach my $item (@$storearr) {
 5380:        $items.=&escape($item).'&';
 5381:    }
 5382:    $items=~s/\&$//;
 5383:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 5384:    if (!$uname) { $uname=$env{'user.name'}; }
 5385:    my $uhome=&homeserver($uname,$udomain);
 5386:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 5387:    my @pairs=split(/\&/,$rep);
 5388:    my %returnhash=();
 5389:    my $i=0;
 5390:    foreach my $item (@$storearr) {
 5391:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 5392:       $i++;
 5393:    }
 5394:    return %returnhash;
 5395: }
 5396: 
 5397: # ------------------------------------------------------------ tmpput interface
 5398: sub tmpput {
 5399:     my ($storehash,$server,$context)=@_;
 5400:     my $items='';
 5401:     foreach my $item (keys(%$storehash)) {
 5402: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 5403:     }
 5404:     $items=~s/\&$//;
 5405:     if (defined($context)) {
 5406:         $items .= ':'.&escape($context);
 5407:     }
 5408:     return &reply("tmpput:$items",$server);
 5409: }
 5410: 
 5411: # ------------------------------------------------------------ tmpget interface
 5412: sub tmpget {
 5413:     my ($token,$server)=@_;
 5414:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5415:     my $rep=&reply("tmpget:$token",$server);
 5416:     my %returnhash;
 5417:     foreach my $item (split(/\&/,$rep)) {
 5418: 	my ($key,$value)=split(/=/,$item);
 5419:         next if ($key =~ /^error: 2 /);
 5420: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 5421:     }
 5422:     return %returnhash;
 5423: }
 5424: 
 5425: # ------------------------------------------------------------ tmpdel interface
 5426: sub tmpdel {
 5427:     my ($token,$server)=@_;
 5428:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 5429:     return &reply("tmpdel:$token",$server);
 5430: }
 5431: 
 5432: # -------------------------------------------------- portfolio access checking
 5433: 
 5434: sub portfolio_access {
 5435:     my ($requrl) = @_;
 5436:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 5437:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 5438:     if ($result) {
 5439:         my %setters;
 5440:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 5441:             my ($startblock,$endblock) =
 5442:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 5443:             if ($startblock && $endblock) {
 5444:                 return 'B';
 5445:             }
 5446:         } else {
 5447:             my ($startblock,$endblock) =
 5448:                 &Apache::loncommon::blockcheck(\%setters,'port');
 5449:             if ($startblock && $endblock) {
 5450:                 return 'B';
 5451:             }
 5452:         }
 5453:     }
 5454:     if ($result eq 'ok') {
 5455:        return 'F';
 5456:     } elsif ($result =~ /^[^:]+:guest_/) {
 5457:        return 'A';
 5458:     }
 5459:     return '';
 5460: }
 5461: 
 5462: sub get_portfolio_access {
 5463:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 5464: 
 5465:     if (!ref($access_hash)) {
 5466: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 5467: 	my %access_controls = &get_access_controls($current_perms,$group,
 5468: 						   $file_name);
 5469: 	$access_hash = $access_controls{$file_name};
 5470:     }
 5471: 
 5472:     my ($public,$guest,@domains,@users,@courses,@groups);
 5473:     my $now = time;
 5474:     if (ref($access_hash) eq 'HASH') {
 5475:         foreach my $key (keys(%{$access_hash})) {
 5476:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 5477:             if ($start > $now) {
 5478:                 next;
 5479:             }
 5480:             if ($end && $end<$now) {
 5481:                 next;
 5482:             }
 5483:             if ($scope eq 'public') {
 5484:                 $public = $key;
 5485:                 last;
 5486:             } elsif ($scope eq 'guest') {
 5487:                 $guest = $key;
 5488:             } elsif ($scope eq 'domains') {
 5489:                 push(@domains,$key);
 5490:             } elsif ($scope eq 'users') {
 5491:                 push(@users,$key);
 5492:             } elsif ($scope eq 'course') {
 5493:                 push(@courses,$key);
 5494:             } elsif ($scope eq 'group') {
 5495:                 push(@groups,$key);
 5496:             }
 5497:         }
 5498:         if ($public) {
 5499:             return 'ok';
 5500:         }
 5501:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 5502:             if ($guest) {
 5503:                 return $guest;
 5504:             }
 5505:         } else {
 5506:             if (@domains > 0) {
 5507:                 foreach my $domkey (@domains) {
 5508:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 5509:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 5510:                             return 'ok';
 5511:                         }
 5512:                     }
 5513:                 }
 5514:             }
 5515:             if (@users > 0) {
 5516:                 foreach my $userkey (@users) {
 5517:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 5518:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 5519:                             if (ref($item) eq 'HASH') {
 5520:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 5521:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 5522:                                     return 'ok';
 5523:                                 }
 5524:                             }
 5525:                         }
 5526:                     } 
 5527:                 }
 5528:             }
 5529:             my %roleshash;
 5530:             my @courses_and_groups = @courses;
 5531:             push(@courses_and_groups,@groups); 
 5532:             if (@courses_and_groups > 0) {
 5533:                 my (%allgroups,%allroles); 
 5534:                 my ($start,$end,$role,$sec,$group);
 5535:                 foreach my $envkey (%env) {
 5536:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 5537:                         my $cid = $2.'_'.$3; 
 5538:                         if ($1 eq 'gr') {
 5539:                             $group = $4;
 5540:                             $allgroups{$cid}{$group} = $env{$envkey};
 5541:                         } else {
 5542:                             if ($4 eq '') {
 5543:                                 $sec = 'none';
 5544:                             } else {
 5545:                                 $sec = $4;
 5546:                             }
 5547:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 5548:                         }
 5549:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 5550:                         my $cid = $2.'_'.$3;
 5551:                         if ($4 eq '') {
 5552:                             $sec = 'none';
 5553:                         } else {
 5554:                             $sec = $4;
 5555:                         }
 5556:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 5557:                     }
 5558:                 }
 5559:                 if (keys(%allroles) == 0) {
 5560:                     return;
 5561:                 }
 5562:                 foreach my $key (@courses_and_groups) {
 5563:                     my %content = %{$$access_hash{$key}};
 5564:                     my $cnum = $content{'number'};
 5565:                     my $cdom = $content{'domain'};
 5566:                     my $cid = $cdom.'_'.$cnum;
 5567:                     if (!exists($allroles{$cid})) {
 5568:                         next;
 5569:                     }    
 5570:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 5571:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 5572:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 5573:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 5574:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 5575:                         foreach my $role (keys(%{$allroles{$cid}})) {
 5576:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 5577:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 5578:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 5579:                                         if (grep/^all$/,@sections) {
 5580:                                             return 'ok';
 5581:                                         } else {
 5582:                                             if (grep/^$sec$/,@sections) {
 5583:                                                 return 'ok';
 5584:                                             }
 5585:                                         }
 5586:                                     }
 5587:                                 }
 5588:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 5589:                                     if (grep/^none$/,@groups) {
 5590:                                         return 'ok';
 5591:                                     }
 5592:                                 } else {
 5593:                                     if (grep/^all$/,@groups) {
 5594:                                         return 'ok';
 5595:                                     } 
 5596:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 5597:                                         if (grep/^$group$/,@groups) {
 5598:                                             return 'ok';
 5599:                                         }
 5600:                                     }
 5601:                                 } 
 5602:                             }
 5603:                         }
 5604:                     }
 5605:                 }
 5606:             }
 5607:             if ($guest) {
 5608:                 return $guest;
 5609:             }
 5610:         }
 5611:     }
 5612:     return;
 5613: }
 5614: 
 5615: sub course_group_datechecker {
 5616:     my ($dates,$now,$status) = @_;
 5617:     my ($start,$end) = split(/\./,$dates);
 5618:     if (!$start && !$end) {
 5619:         return 'ok';
 5620:     }
 5621:     if (grep/^active$/,@{$status}) {
 5622:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 5623:             return 'ok';
 5624:         }
 5625:     }
 5626:     if (grep/^previous$/,@{$status}) {
 5627:         if ($end > $now ) {
 5628:             return 'ok';
 5629:         }
 5630:     }
 5631:     if (grep/^future$/,@{$status}) {
 5632:         if ($start > $now) {
 5633:             return 'ok';
 5634:         }
 5635:     }
 5636:     return; 
 5637: }
 5638: 
 5639: sub parse_portfolio_url {
 5640:     my ($url) = @_;
 5641: 
 5642:     my ($type,$udom,$unum,$group,$file_name);
 5643:     
 5644:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 5645: 	$type = 1;
 5646:         $udom = $1;
 5647:         $unum = $2;
 5648:         $file_name = $3;
 5649:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 5650: 	$type = 2;
 5651:         $udom = $1;
 5652:         $unum = $2;
 5653:         $group = $3;
 5654:         $file_name = $3.'/'.$4;
 5655:     }
 5656:     if (wantarray) {
 5657: 	return ($type,$udom,$unum,$file_name,$group);
 5658:     }
 5659:     return $type;
 5660: }
 5661: 
 5662: sub is_portfolio_url {
 5663:     my ($url) = @_;
 5664:     return scalar(&parse_portfolio_url($url));
 5665: }
 5666: 
 5667: sub is_portfolio_file {
 5668:     my ($file) = @_;
 5669:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 5670:         return 1;
 5671:     }
 5672:     return;
 5673: }
 5674: 
 5675: sub usertools_access {
 5676:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
 5677:     my ($access,%tools);
 5678:     if ($context eq '') {
 5679:         $context = 'tools';
 5680:     }
 5681:     if ($context eq 'requestcourses') {
 5682:         %tools = (
 5683:                       official   => 1,
 5684:                       unofficial => 1,
 5685:                       community  => 1,
 5686:                  );
 5687:     } elsif ($context eq 'requestauthor') {
 5688:         %tools = (
 5689:                       requestauthor => 1,
 5690:                  );
 5691:     } else {
 5692:         %tools = (
 5693:                       aboutme   => 1,
 5694:                       blog      => 1,
 5695:                       webdav    => 1,
 5696:                       portfolio => 1,
 5697:                  );
 5698:     }
 5699:     return if (!defined($tools{$tool}));
 5700: 
 5701:     if ((!defined($udom)) || (!defined($uname))) {
 5702:         $udom = $env{'user.domain'};
 5703:         $uname = $env{'user.name'};
 5704:     }
 5705: 
 5706:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 5707:         if ($action ne 'reload') {
 5708:             if ($context eq 'requestcourses') {
 5709:                 return $env{'environment.canrequest.'.$tool};
 5710:             } elsif ($context eq 'requestauthor') {
 5711:                 return $env{'environment.canrequest.author'};
 5712:             } else {
 5713:                 return $env{'environment.availabletools.'.$tool};
 5714:             }
 5715:         }
 5716:     }
 5717: 
 5718:     my ($toolstatus,$inststatus,$envkey);
 5719:     if ($context eq 'requestauthor') {
 5720:         $envkey = $context; 
 5721:     } else {
 5722:         $envkey = $context.'.'.$tool;
 5723:     }
 5724: 
 5725:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 5726:          ($action ne 'reload')) {
 5727:         $toolstatus = $env{'environment.'.$envkey};
 5728:         $inststatus = $env{'environment.inststatus'};
 5729:     } else {
 5730:         if (ref($userenvref) eq 'HASH') {
 5731:             $toolstatus = $userenvref->{$envkey};
 5732:             $inststatus = $userenvref->{'inststatus'};
 5733:         } else {
 5734:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
 5735:             $toolstatus = $userenv{$envkey};
 5736:             $inststatus = $userenv{'inststatus'};
 5737:         }
 5738:     }
 5739: 
 5740:     if ($toolstatus ne '') {
 5741:         if ($toolstatus) {
 5742:             $access = 1;
 5743:         } else {
 5744:             $access = 0;
 5745:         }
 5746:         return $access;
 5747:     }
 5748: 
 5749:     my ($is_adv,%domdef);
 5750:     if (ref($is_advref) eq 'HASH') {
 5751:         $is_adv = $is_advref->{'is_adv'};
 5752:     } else {
 5753:         $is_adv = &is_advanced_user($udom,$uname);
 5754:     }
 5755:     if (ref($domdefref) eq 'HASH') {
 5756:         %domdef = %{$domdefref};
 5757:     } else {
 5758:         %domdef = &get_domain_defaults($udom);
 5759:     }
 5760:     if (ref($domdef{$tool}) eq 'HASH') {
 5761:         if ($is_adv) {
 5762:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 5763:                 if ($domdef{$tool}{'_LC_adv'}) { 
 5764:                     $access = 1;
 5765:                 } else {
 5766:                     $access = 0;
 5767:                 }
 5768:                 return $access;
 5769:             }
 5770:         }
 5771:         if ($inststatus ne '') {
 5772:             my ($hasaccess,$hasnoaccess);
 5773:             foreach my $affiliation (split(/:/,$inststatus)) {
 5774:                 if ($domdef{$tool}{$affiliation} ne '') { 
 5775:                     if ($domdef{$tool}{$affiliation}) {
 5776:                         $hasaccess = 1;
 5777:                     } else {
 5778:                         $hasnoaccess = 1;
 5779:                     }
 5780:                 }
 5781:             }
 5782:             if ($hasaccess || $hasnoaccess) {
 5783:                 if ($hasaccess) {
 5784:                     $access = 1;
 5785:                 } elsif ($hasnoaccess) {
 5786:                     $access = 0; 
 5787:                 }
 5788:                 return $access;
 5789:             }
 5790:         } else {
 5791:             if ($domdef{$tool}{'default'} ne '') {
 5792:                 if ($domdef{$tool}{'default'}) {
 5793:                     $access = 1;
 5794:                 } elsif ($domdef{$tool}{'default'} == 0) {
 5795:                     $access = 0;
 5796:                 }
 5797:                 return $access;
 5798:             }
 5799:         }
 5800:     } else {
 5801:         if (($context eq 'tools') && ($tool ne 'webdav')) {
 5802:             $access = 1;
 5803:         } else {
 5804:             $access = 0;
 5805:         }
 5806:         return $access;
 5807:     }
 5808: }
 5809: 
 5810: sub is_course_owner {
 5811:     my ($cdom,$cnum,$udom,$uname) = @_;
 5812:     if (($udom eq '') || ($uname eq '')) {
 5813:         $udom = $env{'user.domain'};
 5814:         $uname = $env{'user.name'};
 5815:     }
 5816:     unless (($udom eq '') || ($uname eq '')) {
 5817:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 5818:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 5819:                 return 1;
 5820:             } else {
 5821:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 5822:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 5823:                     return 1;
 5824:                 }
 5825:             }
 5826:         }
 5827:     }
 5828:     return;
 5829: }
 5830: 
 5831: sub is_advanced_user {
 5832:     my ($udom,$uname) = @_;
 5833:     if ($udom ne '' && $uname ne '') {
 5834:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 5835:             if (wantarray) {
 5836:                 return ($env{'user.adv'},$env{'user.author'});
 5837:             } else {
 5838:                 return $env{'user.adv'};
 5839:             }
 5840:         }
 5841:     }
 5842:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 5843:     my %allroles;
 5844:     my ($is_adv,$is_author);
 5845:     foreach my $role (keys(%roleshash)) {
 5846:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 5847:         my $area = '/'.$tdomain.'/'.$trest;
 5848:         if ($sec ne '') {
 5849:             $area .= '/'.$sec;
 5850:         }
 5851:         if (($area ne '') && ($trole ne '')) {
 5852:             my $spec=$trole.'.'.$area;
 5853:             if ($trole =~ /^cr\//) {
 5854:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 5855:             } elsif ($trole ne 'gr') {
 5856:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 5857:             }
 5858:             if ($trole eq 'au') {
 5859:                 $is_author = 1;
 5860:             }
 5861:         }
 5862:     }
 5863:     foreach my $role (keys(%allroles)) {
 5864:         last if ($is_adv);
 5865:         foreach my $item (split(/:/,$allroles{$role})) {
 5866:             if ($item ne '') {
 5867:                 my ($privilege,$restrictions)=split(/&/,$item);
 5868:                 if ($privilege eq 'adv') {
 5869:                     $is_adv = 1;
 5870:                     last;
 5871:                 }
 5872:             }
 5873:         }
 5874:     }
 5875:     if (wantarray) {
 5876:         return ($is_adv,$is_author);
 5877:     }
 5878:     return $is_adv;
 5879: }
 5880: 
 5881: sub check_can_request {
 5882:     my ($dom,$can_request,$request_domains) = @_;
 5883:     my $canreq = 0;
 5884:     my ($types,$typename) = &Apache::loncommon::course_types();
 5885:     my @options = ('approval','validate','autolimit');
 5886:     my $optregex = join('|',@options);
 5887:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 5888:         foreach my $type (@{$types}) {
 5889:             if (&usertools_access($env{'user.name'},
 5890:                                   $env{'user.domain'},
 5891:                                   $type,undef,'requestcourses')) {
 5892:                 $canreq ++;
 5893:                 if (ref($request_domains) eq 'HASH') {
 5894:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 5895:                 }
 5896:                 if ($dom eq $env{'user.domain'}) {
 5897:                     $can_request->{$type} = 1;
 5898:                 }
 5899:             }
 5900:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 5901:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 5902:                 if (@curr > 0) {
 5903:                     foreach my $item (@curr) {
 5904:                         if (ref($request_domains) eq 'HASH') {
 5905:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 5906:                             if ($otherdom ne '') {
 5907:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 5908:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 5909:                                         push(@{$request_domains->{$type}},$otherdom);
 5910:                                     }
 5911:                                 } else {
 5912:                                     push(@{$request_domains->{$type}},$otherdom);
 5913:                                 }
 5914:                             }
 5915:                         }
 5916:                     }
 5917:                     unless($dom eq $env{'user.domain'}) {
 5918:                         $canreq ++;
 5919:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 5920:                             $can_request->{$type} = 1;
 5921:                         }
 5922:                     }
 5923:                 }
 5924:             }
 5925:         }
 5926:     }
 5927:     return $canreq;
 5928: }
 5929: 
 5930: # ---------------------------------------------- Custom access rule evaluation
 5931: 
 5932: sub customaccess {
 5933:     my ($priv,$uri)=@_;
 5934:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 5935:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 5936:     $udom = &LONCAPA::clean_domain($udom);
 5937:     $ucrs = &LONCAPA::clean_username($ucrs);
 5938:     my $access=0;
 5939:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 5940: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 5941: 	if ($type eq 'user') {
 5942: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 5943: 		my ($tdom,$tuname)=split(m{/},$scope);
 5944: 		if ($tdom) {
 5945: 		    if ($tdom ne $env{'user.domain'}) { next; }
 5946: 		}
 5947: 		if ($tuname) {
 5948: 		    if ($tuname ne $env{'user.name'}) { next; }
 5949: 		}
 5950: 		$access=($effect eq 'allow');
 5951: 		last;
 5952: 	    }
 5953: 	} else {
 5954: 	    if ($role) {
 5955: 		if ($role ne $urole) { next; }
 5956: 	    }
 5957: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 5958: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 5959: 		if ($tdom) {
 5960: 		    if ($tdom ne $udom) { next; }
 5961: 		}
 5962: 		if ($tcrs) {
 5963: 		    if ($tcrs ne $ucrs) { next; }
 5964: 		}
 5965: 		if ($tsec) {
 5966: 		    if ($tsec ne $usec) { next; }
 5967: 		}
 5968: 		$access=($effect eq 'allow');
 5969: 		last;
 5970: 	    }
 5971: 	    if ($realm eq '' && $role eq '') {
 5972: 		$access=($effect eq 'allow');
 5973: 	    }
 5974: 	}
 5975:     }
 5976:     return $access;
 5977: }
 5978: 
 5979: # ------------------------------------------------- Check for a user privilege
 5980: 
 5981: sub allowed {
 5982:     my ($priv,$uri,$symb,$role)=@_;
 5983:     my $ver_orguri=$uri;
 5984:     $uri=&deversion($uri);
 5985:     my $orguri=$uri;
 5986:     $uri=&declutter($uri);
 5987: 
 5988:     if ($priv eq 'evb') {
 5989: # Evade communication block restrictions for specified role in a course
 5990:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 5991:             return $1;
 5992:         } else {
 5993:             return;
 5994:         }
 5995:     }
 5996: 
 5997:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 5998: # Free bre access to adm and meta resources
 5999:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 6000: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 6001: 	&& ($priv eq 'bre')) {
 6002: 	return 'F';
 6003:     }
 6004: 
 6005: # Free bre access to user's own portfolio contents
 6006:     my ($space,$domain,$name,@dir)=split('/',$uri);
 6007:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 6008: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 6009:         my %setters;
 6010:         my ($startblock,$endblock) = 
 6011:             &Apache::loncommon::blockcheck(\%setters,'port');
 6012:         if ($startblock && $endblock) {
 6013:             return 'B';
 6014:         } else {
 6015:             return 'F';
 6016:         }
 6017:     }
 6018: 
 6019: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 6020:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 6021:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 6022:         if (exists($env{'request.course.id'})) {
 6023:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6024:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6025:             if (($domain eq $cdom) && ($name eq $cnum)) {
 6026:                 my $courseprivid=$env{'request.course.id'};
 6027:                 $courseprivid=~s/\_/\//;
 6028:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 6029:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 6030:                     return $1; 
 6031:                 } else {
 6032:                     if ($env{'request.course.sec'}) {
 6033:                         $courseprivid.='/'.$env{'request.course.sec'};
 6034:                     }
 6035:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 6036:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 6037:                         return $2;
 6038:                     }
 6039:                 }
 6040:             }
 6041:         }
 6042:     }
 6043: 
 6044: # Free bre to public access
 6045: 
 6046:     if ($priv eq 'bre') {
 6047:         my $copyright=&metadata($uri,'copyright');
 6048: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 6049:            return 'F'; 
 6050:         }
 6051:         if ($copyright eq 'priv') {
 6052:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6053: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 6054: 		return '';
 6055:             }
 6056:         }
 6057:         if ($copyright eq 'domain') {
 6058:             $uri=~/([^\/]+)\/([^\/]+)\//;
 6059: 	    unless (($env{'user.domain'} eq $1) ||
 6060:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 6061: 		return '';
 6062:             }
 6063:         }
 6064:         if ($env{'request.role'}=~ /li\.\//) {
 6065:             # Library role, so allow browsing of resources in this domain.
 6066:             return 'F';
 6067:         }
 6068:         if ($copyright eq 'custom') {
 6069: 	    unless (&customaccess($priv,$uri)) { return ''; }
 6070:         }
 6071:     }
 6072:     # Domain coordinator is trying to create a course
 6073:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 6074:         # uri is the requested domain in this case.
 6075:         # comparison to 'request.role.domain' shows if the user has selected
 6076:         # a role of dc for the domain in question.
 6077:         return 'F' if ($uri eq $env{'request.role.domain'});
 6078:     }
 6079: 
 6080:     my $thisallowed='';
 6081:     my $statecond=0;
 6082:     my $courseprivid='';
 6083: 
 6084:     my $ownaccess;
 6085:     # Community Coordinator or Assistant Co-author browsing resource space.
 6086:     if (($priv eq 'bro') && ($env{'user.author'})) {
 6087:         if ($uri eq '') {
 6088:             $ownaccess = 1;
 6089:         } else {
 6090:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 6091:                 my $udom = $env{'user.domain'};
 6092:                 my $uname = $env{'user.name'};
 6093:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 6094:                     $ownaccess = 1;
 6095:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 6096:                     unless ($uri =~ m{\.\./}) {
 6097:                         $ownaccess = 1;
 6098:                     }
 6099:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 6100:                     my $now = time;
 6101:                     if ($uri =~ m{^([^/]+)/?$}) {
 6102:                         my $adom = $1;
 6103:                         foreach my $key (keys(%env)) {
 6104:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 6105:                                 my ($start,$end) = split('.',$env{$key});
 6106:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6107:                                     $ownaccess = 1;
 6108:                                     last;
 6109:                                 }
 6110:                             }
 6111:                         }
 6112:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 6113:                         my $adom = $1;
 6114:                         my $aname = $2;
 6115:                         foreach my $role ('ca','aa') { 
 6116:                             if ($env{"user.role.$role./$adom/$aname"}) {
 6117:                                 my ($start,$end) =
 6118:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 6119:                                 if (($now >= $start) && (!$end || $end < $now)) {
 6120:                                     $ownaccess = 1;
 6121:                                     last;
 6122:                                 }
 6123:                             }
 6124:                         }
 6125:                     }
 6126:                 }
 6127:             }
 6128:         }
 6129:     }
 6130: 
 6131: # Course
 6132: 
 6133:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 6134:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6135:             $thisallowed.=$1;
 6136:         }
 6137:     }
 6138: 
 6139: # Domain
 6140: 
 6141:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 6142:        =~/\Q$priv\E\&([^\:]*)/) {
 6143:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6144:             $thisallowed.=$1;
 6145:         }
 6146:     }
 6147: 
 6148: # User who is not author or co-author might still be able to edit
 6149: # resource of an author in the domain (e.g., if Domain Coordinator).
 6150:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
 6151:         (&allowed('mdc',$env{'request.course.id'}))) {
 6152:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
 6153:             $thisallowed.=$1;
 6154:         }
 6155:     }
 6156: 
 6157: # Course: uri itself is a course
 6158:     my $courseuri=$uri;
 6159:     $courseuri=~s/\_(\d)/\/$1/;
 6160:     $courseuri=~s/^([^\/])/\/$1/;
 6161: 
 6162:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 6163:        =~/\Q$priv\E\&([^\:]*)/) {
 6164:         unless (($priv eq 'bro') && (!$ownaccess)) {
 6165:             $thisallowed.=$1;
 6166:         }
 6167:     }
 6168: 
 6169: # URI is an uploaded document for this course, default permissions don't matter
 6170: # not allowing 'edit' access (editupload) to uploaded course docs
 6171:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 6172: 	$thisallowed='';
 6173:         my ($match)=&is_on_map($uri);
 6174:         if ($match) {
 6175:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 6176:                   =~/\Q$priv\E\&([^\:]*)/) {
 6177:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6178:                 if (@blockers > 0) {
 6179:                     $thisallowed = 'B';
 6180:                 } else {
 6181:                     $thisallowed.=$1;
 6182:                 }
 6183:             }
 6184:         } else {
 6185:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 6186:             if ($refuri) {
 6187:                 if ($refuri =~ m|^/adm/|) {
 6188:                     $thisallowed='F';
 6189:                 } else {
 6190:                     $refuri=&declutter($refuri);
 6191:                     my ($match) = &is_on_map($refuri);
 6192:                     if ($match) {
 6193:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6194:                         if (@blockers > 0) {
 6195:                             $thisallowed = 'B';
 6196:                         } else {
 6197:                             $thisallowed='F';
 6198:                         }
 6199:                     }
 6200:                 }
 6201:             }
 6202:         }
 6203:     }
 6204: 
 6205:     if ($priv eq 'bre'
 6206: 	&& $thisallowed ne 'F' 
 6207: 	&& $thisallowed ne '2'
 6208: 	&& &is_portfolio_url($uri)) {
 6209: 	$thisallowed = &portfolio_access($uri);
 6210:     }
 6211:     
 6212: # Full access at system, domain or course-wide level? Exit.
 6213:     if ($thisallowed=~/F/) {
 6214: 	return 'F';
 6215:     }
 6216: 
 6217: # If this is generating or modifying users, exit with special codes
 6218: 
 6219:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 6220: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 6221: 	    my ($audom,$auname)=split('/',$uri);
 6222: # no author name given, so this just checks on the general right to make a co-author in this domain
 6223: 	    unless ($auname) { return $thisallowed; }
 6224: # an author name is given, so we are about to actually make a co-author for a certain account
 6225: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 6226: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 6227: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 6228: 	}
 6229: 	return $thisallowed;
 6230:     }
 6231: #
 6232: # Gathered so far: system, domain and course wide privileges
 6233: #
 6234: # Course: See if uri or referer is an individual resource that is part of 
 6235: # the course
 6236: 
 6237:     if ($env{'request.course.id'}) {
 6238: 
 6239:        $courseprivid=$env{'request.course.id'};
 6240:        if ($env{'request.course.sec'}) {
 6241:           $courseprivid.='/'.$env{'request.course.sec'};
 6242:        }
 6243:        $courseprivid=~s/\_/\//;
 6244:        my $checkreferer=1;
 6245:        my ($match,$cond)=&is_on_map($uri);
 6246:        if ($match) {
 6247:            $statecond=$cond;
 6248:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6249:                =~/\Q$priv\E\&([^\:]*)/) {
 6250:                my $value = $1;
 6251:                if ($priv eq 'bre') {
 6252:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
 6253:                    if (@blockers > 0) {
 6254:                        $thisallowed = 'B';
 6255:                    } else {
 6256:                        $thisallowed.=$value;
 6257:                    }
 6258:                } else {
 6259:                    $thisallowed.=$value;
 6260:                }
 6261:                $checkreferer=0;
 6262:            }
 6263:        }
 6264:        
 6265:        if ($checkreferer) {
 6266: 	  my $refuri=$env{'httpref.'.$orguri};
 6267:             unless ($refuri) {
 6268:                 foreach my $key (keys(%env)) {
 6269: 		    if ($key=~/^httpref\..*\*/) {
 6270: 			my $pattern=$key;
 6271:                         $pattern=~s/^httpref\.\/res\///;
 6272:                         $pattern=~s/\*/\[\^\/\]\+/g;
 6273:                         $pattern=~s/\//\\\//g;
 6274:                         if ($orguri=~/$pattern/) {
 6275: 			    $refuri=$env{$key};
 6276:                         }
 6277:                     }
 6278:                 }
 6279:             }
 6280: 
 6281:          if ($refuri) { 
 6282: 	  $refuri=&declutter($refuri);
 6283:           my ($match,$cond)=&is_on_map($refuri);
 6284:             if ($match) {
 6285:               my $refstatecond=$cond;
 6286:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 6287:                   =~/\Q$priv\E\&([^\:]*)/) {
 6288:                   my $value = $1;
 6289:                   if ($priv eq 'bre') {
 6290:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
 6291:                       if (@blockers > 0) {
 6292:                           $thisallowed = 'B';
 6293:                       } else {
 6294:                           $thisallowed.=$value;
 6295:                       }
 6296:                   } else {
 6297:                       $thisallowed.=$value;
 6298:                   }
 6299:                   $uri=$refuri;
 6300:                   $statecond=$refstatecond;
 6301:               }
 6302:           }
 6303:         }
 6304:        }
 6305:    }
 6306: 
 6307: #
 6308: # Gathered now: all privileges that could apply, and condition number
 6309: # 
 6310: #
 6311: # Full or no access?
 6312: #
 6313: 
 6314:     if ($thisallowed=~/F/) {
 6315: 	return 'F';
 6316:     }
 6317: 
 6318:     unless ($thisallowed) {
 6319:         return '';
 6320:     }
 6321: 
 6322: # Restrictions exist, deal with them
 6323: #
 6324: #   C:according to course preferences
 6325: #   R:according to resource settings
 6326: #   L:unless locked
 6327: #   X:according to user session state
 6328: #
 6329: 
 6330: # Possibly locked functionality, check all courses
 6331: # Locks might take effect only after 10 minutes cache expiration for other
 6332: # courses, and 2 minutes for current course
 6333: 
 6334:     my $envkey;
 6335:     if ($thisallowed=~/L/) {
 6336:         foreach $envkey (keys(%env)) {
 6337:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 6338:                my $courseid=$2;
 6339:                my $roleid=$1.'.'.$2;
 6340:                $courseid=~s/^\///;
 6341:                my $expiretime=600;
 6342:                if ($env{'request.role'} eq $roleid) {
 6343: 		  $expiretime=120;
 6344:                }
 6345: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 6346:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 6347:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 6348: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 6349:                }
 6350:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6351:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 6352: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 6353:                        &log($env{'user.domain'},$env{'user.name'},
 6354:                             $env{'user.home'},
 6355:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 6356:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6357:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6358: 		       return '';
 6359:                    }
 6360:                }
 6361:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 6362:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 6363: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 6364:                        &log($env{'user.domain'},$env{'user.name'},
 6365:                             $env{'user.home'},
 6366:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 6367:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 6368:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 6369: 		       return '';
 6370:                    }
 6371:                }
 6372: 	   }
 6373:        }
 6374:     }
 6375:    
 6376: #
 6377: # Rest of the restrictions depend on selected course
 6378: #
 6379: 
 6380:     unless ($env{'request.course.id'}) {
 6381: 	if ($thisallowed eq 'A') {
 6382: 	    return 'A';
 6383:         } elsif ($thisallowed eq 'B') {
 6384:             return 'B';
 6385: 	} else {
 6386: 	    return '1';
 6387: 	}
 6388:     }
 6389: 
 6390: #
 6391: # Now user is definitely in a course
 6392: #
 6393: 
 6394: 
 6395: # Course preferences
 6396: 
 6397:    if ($thisallowed=~/C/) {
 6398:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6399:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 6400:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 6401: 	   =~/\Q$rolecode\E/) {
 6402: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6403: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6404: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 6405: 			$env{'request.course.id'});
 6406: 	   }
 6407:            return '';
 6408:        }
 6409: 
 6410:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 6411: 	   =~/\Q$unamedom\E/) {
 6412: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6413: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 6414: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 6415: 			$env{'request.course.id'});
 6416: 	   }
 6417:            return '';
 6418:        }
 6419:    }
 6420: 
 6421: # Resource preferences
 6422: 
 6423:    if ($thisallowed=~/R/) {
 6424:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 6425:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 6426: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
 6427: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 6428: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 6429: 	   }
 6430: 	   return '';
 6431:        }
 6432:    }
 6433: 
 6434: # Restricted by state or randomout?
 6435: 
 6436:    if ($thisallowed=~/X/) {
 6437:       if ($env{'acc.randomout'}) {
 6438: 	 if (!$symb) { $symb=&symbread($uri,1); }
 6439:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 6440:             return ''; 
 6441:          }
 6442:       }
 6443:       if (&condval($statecond)) {
 6444: 	 return '2';
 6445:       } else {
 6446:          return '';
 6447:       }
 6448:    }
 6449: 
 6450:     if ($thisallowed eq 'A') {
 6451: 	return 'A';
 6452:     } elsif ($thisallowed eq 'B') {
 6453:         return 'B';
 6454:     }
 6455:    return 'F';
 6456: }
 6457: 
 6458: sub get_comm_blocks {
 6459:     my ($cdom,$cnum) = @_;
 6460:     if ($cdom eq '' || $cnum eq '') {
 6461:         return unless ($env{'request.course.id'});
 6462:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 6463:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 6464:     }
 6465:     my %commblocks;
 6466:     my $hashid=$cdom.'_'.$cnum;
 6467:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
 6468:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
 6469:         %commblocks = %{$blocksref};
 6470:     } else {
 6471:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
 6472:         my $cachetime = 600;
 6473:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
 6474:     }
 6475:     return %commblocks;
 6476: }
 6477: 
 6478: sub has_comm_blocking {
 6479:     my ($priv,$symb,$uri,$blocks) = @_;
 6480:     return unless ($env{'request.course.id'});
 6481:     return unless ($priv eq 'bre');
 6482:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
 6483:     my %commblocks;
 6484:     if (ref($blocks) eq 'HASH') {
 6485:         %commblocks = %{$blocks};
 6486:     } else {
 6487:         %commblocks = &get_comm_blocks();
 6488:     }
 6489:     return unless (keys(%commblocks) > 0);
 6490:     if (!$symb) { $symb=&symbread($uri,1); }
 6491:     my ($map,$resid,undef)=&decode_symb($symb);
 6492:     my %tocheck = (
 6493:                     maps      => $map,
 6494:                     resources => $symb,
 6495:                   );
 6496:     my @blockers;
 6497:     my $now = time;
 6498:     my $navmap = Apache::lonnavmaps::navmap->new();
 6499:     foreach my $block (keys(%commblocks)) {
 6500:         if ($block =~ /^(\d+)____(\d+)$/) {
 6501:             my ($start,$end) = ($1,$2);
 6502:             if ($start <= $now && $end >= $now) {
 6503:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 6504:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 6505:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
 6506:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
 6507:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 6508:                                     push(@blockers,$block);
 6509:                                 }
 6510:                             }
 6511:                         }
 6512:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
 6513:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
 6514:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
 6515:                                     push(@blockers,$block);
 6516:                                 }
 6517:                             }
 6518:                         }
 6519:                     }
 6520:                 }
 6521:             }
 6522:         } elsif ($block =~ /^firstaccess____(.+)$/) {
 6523:             my $item = $1;
 6524:             my @to_test;
 6525:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
 6526:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
 6527:                     my $check_interval;
 6528:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
 6529:                         my @interval;
 6530:                         my $type = 'map';
 6531:                         if ($item eq 'course') {
 6532:                             $type = 'course';
 6533:                             @interval=&EXT("resource.0.interval");
 6534:                         } else {
 6535:                             if ($item =~ /___\d+___/) {
 6536:                                 $type = 'resource';
 6537:                                 @interval=&EXT("resource.0.interval",$item);
 6538:                                 if (ref($navmap)) {                        
 6539:                                     my $res = $navmap->getBySymb($item); 
 6540:                                     push(@to_test,$res);
 6541:                                 }
 6542:                             } else {
 6543:                                 my $mapsymb = &symbread($item,1);
 6544:                                 if ($mapsymb) {
 6545:                                     if (ref($navmap)) {
 6546:                                         my $mapres = $navmap->getBySymb($mapsymb);
 6547:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
 6548:                                         foreach my $res (@to_test) {
 6549:                                             my $symb = $res->symb();
 6550:                                             next if ($symb eq $mapsymb);
 6551:                                             if ($symb ne '') {
 6552:                                                 @interval=&EXT("resource.0.interval",$symb);
 6553:                                                 last;
 6554:                                             }
 6555:                                         }
 6556:                                     }
 6557:                                 }
 6558:                             }
 6559:                         }
 6560:                         if ($interval[0] =~ /\d+/) {
 6561:                             my $first_access;
 6562:                             if ($type eq 'resource') {
 6563:                                 $first_access=&get_first_access($interval[1],$item);
 6564:                             } elsif ($type eq 'map') {
 6565:                                 $first_access=&get_first_access($interval[1],undef,$item);
 6566:                             } else {
 6567:                                 $first_access=&get_first_access($interval[1]);
 6568:                             }
 6569:                             if ($first_access) {
 6570:                                 my $timesup = $first_access+$interval[0];
 6571:                                 if ($timesup > $now) {
 6572:                                     foreach my $res (@to_test) {
 6573:                                         if ($res->is_problem()) {
 6574:                                             if ($res->completable()) {
 6575:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
 6576:                                                     push(@blockers,$block);
 6577:                                                 }
 6578:                                                 last;
 6579:                                             }
 6580:                                         }
 6581:                                     }
 6582:                                 }
 6583:                             }
 6584:                         }
 6585:                     }
 6586:                 }
 6587:             }
 6588:         }
 6589:     }
 6590:     return @blockers;
 6591: }
 6592: 
 6593: sub check_docs_block {
 6594:     my ($docsblock,$tocheck) =@_;
 6595:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
 6596:         return;
 6597:     }
 6598:     if (ref($docsblock->{'maps'}) eq 'HASH') {
 6599:         if ($tocheck->{'maps'}) {
 6600:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
 6601:                 return 1;
 6602:             }
 6603:         }
 6604:     }
 6605:     if (ref($docsblock->{'resources'}) eq 'HASH') {
 6606:         if ($tocheck->{'resources'}) {
 6607:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
 6608:                 return 1;
 6609:             }
 6610:         }
 6611:     }
 6612:     return;
 6613: }
 6614: 
 6615: #
 6616: #   Removes the versino from a URI and
 6617: #   splits it in to its filename and path to the filename.
 6618: #   Seems like File::Basename could have done this more clearly.
 6619: #   Parameters:
 6620: #      $uri   - input URI
 6621: #   Returns:
 6622: #     Two element list consisting of 
 6623: #     $pathname  - the URI up to and excluding the trailing /
 6624: #     $filename  - The part of the URI following the last /
 6625: #  NOTE:
 6626: #    Another realization of this is simply:
 6627: #    use File::Basename;
 6628: #    ...
 6629: #    $uri = shift;
 6630: #    $filename = basename($uri);
 6631: #    $path     = dirname($uri);
 6632: #    return ($filename, $path);
 6633: #
 6634: #     The implementation below is probably faster however.
 6635: #
 6636: sub split_uri_for_cond {
 6637:     my $uri=&deversion(&declutter(shift));
 6638:     my @uriparts=split(/\//,$uri);
 6639:     my $filename=pop(@uriparts);
 6640:     my $pathname=join('/',@uriparts);
 6641:     return ($pathname,$filename);
 6642: }
 6643: # --------------------------------------------------- Is a resource on the map?
 6644: 
 6645: sub is_on_map {
 6646:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 6647:     #Trying to find the conditional for the file
 6648:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 6649: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 6650:     if ($match) {
 6651: 	return (1,$1);
 6652:     } else {
 6653: 	return (0,0);
 6654:     }
 6655: }
 6656: 
 6657: # --------------------------------------------------------- Get symb from alias
 6658: 
 6659: sub get_symb_from_alias {
 6660:     my $symb=shift;
 6661:     my ($map,$resid,$url)=&decode_symb($symb);
 6662: # Already is a symb
 6663:     if ($url) { return $symb; }
 6664: # Must be an alias
 6665:     my $aliassymb='';
 6666:     my %bighash;
 6667:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6668:                             &GDBM_READER(),0640)) {
 6669:         my $rid=$bighash{'mapalias_'.$symb};
 6670: 	if ($rid) {
 6671: 	    my ($mapid,$resid)=split(/\./,$rid);
 6672: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 6673: 				    $resid,$bighash{'src_'.$rid});
 6674: 	}
 6675:         untie %bighash;
 6676:     }
 6677:     return $aliassymb;
 6678: }
 6679: 
 6680: # ----------------------------------------------------------------- Define Role
 6681: 
 6682: sub definerole {
 6683:   if (allowed('mcr','/')) {
 6684:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 6685:     foreach my $role (split(':',$sysrole)) {
 6686: 	my ($crole,$cqual)=split(/\&/,$role);
 6687:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 6688:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 6689: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 6690:                return "refused:s:$crole&$cqual"; 
 6691:             }
 6692:         }
 6693:     }
 6694:     foreach my $role (split(':',$domrole)) {
 6695: 	my ($crole,$cqual)=split(/\&/,$role);
 6696:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 6697:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 6698: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 6699:                return "refused:d:$crole&$cqual"; 
 6700:             }
 6701:         }
 6702:     }
 6703:     foreach my $role (split(':',$courole)) {
 6704: 	my ($crole,$cqual)=split(/\&/,$role);
 6705:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 6706:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 6707: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 6708:                return "refused:c:$crole&$cqual"; 
 6709:             }
 6710:         }
 6711:     }
 6712:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 6713:                 "$env{'user.domain'}:$env{'user.name'}:".
 6714: 	        "rolesdef_$rolename=".
 6715:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 6716:     return reply($command,$env{'user.home'});
 6717:   } else {
 6718:     return 'refused';
 6719:   }
 6720: }
 6721: 
 6722: # ---------------- Make a metadata query against the network of library servers
 6723: 
 6724: sub metadata_query {
 6725:     my ($query,$custom,$customshow,$server_array)=@_;
 6726:     my %rhash;
 6727:     my %libserv = &all_library();
 6728:     my @server_list = (defined($server_array) ? @$server_array
 6729:                                               : keys(%libserv) );
 6730:     for my $server (@server_list) {
 6731: 	unless ($custom or $customshow) {
 6732: 	    my $reply=&reply("querysend:".&escape($query),$server);
 6733: 	    $rhash{$server}=$reply;
 6734: 	}
 6735: 	else {
 6736: 	    my $reply=&reply("querysend:".&escape($query).':'.
 6737: 			     &escape($custom).':'.&escape($customshow),
 6738: 			     $server);
 6739: 	    $rhash{$server}=$reply;
 6740: 	}
 6741:     }
 6742:     return \%rhash;
 6743: }
 6744: 
 6745: # ----------------------------------------- Send log queries and wait for reply
 6746: 
 6747: sub log_query {
 6748:     my ($uname,$udom,$query,%filters)=@_;
 6749:     my $uhome=&homeserver($uname,$udom);
 6750:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 6751:     my $uhost=&hostname($uhome);
 6752:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 6753:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 6754:                        $uhome);
 6755:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 6756:     return get_query_reply($queryid);
 6757: }
 6758: 
 6759: # -------------------------- Update MySQL table for portfolio file
 6760: 
 6761: sub update_portfolio_table {
 6762:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 6763:     if ($group ne '') {
 6764:         $file_name =~s /^\Q$group\E//;
 6765:     }
 6766:     my $homeserver = &homeserver($uname,$udom);
 6767:     my $queryid=
 6768:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 6769:                ':'.&escape($file_name).':'.$action,$homeserver);
 6770:     my $reply = &get_query_reply($queryid);
 6771:     return $reply;
 6772: }
 6773: 
 6774: # -------------------------- Update MySQL allusers table
 6775: 
 6776: sub update_allusers_table {
 6777:     my ($uname,$udom,$names) = @_;
 6778:     my $homeserver = &homeserver($uname,$udom);
 6779:     my $queryid=
 6780:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 6781:                'lastname='.&escape($names->{'lastname'}).'%%'.
 6782:                'firstname='.&escape($names->{'firstname'}).'%%'.
 6783:                'middlename='.&escape($names->{'middlename'}).'%%'.
 6784:                'generation='.&escape($names->{'generation'}).'%%'.
 6785:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 6786:                'id='.&escape($names->{'id'}),$homeserver);
 6787:     return;
 6788: }
 6789: 
 6790: # ------- Request retrieval of institutional classlists for course(s)
 6791: 
 6792: sub fetch_enrollment_query {
 6793:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 6794:     my $homeserver;
 6795:     my $maxtries = 1;
 6796:     if ($context eq 'automated') {
 6797:         $homeserver = $perlvar{'lonHostID'};
 6798:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 6799:     } else {
 6800:         $homeserver = &homeserver($cnum,$dom);
 6801:     }
 6802:     my $host=&hostname($homeserver);
 6803:     my $cmd = '';
 6804:     foreach my $affiliate (keys(%{$affiliatesref})) {
 6805:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 6806:     }
 6807:     $cmd =~ s/%%$//;
 6808:     $cmd = &escape($cmd);
 6809:     my $query = 'fetchenrollment';
 6810:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 6811:     unless ($queryid=~/^\Q$host\E\_/) { 
 6812:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 6813:         return 'error: '.$queryid;
 6814:     }
 6815:     my $reply = &get_query_reply($queryid);
 6816:     my $tries = 1;
 6817:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 6818:         $reply = &get_query_reply($queryid);
 6819:         $tries ++;
 6820:     }
 6821:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 6822:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 6823:     } else {
 6824:         my @responses = split(/:/,$reply);
 6825:         if ($homeserver eq $perlvar{'lonHostID'}) {
 6826:             foreach my $line (@responses) {
 6827:                 my ($key,$value) = split(/=/,$line,2);
 6828:                 $$replyref{$key} = $value;
 6829:             }
 6830:         } else {
 6831:             my $pathname = LONCAPA::tempdir();
 6832:             foreach my $line (@responses) {
 6833:                 my ($key,$value) = split(/=/,$line);
 6834:                 $$replyref{$key} = $value;
 6835:                 if ($value > 0) {
 6836:                     foreach my $item (@{$$affiliatesref{$key}}) {
 6837:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 6838:                         my $destname = $pathname.'/'.$filename;
 6839:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 6840:                         if ($xml_classlist =~ /^error/) {
 6841:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 6842:                         } else {
 6843:                             if ( open(FILE,">$destname") ) {
 6844:                                 print FILE &unescape($xml_classlist);
 6845:                                 close(FILE);
 6846:                             } else {
 6847:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 6848:                             }
 6849:                         }
 6850:                     }
 6851:                 }
 6852:             }
 6853:         }
 6854:         return 'ok';
 6855:     }
 6856:     return 'error';
 6857: }
 6858: 
 6859: sub get_query_reply {
 6860:     my $queryid=shift;
 6861:     my $replyfile=LONCAPA::tempdir().$queryid;
 6862:     my $reply='';
 6863:     for (1..100) {
 6864: 	sleep 2;
 6865:         if (-e $replyfile.'.end') {
 6866: 	    if (open(my $fh,$replyfile)) {
 6867: 		$reply = join('',<$fh>);
 6868: 		close($fh);
 6869: 	   } else { return 'error: reply_file_error'; }
 6870:            return &unescape($reply);
 6871: 	}
 6872:     }
 6873:     return 'timeout:'.$queryid;
 6874: }
 6875: 
 6876: sub courselog_query {
 6877: #
 6878: # possible filters:
 6879: # url: url or symb
 6880: # username
 6881: # domain
 6882: # action: view, submit, grade
 6883: # start: timestamp
 6884: # end: timestamp
 6885: #
 6886:     my (%filters)=@_;
 6887:     unless ($env{'request.course.id'}) { return 'no_course'; }
 6888:     if ($filters{'url'}) {
 6889: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 6890:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 6891:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 6892:     }
 6893:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 6894:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 6895:     return &log_query($cname,$cdom,'courselog',%filters);
 6896: }
 6897: 
 6898: sub userlog_query {
 6899: #
 6900: # possible filters:
 6901: # action: log check role
 6902: # start: timestamp
 6903: # end: timestamp
 6904: #
 6905:     my ($uname,$udom,%filters)=@_;
 6906:     return &log_query($uname,$udom,'userlog',%filters);
 6907: }
 6908: 
 6909: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 6910: 
 6911: sub auto_run {
 6912:     my ($cnum,$cdom) = @_;
 6913:     my $response = 0;
 6914:     my $settings;
 6915:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 6916:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 6917:         $settings = $domconfig{'autoenroll'};
 6918:         if ($settings->{'run'} eq '1') {
 6919:             $response = 1;
 6920:         }
 6921:     } else {
 6922:         my $homeserver;
 6923:         if (&is_course($cdom,$cnum)) {
 6924:             $homeserver = &homeserver($cnum,$cdom);
 6925:         } else {
 6926:             $homeserver = &domain($cdom,'primary');
 6927:         }
 6928:         if ($homeserver ne 'no_host') {
 6929:             $response = &reply('autorun:'.$cdom,$homeserver);
 6930:         }
 6931:     }
 6932:     return $response;
 6933: }
 6934: 
 6935: sub auto_get_sections {
 6936:     my ($cnum,$cdom,$inst_coursecode) = @_;
 6937:     my $homeserver;
 6938:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 6939:         $homeserver = &homeserver($cnum,$cdom);
 6940:     }
 6941:     if (!defined($homeserver)) { 
 6942:         if ($cdom =~ /^$match_domain$/) {
 6943:             $homeserver = &domain($cdom,'primary');
 6944:         }
 6945:     }
 6946:     my @secs;
 6947:     if (defined($homeserver)) {
 6948:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 6949:         unless ($response eq 'refused') {
 6950:             @secs = split(/:/,$response);
 6951:         }
 6952:     }
 6953:     return @secs;
 6954: }
 6955: 
 6956: sub auto_new_course {
 6957:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
 6958:     my $homeserver = &homeserver($cnum,$cdom);
 6959:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
 6960:     return $response;
 6961: }
 6962: 
 6963: sub auto_validate_courseID {
 6964:     my ($cnum,$cdom,$inst_course_id) = @_;
 6965:     my $homeserver = &homeserver($cnum,$cdom);
 6966:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 6967:     return $response;
 6968: }
 6969: 
 6970: sub auto_validate_instcode {
 6971:     my ($cnum,$cdom,$instcode,$owner) = @_;
 6972:     my ($homeserver,$response);
 6973:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 6974:         $homeserver = &homeserver($cnum,$cdom);
 6975:     }
 6976:     if (!defined($homeserver)) {
 6977:         if ($cdom =~ /^$match_domain$/) {
 6978:             $homeserver = &domain($cdom,'primary');
 6979:         }
 6980:     }
 6981:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 6982:                         &escape($instcode).':'.&escape($owner),$homeserver));
 6983:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
 6984:     return ($outcome,$description);
 6985: }
 6986: 
 6987: sub auto_create_password {
 6988:     my ($cnum,$cdom,$authparam,$udom) = @_;
 6989:     my ($homeserver,$response);
 6990:     my $create_passwd = 0;
 6991:     my $authchk = '';
 6992:     if ($udom =~ /^$match_domain$/) {
 6993:         $homeserver = &domain($udom,'primary');
 6994:     }
 6995:     if ($homeserver eq '') {
 6996:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 6997:             $homeserver = &homeserver($cnum,$cdom);
 6998:         }
 6999:     }
 7000:     if ($homeserver eq '') {
 7001:         $authchk = 'nodomain';
 7002:     } else {
 7003:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 7004:         if ($response eq 'refused') {
 7005:             $authchk = 'refused';
 7006:         } else {
 7007:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 7008:         }
 7009:     }
 7010:     return ($authparam,$create_passwd,$authchk);
 7011: }
 7012: 
 7013: sub auto_photo_permission {
 7014:     my ($cnum,$cdom,$students) = @_;
 7015:     my $homeserver = &homeserver($cnum,$cdom);
 7016:     my ($outcome,$perm_reqd,$conditions) = 
 7017: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 7018:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7019: 	return (undef,undef);
 7020:     }
 7021:     return ($outcome,$perm_reqd,$conditions);
 7022: }
 7023: 
 7024: sub auto_checkphotos {
 7025:     my ($uname,$udom,$pid) = @_;
 7026:     my $homeserver = &homeserver($uname,$udom);
 7027:     my ($result,$resulttype);
 7028:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 7029: 				   &escape($uname).':'.&escape($pid),
 7030: 				   $homeserver));
 7031:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7032: 	return (undef,undef);
 7033:     }
 7034:     if ($outcome) {
 7035:         ($result,$resulttype) = split(/:/,$outcome);
 7036:     } 
 7037:     return ($result,$resulttype);
 7038: }
 7039: 
 7040: sub auto_photochoice {
 7041:     my ($cnum,$cdom) = @_;
 7042:     my $homeserver = &homeserver($cnum,$cdom);
 7043:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 7044: 						       &escape($cdom),
 7045: 						       $homeserver)));
 7046:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 7047: 	return (undef,undef);
 7048:     }
 7049:     return ($update,$comment);
 7050: }
 7051: 
 7052: sub auto_photoupdate {
 7053:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 7054:     my $homeserver = &homeserver($cnum,$dom);
 7055:     my $host=&hostname($homeserver);
 7056:     my $cmd = '';
 7057:     my $maxtries = 1;
 7058:     foreach my $affiliate (keys(%{$affiliatesref})) {
 7059:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 7060:     }
 7061:     $cmd =~ s/%%$//;
 7062:     $cmd = &escape($cmd);
 7063:     my $query = 'institutionalphotos';
 7064:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 7065:     unless ($queryid=~/^\Q$host\E\_/) {
 7066:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 7067:         return 'error: '.$queryid;
 7068:     }
 7069:     my $reply = &get_query_reply($queryid);
 7070:     my $tries = 1;
 7071:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 7072:         $reply = &get_query_reply($queryid);
 7073:         $tries ++;
 7074:     }
 7075:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 7076:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 7077:     } else {
 7078:         my @responses = split(/:/,$reply);
 7079:         my $outcome = shift(@responses); 
 7080:         foreach my $item (@responses) {
 7081:             my ($key,$value) = split(/=/,$item);
 7082:             $$photo{$key} = $value;
 7083:         }
 7084:         return $outcome;
 7085:     }
 7086:     return 'error';
 7087: }
 7088: 
 7089: sub auto_instcode_format {
 7090:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 7091: 	$cat_order) = @_;
 7092:     my $courses = '';
 7093:     my @homeservers;
 7094:     if ($caller eq 'global') {
 7095: 	my %servers = &get_servers($codedom,'library');
 7096: 	foreach my $tryserver (keys(%servers)) {
 7097: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7098: 		push(@homeservers,$tryserver);
 7099: 	    }
 7100:         }
 7101:     } elsif ($caller eq 'requests') {
 7102:         if ($codedom =~ /^$match_domain$/) {
 7103:             my $chome = &domain($codedom,'primary');
 7104:             unless ($chome eq 'no_host') {
 7105:                 push(@homeservers,$chome);
 7106:             }
 7107:         }
 7108:     } else {
 7109:         push(@homeservers,&homeserver($caller,$codedom));
 7110:     }
 7111:     foreach my $code (keys(%{$instcodes})) {
 7112:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 7113:     }
 7114:     chop($courses);
 7115:     my $ok_response = 0;
 7116:     my $response;
 7117:     while (@homeservers > 0 && $ok_response == 0) {
 7118:         my $server = shift(@homeservers); 
 7119:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 7120:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 7121:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 7122: 		split(/:/,$response);
 7123:             %{$codes} = (%{$codes},&str2hash($codes_str));
 7124:             push(@{$codetitles},&str2array($codetitles_str));
 7125:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 7126:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 7127:             $ok_response = 1;
 7128:         }
 7129:     }
 7130:     if ($ok_response) {
 7131:         return 'ok';
 7132:     } else {
 7133:         return $response;
 7134:     }
 7135: }
 7136: 
 7137: sub auto_instcode_defaults {
 7138:     my ($domain,$returnhash,$code_order) = @_;
 7139:     my @homeservers;
 7140: 
 7141:     my %servers = &get_servers($domain,'library');
 7142:     foreach my $tryserver (keys(%servers)) {
 7143: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7144: 	    push(@homeservers,$tryserver);
 7145: 	}
 7146:     }
 7147: 
 7148:     my $response;
 7149:     foreach my $server (@homeservers) {
 7150:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 7151:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7152: 	
 7153: 	foreach my $pair (split(/\&/,$response)) {
 7154: 	    my ($name,$value)=split(/\=/,$pair);
 7155: 	    if ($name eq 'code_order') {
 7156: 		@{$code_order} = split(/\&/,&unescape($value));
 7157: 	    } else {
 7158: 		$returnhash->{&unescape($name)}=&unescape($value);
 7159: 	    }
 7160: 	}
 7161: 	return 'ok';
 7162:     }
 7163: 
 7164:     return $response;
 7165: }
 7166: 
 7167: sub auto_possible_instcodes {
 7168:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 7169:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 7170:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 7171:         return;
 7172:     }
 7173:     my (@homeservers,$uhome);
 7174:     if (defined(&domain($domain,'primary'))) {
 7175:         $uhome=&domain($domain,'primary');
 7176:         push(@homeservers,&domain($domain,'primary'));
 7177:     } else {
 7178:         my %servers = &get_servers($domain,'library');
 7179:         foreach my $tryserver (keys(%servers)) {
 7180:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 7181:                 push(@homeservers,$tryserver);
 7182:             }
 7183:         }
 7184:     }
 7185:     my $response;
 7186:     foreach my $server (@homeservers) {
 7187:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 7188:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 7189:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 7190:             split(':',$response);
 7191:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 7192:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 7193:         foreach my $item (split('&',$cat_title)) {   
 7194:             my ($name,$value)=split('=',$item);
 7195:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 7196:         }
 7197:         foreach my $item (split('&',$cat_order)) {
 7198:             my ($name,$value)=split('=',$item);
 7199:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 7200:         }
 7201:         return 'ok';
 7202:     }
 7203:     return $response;
 7204: }
 7205: 
 7206: sub auto_courserequest_checks {
 7207:     my ($dom) = @_;
 7208:     my ($homeserver,%validations);
 7209:     if ($dom =~ /^$match_domain$/) {
 7210:         $homeserver = &domain($dom,'primary');
 7211:     }
 7212:     unless ($homeserver eq 'no_host') {
 7213:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 7214:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 7215:             my @items = split(/&/,$response);
 7216:             foreach my $item (@items) {
 7217:                 my ($key,$value) = split('=',$item);
 7218:                 $validations{&unescape($key)} = &thaw_unescape($value);
 7219:             }
 7220:         }
 7221:     }
 7222:     return %validations; 
 7223: }
 7224: 
 7225: sub auto_courserequest_validation {
 7226:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
 7227:     my ($homeserver,$response);
 7228:     if ($dom =~ /^$match_domain$/) {
 7229:         $homeserver = &domain($dom,'primary');
 7230:     }
 7231:     unless ($homeserver eq 'no_host') {  
 7232:           
 7233:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 7234:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 7235:                                     ':'.&escape($instcode).':'.&escape($instseclist),
 7236:                                     $homeserver));
 7237:     }
 7238:     return $response;
 7239: }
 7240: 
 7241: sub auto_validate_class_sec {
 7242:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 7243:     my $homeserver = &homeserver($cnum,$cdom);
 7244:     my $ownerlist;
 7245:     if (ref($owners) eq 'ARRAY') {
 7246:         $ownerlist = join(',',@{$owners});
 7247:     } else {
 7248:         $ownerlist = $owners;
 7249:     }
 7250:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 7251:                         &escape($ownerlist).':'.$cdom,$homeserver);
 7252:     return $response;
 7253: }
 7254: 
 7255: # ------------------------------------------------------- Course Group routines
 7256: 
 7257: sub get_coursegroups {
 7258:     my ($cdom,$cnum,$group,$namespace) = @_;
 7259:     return(&dump($namespace,$cdom,$cnum,$group));
 7260: }
 7261: 
 7262: sub modify_coursegroup {
 7263:     my ($cdom,$cnum,$groupsettings) = @_;
 7264:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 7265: }
 7266: 
 7267: sub toggle_coursegroup_status {
 7268:     my ($cdom,$cnum,$group,$action) = @_;
 7269:     my ($from_namespace,$to_namespace);
 7270:     if ($action eq 'delete') {
 7271:         $from_namespace = 'coursegroups';
 7272:         $to_namespace = 'deleted_groups';
 7273:     } else {
 7274:         $from_namespace = 'deleted_groups';
 7275:         $to_namespace = 'coursegroups';
 7276:     }
 7277:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 7278:     if (my $tmp = &error(%curr_group)) {
 7279:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 7280:         return ('read error',$tmp);
 7281:     } else {
 7282:         my %savedsettings = %curr_group; 
 7283:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 7284:         my $deloutcome;
 7285:         if ($result eq 'ok') {
 7286:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 7287:         } else {
 7288:             return ('write error',$result);
 7289:         }
 7290:         if ($deloutcome eq 'ok') {
 7291:             return 'ok';
 7292:         } else {
 7293:             return ('delete error',$deloutcome);
 7294:         }
 7295:     }
 7296: }
 7297: 
 7298: sub modify_group_roles {
 7299:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 7300:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 7301:     my $role = 'gr/'.&escape($userprivs);
 7302:     my ($uname,$udom) = split(/:/,$user);
 7303:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 7304:     if ($result eq 'ok') {
 7305:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 7306:     }
 7307:     return $result;
 7308: }
 7309: 
 7310: sub modify_coursegroup_membership {
 7311:     my ($cdom,$cnum,$membership) = @_;
 7312:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 7313:     return $result;
 7314: }
 7315: 
 7316: sub get_active_groups {
 7317:     my ($udom,$uname,$cdom,$cnum) = @_;
 7318:     my $now = time;
 7319:     my %groups = ();
 7320:     foreach my $key (keys(%env)) {
 7321:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 7322:             my ($start,$end) = split(/\./,$env{$key});
 7323:             if (($end!=0) && ($end<$now)) { next; }
 7324:             if (($start!=0) && ($start>$now)) { next; }
 7325:             if ($1 eq $cdom && $2 eq $cnum) {
 7326:                 $groups{$3} = $env{$key} ;
 7327:             }
 7328:         }
 7329:     }
 7330:     return %groups;
 7331: }
 7332: 
 7333: sub get_group_membership {
 7334:     my ($cdom,$cnum,$group) = @_;
 7335:     return(&dump('groupmembership',$cdom,$cnum,$group));
 7336: }
 7337: 
 7338: sub get_users_groups {
 7339:     my ($udom,$uname,$courseid) = @_;
 7340:     my @usersgroups;
 7341:     my $cachetime=1800;
 7342: 
 7343:     my $hashid="$udom:$uname:$courseid";
 7344:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 7345:     if (defined($cached)) {
 7346:         @usersgroups = split(/:/,$grouplist);
 7347:     } else {  
 7348:         $grouplist = '';
 7349:         my $courseurl = &courseid_to_courseurl($courseid);
 7350:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 7351:         my $access_end = $env{'course.'.$courseid.
 7352:                               '.default_enrollment_end_date'};
 7353:         my $now = time;
 7354:         foreach my $key (keys(%roleshash)) {
 7355:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 7356:                 my $group = $1;
 7357:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 7358:                     my $start = $2;
 7359:                     my $end = $1;
 7360:                     if ($start == -1) { next; } # deleted from group
 7361:                     if (($start!=0) && ($start>$now)) { next; }
 7362:                     if (($end!=0) && ($end<$now)) {
 7363:                         if ($access_end && $access_end < $now) {
 7364:                             if ($access_end - $end < 86400) {
 7365:                                 push(@usersgroups,$group);
 7366:                             }
 7367:                         }
 7368:                         next;
 7369:                     }
 7370:                     push(@usersgroups,$group);
 7371:                 }
 7372:             }
 7373:         }
 7374:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 7375:         $grouplist = join(':',@usersgroups);
 7376:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 7377:     }
 7378:     return @usersgroups;
 7379: }
 7380: 
 7381: sub devalidate_getgroups_cache {
 7382:     my ($udom,$uname,$cdom,$cnum)=@_;
 7383:     my $courseid = $cdom.'_'.$cnum;
 7384: 
 7385:     my $hashid="$udom:$uname:$courseid";
 7386:     &devalidate_cache_new('getgroups',$hashid);
 7387: }
 7388: 
 7389: # ------------------------------------------------------------------ Plain Text
 7390: 
 7391: sub plaintext {
 7392:     my ($short,$type,$cid,$forcedefault) = @_;
 7393:     if ($short =~ m{^cr/}) {
 7394: 	return (split('/',$short))[-1];
 7395:     }
 7396:     if (!defined($cid)) {
 7397:         $cid = $env{'request.course.id'};
 7398:     }
 7399:     my %rolenames = (
 7400:                       Course    => 'std',
 7401:                       Community => 'alt1',
 7402:                     );
 7403:     if ($cid ne '') {
 7404:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 7405:             unless ($forcedefault) {
 7406:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 7407:                 &Apache::lonlocal::mt_escape(\$roletext);
 7408:                 return &Apache::lonlocal::mt($roletext);
 7409:             }
 7410:         }
 7411:     }
 7412:     if ((defined($type)) && (defined($rolenames{$type})) &&
 7413:         (defined($rolenames{$type})) && 
 7414:         (defined($prp{$short}{$rolenames{$type}}))) {
 7415:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 7416:     } elsif ($cid ne '') {
 7417:         my $crstype = $env{'course.'.$cid.'.type'};
 7418:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 7419:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 7420:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 7421:         }
 7422:     }
 7423:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 7424: }
 7425: 
 7426: # ----------------------------------------------------------------- Assign Role
 7427: 
 7428: sub assignrole {
 7429:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 7430:         $context)=@_;
 7431:     my $mrole;
 7432:     if ($role =~ /^cr\//) {
 7433:         my $cwosec=$url;
 7434:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 7435: 	unless (&allowed('ccr',$cwosec)) {
 7436:            my $refused = 1;
 7437:            if ($context eq 'requestcourses') {
 7438:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 7439:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 7440:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 7441:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 7442:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7443:                            if ($crsenv{'internal.courseowner'} eq
 7444:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 7445:                                $refused = '';
 7446:                            }
 7447:                        }
 7448:                    }
 7449:                }
 7450:            }
 7451:            if ($refused) {
 7452:                &logthis('Refused custom assignrole: '.
 7453:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 7454:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 7455:                return 'refused';
 7456:            }
 7457:         }
 7458:         $mrole='cr';
 7459:     } elsif ($role =~ /^gr\//) {
 7460:         my $cwogrp=$url;
 7461:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 7462:         unless (&allowed('mdg',$cwogrp)) {
 7463:             &logthis('Refused group assignrole: '.
 7464:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 7465:                     $env{'user.name'}.' at '.$env{'user.domain'});
 7466:             return 'refused';
 7467:         }
 7468:         $mrole='gr';
 7469:     } else {
 7470:         my $cwosec=$url;
 7471:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 7472:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 7473:             my $refused;
 7474:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 7475:                 if (!(&allowed('c'.$role,$url))) {
 7476:                     $refused = 1;
 7477:                 }
 7478:             } else {
 7479:                 $refused = 1;
 7480:             }
 7481:             if ($refused) {
 7482:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 7483:                 if (!$selfenroll && $context eq 'course') {
 7484:                     my %crsenv;
 7485:                     if ($role eq 'cc' || $role eq 'co') {
 7486:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7487:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 7488:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 7489:                                 if ($crsenv{'internal.courseowner'} eq 
 7490:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 7491:                                     $refused = '';
 7492:                                 }
 7493:                             }
 7494:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 7495:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 7496:                                 if ($crsenv{'internal.courseowner'} eq 
 7497:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 7498:                                     $refused = '';
 7499:                                 }
 7500:                             }
 7501:                         }
 7502:                     }
 7503:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 7504:                     $refused = '';
 7505:                 } elsif ($context eq 'requestcourses') {
 7506:                     my @possroles = ('st','ta','ep','in','cc','co');
 7507:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 7508:                         my $wrongcc;
 7509:                         if ($cnum =~ /^$match_community$/) {
 7510:                             $wrongcc = 1 if ($role eq 'cc');
 7511:                         } else {
 7512:                             $wrongcc = 1 if ($role eq 'co');
 7513:                         }
 7514:                         unless ($wrongcc) {
 7515:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 7516:                             if ($crsenv{'internal.courseowner'} eq 
 7517:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 7518:                                 $refused = '';
 7519:                             }
 7520:                         }
 7521:                     }
 7522:                 } elsif ($context eq 'requestauthor') {
 7523:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
 7524:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
 7525:                         if ($env{'environment.requestauthor'} eq 'automatic') {
 7526:                             $refused = '';
 7527:                         } else {
 7528:                             my %domdefaults = &get_domain_defaults($udom);
 7529:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
 7530:                                 my $checkbystatus;
 7531:                                 if ($env{'user.adv'}) { 
 7532:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
 7533:                                     if ($disposition eq 'automatic') {
 7534:                                         $refused = '';
 7535:                                     } elsif ($disposition eq '') {
 7536:                                         $checkbystatus = 1;
 7537:                                     } 
 7538:                                 } else {
 7539:                                     $checkbystatus = 1;
 7540:                                 }
 7541:                                 if ($checkbystatus) {
 7542:                                     if ($env{'environment.inststatus'}) {
 7543:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
 7544:                                         foreach my $type (@inststatuses) {
 7545:                                             if (($type ne '') &&
 7546:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
 7547:                                                 $refused = '';
 7548:                                             }
 7549:                                         }
 7550:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
 7551:                                         $refused = '';
 7552:                                     }
 7553:                                 }
 7554:                             }
 7555:                         }
 7556:                     }
 7557:                 }
 7558:                 if ($refused) {
 7559:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 7560:                              ' '.$role.' '.$end.' '.$start.' by '.
 7561: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 7562:                     return 'refused';
 7563:                 }
 7564:             }
 7565:         } elsif ($role eq 'au') {
 7566:             if ($url ne '/'.$udom.'/') {
 7567:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
 7568:                          ' to assign author role for '.$uname.':'.$udom.
 7569:                          ' in domain: '.$url.' refused (wrong domain).');
 7570:                 return 'refused';
 7571:             }
 7572:         }
 7573:         $mrole=$role;
 7574:     }
 7575:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 7576:                 "$udom:$uname:$url".'_'."$mrole=$role";
 7577:     if ($end) { $command.='_'.$end; }
 7578:     if ($start) {
 7579: 	if ($end) { 
 7580:            $command.='_'.$start; 
 7581:         } else {
 7582:            $command.='_0_'.$start;
 7583:         }
 7584:     }
 7585:     my $origstart = $start;
 7586:     my $origend = $end;
 7587:     my $delflag;
 7588: # actually delete
 7589:     if ($deleteflag) {
 7590: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 7591: # modify command to delete the role
 7592:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 7593:                 "$udom:$uname:$url".'_'."$mrole";
 7594: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 7595: # set start and finish to negative values for userrolelog
 7596:            $start=-1;
 7597:            $end=-1;
 7598:            $delflag = 1;
 7599:         }
 7600:     }
 7601: # send command
 7602:     my $answer=&reply($command,&homeserver($uname,$udom));
 7603: # log new user role if status is ok
 7604:     if ($answer eq 'ok') {
 7605: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 7606: # for course roles, perform group memberships changes triggered by role change.
 7607:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
 7608:         unless ($role =~ /^gr/) {
 7609:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 7610:                                              $origstart,$selfenroll,$context);
 7611:         }
 7612:         if ($role eq 'cc') {
 7613:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 7614:         }
 7615:     }
 7616:     return $answer;
 7617: }
 7618: 
 7619: sub autoupdate_coowners {
 7620:     my ($url,$end,$start,$uname,$udom) = @_;
 7621:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 7622:     if (($cdom ne '') && ($cnum ne '')) {
 7623:         my $now = time;
 7624:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 7625:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 7626:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 7627:             my $instcode = $coursehash{'internal.coursecode'};
 7628:             if ($instcode ne '') {
 7629:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 7630:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 7631:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 7632:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 7633:                         if ($result eq 'valid') {
 7634:                             if ($coursehash{'internal.co-owners'}) {
 7635:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 7636:                                     push(@newcoowners,$coowner);
 7637:                                 }
 7638:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 7639:                                     push(@newcoowners,$uname.':'.$udom);
 7640:                                 }
 7641:                                 @newcoowners = sort(@newcoowners);
 7642:                             } else {
 7643:                                 push(@newcoowners,$uname.':'.$udom);
 7644:                             }
 7645:                         } else {
 7646:                             if ($coursehash{'internal.co-owners'}) {
 7647:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 7648:                                     unless ($coowner eq $uname.':'.$udom) {
 7649:                                         push(@newcoowners,$coowner);
 7650:                                     }
 7651:                                 }
 7652:                                 unless (@newcoowners > 0) {
 7653:                                     $delcoowners = 1;
 7654:                                     $coowners = '';
 7655:                                 }
 7656:                             }
 7657:                         }
 7658:                         if (@newcoowners || $delcoowners) {
 7659:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 7660:                                             $delcoowners,@newcoowners);
 7661:                         }
 7662:                     }
 7663:                 }
 7664:             }
 7665:         }
 7666:     }
 7667: }
 7668: 
 7669: sub store_coowners {
 7670:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 7671:     my $cid = $cdom.'_'.$cnum;
 7672:     my ($coowners,$delresult,$putresult);
 7673:     if (@newcoowners) {
 7674:         $coowners = join(',',@newcoowners);
 7675:         my %coownershash = (
 7676:                             'internal.co-owners' => $coowners,
 7677:                            );
 7678:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 7679:         if ($putresult eq 'ok') {
 7680:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 7681:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 7682:             }
 7683:         }
 7684:     }
 7685:     if ($delcoowners) {
 7686:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 7687:         if ($delresult eq 'ok') {
 7688:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 7689:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 7690:             }
 7691:         }
 7692:     }
 7693:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 7694:         my %crsinfo =
 7695:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 7696:         if (ref($crsinfo{$cid}) eq 'HASH') {
 7697:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 7698:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 7699:         }
 7700:     }
 7701: }
 7702: 
 7703: # -------------------------------------------------- Modify user authentication
 7704: # Overrides without validation
 7705: 
 7706: sub modifyuserauth {
 7707:     my ($udom,$uname,$umode,$upass)=@_;
 7708:     my $uhome=&homeserver($uname,$udom);
 7709:     unless (&allowed('mau',$udom)) { return 'refused'; }
 7710:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 7711:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 7712:              ' in domain '.$env{'request.role.domain'});  
 7713:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 7714: 		     &escape($upass),$uhome);
 7715:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 7716:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 7717:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 7718:     &log($udom,,$uname,$uhome,
 7719:         'Authentication changed by '.$env{'user.domain'}.', '.
 7720:                                      $env{'user.name'}.', '.$umode.
 7721:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 7722:     unless ($reply eq 'ok') {
 7723:         &logthis('Authentication mode error: '.$reply);
 7724: 	return 'error: '.$reply;
 7725:     }   
 7726:     return 'ok';
 7727: }
 7728: 
 7729: # --------------------------------------------------------------- Modify a user
 7730: 
 7731: sub modifyuser {
 7732:     my ($udom,    $uname, $uid,
 7733:         $umode,   $upass, $first,
 7734:         $middle,  $last,  $gene,
 7735:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 7736:     $udom= &LONCAPA::clean_domain($udom);
 7737:     $uname=&LONCAPA::clean_username($uname);
 7738:     my $showcandelete = 'none';
 7739:     if (ref($candelete) eq 'ARRAY') {
 7740:         if (@{$candelete} > 0) {
 7741:             $showcandelete = join(', ',@{$candelete});
 7742:         }
 7743:     }
 7744:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 7745:              $umode.', '.$first.', '.$middle.', '.
 7746: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 7747:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 7748:                                      ' desiredhome not specified'). 
 7749:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 7750:              ' in domain '.$env{'request.role.domain'});
 7751:     my $uhome=&homeserver($uname,$udom,'true');
 7752:     my $newuser;
 7753:     if ($uhome eq 'no_host') {
 7754:         $newuser = 1;
 7755:     }
 7756: # ----------------------------------------------------------------- Create User
 7757:     if (($uhome eq 'no_host') && 
 7758: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 7759:         my $unhome='';
 7760:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 7761:             $unhome = $desiredhome;
 7762: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 7763: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 7764:         } else { # load balancing routine for determining $unhome
 7765:             my $loadm=10000000;
 7766: 	    my %servers = &get_servers($udom,'library');
 7767: 	    foreach my $tryserver (keys(%servers)) {
 7768: 		my $answer=reply('load',$tryserver);
 7769: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 7770: 		    $loadm=$answer;
 7771: 		    $unhome=$tryserver;
 7772: 		}
 7773: 	    }
 7774:         }
 7775:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 7776: 	    return 'error: unable to find a home server for '.$uname.
 7777:                    ' in domain '.$udom;
 7778:         }
 7779:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 7780:                          &escape($upass),$unhome);
 7781: 	unless ($reply eq 'ok') {
 7782:             return 'error: '.$reply;
 7783:         }   
 7784:         $uhome=&homeserver($uname,$udom,'true');
 7785:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 7786: 	    return 'error: unable verify users home machine.';
 7787:         }
 7788:     }   # End of creation of new user
 7789: # ---------------------------------------------------------------------- Add ID
 7790:     if ($uid) {
 7791:        $uid=~tr/A-Z/a-z/;
 7792:        my %uidhash=&idrget($udom,$uname);
 7793:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 7794:          && (!$forceid)) {
 7795: 	  unless ($uid eq $uidhash{$uname}) {
 7796: 	      return 'error: user id "'.$uid.'" does not match '.
 7797:                   'current user id "'.$uidhash{$uname}.'".';
 7798:           }
 7799:        } else {
 7800: 	  &idput($udom,($uname => $uid));
 7801:        }
 7802:     }
 7803: # -------------------------------------------------------------- Add names, etc
 7804:     my @tmp=&get('environment',
 7805: 		   ['firstname','middlename','lastname','generation','id',
 7806:                     'permanentemail','inststatus'],
 7807: 		   $udom,$uname);
 7808:     my (%names,%oldnames);
 7809:     if ($tmp[0] =~ m/^error:.*/) { 
 7810:         %names=(); 
 7811:     } else {
 7812:         %names = @tmp;
 7813:         %oldnames = %names;
 7814:     }
 7815: #
 7816: # If name, email and/or uid are blank (e.g., because an uploaded file
 7817: # of users did not contain them), do not overwrite existing values
 7818: # unless field is in $candelete array ref.  
 7819: #
 7820: 
 7821:     my @fields = ('firstname','middlename','lastname','generation',
 7822:                   'permanentemail','id');
 7823:     my %newvalues;
 7824:     if (ref($candelete) eq 'ARRAY') {
 7825:         foreach my $field (@fields) {
 7826:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 7827:                 if ($field eq 'firstname') {
 7828:                     $names{$field} = $first;
 7829:                 } elsif ($field eq 'middlename') {
 7830:                     $names{$field} = $middle;
 7831:                 } elsif ($field eq 'lastname') {
 7832:                     $names{$field} = $last;
 7833:                 } elsif ($field eq 'generation') { 
 7834:                     $names{$field} = $gene;
 7835:                 } elsif ($field eq 'permanentemail') {
 7836:                     $names{$field} = $email;
 7837:                 } elsif ($field eq 'id') {
 7838:                     $names{$field}  = $uid;
 7839:                 }
 7840:             }
 7841:         }
 7842:     }
 7843:     if ($first)  { $names{'firstname'}  = $first; }
 7844:     if (defined($middle)) { $names{'middlename'} = $middle; }
 7845:     if ($last)   { $names{'lastname'}   = $last; }
 7846:     if (defined($gene))   { $names{'generation'} = $gene; }
 7847:     if ($email) {
 7848:        $email=~s/[^\w\@\.\-\,]//gs;
 7849:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 7850:     }
 7851:     if ($uid) { $names{'id'}  = $uid; }
 7852:     if (defined($inststatus)) {
 7853:         $names{'inststatus'} = '';
 7854:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 7855:         if (ref($usertypes) eq 'HASH') {
 7856:             my @okstatuses; 
 7857:             foreach my $item (split(/:/,$inststatus)) {
 7858:                 if (defined($usertypes->{$item})) {
 7859:                     push(@okstatuses,$item);  
 7860:                 }
 7861:             }
 7862:             if (@okstatuses) {
 7863:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 7864:             }
 7865:         }
 7866:     }
 7867:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 7868:                  $umode.', '.$first.', '.$middle.', '.
 7869:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 7870:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 7871:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 7872:     } else {
 7873:         $logmsg .= ' during self creation';
 7874:     }
 7875:     my $changed;
 7876:     if ($newuser) {
 7877:         $changed = 1;
 7878:     } else {
 7879:         foreach my $field (@fields) {
 7880:             if ($names{$field} ne $oldnames{$field}) {
 7881:                 $changed = 1;
 7882:                 last;
 7883:             }
 7884:         }
 7885:     }
 7886:     unless ($changed) {
 7887:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 7888:         &logthis($logmsg);
 7889:         return 'ok';
 7890:     }
 7891:     my $reply = &put('environment', \%names, $udom,$uname);
 7892:     if ($reply ne 'ok') { 
 7893:         return 'error: '.$reply;
 7894:     }
 7895:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
 7896:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
 7897:     }
 7898:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 7899:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 7900:     $logmsg = 'Success modifying user '.$logmsg;
 7901:     &logthis($logmsg);
 7902:     return 'ok';
 7903: }
 7904: 
 7905: # -------------------------------------------------------------- Modify student
 7906: 
 7907: sub modifystudent {
 7908:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 7909:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 7910:         $selfenroll,$context,$inststatus)=@_;
 7911:     if (!$cid) {
 7912: 	unless ($cid=$env{'request.course.id'}) {
 7913: 	    return 'not_in_class';
 7914: 	}
 7915:     }
 7916: # --------------------------------------------------------------- Make the user
 7917:     my $reply=&modifyuser
 7918: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 7919:          $desiredhome,$email,$inststatus);
 7920:     unless ($reply eq 'ok') { return $reply; }
 7921:     # This will cause &modify_student_enrollment to get the uid from the
 7922:     # students environment
 7923:     $uid = undef if (!$forceid);
 7924:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 7925: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
 7926:     return $reply;
 7927: }
 7928: 
 7929: sub modify_student_enrollment {
 7930:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
 7931:     my ($cdom,$cnum,$chome);
 7932:     if (!$cid) {
 7933: 	unless ($cid=$env{'request.course.id'}) {
 7934: 	    return 'not_in_class';
 7935: 	}
 7936: 	$cdom=$env{'course.'.$cid.'.domain'};
 7937: 	$cnum=$env{'course.'.$cid.'.num'};
 7938:     } else {
 7939: 	($cdom,$cnum)=split(/_/,$cid);
 7940:     }
 7941:     $chome=$env{'course.'.$cid.'.home'};
 7942:     if (!$chome) {
 7943: 	$chome=&homeserver($cnum,$cdom);
 7944:     }
 7945:     if (!$chome) { return 'unknown_course'; }
 7946:     # Make sure the user exists
 7947:     my $uhome=&homeserver($uname,$udom);
 7948:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 7949: 	return 'error: no such user';
 7950:     }
 7951:     # Get student data if we were not given enough information
 7952:     if (!defined($first)  || $first  eq '' || 
 7953:         !defined($last)   || $last   eq '' || 
 7954:         !defined($uid)    || $uid    eq '' || 
 7955:         !defined($middle) || $middle eq '' || 
 7956:         !defined($gene)   || $gene   eq '') {
 7957:         # They did not supply us with enough data to enroll the student, so
 7958:         # we need to pick up more information.
 7959:         my %tmp = &get('environment',
 7960:                        ['firstname','middlename','lastname', 'generation','id']
 7961:                        ,$udom,$uname);
 7962: 
 7963:         #foreach my $key (keys(%tmp)) {
 7964:         #    &logthis("key $key = ".$tmp{$key});
 7965:         #}
 7966:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 7967:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 7968:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 7969:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 7970:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 7971:     }
 7972:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 7973:     my $user = "$uname:$udom";
 7974:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
 7975:     my $reply=cput('classlist',
 7976: 		   {$user => 
 7977: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 7978: 		   $cdom,$cnum);
 7979:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
 7980:         &devalidate_getsection_cache($udom,$uname,$cid);
 7981:     } else { 
 7982: 	return 'error: '.$reply;
 7983:     }
 7984:     # Add student role to user
 7985:     my $uurl='/'.$cid;
 7986:     $uurl=~s/\_/\//g;
 7987:     if ($usec) {
 7988: 	$uurl.='/'.$usec;
 7989:     }
 7990:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
 7991:                              $selfenroll,$context);
 7992:     if ($result ne 'ok') {
 7993:         if ($old_entry{$user} ne '') {
 7994:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
 7995:         } else {
 7996:             $reply = &del('classlist',[$user],$cdom,$cnum);
 7997:         }
 7998:     }
 7999:     return $result; 
 8000: }
 8001: 
 8002: sub format_name {
 8003:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 8004:     my $name;
 8005:     if ($first ne 'lastname') {
 8006: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 8007:     } else {
 8008: 	if ($lastname=~/\S/) {
 8009: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 8010: 	    $name=~s/\s+,/,/;
 8011: 	} else {
 8012: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 8013: 	}
 8014:     }
 8015:     $name=~s/^\s+//;
 8016:     $name=~s/\s+$//;
 8017:     $name=~s/\s+/ /g;
 8018:     return $name;
 8019: }
 8020: 
 8021: # ------------------------------------------------- Write to course preferences
 8022: 
 8023: sub writecoursepref {
 8024:     my ($courseid,%prefs)=@_;
 8025:     $courseid=~s/^\///;
 8026:     $courseid=~s/\_/\//g;
 8027:     my ($cdomain,$cnum)=split(/\//,$courseid);
 8028:     my $chome=homeserver($cnum,$cdomain);
 8029:     if (($chome eq '') || ($chome eq 'no_host')) { 
 8030: 	return 'error: no such course';
 8031:     }
 8032:     my $cstring='';
 8033:     foreach my $pref (keys(%prefs)) {
 8034: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 8035:     }
 8036:     $cstring=~s/\&$//;
 8037:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 8038: }
 8039: 
 8040: # ---------------------------------------------------------- Make/modify course
 8041: 
 8042: sub createcourse {
 8043:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 8044:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 8045:     $url=&declutter($url);
 8046:     my $cid='';
 8047:     if ($context eq 'requestcourses') {
 8048:         my $can_create = 0;
 8049:         my ($ownername,$ownerdom) = split(':',$course_owner);
 8050:         if ($udom eq $ownerdom) {
 8051:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 8052:                                   $context)) {
 8053:                 $can_create = 1;
 8054:             }
 8055:         } else {
 8056:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 8057:                                            $category);
 8058:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 8059:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 8060:                 if (@curr > 0) {
 8061:                     my @options = qw(approval validate autolimit);
 8062:                     my $optregex = join('|',@options);
 8063:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 8064:                         $can_create = 1;
 8065:                     }
 8066:                 }
 8067:             }
 8068:         }
 8069:         if ($can_create) {
 8070:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 8071:                 unless (&allowed('ccc',$udom)) {
 8072:                     return 'refused'; 
 8073:                 }
 8074:             }
 8075:         } else {
 8076:             return 'refused';
 8077:         }
 8078:     } elsif (!&allowed('ccc',$udom)) {
 8079:         return 'refused';
 8080:     }
 8081: # --------------------------------------------------------------- Get Unique ID
 8082:     my $uname;
 8083:     if ($cnum =~ /^$match_courseid$/) {
 8084:         my $chome=&homeserver($cnum,$udom,'true');
 8085:         if (($chome eq '') || ($chome eq 'no_host')) {
 8086:             $uname = $cnum;
 8087:         } else {
 8088:             $uname = &generate_coursenum($udom,$crstype);
 8089:         }
 8090:     } else {
 8091:         $uname = &generate_coursenum($udom,$crstype);
 8092:     }
 8093:     return $uname if ($uname =~ /^error/);
 8094: # -------------------------------------------------- Check supplied server name
 8095:     if (!defined($course_server)) {
 8096:         if (defined(&domain($udom,'primary'))) {
 8097:             $course_server = &domain($udom,'primary');
 8098:         } else {
 8099:             $course_server = $env{'user.home'}; 
 8100:         }
 8101:     }
 8102:     my %host_servers =
 8103:         &Apache::lonnet::get_servers($udom,'library');
 8104:     unless ($host_servers{$course_server}) {
 8105:         return 'error: invalid home server for course: '.$course_server;
 8106:     }
 8107: # ------------------------------------------------------------- Make the course
 8108:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 8109:                       $course_server);
 8110:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 8111:     my $uhome=&homeserver($uname,$udom,'true');
 8112:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 8113: 	return 'error: no such course';
 8114:     }
 8115: # ----------------------------------------------------------------- Course made
 8116: # log existence
 8117:     my $now = time;
 8118:     my $newcourse = {
 8119:                     $udom.'_'.$uname => {
 8120:                                      description => $description,
 8121:                                      inst_code   => $inst_code,
 8122:                                      owner       => $course_owner,
 8123:                                      type        => $crstype,
 8124:                                      creator     => $env{'user.name'}.':'.
 8125:                                                     $env{'user.domain'},
 8126:                                      created     => $now,
 8127:                                      context     => $context,
 8128:                                                 },
 8129:                     };
 8130:     &courseidput($udom,$newcourse,$uhome,'notime');
 8131: # set toplevel url
 8132:     my $topurl=$url;
 8133:     unless ($nonstandard) {
 8134: # ------------------------------------------ For standard courses, make top url
 8135:         my $mapurl=&clutter($url);
 8136:         if ($mapurl eq '/res/') { $mapurl=''; }
 8137:         $env{'form.initmap'}=(<<ENDINITMAP);
 8138: <map>
 8139: <resource id="1" type="start"></resource>
 8140: <resource id="2" src="$mapurl"></resource>
 8141: <resource id="3" type="finish"></resource>
 8142: <link index="1" from="1" to="2"></link>
 8143: <link index="2" from="2" to="3"></link>
 8144: </map>
 8145: ENDINITMAP
 8146:         $topurl=&declutter(
 8147:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 8148:                           );
 8149:     }
 8150: # ----------------------------------------------------------- Write preferences
 8151:     &writecoursepref($udom.'_'.$uname,
 8152:                      ('description'              => $description,
 8153:                       'url'                      => $topurl,
 8154:                       'internal.creator'         => $env{'user.name'}.':'.
 8155:                                                     $env{'user.domain'},
 8156:                       'internal.created'         => $now,
 8157:                       'internal.creationcontext' => $context)
 8158:                     );
 8159:     return '/'.$udom.'/'.$uname;
 8160: }
 8161: 
 8162: # ------------------------------------------------------------------- Create ID
 8163: sub generate_coursenum {
 8164:     my ($udom,$crstype) = @_;
 8165:     my $domdesc = &domain($udom);
 8166:     return 'error: invalid domain' if ($domdesc eq '');
 8167:     my $first;
 8168:     if ($crstype eq 'Community') {
 8169:         $first = '0';
 8170:     } else {
 8171:         $first = int(1+rand(9)); 
 8172:     } 
 8173:     my $uname=$first.
 8174:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8175:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8176:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8177: # ----------------------------------------------- Make sure that does not exist
 8178:     my $uhome=&homeserver($uname,$udom,'true');
 8179:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8180:         if ($crstype eq 'Community') {
 8181:             $first = '0';
 8182:         } else {
 8183:             $first = int(1+rand(9));
 8184:         }
 8185:         $uname=$first.
 8186:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 8187:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
 8188:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 8189:         $uhome=&homeserver($uname,$udom,'true');
 8190:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
 8191:             return 'error: unable to generate unique course-ID';
 8192:         }
 8193:     }
 8194:     return $uname;
 8195: }
 8196: 
 8197: sub is_course {
 8198:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
 8199:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
 8200: 
 8201:     return unless $cdom and $cnum;
 8202: 
 8203:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
 8204:         '.');
 8205: 
 8206:     return unless exists($courses{$cdom.'_'.$cnum});
 8207:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
 8208: }
 8209: 
 8210: sub store_userdata {
 8211:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
 8212:     my $result;
 8213:     if ($datakey ne '') {
 8214:         if (ref($storehash) eq 'HASH') {
 8215:             if ($udom eq '' || $uname eq '') {
 8216:                 $udom = $env{'user.domain'};
 8217:                 $uname = $env{'user.name'};
 8218:             }
 8219:             my $uhome=&homeserver($uname,$udom);
 8220:             if (($uhome eq '') || ($uhome eq 'no_host')) {
 8221:                 $result = 'error: no_host';
 8222:             } else {
 8223:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
 8224:                 $storehash->{'host'} = $perlvar{'lonHostID'};
 8225: 
 8226:                 my $namevalue='';
 8227:                 foreach my $key (keys(%{$storehash})) {
 8228:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 8229:                 }
 8230:                 $namevalue=~s/\&$//;
 8231:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
 8232:                                   $namevalue,$uhome);
 8233:             }
 8234:         } else {
 8235:             $result = 'error: data to store was not a hash reference'; 
 8236:         }
 8237:     } else {
 8238:         $result= 'error: invalid requestkey'; 
 8239:     }
 8240:     return $result;
 8241: }
 8242: 
 8243: # ---------------------------------------------------------- Assign Custom Role
 8244: 
 8245: sub assigncustomrole {
 8246:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 8247:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 8248:                        $end,$start,$deleteflag,$selfenroll,$context);
 8249: }
 8250: 
 8251: # ----------------------------------------------------------------- Revoke Role
 8252: 
 8253: sub revokerole {
 8254:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 8255:     my $now=time;
 8256:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 8257: }
 8258: 
 8259: # ---------------------------------------------------------- Revoke Custom Role
 8260: 
 8261: sub revokecustomrole {
 8262:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 8263:     my $now=time;
 8264:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 8265:            $deleteflag,$selfenroll,$context);
 8266: }
 8267: 
 8268: # ------------------------------------------------------------ Disk usage
 8269: sub diskusage {
 8270:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 8271:     $directorypath =~ s/\/$//;
 8272:     my $listing=&reply('du2:'.&escape($directorypath).':'
 8273:                        .&escape($getpropath).':'.&escape($uname).':'
 8274:                        .&escape($udom),homeserver($uname,$udom));
 8275:     if ($listing eq 'unknown_cmd') {
 8276:         if ($getpropath) {
 8277:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 8278:         }
 8279:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 8280:     }
 8281:     return $listing;
 8282: }
 8283: 
 8284: sub is_locked {
 8285:     my ($file_name, $domain, $user, $which) = @_;
 8286:     my @check;
 8287:     my $is_locked;
 8288:     push (@check,$file_name);
 8289:     my %locked = &get('file_permissions',\@check,
 8290: 		      $env{'user.domain'},$env{'user.name'});
 8291:     my ($tmp)=keys(%locked);
 8292:     if ($tmp=~/^error:/) { undef(%locked); }
 8293:     
 8294:     if (ref($locked{$file_name}) eq 'ARRAY') {
 8295:         $is_locked = 'false';
 8296:         foreach my $entry (@{$locked{$file_name}}) {
 8297:            if (ref($entry) eq 'ARRAY') {
 8298:                $is_locked = 'true';
 8299:                if (ref($which) eq 'ARRAY') {
 8300:                    push(@{$which},$entry);
 8301:                } else {
 8302:                    last;
 8303:                }
 8304:            }
 8305:        }
 8306:     } else {
 8307:         $is_locked = 'false';
 8308:     }
 8309:     return $is_locked;
 8310: }
 8311: 
 8312: sub declutter_portfile {
 8313:     my ($file) = @_;
 8314:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 8315:     return $file;
 8316: }
 8317: 
 8318: # ------------------------------------------------------------- Mark as Read Only
 8319: 
 8320: sub mark_as_readonly {
 8321:     my ($domain,$user,$files,$what) = @_;
 8322:     my %current_permissions = &dump('file_permissions',$domain,$user);
 8323:     my ($tmp)=keys(%current_permissions);
 8324:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8325:     foreach my $file (@{$files}) {
 8326: 	$file = &declutter_portfile($file);
 8327:         push(@{$current_permissions{$file}},$what);
 8328:     }
 8329:     &put('file_permissions',\%current_permissions,$domain,$user);
 8330:     return;
 8331: }
 8332: 
 8333: # ------------------------------------------------------------Save Selected Files
 8334: 
 8335: sub save_selected_files {
 8336:     my ($user, $path, @files) = @_;
 8337:     my $filename = $user."savedfiles";
 8338:     my @other_files = &files_not_in_path($user, $path);
 8339:     open (OUT, '>'.$tmpdir.$filename);
 8340:     foreach my $file (@files) {
 8341:         print (OUT $env{'form.currentpath'}.$file."\n");
 8342:     }
 8343:     foreach my $file (@other_files) {
 8344:         print (OUT $file."\n");
 8345:     }
 8346:     close (OUT);
 8347:     return 'ok';
 8348: }
 8349: 
 8350: sub clear_selected_files {
 8351:     my ($user) = @_;
 8352:     my $filename = $user."savedfiles";
 8353:     open (OUT, '>'.LONCAPA::tempdir().$filename);
 8354:     print (OUT undef);
 8355:     close (OUT);
 8356:     return ("ok");    
 8357: }
 8358: 
 8359: sub files_in_path {
 8360:     my ($user, $path) = @_;
 8361:     my $filename = $user."savedfiles";
 8362:     my %return_files;
 8363:     open (IN, '<'.LONCAPA::tempdir().$filename);
 8364:     while (my $line_in = <IN>) {
 8365:         chomp ($line_in);
 8366:         my @paths_and_file = split (m!/!, $line_in);
 8367:         my $file_part = pop (@paths_and_file);
 8368:         my $path_part = join ('/', @paths_and_file);
 8369:         $path_part.='/';
 8370:         my $path_and_file = $path_part.$file_part;
 8371:         if ($path_part eq $path) {
 8372:             $return_files{$file_part}= 'selected';
 8373:         }
 8374:     }
 8375:     close (IN);
 8376:     return (\%return_files);
 8377: }
 8378: 
 8379: # called in portfolio select mode, to show files selected NOT in current directory
 8380: sub files_not_in_path {
 8381:     my ($user, $path) = @_;
 8382:     my $filename = $user."savedfiles";
 8383:     my @return_files;
 8384:     my $path_part;
 8385:     open(IN, '<'.LONCAPA::.$filename);
 8386:     while (my $line = <IN>) {
 8387:         #ok, I know it's clunky, but I want it to work
 8388:         my @paths_and_file = split(m|/|, $line);
 8389:         my $file_part = pop(@paths_and_file);
 8390:         chomp($file_part);
 8391:         my $path_part = join('/', @paths_and_file);
 8392:         $path_part .= '/';
 8393:         my $path_and_file = $path_part.$file_part;
 8394:         if ($path_part ne $path) {
 8395:             push(@return_files, ($path_and_file));
 8396:         }
 8397:     }
 8398:     close(OUT);
 8399:     return (@return_files);
 8400: }
 8401: 
 8402: #----------------------------------------------Get portfolio file permissions
 8403: 
 8404: sub get_portfile_permissions {
 8405:     my ($domain,$user) = @_;
 8406:     my %current_permissions = &dump('file_permissions',$domain,$user);
 8407:     my ($tmp)=keys(%current_permissions);
 8408:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8409:     return \%current_permissions;
 8410: }
 8411: 
 8412: #---------------------------------------------Get portfolio file access controls
 8413: 
 8414: sub get_access_controls {
 8415:     my ($current_permissions,$group,$file) = @_;
 8416:     my %access;
 8417:     my $real_file = $file;
 8418:     $file =~ s/\.meta$//;
 8419:     if (defined($file)) {
 8420:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 8421:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 8422:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 8423:             }
 8424:         }
 8425:     } else {
 8426:         foreach my $key (keys(%{$current_permissions})) {
 8427:             if ($key =~ /\0accesscontrol$/) {
 8428:                 if (defined($group)) {
 8429:                     if ($key !~ m-^\Q$group\E/-) {
 8430:                         next;
 8431:                     }
 8432:                 }
 8433:                 my ($fullpath) = split(/\0/,$key);
 8434:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 8435:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 8436:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 8437:                     }
 8438:                 }
 8439:             }
 8440:         }
 8441:     }
 8442:     return %access;
 8443: }
 8444: 
 8445: sub modify_access_controls {
 8446:     my ($file_name,$changes,$domain,$user)=@_;
 8447:     my ($outcome,$deloutcome);
 8448:     my %store_permissions;
 8449:     my %new_values;
 8450:     my %new_control;
 8451:     my %translation;
 8452:     my @deletions = ();
 8453:     my $now = time;
 8454:     if (exists($$changes{'activate'})) {
 8455:         if (ref($$changes{'activate'}) eq 'HASH') {
 8456:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 8457:             my $numnew = scalar(@newitems);
 8458:             for (my $i=0; $i<$numnew; $i++) {
 8459:                 my $newkey = $newitems[$i];
 8460:                 my $newid = &Apache::loncommon::get_cgi_id();
 8461:                 if ($newkey =~ /^\d+:/) { 
 8462:                     $newkey =~ s/^(\d+)/$newid/;
 8463:                     $translation{$1} = $newid;
 8464:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 8465:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 8466:                     $translation{$1} = $newid;
 8467:                 }
 8468:                 $new_values{$file_name."\0".$newkey} = 
 8469:                                           $$changes{'activate'}{$newitems[$i]};
 8470:                 $new_control{$newkey} = $now;
 8471:             }
 8472:         }
 8473:     }
 8474:     my %todelete;
 8475:     my %changed_items;
 8476:     foreach my $action ('delete','update') {
 8477:         if (exists($$changes{$action})) {
 8478:             if (ref($$changes{$action}) eq 'HASH') {
 8479:                 foreach my $key (keys(%{$$changes{$action}})) {
 8480:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 8481:                     if ($action eq 'delete') { 
 8482:                         $todelete{$itemnum} = 1;
 8483:                     } else {
 8484:                         $changed_items{$itemnum} = $key;
 8485:                     }
 8486:                 }
 8487:             }
 8488:         }
 8489:     }
 8490:     # get lock on access controls for file.
 8491:     my $lockhash = {
 8492:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 8493:                                                        ':'.$env{'user.domain'},
 8494:                    }; 
 8495:     my $tries = 0;
 8496:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 8497:    
 8498:     while (($gotlock ne 'ok') && $tries <3) {
 8499:         $tries ++;
 8500:         sleep 1;
 8501:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 8502:     }
 8503:     if ($gotlock eq 'ok') {
 8504:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 8505:         my ($tmp)=keys(%curr_permissions);
 8506:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 8507:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 8508:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 8509:             if (ref($curr_controls) eq 'HASH') {
 8510:                 foreach my $control_item (keys(%{$curr_controls})) {
 8511:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 8512:                     if (defined($todelete{$itemnum})) {
 8513:                         push(@deletions,$file_name."\0".$control_item);
 8514:                     } else {
 8515:                         if (defined($changed_items{$itemnum})) {
 8516:                             $new_control{$changed_items{$itemnum}} = $now;
 8517:                             push(@deletions,$file_name."\0".$control_item);
 8518:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 8519:                         } else {
 8520:                             $new_control{$control_item} = $$curr_controls{$control_item};
 8521:                         }
 8522:                     }
 8523:                 }
 8524:             }
 8525:         }
 8526:         my ($group);
 8527:         if (&is_course($domain,$user)) {
 8528:             ($group,my $file) = split(/\//,$file_name,2);
 8529:         }
 8530:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 8531:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 8532:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 8533:         #  remove lock
 8534:         my @del_lock = ($file_name."\0".'locked_access_records');
 8535:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 8536:         my $sqlresult =
 8537:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 8538:                                     $group);
 8539:     } else {
 8540:         $outcome = "error: could not obtain lockfile\n";  
 8541:     }
 8542:     return ($outcome,$deloutcome,\%new_values,\%translation);
 8543: }
 8544: 
 8545: sub make_public_indefinitely {
 8546:     my ($requrl) = @_;
 8547:     my $now = time;
 8548:     my $action = 'activate';
 8549:     my $aclnum = 0;
 8550:     if (&is_portfolio_url($requrl)) {
 8551:         my (undef,$udom,$unum,$file_name,$group) =
 8552:             &parse_portfolio_url($requrl);
 8553:         my $current_perms = &get_portfile_permissions($udom,$unum);
 8554:         my %access_controls = &get_access_controls($current_perms,
 8555:                                                    $group,$file_name);
 8556:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 8557:             my ($num,$scope,$end,$start) = 
 8558:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 8559:             if ($scope eq 'public') {
 8560:                 if ($start <= $now && $end == 0) {
 8561:                     $action = 'none';
 8562:                 } else {
 8563:                     $action = 'update';
 8564:                     $aclnum = $num;
 8565:                 }
 8566:                 last;
 8567:             }
 8568:         }
 8569:         if ($action eq 'none') {
 8570:              return 'ok';
 8571:         } else {
 8572:             my %changes;
 8573:             my $newend = 0;
 8574:             my $newstart = $now;
 8575:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 8576:             $changes{$action}{$newkey} = {
 8577:                 type => 'public',
 8578:                 time => {
 8579:                     start => $newstart,
 8580:                     end   => $newend,
 8581:                 },
 8582:             };
 8583:             my ($outcome,$deloutcome,$new_values,$translation) =
 8584:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 8585:             return $outcome;
 8586:         }
 8587:     } else {
 8588:         return 'invalid';
 8589:     }
 8590: }
 8591: 
 8592: #------------------------------------------------------Get Marked as Read Only
 8593: 
 8594: sub get_marked_as_readonly {
 8595:     my ($domain,$user,$what,$group) = @_;
 8596:     my $current_permissions = &get_portfile_permissions($domain,$user);
 8597:     my @readonly_files;
 8598:     my $cmp1=$what;
 8599:     if (ref($what)) { $cmp1=join('',@{$what}) };
 8600:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 8601:         if (defined($group)) {
 8602:             if ($file_name !~ m-^\Q$group\E/-) {
 8603:                 next;
 8604:             }
 8605:         }
 8606:         if (ref($value) eq "ARRAY"){
 8607:             foreach my $stored_what (@{$value}) {
 8608:                 my $cmp2=$stored_what;
 8609:                 if (ref($stored_what) eq 'ARRAY') {
 8610:                     $cmp2=join('',@{$stored_what});
 8611:                 }
 8612:                 if ($cmp1 eq $cmp2) {
 8613:                     push(@readonly_files, $file_name);
 8614:                     last;
 8615:                 } elsif (!defined($what)) {
 8616:                     push(@readonly_files, $file_name);
 8617:                     last;
 8618:                 }
 8619:             }
 8620:         }
 8621:     }
 8622:     return @readonly_files;
 8623: }
 8624: #-----------------------------------------------------------Get Marked as Read Only Hash
 8625: 
 8626: sub get_marked_as_readonly_hash {
 8627:     my ($current_permissions,$group,$what) = @_;
 8628:     my %readonly_files;
 8629:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 8630:         if (defined($group)) {
 8631:             if ($file_name !~ m-^\Q$group\E/-) {
 8632:                 next;
 8633:             }
 8634:         }
 8635:         if (ref($value) eq "ARRAY"){
 8636:             foreach my $stored_what (@{$value}) {
 8637:                 if (ref($stored_what) eq 'ARRAY') {
 8638:                     foreach my $lock_descriptor(@{$stored_what}) {
 8639:                         if ($lock_descriptor eq 'graded') {
 8640:                             $readonly_files{$file_name} = 'graded';
 8641:                         } elsif ($lock_descriptor eq 'handback') {
 8642:                             $readonly_files{$file_name} = 'handback';
 8643:                         } else {
 8644:                             if (!exists($readonly_files{$file_name})) {
 8645:                                 $readonly_files{$file_name} = 'locked';
 8646:                             }
 8647:                         }
 8648:                     }
 8649:                 } 
 8650:             }
 8651:         } 
 8652:     }
 8653:     return %readonly_files;
 8654: }
 8655: # ------------------------------------------------------------ Unmark as Read Only
 8656: 
 8657: sub unmark_as_readonly {
 8658:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 8659:     # for portfolio submissions, $what contains [$symb,$crsid] 
 8660:     my ($domain,$user,$what,$file_name,$group) = @_;
 8661:     $file_name = &declutter_portfile($file_name);
 8662:     my $symb_crs = $what;
 8663:     if (ref($what)) { $symb_crs=join('',@$what); }
 8664:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 8665:     my ($tmp)=keys(%current_permissions);
 8666:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 8667:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 8668:     foreach my $file (@readonly_files) {
 8669: 	my $clean_file = &declutter_portfile($file);
 8670: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 8671: 	my $current_locks = $current_permissions{$file};
 8672:         my @new_locks;
 8673:         my @del_keys;
 8674:         if (ref($current_locks) eq "ARRAY"){
 8675:             foreach my $locker (@{$current_locks}) {
 8676:                 my $compare=$locker;
 8677:                 if (ref($locker) eq 'ARRAY') {
 8678:                     $compare=join('',@{$locker});
 8679:                     if ($compare ne $symb_crs) {
 8680:                         push(@new_locks, $locker);
 8681:                     }
 8682:                 }
 8683:             }
 8684:             if (scalar(@new_locks) > 0) {
 8685:                 $current_permissions{$file} = \@new_locks;
 8686:             } else {
 8687:                 push(@del_keys, $file);
 8688:                 &del('file_permissions',\@del_keys, $domain, $user);
 8689:                 delete($current_permissions{$file});
 8690:             }
 8691:         }
 8692:     }
 8693:     &put('file_permissions',\%current_permissions,$domain,$user);
 8694:     return;
 8695: }
 8696: 
 8697: # ------------------------------------------------------------ Directory lister
 8698: 
 8699: sub dirlist {
 8700:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 8701:     $uri=~s/^\///;
 8702:     $uri=~s/\/$//;
 8703:     my ($udom, $uname);
 8704:     if ($getuserdir) {
 8705:         $udom = $userdomain;
 8706:         $uname = $username;
 8707:     } else {
 8708:         (undef,$udom,$uname)=split(/\//,$uri);
 8709:         if(defined($userdomain)) {
 8710:             $udom = $userdomain;
 8711:         }
 8712:         if(defined($username)) {
 8713:             $uname = $username;
 8714:         }
 8715:     }
 8716:     my ($dirRoot,$listing,@listing_results);
 8717: 
 8718:     $dirRoot = $perlvar{'lonDocRoot'};
 8719:     if (defined($getpropath)) {
 8720:         $dirRoot = &propath($udom,$uname);
 8721:         $dirRoot =~ s/\/$//;
 8722:     } elsif (defined($getuserdir)) {
 8723:         my $subdir=$uname.'__';
 8724:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 8725:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 8726:                    ."/$udom/$subdir/$uname";
 8727:     } elsif (defined($alternateRoot)) {
 8728:         $dirRoot = $alternateRoot;
 8729:     }
 8730: 
 8731:     if($udom) {
 8732:         if($uname) {
 8733:             my $uhome = &homeserver($uname,$udom);
 8734:             if ($uhome eq 'no_host') {
 8735:                 return ([],'no_host');
 8736:             }
 8737:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 8738:                               .$getuserdir.':'.&escape($dirRoot)
 8739:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
 8740:             if ($listing eq 'unknown_cmd') {
 8741:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
 8742:             } else {
 8743:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 8744:             }
 8745:             if ($listing eq 'unknown_cmd') {
 8746:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
 8747:                 @listing_results = split(/:/,$listing);
 8748:             } else {
 8749:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 8750:             }
 8751:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
 8752:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
 8753:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 8754:                 return ([],$listing);
 8755:             } else {
 8756:                 return (\@listing_results);
 8757:             }
 8758:         } elsif(!$alternateRoot) {
 8759:             my (%allusers,%listerror);
 8760: 	    my %servers = &get_servers($udom,'library');
 8761:  	    foreach my $tryserver (keys(%servers)) {
 8762:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 8763:                                   &escape($udom),$tryserver);
 8764:                 if ($listing eq 'unknown_cmd') {
 8765: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 8766: 				      $udom, $tryserver);
 8767:                 } else {
 8768:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 8769:                 }
 8770: 		if ($listing eq 'unknown_cmd') {
 8771: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 8772: 				      $udom, $tryserver);
 8773: 		    @listing_results = split(/:/,$listing);
 8774: 		} else {
 8775: 		    @listing_results =
 8776: 			map { &unescape($_); } split(/:/,$listing);
 8777: 		}
 8778:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
 8779:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
 8780:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
 8781:                     $listerror{$tryserver} = $listing;
 8782:                 } else {
 8783: 		    foreach my $line (@listing_results) {
 8784: 			my ($entry) = split(/&/,$line,2);
 8785: 			$allusers{$entry} = 1;
 8786: 		    }
 8787: 		}
 8788:             }
 8789:             my @alluserslist=();
 8790:             foreach my $user (sort(keys(%allusers))) {
 8791:                 push(@alluserslist,$user.'&user');
 8792:             }
 8793:             return (\@alluserslist);
 8794:         } else {
 8795:             return ([],'missing username');
 8796:         }
 8797:     } elsif(!defined($getpropath)) {
 8798:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
 8799:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
 8800:         return (\@all_domains);
 8801:     } else {
 8802:         return ([],'missing domain');
 8803:     }
 8804: }
 8805: 
 8806: # --------------------------------------------- GetFileTimestamp
 8807: # This function utilizes dirlist and returns the date stamp for
 8808: # when it was last modified.  It will also return an error of -1
 8809: # if an error occurs
 8810: 
 8811: sub GetFileTimestamp {
 8812:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 8813:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 8814:     $studentName   = &LONCAPA::clean_username($studentName);
 8815:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
 8816:                                     undef,$getuserdir);
 8817:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 8818:         return -1;
 8819:     }
 8820:     if (ref($fileref) eq 'ARRAY') {
 8821:         my @stats = split('&',$fileref->[0]);
 8822:         # @stats contains first the filename, then the stat output
 8823:         return $stats[10]; # so this is 10 instead of 9.
 8824:     } else {
 8825:         return -1;
 8826:     }
 8827: }
 8828: 
 8829: sub stat_file {
 8830:     my ($uri) = @_;
 8831:     $uri = &clutter_with_no_wrapper($uri);
 8832: 
 8833:     my ($udom,$uname,$file);
 8834:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 8835: 	($udom,$uname,$file) =
 8836: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 8837: 	$file = 'userfiles/'.$file;
 8838:     }
 8839:     if ($uri =~ m-^/res/-) {
 8840: 	($udom,$uname) = 
 8841: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 8842: 	$file = $uri;
 8843:     }
 8844: 
 8845:     if (!$udom || !$uname || !$file) {
 8846: 	# unable to handle the uri
 8847: 	return ();
 8848:     }
 8849:     my $getpropath;
 8850:     if ($file =~ /^userfiles\//) {
 8851:         $getpropath = 1;
 8852:     }
 8853:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
 8854:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
 8855:         return ();
 8856:     } else {
 8857:         if (ref($listref) eq 'ARRAY') {
 8858:             my @stats = split('&',$listref->[0]);
 8859: 	    shift(@stats); #filename is first
 8860: 	    return @stats;
 8861:         }
 8862:     }
 8863:     return ();
 8864: }
 8865: 
 8866: # -------------------------------------------------------- Value of a Condition
 8867: 
 8868: # gets the value of a specific preevaluated condition
 8869: #    stored in the string  $env{user.state.<cid>}
 8870: # or looks up a condition reference in the bighash and if if hasn't
 8871: # already been evaluated recurses into docondval to get the value of
 8872: # the condition, then memoizing it to 
 8873: #   $env{user.state.<cid>.<condition>}
 8874: sub directcondval {
 8875:     my $number=shift;
 8876:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 8877: 	&Apache::lonuserstate::evalstate();
 8878:     }
 8879:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 8880: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 8881:     } elsif ($number =~ /^_/) {
 8882: 	my $sub_condition;
 8883: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8884: 		&GDBM_READER(),0640)) {
 8885: 	    $sub_condition=$bighash{'conditions'.$number};
 8886: 	    untie(%bighash);
 8887: 	}
 8888: 	my $value = &docondval($sub_condition);
 8889: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 8890: 	return $value;
 8891:     }
 8892:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 8893:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 8894:     } else {
 8895:        return 2;
 8896:     }
 8897: }
 8898: 
 8899: # get the collection of conditions for this resource
 8900: sub condval {
 8901:     my $condidx=shift;
 8902:     my $allpathcond='';
 8903:     foreach my $cond (split(/\|/,$condidx)) {
 8904: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 8905: 	    $allpathcond.=
 8906: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 8907: 	}
 8908:     }
 8909:     $allpathcond=~s/\|$//;
 8910:     return &docondval($allpathcond);
 8911: }
 8912: 
 8913: #evaluates an expression of conditions
 8914: sub docondval {
 8915:     my ($allpathcond) = @_;
 8916:     my $result=0;
 8917:     if ($env{'request.course.id'}
 8918: 	&& defined($allpathcond)) {
 8919: 	my $operand='|';
 8920: 	my @stack;
 8921: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 8922: 	    if ($chunk eq '(') {
 8923: 		push @stack,($operand,$result);
 8924: 	    } elsif ($chunk eq ')') {
 8925: 		my $before=pop @stack;
 8926: 		if (pop @stack eq '&') {
 8927: 		    $result=$result>$before?$before:$result;
 8928: 		} else {
 8929: 		    $result=$result>$before?$result:$before;
 8930: 		}
 8931: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 8932: 		$operand=$chunk;
 8933: 	    } else {
 8934: 		my $new=directcondval($chunk);
 8935: 		if ($operand eq '&') {
 8936: 		    $result=$result>$new?$new:$result;
 8937: 		} else {
 8938: 		    $result=$result>$new?$result:$new;
 8939: 		}
 8940: 	    }
 8941: 	}
 8942:     }
 8943:     return $result;
 8944: }
 8945: 
 8946: # ---------------------------------------------------- Devalidate courseresdata
 8947: 
 8948: sub devalidatecourseresdata {
 8949:     my ($coursenum,$coursedomain)=@_;
 8950:     my $hashid=$coursenum.':'.$coursedomain;
 8951:     &devalidate_cache_new('courseres',$hashid);
 8952: }
 8953: 
 8954: 
 8955: # --------------------------------------------------- Course Resourcedata Query
 8956: #
 8957: #  Parameters:
 8958: #      $coursenum    - Number of the course.
 8959: #      $coursedomain - Domain at which the course was created.
 8960: #  Returns:
 8961: #     A hash of the course parameters along (I think) with timestamps
 8962: #     and version info.
 8963: 
 8964: sub get_courseresdata {
 8965:     my ($coursenum,$coursedomain)=@_;
 8966:     my $coursehom=&homeserver($coursenum,$coursedomain);
 8967:     my $hashid=$coursenum.':'.$coursedomain;
 8968:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 8969:     my %dumpreply;
 8970:     unless (defined($cached)) {
 8971: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 8972: 	$result=\%dumpreply;
 8973: 	my ($tmp) = keys(%dumpreply);
 8974: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 8975: 	    &do_cache_new('courseres',$hashid,$result,600);
 8976: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 8977: 	    return $tmp;
 8978: 	} elsif ($tmp =~ /^(error)/) {
 8979: 	    $result=undef;
 8980: 	    &do_cache_new('courseres',$hashid,$result,600);
 8981: 	}
 8982:     }
 8983:     return $result;
 8984: }
 8985: 
 8986: sub devalidateuserresdata {
 8987:     my ($uname,$udom)=@_;
 8988:     my $hashid="$udom:$uname";
 8989:     &devalidate_cache_new('userres',$hashid);
 8990: }
 8991: 
 8992: sub get_userresdata {
 8993:     my ($uname,$udom)=@_;
 8994:     #most student don\'t have any data set, check if there is some data
 8995:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 8996: 
 8997:     my $hashid="$udom:$uname";
 8998:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 8999:     if (!defined($cached)) {
 9000: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 9001: 	$result=\%resourcedata;
 9002: 	&do_cache_new('userres',$hashid,$result,600);
 9003:     }
 9004:     my ($tmp)=keys(%$result);
 9005:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 9006: 	return $result;
 9007:     }
 9008:     #error 2 occurs when the .db doesn't exist
 9009:     if ($tmp!~/error: 2 /) {
 9010: 	&logthis("<font color=\"blue\">WARNING:".
 9011: 		 " Trying to get resource data for ".
 9012: 		 $uname." at ".$udom.": ".
 9013: 		 $tmp."</font>");
 9014:     } elsif ($tmp=~/error: 2 /) {
 9015: 	#&EXT_cache_set($udom,$uname);
 9016: 	&do_cache_new('userres',$hashid,undef,600);
 9017: 	undef($tmp); # not really an error so don't send it back
 9018:     }
 9019:     return $tmp;
 9020: }
 9021: #----------------------------------------------- resdata - return resource data
 9022: #  Purpose:
 9023: #    Return resource data for either users or for a course.
 9024: #  Parameters:
 9025: #     $name      - Course/user name.
 9026: #     $domain    - Name of the domain the user/course is registered on.
 9027: #     $type      - Type of thing $name is (must be 'course' or 'user'
 9028: #     @which     - Array of names of resources desired.
 9029: #  Returns:
 9030: #     The value of the first reasource in @which that is found in the
 9031: #     resource hash.
 9032: #  Exceptional Conditions:
 9033: #     If the $type passed in is not valid (not the string 'course' or 
 9034: #     'user', an undefined  reference is returned.
 9035: #     If none of the resources are found, an undef is returned
 9036: sub resdata {
 9037:     my ($name,$domain,$type,@which)=@_;
 9038:     my $result;
 9039:     if ($type eq 'course') {
 9040: 	$result=&get_courseresdata($name,$domain);
 9041:     } elsif ($type eq 'user') {
 9042: 	$result=&get_userresdata($name,$domain);
 9043:     }
 9044:     if (!ref($result)) { return $result; }    
 9045:     foreach my $item (@which) {
 9046: 	if (defined($result->{$item->[0]})) {
 9047: 	    return [$result->{$item->[0]},$item->[1]];
 9048: 	}
 9049:     }
 9050:     return undef;
 9051: }
 9052: 
 9053: #
 9054: # EXT resource caching routines
 9055: #
 9056: 
 9057: sub clear_EXT_cache_status {
 9058:     &delenv('cache.EXT.');
 9059: }
 9060: 
 9061: sub EXT_cache_status {
 9062:     my ($target_domain,$target_user) = @_;
 9063:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 9064:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 9065:         # We know already the user has no data
 9066:         return 1;
 9067:     } else {
 9068:         return 0;
 9069:     }
 9070: }
 9071: 
 9072: sub EXT_cache_set {
 9073:     my ($target_domain,$target_user) = @_;
 9074:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 9075:     #&appenv({$cachename => time});
 9076: }
 9077: 
 9078: # --------------------------------------------------------- Value of a Variable
 9079: sub EXT {
 9080: 
 9081:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 9082:     unless ($varname) { return ''; }
 9083:     #get real user name/domain, courseid and symb
 9084:     my $courseid;
 9085:     my $publicuser;
 9086:     if ($symbparm) {
 9087: 	$symbparm=&get_symb_from_alias($symbparm);
 9088:     }
 9089:     if (!($uname && $udom)) {
 9090:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 9091:       if (!$symbparm) {	$symbparm=$cursymb; }
 9092:     } else {
 9093: 	$courseid=$env{'request.course.id'};
 9094:     }
 9095:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 9096:     my $rest;
 9097:     if (defined($therest[0])) {
 9098:        $rest=join('.',@therest);
 9099:     } else {
 9100:        $rest='';
 9101:     }
 9102: 
 9103:     my $qualifierrest=$qualifier;
 9104:     if ($rest) { $qualifierrest.='.'.$rest; }
 9105:     my $spacequalifierrest=$space;
 9106:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 9107:     if ($realm eq 'user') {
 9108: # --------------------------------------------------------------- user.resource
 9109: 	if ($space eq 'resource') {
 9110: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 9111: 		  || defined($Apache::lonhomework::parsing_a_task))
 9112: 		 &&
 9113: 		 ($symbparm eq &symbread()) ) {	
 9114: 		# if we are in the middle of processing the resource the
 9115: 		# get the value we are planning on committing
 9116:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 9117:                     return $Apache::lonhomework::results{$qualifierrest};
 9118:                 } else {
 9119:                     return $Apache::lonhomework::history{$qualifierrest};
 9120:                 }
 9121: 	    } else {
 9122: 		my %restored;
 9123: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 9124: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 9125: 		} else {
 9126: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 9127: 		}
 9128: 		return $restored{$qualifierrest};
 9129: 	    }
 9130: # ----------------------------------------------------------------- user.access
 9131:         } elsif ($space eq 'access') {
 9132: 	    # FIXME - not supporting calls for a specific user
 9133:             return &allowed($qualifier,$rest);
 9134: # ------------------------------------------ user.preferences, user.environment
 9135:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 9136: 	    if (($uname eq $env{'user.name'}) &&
 9137: 		($udom eq $env{'user.domain'})) {
 9138: 		return $env{join('.',('environment',$qualifierrest))};
 9139: 	    } else {
 9140: 		my %returnhash;
 9141: 		if (!$publicuser) {
 9142: 		    %returnhash=&userenvironment($udom,$uname,
 9143: 						 $qualifierrest);
 9144: 		}
 9145: 		return $returnhash{$qualifierrest};
 9146: 	    }
 9147: # ----------------------------------------------------------------- user.course
 9148:         } elsif ($space eq 'course') {
 9149: 	    # FIXME - not supporting calls for a specific user
 9150:             return $env{join('.',('request.course',$qualifier))};
 9151: # ------------------------------------------------------------------- user.role
 9152:         } elsif ($space eq 'role') {
 9153: 	    # FIXME - not supporting calls for a specific user
 9154:             my ($role,$where)=split(/\./,$env{'request.role'});
 9155:             if ($qualifier eq 'value') {
 9156: 		return $role;
 9157:             } elsif ($qualifier eq 'extent') {
 9158:                 return $where;
 9159:             }
 9160: # ----------------------------------------------------------------- user.domain
 9161:         } elsif ($space eq 'domain') {
 9162:             return $udom;
 9163: # ------------------------------------------------------------------- user.name
 9164:         } elsif ($space eq 'name') {
 9165:             return $uname;
 9166: # ---------------------------------------------------- Any other user namespace
 9167:         } else {
 9168: 	    my %reply;
 9169: 	    if (!$publicuser) {
 9170: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 9171: 	    }
 9172: 	    return $reply{$qualifierrest};
 9173:         }
 9174:     } elsif ($realm eq 'query') {
 9175: # ---------------------------------------------- pull stuff out of query string
 9176:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 9177: 						[$spacequalifierrest]);
 9178: 	return $env{'form.'.$spacequalifierrest}; 
 9179:    } elsif ($realm eq 'request') {
 9180: # ------------------------------------------------------------- request.browser
 9181:         if ($space eq 'browser') {
 9182:             return $env{'browser.'.$qualifier};
 9183: # ------------------------------------------------------------ request.filename
 9184:         } else {
 9185:             return $env{'request.'.$spacequalifierrest};
 9186:         }
 9187:     } elsif ($realm eq 'course') {
 9188: # ---------------------------------------------------------- course.description
 9189:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 9190:     } elsif ($realm eq 'resource') {
 9191: 
 9192: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 9193: 	    if (!$symbparm) { $symbparm=&symbread(); }
 9194: 	}
 9195: 
 9196: 	if ($space eq 'title') {
 9197: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 9198: 	    return &gettitle($symbparm);
 9199: 	}
 9200: 	
 9201: 	if ($space eq 'map') {
 9202: 	    my ($map) = &decode_symb($symbparm);
 9203: 	    return &symbread($map);
 9204: 	}
 9205: 	if ($space eq 'filename') {
 9206: 	    if ($symbparm) {
 9207: 		return &clutter((&decode_symb($symbparm))[2]);
 9208: 	    }
 9209: 	    return &hreflocation('',$env{'request.filename'});
 9210: 	}
 9211: 
 9212: 	my ($section, $group, @groups);
 9213: 	my ($courselevelm,$courselevel);
 9214: 	if ($symbparm && defined($courseid) && 
 9215: 	    $courseid eq $env{'request.course.id'}) {
 9216: 
 9217: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 9218: 
 9219: # ----------------------------------------------------- Cascading lookup scheme
 9220: 	    my $symbp=$symbparm;
 9221: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 9222: 
 9223: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 9224: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 9225: 
 9226: 	    if (($env{'user.name'} eq $uname) &&
 9227: 		($env{'user.domain'} eq $udom)) {
 9228: 		$section=$env{'request.course.sec'};
 9229:                 @groups = split(/:/,$env{'request.course.groups'});  
 9230:                 @groups=&sort_course_groups($courseid,@groups); 
 9231: 	    } else {
 9232: 		if (! defined($usection)) {
 9233: 		    $section=&getsection($udom,$uname,$courseid);
 9234: 		} else {
 9235: 		    $section = $usection;
 9236: 		}
 9237:                 @groups = &get_users_groups($udom,$uname,$courseid);
 9238: 	    }
 9239: 
 9240: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 9241: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 9242: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 9243: 
 9244: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 9245: 	    my $courselevelr=$courseid.'.'.$symbparm;
 9246: 	    $courselevelm=$courseid.'.'.$mapparm;
 9247: 
 9248: # ----------------------------------------------------------- first, check user
 9249: 
 9250: 	    my $userreply=&resdata($uname,$udom,'user',
 9251: 				       ([$courselevelr,'resource'],
 9252: 					[$courselevelm,'map'     ],
 9253: 					[$courselevel, 'course'  ]));
 9254: 	    if (defined($userreply)) { return &get_reply($userreply); }
 9255: 
 9256: # ------------------------------------------------ second, check some of course
 9257:             my $coursereply;
 9258:             if (@groups > 0) {
 9259:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 9260:                                        $mapparm,$spacequalifierrest);
 9261:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 9262:             }
 9263: 
 9264: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 9265: 				  $env{'course.'.$courseid.'.domain'},
 9266: 				  'course',
 9267: 				  ([$seclevelr,   'resource'],
 9268: 				   [$seclevelm,   'map'     ],
 9269: 				   [$seclevel,    'course'  ],
 9270: 				   [$courselevelr,'resource']));
 9271: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 9272: 
 9273: # ------------------------------------------------------ third, check map parms
 9274: 	    my %parmhash=();
 9275: 	    my $thisparm='';
 9276: 	    if (tie(%parmhash,'GDBM_File',
 9277: 		    $env{'request.course.fn'}.'_parms.db',
 9278: 		    &GDBM_READER(),0640)) {
 9279: 		$thisparm=$parmhash{$symbparm};
 9280: 		untie(%parmhash);
 9281: 	    }
 9282: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 9283: 	}
 9284: # ------------------------------------------ fourth, look in resource metadata
 9285: 
 9286: 	$spacequalifierrest=~s/\./\_/;
 9287: 	my $filename;
 9288: 	if (!$symbparm) { $symbparm=&symbread(); }
 9289: 	if ($symbparm) {
 9290: 	    $filename=(&decode_symb($symbparm))[2];
 9291: 	} else {
 9292: 	    $filename=$env{'request.filename'};
 9293: 	}
 9294: 	my $metadata=&metadata($filename,$spacequalifierrest);
 9295: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 9296: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 9297: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 9298: 
 9299: # ---------------------------------------------- fourth, look in rest of course
 9300: 	if ($symbparm && defined($courseid) && 
 9301: 	    $courseid eq $env{'request.course.id'}) {
 9302: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 9303: 				     $env{'course.'.$courseid.'.domain'},
 9304: 				     'course',
 9305: 				     ([$courselevelm,'map'   ],
 9306: 				      [$courselevel, 'course']));
 9307: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 9308: 	}
 9309: # ------------------------------------------------------------------ Cascade up
 9310: 	unless ($space eq '0') {
 9311: 	    my @parts=split(/_/,$space);
 9312: 	    my $id=pop(@parts);
 9313: 	    my $part=join('_',@parts);
 9314: 	    if ($part eq '') { $part='0'; }
 9315: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 9316: 				 $symbparm,$udom,$uname,$section,1);
 9317: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 9318: 	}
 9319: 	if ($recurse) { return undef; }
 9320: 	my $pack_def=&packages_tab_default($filename,$varname);
 9321: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 9322: # ---------------------------------------------------- Any other user namespace
 9323:     } elsif ($realm eq 'environment') {
 9324: # ----------------------------------------------------------------- environment
 9325: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 9326: 	    return $env{'environment.'.$spacequalifierrest};
 9327: 	} else {
 9328: 	    if ($uname eq 'anonymous' && $udom eq '') {
 9329: 		return '';
 9330: 	    }
 9331: 	    my %returnhash=&userenvironment($udom,$uname,
 9332: 					    $spacequalifierrest);
 9333: 	    return $returnhash{$spacequalifierrest};
 9334: 	}
 9335:     } elsif ($realm eq 'system') {
 9336: # ----------------------------------------------------------------- system.time
 9337: 	if ($space eq 'time') {
 9338: 	    return time;
 9339:         }
 9340:     } elsif ($realm eq 'server') {
 9341: # ----------------------------------------------------------------- system.time
 9342: 	if ($space eq 'name') {
 9343: 	    return $ENV{'SERVER_NAME'};
 9344:         }
 9345:     }
 9346:     return '';
 9347: }
 9348: 
 9349: sub get_reply {
 9350:     my ($reply_value) = @_;
 9351:     if (ref($reply_value) eq 'ARRAY') {
 9352:         if (wantarray) {
 9353: 	    return @$reply_value;
 9354:         }
 9355:         return $reply_value->[0];
 9356:     } else {
 9357:         return $reply_value;
 9358:     }
 9359: }
 9360: 
 9361: sub check_group_parms {
 9362:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 9363:     my @groupitems = ();
 9364:     my $resultitem;
 9365:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 9366:     foreach my $group (@{$groups}) {
 9367:         foreach my $level (@levels) {
 9368:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 9369:              push(@groupitems,[$item,$level->[1]]);
 9370:         }
 9371:     }
 9372:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 9373:                             $env{'course.'.$courseid.'.domain'},
 9374:                                      'course',@groupitems);
 9375:     return $coursereply;
 9376: }
 9377: 
 9378: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 9379:     my ($courseid,@groups) = @_;
 9380:     @groups = sort(@groups);
 9381:     return @groups;
 9382: }
 9383: 
 9384: sub packages_tab_default {
 9385:     my ($uri,$varname)=@_;
 9386:     my (undef,$part,$name)=split(/\./,$varname);
 9387: 
 9388:     my (@extension,@specifics,$do_default);
 9389:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 9390: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 9391: 	if ($pack_type eq 'default') {
 9392: 	    $do_default=1;
 9393: 	} elsif ($pack_type eq 'extension') {
 9394: 	    push(@extension,[$package,$pack_type,$pack_part]);
 9395: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 9396: 	    # only look at packages defaults for packages that this id is
 9397: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 9398: 	}
 9399:     }
 9400:     # first look for a package that matches the requested part id
 9401:     foreach my $package (@specifics) {
 9402: 	my (undef,$pack_type,$pack_part)=@{$package};
 9403: 	next if ($pack_part ne $part);
 9404: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9405: 	    return $packagetab{"$pack_type&$name&default"};
 9406: 	}
 9407:     }
 9408:     # look for any possible matching non extension_ package
 9409:     foreach my $package (@specifics) {
 9410: 	my (undef,$pack_type,$pack_part)=@{$package};
 9411: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9412: 	    return $packagetab{"$pack_type&$name&default"};
 9413: 	}
 9414: 	if ($pack_type eq 'part') { $pack_part='0'; }
 9415: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 9416: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 9417: 	}
 9418:     }
 9419:     # look for any posible extension_ match
 9420:     foreach my $package (@extension) {
 9421: 	my ($package,$pack_type)=@{$package};
 9422: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 9423: 	    return $packagetab{"$pack_type&$name&default"};
 9424: 	}
 9425: 	if (defined($packagetab{$package."&$name&default"})) {
 9426: 	    return $packagetab{$package."&$name&default"};
 9427: 	}
 9428:     }
 9429:     # look for a global default setting
 9430:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 9431: 	return $packagetab{"default&$name&default"};
 9432:     }
 9433:     return undef;
 9434: }
 9435: 
 9436: sub add_prefix_and_part {
 9437:     my ($prefix,$part)=@_;
 9438:     my $keyroot;
 9439:     if (defined($prefix) && $prefix !~ /^__/) {
 9440: 	# prefix that has a part already
 9441: 	$keyroot=$prefix;
 9442:     } elsif (defined($prefix)) {
 9443: 	# prefix that is missing a part
 9444: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 9445:     } else {
 9446: 	# no prefix at all
 9447: 	if (defined($part)) { $keyroot='_'.$part; }
 9448:     }
 9449:     return $keyroot;
 9450: }
 9451: 
 9452: # ---------------------------------------------------------------- Get metadata
 9453: 
 9454: my %metaentry;
 9455: my %importedpartids;
 9456: sub metadata {
 9457:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 9458:     $uri=&declutter($uri);
 9459:     # if it is a non metadata possible uri return quickly
 9460:     if (($uri eq '') || 
 9461: 	(($uri =~ m|^/*adm/|) && 
 9462: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 9463:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
 9464: 	return undef;
 9465:     }
 9466:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
 9467: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
 9468: 	return undef;
 9469:     }
 9470:     my $filename=$uri;
 9471:     $uri=~s/\.meta$//;
 9472: #
 9473: # Is the metadata already cached?
 9474: # Look at timestamp of caching
 9475: # Everything is cached by the main uri, libraries are never directly cached
 9476: #
 9477:     if (!defined($liburi)) {
 9478: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 9479: 	if (defined($cached)) { return $result->{':'.$what}; }
 9480:     }
 9481:     {
 9482: # Imported parts would go here
 9483:         my %importedids=();
 9484:         my @origfileimportpartids=();
 9485:         my $importedparts=0;
 9486: #
 9487: # Is this a recursive call for a library?
 9488: #
 9489: #	if (! exists($metacache{$uri})) {
 9490: #	    $metacache{$uri}={};
 9491: #	}
 9492: 	my $cachetime = 60*60;
 9493:         if ($liburi) {
 9494: 	    $liburi=&declutter($liburi);
 9495:             $filename=$liburi;
 9496:         } else {
 9497: 	    &devalidate_cache_new('meta',$uri);
 9498: 	    undef(%metaentry);
 9499: 	}
 9500:         my %metathesekeys=();
 9501:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 9502: 	my $metastring;
 9503: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
 9504: 	    my $which = &hreflocation('','/'.($liburi || $uri));
 9505: 	    $metastring = 
 9506: 		&Apache::lonnet::ssi_body($which,
 9507: 					  ('grade_target' => 'meta'));
 9508: 	    $cachetime = 1; # only want this cached in the child not long term
 9509: 	} elsif (($uri !~ m -^(editupload)/-) && 
 9510:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
 9511: 	    my $file=&filelocation('',&clutter($filename));
 9512: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 9513: 	    $metastring=&getfile($file);
 9514: 	}
 9515:         my $parser=HTML::LCParser->new(\$metastring);
 9516:         my $token;
 9517:         undef %metathesekeys;
 9518:         while ($token=$parser->get_token) {
 9519: 	    if ($token->[0] eq 'S') {
 9520: 		if (defined($token->[2]->{'package'})) {
 9521: #
 9522: # This is a package - get package info
 9523: #
 9524: 		    my $package=$token->[2]->{'package'};
 9525: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9526: 		    if (defined($token->[2]->{'id'})) { 
 9527: 			$keyroot.='_'.$token->[2]->{'id'}; 
 9528: 		    }
 9529: 		    if ($metaentry{':packages'}) {
 9530: 			$metaentry{':packages'}.=','.$package.$keyroot;
 9531: 		    } else {
 9532: 			$metaentry{':packages'}=$package.$keyroot;
 9533: 		    }
 9534: 		    foreach my $pack_entry (keys(%packagetab)) {
 9535: 			my $part=$keyroot;
 9536: 			$part=~s/^\_//;
 9537: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 9538: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 9539: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 9540: 			    # ignore package.tab specified default values
 9541:                             # here &package_tab_default() will fetch those
 9542: 			    if ($subp eq 'default') { next; }
 9543: 			    my $value=$packagetab{$pack_entry};
 9544: 			    my $unikey;
 9545: 			    if ($pack =~ /_0$/) {
 9546: 				$unikey='parameter_0_'.$name;
 9547: 				$part=0;
 9548: 			    } else {
 9549: 				$unikey='parameter'.$keyroot.'_'.$name;
 9550: 			    }
 9551: 			    if ($subp eq 'display') {
 9552: 				$value.=' [Part: '.$part.']';
 9553: 			    }
 9554: 			    $metaentry{':'.$unikey.'.part'}=$part;
 9555: 			    $metathesekeys{$unikey}=1;
 9556: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 9557: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 9558: 			    }
 9559: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 9560: 				$metaentry{':'.$unikey}=
 9561: 				    $metaentry{':'.$unikey.'.default'};
 9562: 			    }
 9563: 			}
 9564: 		    }
 9565: 		} else {
 9566: #
 9567: # This is not a package - some other kind of start tag
 9568: #
 9569: 		    my $entry=$token->[1];
 9570: 		    my $unikey='';
 9571: 
 9572: 		    if ($entry eq 'import') {
 9573: #
 9574: # Importing a library here
 9575: #
 9576:                         my $location=$parser->get_text('/import');
 9577:                         my $dir=$filename;
 9578:                         $dir=~s|[^/]*$||;
 9579:                         $location=&filelocation($dir,$location);
 9580:                        
 9581:                         my $importmode=$token->[2]->{'importmode'};
 9582:                         if ($importmode eq 'problem') {
 9583: # Import as problem/response
 9584:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9585:                         } elsif ($importmode eq 'part') {
 9586: # Import as part(s)
 9587:                            $importedparts=1;
 9588: # We need to get the original file and the imported file to get the part order correct
 9589: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
 9590: # Load and inspect original file
 9591:                            if ($#origfileimportpartids<0) {
 9592:                               undef(%importedpartids);
 9593:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
 9594:                               my $origfile=&getfile($origfilelocation);
 9595:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
 9596:                            }
 9597: 
 9598: # Load and inspect imported file
 9599:                            my $impfile=&getfile($location);
 9600:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
 9601:                            if ($#impfilepartids>=0) {
 9602: # This problem had parts
 9603:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
 9604:                            } else {
 9605: # Importing by turning a single problem into a problem part
 9606: # It gets the import-tags ID as part-ID
 9607:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
 9608:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
 9609:                            }
 9610:                         } else {
 9611: # Normal import
 9612:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9613:                            if (defined($token->[2]->{'id'})) {
 9614:                               $unikey.='_'.$token->[2]->{'id'};
 9615:                            }
 9616:                         }
 9617: 
 9618: 			if ($depthcount<20) {
 9619: 			    my $metadata = 
 9620: 				&metadata($uri,'keys', $location,$unikey,
 9621: 					  $depthcount+1);
 9622: 			    foreach my $meta (split(',',$metadata)) {
 9623: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 9624: 				$metathesekeys{$meta}=1;
 9625: 			    }
 9626: 			
 9627:                         }
 9628: 		    } else {
 9629: #
 9630: # Not importing, some other kind of non-package, non-library start tag
 9631: # 
 9632:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
 9633:                         if (defined($token->[2]->{'id'})) {
 9634:                             $unikey.='_'.$token->[2]->{'id'};
 9635:                         }
 9636: 			if (defined($token->[2]->{'name'})) { 
 9637: 			    $unikey.='_'.$token->[2]->{'name'}; 
 9638: 			}
 9639: 			$metathesekeys{$unikey}=1;
 9640: 			foreach my $param (@{$token->[3]}) {
 9641: 			    $metaentry{':'.$unikey.'.'.$param} =
 9642: 				$token->[2]->{$param};
 9643: 			}
 9644: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 9645: 			my $default=$metaentry{':'.$unikey.'.default'};
 9646: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 9647: 		 # only ws inside the tag, and not in default, so use default
 9648: 		 # as value
 9649: 			    $metaentry{':'.$unikey}=$default;
 9650: 			} elsif ( $internaltext =~ /\S/ ) {
 9651: 		  # something interesting inside the tag
 9652: 			    $metaentry{':'.$unikey}=$internaltext;
 9653: 			} else {
 9654: 		  # no interesting values, don't set a default
 9655: 			}
 9656: # end of not-a-package not-a-library import
 9657: 		    }
 9658: # end of not-a-package start tag
 9659: 		}
 9660: # the next is the end of "start tag"
 9661: 	    }
 9662: 	}
 9663: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 9664: 	$extension = lc($extension);
 9665: 	if ($extension eq 'htm') { $extension='html'; }
 9666: 
 9667: 	foreach my $key (keys(%packagetab)) {
 9668: 	    #no specific packages #how's our extension
 9669: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 9670: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 9671: 					 \%metathesekeys);
 9672: 	}
 9673: 
 9674: 	if (!exists($metaentry{':packages'})
 9675: 	    || $packagetab{"import_defaults&extension_$extension"}) {
 9676: 	    foreach my $key (keys(%packagetab)) {
 9677: 		#no specific packages well let's get default then
 9678: 		if ($key!~/^default&/) { next; }
 9679: 		&metadata_create_package_def($uri,$key,'default',
 9680: 					     \%metathesekeys);
 9681: 	    }
 9682: 	}
 9683: # are there custom rights to evaluate
 9684: 	if ($metaentry{':copyright'} eq 'custom') {
 9685: 
 9686:     #
 9687:     # Importing a rights file here
 9688:     #
 9689: 	    unless ($depthcount) {
 9690: 		my $location=$metaentry{':customdistributionfile'};
 9691: 		my $dir=$filename;
 9692: 		$dir=~s|[^/]*$||;
 9693: 		$location=&filelocation($dir,$location);
 9694: 		my $rights_metadata =
 9695: 		    &metadata($uri,'keys',$location,'_rights',
 9696: 			      $depthcount+1);
 9697: 		foreach my $rights (split(',',$rights_metadata)) {
 9698: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 9699: 		    $metathesekeys{$rights}=1;
 9700: 		}
 9701: 	    }
 9702: 	}
 9703: 	# uniqifiy package listing
 9704: 	my %seen;
 9705: 	my @uniq_packages =
 9706: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 9707: 	$metaentry{':packages'} = join(',',@uniq_packages);
 9708: 
 9709:         if ($importedparts) {
 9710: # We had imported parts and need to rebuild partorder
 9711:            $metaentry{':partorder'}='';
 9712:            $metathesekeys{'partorder'}=1;
 9713:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
 9714:                if ($origfileimportpartids[$index] eq 'part') {
 9715: # original part, part of the problem
 9716:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
 9717:                } else {
 9718: # we have imported parts at this position
 9719:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
 9720:                }
 9721:            }
 9722:            $metaentry{':partorder'}=~s/^\,//;
 9723:         }
 9724: 
 9725: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 9726: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 9727: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 9728: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
 9729: # this is the end of "was not already recently cached
 9730:     }
 9731:     return $metaentry{':'.$what};
 9732: }
 9733: 
 9734: sub metadata_create_package_def {
 9735:     my ($uri,$key,$package,$metathesekeys)=@_;
 9736:     my ($pack,$name,$subp)=split(/\&/,$key);
 9737:     if ($subp eq 'default') { next; }
 9738:     
 9739:     if (defined($metaentry{':packages'})) {
 9740: 	$metaentry{':packages'}.=','.$package;
 9741:     } else {
 9742: 	$metaentry{':packages'}=$package;
 9743:     }
 9744:     my $value=$packagetab{$key};
 9745:     my $unikey;
 9746:     $unikey='parameter_0_'.$name;
 9747:     $metaentry{':'.$unikey.'.part'}=0;
 9748:     $$metathesekeys{$unikey}=1;
 9749:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 9750: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 9751:     }
 9752:     if (defined($metaentry{':'.$unikey.'.default'})) {
 9753: 	$metaentry{':'.$unikey}=
 9754: 	    $metaentry{':'.$unikey.'.default'};
 9755:     }
 9756: }
 9757: 
 9758: sub metadata_generate_part0 {
 9759:     my ($metadata,$metacache,$uri) = @_;
 9760:     my %allnames;
 9761:     foreach my $metakey (keys(%$metadata)) {
 9762: 	if ($metakey=~/^parameter\_(.*)/) {
 9763: 	  my $part=$$metacache{':'.$metakey.'.part'};
 9764: 	  my $name=$$metacache{':'.$metakey.'.name'};
 9765: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 9766: 	    $allnames{$name}=$part;
 9767: 	  }
 9768: 	}
 9769:     }
 9770:     foreach my $name (keys(%allnames)) {
 9771:       $$metadata{"parameter_0_$name"}=1;
 9772:       my $key=":parameter_0_$name";
 9773:       $$metacache{"$key.part"}='0';
 9774:       $$metacache{"$key.name"}=$name;
 9775:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 9776: 					   $allnames{$name}.'_'.$name.
 9777: 					   '.type'};
 9778:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 9779: 			     '.display'};
 9780:       my $expr='[Part: '.$allnames{$name}.']';
 9781:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 9782:       $$metacache{"$key.display"}=$olddis;
 9783:     }
 9784: }
 9785: 
 9786: # ------------------------------------------------------ Devalidate title cache
 9787: 
 9788: sub devalidate_title_cache {
 9789:     my ($url)=@_;
 9790:     if (!$env{'request.course.id'}) { return; }
 9791:     my $symb=&symbread($url);
 9792:     if (!$symb) { return; }
 9793:     my $key=$env{'request.course.id'}."\0".$symb;
 9794:     &devalidate_cache_new('title',$key);
 9795: }
 9796: 
 9797: # ------------------------------------------------- Get the title of a course
 9798: 
 9799: sub current_course_title {
 9800:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
 9801: }
 9802: # ------------------------------------------------- Get the title of a resource
 9803: 
 9804: sub gettitle {
 9805:     my $urlsymb=shift;
 9806:     my $symb=&symbread($urlsymb);
 9807:     if ($symb) {
 9808: 	my $key=$env{'request.course.id'}."\0".$symb;
 9809: 	my ($result,$cached)=&is_cached_new('title',$key);
 9810: 	if (defined($cached)) { 
 9811: 	    return $result;
 9812: 	}
 9813: 	my ($map,$resid,$url)=&decode_symb($symb);
 9814: 	my $title='';
 9815: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
 9816: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
 9817: 	} else {
 9818: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9819: 		    &GDBM_READER(),0640)) {
 9820: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
 9821: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
 9822: 		untie(%bighash);
 9823: 	    }
 9824: 	}
 9825: 	$title=~s/\&colon\;/\:/gs;
 9826: 	if ($title) {
 9827: # Remember both $symb and $title for dynamic metadata
 9828:             $accesshash{$symb.'___crstitle'}=$title;
 9829:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
 9830: # Cache this title and then return it
 9831: 	    return &do_cache_new('title',$key,$title,600);
 9832: 	}
 9833: 	$urlsymb=$url;
 9834:     }
 9835:     my $title=&metadata($urlsymb,'title');
 9836:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 9837:     return $title;
 9838: }
 9839: 
 9840: sub get_slot {
 9841:     my ($which,$cnum,$cdom)=@_;
 9842:     if (!$cnum || !$cdom) {
 9843: 	(undef,my $courseid)=&whichuser();
 9844: 	$cdom=$env{'course.'.$courseid.'.domain'};
 9845: 	$cnum=$env{'course.'.$courseid.'.num'};
 9846:     }
 9847:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 9848:     my %slotinfo;
 9849:     if (exists($remembered{$key})) {
 9850: 	$slotinfo{$which} = $remembered{$key};
 9851:     } else {
 9852: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 9853: 	&Apache::lonhomework::showhash(%slotinfo);
 9854: 	my ($tmp)=keys(%slotinfo);
 9855: 	if ($tmp=~/^error:/) { return (); }
 9856: 	$remembered{$key} = $slotinfo{$which};
 9857:     }
 9858:     if (ref($slotinfo{$which}) eq 'HASH') {
 9859: 	return %{$slotinfo{$which}};
 9860:     }
 9861:     return $slotinfo{$which};
 9862: }
 9863: 
 9864: sub get_reservable_slots {
 9865:     my ($cnum,$cdom,$uname,$udom) = @_;
 9866:     my $now = time;
 9867:     my $reservable_info;
 9868:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
 9869:     if (exists($remembered{$key})) {
 9870:         $reservable_info = $remembered{$key};
 9871:     } else {
 9872:         my %resv;
 9873:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
 9874:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
 9875:         $reservable_info = \%resv;
 9876:         $remembered{$key} = $reservable_info;
 9877:     }
 9878:     return $reservable_info;
 9879: }
 9880: 
 9881: sub get_course_slots {
 9882:     my ($cnum,$cdom) = @_;
 9883:     my $hashid=$cnum.':'.$cdom;
 9884:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
 9885:     if (defined($cached)) {
 9886:         if (ref($result) eq 'HASH') {
 9887:             return %{$result};
 9888:         }
 9889:     } else {
 9890:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
 9891:         my ($tmp) = keys(%slots);
 9892:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 9893:             &Apache::lonnet::do_cache_new('allslots',$hashid,\%slots,600);
 9894:             return %slots;
 9895:         }
 9896:     }
 9897:     return;
 9898: }
 9899: 
 9900: sub devalidate_slots_cache {
 9901:     my ($cnum,$cdom)=@_;
 9902:     my $hashid=$cnum.':'.$cdom;
 9903:     &devalidate_cache_new('allslots',$hashid);
 9904: }
 9905: 
 9906: sub get_coursechange {
 9907:     my ($cdom,$cnum) = @_;
 9908:     if ($cdom eq '' || $cnum eq '') {
 9909:         return unless ($env{'request.course.id'});
 9910:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 9911:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 9912:     }
 9913:     my $hashid=$cdom.'_'.$cnum;
 9914:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
 9915:     if ((defined($cached)) && ($change ne '')) {
 9916:         return $change;
 9917:     } else {
 9918:         my %crshash;
 9919:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
 9920:         if ($crshash{'internal.contentchange'} eq '') {
 9921:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
 9922:             if ($change eq '') {
 9923:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
 9924:                 $change = $crshash{'internal.created'};
 9925:             }
 9926:         } else {
 9927:             $change = $crshash{'internal.contentchange'};
 9928:         }
 9929:         my $cachetime = 600;
 9930:         &do_cache_new('crschange',$hashid,$change,$cachetime);
 9931:     }
 9932:     return $change;
 9933: }
 9934: 
 9935: sub devalidate_coursechange_cache {
 9936:     my ($cnum,$cdom)=@_;
 9937:     my $hashid=$cnum.':'.$cdom;
 9938:     &devalidate_cache_new('crschange',$hashid);
 9939: }
 9940: 
 9941: # ------------------------------------------------- Update symbolic store links
 9942: 
 9943: sub symblist {
 9944:     my ($mapname,%newhash)=@_;
 9945:     $mapname=&deversion(&declutter($mapname));
 9946:     my %hash;
 9947:     if (($env{'request.course.fn'}) && (%newhash)) {
 9948:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 9949:                       &GDBM_WRCREAT(),0640)) {
 9950: 	    foreach my $url (keys(%newhash)) {
 9951: 		next if ($url eq 'last_known'
 9952: 			 && $env{'form.no_update_last_known'});
 9953: 		$hash{declutter($url)}=&encode_symb($mapname,
 9954: 						    $newhash{$url}->[1],
 9955: 						    $newhash{$url}->[0]);
 9956:             }
 9957:             if (untie(%hash)) {
 9958: 		return 'ok';
 9959:             }
 9960:         }
 9961:     }
 9962:     return 'error';
 9963: }
 9964: 
 9965: # --------------------------------------------------------------- Verify a symb
 9966: 
 9967: sub symbverify {
 9968:     my ($symb,$thisurl)=@_;
 9969:     my $thisfn=$thisurl;
 9970:     $thisfn=&declutter($thisfn);
 9971: # direct jump to resource in page or to a sequence - will construct own symbs
 9972:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 9973: # check URL part
 9974:     my ($map,$resid,$url)=&decode_symb($symb);
 9975: 
 9976:     unless ($url eq $thisfn) { return 0; }
 9977: 
 9978:     $symb=&symbclean($symb);
 9979:     $thisurl=&deversion($thisurl);
 9980:     $thisfn=&deversion($thisfn);
 9981: 
 9982:     my %bighash;
 9983:     my $okay=0;
 9984: 
 9985:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 9986:                             &GDBM_READER(),0640)) {
 9987:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
 9988:             $thisurl =~ s/\?.+$//;
 9989:         }
 9990:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 9991:         unless ($ids) {
 9992:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
 9993:             $ids=$bighash{$idkey};
 9994:         }
 9995:         if ($ids) {
 9996: # ------------------------------------------------------------------- Has ID(s)
 9997: 	    foreach my $id (split(/\,/,$ids)) {
 9998: 	       my ($mapid,$resid)=split(/\./,$id);
 9999:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
10000:                    $symb =~ s/\?.+$//;
10001:                }
10002:                if (
10003:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
10004:    eq $symb) { 
10005: 		   if (($env{'request.role.adv'}) ||
10006: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
10007:                        ($thisurl eq '/adm/navmaps')) {
10008: 		       $okay=1; 
10009: 		   }
10010: 	       }
10011: 	   }
10012:         }
10013: 	untie(%bighash);
10014:     }
10015:     return $okay;
10016: }
10017: 
10018: # --------------------------------------------------------------- Clean-up symb
10019: 
10020: sub symbclean {
10021:     my $symb=shift;
10022:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10023: # remove version from map
10024:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
10025: 
10026: # remove version from URL
10027:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
10028: 
10029: # remove wrapper
10030: 
10031:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
10032:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
10033:     return $symb;
10034: }
10035: 
10036: # ---------------------------------------------- Split symb to find map and url
10037: 
10038: sub encode_symb {
10039:     my ($map,$resid,$url)=@_;
10040:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
10041: }
10042: 
10043: sub decode_symb {
10044:     my $symb=shift;
10045:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10046:     my ($map,$resid,$url)=split(/___/,$symb);
10047:     return (&fixversion($map),$resid,&fixversion($url));
10048: }
10049: 
10050: sub fixversion {
10051:     my $fn=shift;
10052:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
10053:     my %bighash;
10054:     my $uri=&clutter($fn);
10055:     my $key=$env{'request.course.id'}.'_'.$uri;
10056: # is this cached?
10057:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
10058:     if (defined($cached)) { return $result; }
10059: # unfortunately not cached, or expired
10060:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10061: 	    &GDBM_READER(),0640)) {
10062:  	if ($bighash{'version_'.$uri}) {
10063:  	    my $version=$bighash{'version_'.$uri};
10064:  	    unless (($version eq 'mostrecent') || 
10065: 		    ($version==&getversion($uri))) {
10066:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
10067:  	    }
10068:  	}
10069:  	untie %bighash;
10070:     }
10071:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
10072: }
10073: 
10074: sub deversion {
10075:     my $url=shift;
10076:     $url=~s/\.\d+\.(\w+)$/\.$1/;
10077:     return $url;
10078: }
10079: 
10080: # ------------------------------------------------------ Return symb list entry
10081: 
10082: sub symbread {
10083:     my ($thisfn,$donotrecurse)=@_;
10084:     my $cache_str='request.symbread.cached.'.$thisfn;
10085:     if (defined($env{$cache_str})) {
10086:         if (($thisfn) || ($env{$cache_str} ne '')) {
10087:             return $env{$cache_str};
10088:         }
10089:     }
10090: # no filename provided? try from environment
10091:     unless ($thisfn) {
10092:         if ($env{'request.symb'}) {
10093: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
10094: 	}
10095: 	$thisfn=$env{'request.filename'};
10096:     }
10097:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
10098: # is that filename actually a symb? Verify, clean, and return
10099:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
10100: 	if (&symbverify($thisfn,$1)) {
10101: 	    return $env{$cache_str}=&symbclean($thisfn);
10102: 	}
10103:     }
10104:     $thisfn=declutter($thisfn);
10105:     my %hash;
10106:     my %bighash;
10107:     my $syval='';
10108:     if (($env{'request.course.fn'}) && ($thisfn)) {
10109:         my $targetfn = $thisfn;
10110:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
10111:             $targetfn = 'adm/wrapper/'.$thisfn;
10112:         }
10113: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
10114: 	    $targetfn=$1;
10115: 	}
10116:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10117:                       &GDBM_READER(),0640)) {
10118: 	    $syval=$hash{$targetfn};
10119:             untie(%hash);
10120:         }
10121: # ---------------------------------------------------------- There was an entry
10122:         if ($syval) {
10123: 	    #unless ($syval=~/\_\d+$/) {
10124: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
10125: 		    #&appenv({'request.ambiguous' => $thisfn});
10126: 		    #return $env{$cache_str}='';
10127: 		#}    
10128: 		#$syval.=$1;
10129: 	    #}
10130:         } else {
10131: # ------------------------------------------------------- Was not in symb table
10132:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10133:                             &GDBM_READER(),0640)) {
10134: # ---------------------------------------------- Get ID(s) for current resource
10135:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
10136:               unless ($ids) { 
10137:                  $ids=$bighash{'ids_/'.$thisfn};
10138:               }
10139:               unless ($ids) {
10140: # alias?
10141: 		  $ids=$bighash{'mapalias_'.$thisfn};
10142:               }
10143:               if ($ids) {
10144: # ------------------------------------------------------------------- Has ID(s)
10145:                  my @possibilities=split(/\,/,$ids);
10146:                  if ($#possibilities==0) {
10147: # ----------------------------------------------- There is only one possibility
10148: 		     my ($mapid,$resid)=split(/\./,$ids);
10149: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
10150: 						    $resid,$thisfn);
10151:                  } elsif (!$donotrecurse) {
10152: # ------------------------------------------ There is more than one possibility
10153:                      my $realpossible=0;
10154:                      foreach my $id (@possibilities) {
10155: 			 my $file=$bighash{'src_'.$id};
10156:                          if (&allowed('bre',$file)) {
10157:          		    my ($mapid,$resid)=split(/\./,$id);
10158:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
10159: 				$realpossible++;
10160:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
10161: 						    $resid,$thisfn);
10162:                             }
10163: 			 }
10164:                      }
10165: 		     if ($realpossible!=1) { $syval=''; }
10166:                  } else {
10167:                      $syval='';
10168:                  }
10169: 	      }
10170:               untie(%bighash)
10171:            }
10172:         }
10173:         if ($syval) {
10174: 	    return $env{$cache_str}=$syval;
10175:         }
10176:     }
10177:     &appenv({'request.ambiguous' => $thisfn});
10178:     return $env{$cache_str}='';
10179: }
10180: 
10181: # ---------------------------------------------------------- Return random seed
10182: 
10183: sub numval {
10184:     my $txt=shift;
10185:     $txt=~tr/A-J/0-9/;
10186:     $txt=~tr/a-j/0-9/;
10187:     $txt=~tr/K-T/0-9/;
10188:     $txt=~tr/k-t/0-9/;
10189:     $txt=~tr/U-Z/0-5/;
10190:     $txt=~tr/u-z/0-5/;
10191:     $txt=~s/\D//g;
10192:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
10193:     return int($txt);
10194: }
10195: 
10196: sub numval2 {
10197:     my $txt=shift;
10198:     $txt=~tr/A-J/0-9/;
10199:     $txt=~tr/a-j/0-9/;
10200:     $txt=~tr/K-T/0-9/;
10201:     $txt=~tr/k-t/0-9/;
10202:     $txt=~tr/U-Z/0-5/;
10203:     $txt=~tr/u-z/0-5/;
10204:     $txt=~s/\D//g;
10205:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10206:     my $total;
10207:     foreach my $val (@txts) { $total+=$val; }
10208:     if ($_64bit) { if ($total > 2**32) { return -1; } }
10209:     return int($total);
10210: }
10211: 
10212: sub numval3 {
10213:     use integer;
10214:     my $txt=shift;
10215:     $txt=~tr/A-J/0-9/;
10216:     $txt=~tr/a-j/0-9/;
10217:     $txt=~tr/K-T/0-9/;
10218:     $txt=~tr/k-t/0-9/;
10219:     $txt=~tr/U-Z/0-5/;
10220:     $txt=~tr/u-z/0-5/;
10221:     $txt=~s/\D//g;
10222:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10223:     my $total;
10224:     foreach my $val (@txts) { $total+=$val; }
10225:     if ($_64bit) { $total=(($total<<32)>>32); }
10226:     return $total;
10227: }
10228: 
10229: sub digest {
10230:     my ($data)=@_;
10231:     my $digest=&Digest::MD5::md5($data);
10232:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
10233:     my ($e,$f);
10234:     {
10235:         use integer;
10236:         $e=($a+$b);
10237:         $f=($c+$d);
10238:         if ($_64bit) {
10239:             $e=(($e<<32)>>32);
10240:             $f=(($f<<32)>>32);
10241:         }
10242:     }
10243:     if (wantarray) {
10244: 	return ($e,$f);
10245:     } else {
10246: 	my $g;
10247: 	{
10248: 	    use integer;
10249: 	    $g=($e+$f);
10250: 	    if ($_64bit) {
10251: 		$g=(($g<<32)>>32);
10252: 	    }
10253: 	}
10254: 	return $g;
10255:     }
10256: }
10257: 
10258: sub latest_rnd_algorithm_id {
10259:     return '64bit5';
10260: }
10261: 
10262: sub get_rand_alg {
10263:     my ($courseid)=@_;
10264:     if (!$courseid) { $courseid=(&whichuser())[1]; }
10265:     if ($courseid) {
10266: 	return $env{"course.$courseid.rndseed"};
10267:     }
10268:     return &latest_rnd_algorithm_id();
10269: }
10270: 
10271: sub validCODE {
10272:     my ($CODE)=@_;
10273:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
10274:     return 0;
10275: }
10276: 
10277: sub getCODE {
10278:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
10279:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
10280: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
10281: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
10282: 	return $Apache::lonhomework::history{'resource.CODE'};
10283:     }
10284:     return undef;
10285: }
10286: #
10287: #  Determines the random seed for a specific context:
10288: #
10289: # parameters:
10290: #   symb      - in course context the symb for the seed.
10291: #   course_id - The course id of the form domain_coursenum.
10292: #   domain    - Domain for the user.
10293: #   course    - Course for the user.
10294: #   cenv      - environment of the course.
10295: #
10296: # NOTE:
10297: #   All parameters are picked out of the environment if missing
10298: #   or not defined.
10299: #   If a symb cannot be determined the current time is used instead.
10300: #
10301: #  For a given well defined symb, courside, domain, username,
10302: #  and course environment, the seed is reproducible.
10303: #
10304: sub rndseed {
10305:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
10306:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
10307:     if (!defined($symb)) {
10308: 	unless ($symb=$wsymb) { return time; }
10309:     }
10310:     if (!defined $courseid) { 
10311: 	$courseid=$wcourseid; 
10312:     }
10313:     if (!defined $domain) { $domain=$wdomain; }
10314:     if (!defined $username) { $username=$wusername }
10315: 
10316:     my $which;
10317:     if (defined($cenv->{'rndseed'})) {
10318: 	$which = $cenv->{'rndseed'};
10319:     } else {
10320: 	$which =&get_rand_alg($courseid);
10321:     }
10322:     if (defined(&getCODE())) {
10323: 
10324: 	if ($which eq '64bit5') {
10325: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
10326: 	} elsif ($which eq '64bit4') {
10327: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
10328: 	} else {
10329: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
10330: 	}
10331:     } elsif ($which eq '64bit5') {
10332: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
10333:     } elsif ($which eq '64bit4') {
10334: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
10335:     } elsif ($which eq '64bit3') {
10336: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
10337:     } elsif ($which eq '64bit2') {
10338: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
10339:     } elsif ($which eq '64bit') {
10340: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
10341:     }
10342:     return &rndseed_32bit($symb,$courseid,$domain,$username);
10343: }
10344: 
10345: sub rndseed_32bit {
10346:     my ($symb,$courseid,$domain,$username)=@_;
10347:     {
10348: 	use integer;
10349: 	my $symbchck=unpack("%32C*",$symb) << 27;
10350: 	my $symbseed=numval($symb) << 22;
10351: 	my $namechck=unpack("%32C*",$username) << 17;
10352: 	my $nameseed=numval($username) << 12;
10353: 	my $domainseed=unpack("%32C*",$domain) << 7;
10354: 	my $courseseed=unpack("%32C*",$courseid);
10355: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
10356: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10357: 	#&logthis("rndseed :$num:$symb");
10358: 	if ($_64bit) { $num=(($num<<32)>>32); }
10359: 	return $num;
10360:     }
10361: }
10362: 
10363: sub rndseed_64bit {
10364:     my ($symb,$courseid,$domain,$username)=@_;
10365:     {
10366: 	use integer;
10367: 	my $symbchck=unpack("%32S*",$symb) << 21;
10368: 	my $symbseed=numval($symb) << 10;
10369: 	my $namechck=unpack("%32S*",$username);
10370: 	
10371: 	my $nameseed=numval($username) << 21;
10372: 	my $domainseed=unpack("%32S*",$domain) << 10;
10373: 	my $courseseed=unpack("%32S*",$courseid);
10374: 	
10375: 	my $num1=$symbchck+$symbseed+$namechck;
10376: 	my $num2=$nameseed+$domainseed+$courseseed;
10377: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10378: 	#&logthis("rndseed :$num:$symb");
10379: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10380: 	return "$num1,$num2";
10381:     }
10382: }
10383: 
10384: sub rndseed_64bit2 {
10385:     my ($symb,$courseid,$domain,$username)=@_;
10386:     {
10387: 	use integer;
10388: 	# strings need to be an even # of cahracters long, it it is odd the
10389:         # last characters gets thrown away
10390: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
10391: 	my $symbseed=numval($symb) << 10;
10392: 	my $namechck=unpack("%32S*",$username.' ');
10393: 	
10394: 	my $nameseed=numval($username) << 21;
10395: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
10396: 	my $courseseed=unpack("%32S*",$courseid.' ');
10397: 	
10398: 	my $num1=$symbchck+$symbseed+$namechck;
10399: 	my $num2=$nameseed+$domainseed+$courseseed;
10400: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10401: 	#&logthis("rndseed :$num:$symb");
10402: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10403: 	return "$num1,$num2";
10404:     }
10405: }
10406: 
10407: sub rndseed_64bit3 {
10408:     my ($symb,$courseid,$domain,$username)=@_;
10409:     {
10410: 	use integer;
10411: 	# strings need to be an even # of cahracters long, it it is odd the
10412:         # last characters gets thrown away
10413: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
10414: 	my $symbseed=numval2($symb) << 10;
10415: 	my $namechck=unpack("%32S*",$username.' ');
10416: 	
10417: 	my $nameseed=numval2($username) << 21;
10418: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
10419: 	my $courseseed=unpack("%32S*",$courseid.' ');
10420: 	
10421: 	my $num1=$symbchck+$symbseed+$namechck;
10422: 	my $num2=$nameseed+$domainseed+$courseseed;
10423: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10424: 	#&logthis("rndseed :$num1:$num2:$_64bit");
10425: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10426: 	
10427: 	return "$num1:$num2";
10428:     }
10429: }
10430: 
10431: sub rndseed_64bit4 {
10432:     my ($symb,$courseid,$domain,$username)=@_;
10433:     {
10434: 	use integer;
10435: 	# strings need to be an even # of cahracters long, it it is odd the
10436:         # last characters gets thrown away
10437: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
10438: 	my $symbseed=numval3($symb) << 10;
10439: 	my $namechck=unpack("%32S*",$username.' ');
10440: 	
10441: 	my $nameseed=numval3($username) << 21;
10442: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
10443: 	my $courseseed=unpack("%32S*",$courseid.' ');
10444: 	
10445: 	my $num1=$symbchck+$symbseed+$namechck;
10446: 	my $num2=$nameseed+$domainseed+$courseseed;
10447: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10448: 	#&logthis("rndseed :$num1:$num2:$_64bit");
10449: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10450: 	
10451: 	return "$num1:$num2";
10452:     }
10453: }
10454: 
10455: sub rndseed_64bit5 {
10456:     my ($symb,$courseid,$domain,$username)=@_;
10457:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
10458:     return "$num1:$num2";
10459: }
10460: 
10461: sub rndseed_CODE_64bit {
10462:     my ($symb,$courseid,$domain,$username)=@_;
10463:     {
10464: 	use integer;
10465: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
10466: 	my $symbseed=numval2($symb);
10467: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
10468: 	my $CODEseed=numval(&getCODE());
10469: 	my $courseseed=unpack("%32S*",$courseid.' ');
10470: 	my $num1=$symbseed+$CODEchck;
10471: 	my $num2=$CODEseed+$courseseed+$symbchck;
10472: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
10473: 	#&logthis("rndseed :$num1:$num2:$symb");
10474: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
10475: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
10476: 	return "$num1:$num2";
10477:     }
10478: }
10479: 
10480: sub rndseed_CODE_64bit4 {
10481:     my ($symb,$courseid,$domain,$username)=@_;
10482:     {
10483: 	use integer;
10484: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
10485: 	my $symbseed=numval3($symb);
10486: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
10487: 	my $CODEseed=numval3(&getCODE());
10488: 	my $courseseed=unpack("%32S*",$courseid.' ');
10489: 	my $num1=$symbseed+$CODEchck;
10490: 	my $num2=$CODEseed+$courseseed+$symbchck;
10491: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
10492: 	#&logthis("rndseed :$num1:$num2:$symb");
10493: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
10494: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
10495: 	return "$num1:$num2";
10496:     }
10497: }
10498: 
10499: sub rndseed_CODE_64bit5 {
10500:     my ($symb,$courseid,$domain,$username)=@_;
10501:     my $code = &getCODE();
10502:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
10503:     return "$num1:$num2";
10504: }
10505: 
10506: sub setup_random_from_rndseed {
10507:     my ($rndseed)=@_;
10508:     if ($rndseed =~/([,:])/) {
10509: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
10510: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
10511:     } else {
10512: 	&Math::Random::random_set_seed_from_phrase($rndseed);
10513:     }
10514: }
10515: 
10516: sub latest_receipt_algorithm_id {
10517:     return 'receipt3';
10518: }
10519: 
10520: sub recunique {
10521:     my $fucourseid=shift;
10522:     my $unique;
10523:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
10524: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
10525: 	$unique=$env{"course.$fucourseid.internal.encseed"};
10526:     } else {
10527: 	$unique=$perlvar{'lonReceipt'};
10528:     }
10529:     return unpack("%32C*",$unique);
10530: }
10531: 
10532: sub recprefix {
10533:     my $fucourseid=shift;
10534:     my $prefix;
10535:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
10536: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
10537: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
10538:     } else {
10539: 	$prefix=$perlvar{'lonHostID'};
10540:     }
10541:     return unpack("%32C*",$prefix);
10542: }
10543: 
10544: sub ireceipt {
10545:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
10546: 
10547:     my $return =&recprefix($fucourseid).'-';
10548: 
10549:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
10550: 	$env{'request.state'} eq 'construct') {
10551: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
10552: 	return $return;
10553:     }
10554: 
10555:     my $cuname=unpack("%32C*",$funame);
10556:     my $cudom=unpack("%32C*",$fudom);
10557:     my $cucourseid=unpack("%32C*",$fucourseid);
10558:     my $cusymb=unpack("%32C*",$fusymb);
10559:     my $cunique=&recunique($fucourseid);
10560:     my $cpart=unpack("%32S*",$part);
10561:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
10562: 
10563: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
10564: 			       
10565: 	$return.= ($cunique%$cuname+
10566: 		   $cunique%$cudom+
10567: 		   $cusymb%$cuname+
10568: 		   $cusymb%$cudom+
10569: 		   $cucourseid%$cuname+
10570: 		   $cucourseid%$cudom+
10571: 		   $cpart%$cuname+
10572: 		   $cpart%$cudom);
10573:     } else {
10574: 	$return.= ($cunique%$cuname+
10575: 		   $cunique%$cudom+
10576: 		   $cusymb%$cuname+
10577: 		   $cusymb%$cudom+
10578: 		   $cucourseid%$cuname+
10579: 		   $cucourseid%$cudom);
10580:     }
10581:     return $return;
10582: }
10583: 
10584: sub receipt {
10585:     my ($part)=@_;
10586:     my ($symb,$courseid,$domain,$name) = &whichuser();
10587:     return &ireceipt($name,$domain,$courseid,$symb,$part);
10588: }
10589: 
10590: sub whichuser {
10591:     my ($passedsymb)=@_;
10592:     my ($symb,$courseid,$domain,$name,$publicuser);
10593:     if (defined($env{'form.grade_symb'})) {
10594: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
10595: 	my $allowed=&allowed('vgr',$tmp_courseid);
10596: 	if (!$allowed &&
10597: 	    exists($env{'request.course.sec'}) &&
10598: 	    $env{'request.course.sec'} !~ /^\s*$/) {
10599: 	    $allowed=&allowed('vgr',$tmp_courseid.
10600: 			      '/'.$env{'request.course.sec'});
10601: 	}
10602: 	if ($allowed) {
10603: 	    ($symb)=&get_env_multiple('form.grade_symb');
10604: 	    $courseid=$tmp_courseid;
10605: 	    ($domain)=&get_env_multiple('form.grade_domain');
10606: 	    ($name)=&get_env_multiple('form.grade_username');
10607: 	    return ($symb,$courseid,$domain,$name,$publicuser);
10608: 	}
10609:     }
10610:     if (!$passedsymb) {
10611: 	$symb=&symbread();
10612:     } else {
10613: 	$symb=$passedsymb;
10614:     }
10615:     $courseid=$env{'request.course.id'};
10616:     $domain=$env{'user.domain'};
10617:     $name=$env{'user.name'};
10618:     if ($name eq 'public' && $domain eq 'public') {
10619: 	if (!defined($env{'form.username'})) {
10620: 	    $env{'form.username'}.=time.rand(10000000);
10621: 	}
10622: 	$name.=$env{'form.username'};
10623:     }
10624:     return ($symb,$courseid,$domain,$name,$publicuser);
10625: 
10626: }
10627: 
10628: # ------------------------------------------------------------ Serves up a file
10629: # returns either the contents of the file or 
10630: # -1 if the file doesn't exist
10631: #
10632: # if the target is a file that was uploaded via DOCS, 
10633: # a check will be made to see if a current copy exists on the local server,
10634: # if it does this will be served, otherwise a copy will be retrieved from
10635: # the home server for the course and stored in /home/httpd/html/userfiles on
10636: # the local server.   
10637: 
10638: sub getfile {
10639:     my ($file) = @_;
10640:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
10641:     &repcopy($file);
10642:     return &readfile($file);
10643: }
10644: 
10645: sub repcopy_userfile {
10646:     my ($file)=@_;
10647:     my $londocroot = $perlvar{'lonDocRoot'};
10648:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
10649:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
10650:     my ($cdom,$cnum,$filename) = 
10651: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
10652:     my $uri="/uploaded/$cdom/$cnum/$filename";
10653:     if (-e "$file") {
10654: # we already have a local copy, check it out
10655: 	my @fileinfo = stat($file);
10656: 	my $rtncode;
10657: 	my $info;
10658: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
10659: 	if ($lwpresp ne 'ok') {
10660: # there is no such file anymore, even though we had a local copy
10661: 	    if ($rtncode eq '404') {
10662: 		unlink($file);
10663: 	    }
10664: 	    return -1;
10665: 	}
10666: 	if ($info < $fileinfo[9]) {
10667: # nice, the file we have is up-to-date, just say okay
10668: 	    return 'ok';
10669: 	} else {
10670: # the file is outdated, get rid of it
10671: 	    unlink($file);
10672: 	}
10673:     }
10674: # one way or the other, at this point, we don't have the file
10675: # construct the correct path for the file
10676:     my @parts = ($cdom,$cnum); 
10677:     if ($filename =~ m|^(.+)/[^/]+$|) {
10678: 	push @parts, split(/\//,$1);
10679:     }
10680:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
10681:     foreach my $part (@parts) {
10682: 	$path .= '/'.$part;
10683: 	if (!-e $path) {
10684: 	    mkdir($path,0770);
10685: 	}
10686:     }
10687: # now the path exists for sure
10688: # get a user agent
10689:     my $ua=new LWP::UserAgent;
10690:     my $transferfile=$file.'.in.transfer';
10691: # FIXME: this should flock
10692:     if (-e $transferfile) { return 'ok'; }
10693:     my $request;
10694:     $uri=~s/^\///;
10695:     my $homeserver = &homeserver($cnum,$cdom);
10696:     my $protocol = $protocol{$homeserver};
10697:     $protocol = 'http' if ($protocol ne 'https');
10698:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
10699:     my $response=$ua->request($request,$transferfile);
10700: # did it work?
10701:     if ($response->is_error()) {
10702: 	unlink($transferfile);
10703: 	&logthis("Userfile repcopy failed for $uri");
10704: 	return -1;
10705:     }
10706: # worked, rename the transfer file
10707:     rename($transferfile,$file);
10708:     return 'ok';
10709: }
10710: 
10711: sub tokenwrapper {
10712:     my $uri=shift;
10713:     $uri=~s|^https?\://([^/]+)||;
10714:     $uri=~s|^/||;
10715:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
10716:     my $token=$1;
10717:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
10718:     if ($udom && $uname && $file) {
10719: 	$file=~s|(\?\.*)*$||;
10720:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
10721:         my $homeserver = &homeserver($uname,$udom);
10722:         my $protocol = $protocol{$homeserver};
10723:         $protocol = 'http' if ($protocol ne 'https');
10724:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
10725:                (($uri=~/\?/)?'&':'?').'token='.$token.
10726:                                '&tokenissued='.$perlvar{'lonHostID'};
10727:     } else {
10728:         return '/adm/notfound.html';
10729:     }
10730: }
10731: 
10732: # call with reqtype HEAD: get last modification time
10733: # call with reqtype GET: get the file contents
10734: # Do not call this with reqtype GET for large files! It loads everything into memory
10735: #
10736: sub getuploaded {
10737:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
10738:     $uri=~s/^\///;
10739:     my $homeserver = &homeserver($cnum,$cdom);
10740:     my $protocol = $protocol{$homeserver};
10741:     $protocol = 'http' if ($protocol ne 'https');
10742:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
10743:     my $ua=new LWP::UserAgent;
10744:     my $request=new HTTP::Request($reqtype,$uri);
10745:     my $response=$ua->request($request);
10746:     $$rtncode = $response->code;
10747:     if (! $response->is_success()) {
10748: 	return 'failed';
10749:     }      
10750:     if ($reqtype eq 'HEAD') {
10751: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
10752:     } elsif ($reqtype eq 'GET') {
10753: 	$$info = $response->content;
10754:     }
10755:     return 'ok';
10756: }
10757: 
10758: sub readfile {
10759:     my $file = shift;
10760:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
10761:     my $fh;
10762:     open($fh,"<$file");
10763:     my $a='';
10764:     while (my $line = <$fh>) { $a .= $line; }
10765:     return $a;
10766: }
10767: 
10768: sub filelocation {
10769:     my ($dir,$file) = @_;
10770:     my $location;
10771:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
10772: 
10773:     if ($file =~ m-^/adm/-) {
10774: 	$file=~s-^/adm/wrapper/-/-;
10775: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
10776:     }
10777: 
10778:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
10779:         $location = $file;
10780:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
10781:         my ($udom,$uname,$filename)=
10782:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
10783:         my $home=&homeserver($uname,$udom);
10784:         my $is_me=0;
10785:         my @ids=&current_machine_ids();
10786:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
10787:         if ($is_me) {
10788:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
10789:         } else {
10790:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
10791:   	      $udom.'/'.$uname.'/'.$filename;
10792:         }
10793:     } elsif ($file =~ m-^/adm/-) {
10794: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
10795:     } else {
10796:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
10797:         $file=~s:^/(res|priv)/:/:;
10798:         my $space=$1;
10799:         if ( !( $file =~ m:^/:) ) {
10800:             $location = $dir. '/'.$file;
10801:         } else {
10802:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
10803:         }
10804:     }
10805:     $location=~s://+:/:g; # remove duplicate /
10806:     while ($location=~m{/\.\./}) {
10807: 	if ($location =~ m{/[^/]+/\.\./}) {
10808: 	    $location=~ s{/[^/]+/\.\./}{/}g;
10809: 	} else {
10810: 	    $location=~ s{/\.\./}{/}g;
10811: 	}
10812:     } #remove dir/..
10813:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
10814:     return $location;
10815: }
10816: 
10817: sub hreflocation {
10818:     my ($dir,$file)=@_;
10819:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
10820: 	$file=filelocation($dir,$file);
10821:     } elsif ($file=~m-^/adm/-) {
10822: 	$file=~s-^/adm/wrapper/-/-;
10823: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
10824:     }
10825:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
10826: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
10827:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
10828: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
10829: 	        {/uploaded/$1/$2/}x;
10830:     }
10831:     if ($file=~ m{^/userfiles/}) {
10832: 	$file =~ s{^/userfiles/}{/uploaded/};
10833:     }
10834:     return $file;
10835: }
10836: 
10837: 
10838: 
10839: 
10840: 
10841: sub current_machine_domains {
10842:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
10843: }
10844: 
10845: sub machine_domains {
10846:     my ($hostname) = @_;
10847:     my @domains;
10848:     my %hostname = &all_hostnames();
10849:     while( my($id, $name) = each(%hostname)) {
10850: #	&logthis("-$id-$name-$hostname-");
10851: 	if ($hostname eq $name) {
10852: 	    push(@domains,&host_domain($id));
10853: 	}
10854:     }
10855:     return @domains;
10856: }
10857: 
10858: sub current_machine_ids {
10859:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
10860: }
10861: 
10862: sub machine_ids {
10863:     my ($hostname) = @_;
10864:     $hostname ||= &hostname($perlvar{'lonHostID'});
10865:     my @ids;
10866:     my %name_to_host = &all_names();
10867:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
10868: 	return @{ $name_to_host{$hostname} };
10869:     }
10870:     return;
10871: }
10872: 
10873: sub additional_machine_domains {
10874:     my @domains;
10875:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
10876:     while( my $line = <$fh>) {
10877:         $line =~ s/\s//g;
10878:         push(@domains,$line);
10879:     }
10880:     return @domains;
10881: }
10882: 
10883: sub default_login_domain {
10884:     my $domain = $perlvar{'lonDefDomain'};
10885:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
10886:     foreach my $posdom (&current_machine_domains(),
10887:                         &additional_machine_domains()) {
10888:         if (lc($posdom) eq lc($testdomain)) {
10889:             $domain=$posdom;
10890:             last;
10891:         }
10892:     }
10893:     return $domain;
10894: }
10895: 
10896: # ------------------------------------------------------------- Declutters URLs
10897: 
10898: sub declutter {
10899:     my $thisfn=shift;
10900:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
10901:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
10902:     $thisfn=~s/^\///;
10903:     $thisfn=~s|^adm/wrapper/||;
10904:     $thisfn=~s|^adm/coursedocs/showdoc/||;
10905:     $thisfn=~s/^res\///;
10906:     $thisfn=~s/^priv\///;
10907:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
10908:         $thisfn=~s/\?.+$//;
10909:     }
10910:     return $thisfn;
10911: }
10912: 
10913: # ------------------------------------------------------------- Clutter up URLs
10914: 
10915: sub clutter {
10916:     my $thisfn='/'.&declutter(shift);
10917:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
10918: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
10919:        $thisfn='/res'.$thisfn; 
10920:     }
10921:     if ($thisfn !~m|^/adm|) {
10922: 	if ($thisfn =~ m|^/ext/|) {
10923: 	    $thisfn='/adm/wrapper'.$thisfn;
10924: 	} else {
10925: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
10926: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
10927: 	    if ($embstyle eq 'ssi'
10928: 		|| ($embstyle eq 'hdn')
10929: 		|| ($embstyle eq 'rat')
10930: 		|| ($embstyle eq 'prv')
10931: 		|| ($embstyle eq 'ign')) {
10932: 		#do nothing with these
10933: 	    } elsif (($embstyle eq 'img') 
10934: 		|| ($embstyle eq 'emb')
10935: 		|| ($embstyle eq 'wrp')) {
10936: 		$thisfn='/adm/wrapper'.$thisfn;
10937: 	    } elsif ($embstyle eq 'unk'
10938: 		     && $thisfn!~/\.(sequence|page)$/) {
10939: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
10940: 	    } else {
10941: #		&logthis("Got a blank emb style");
10942: 	    }
10943: 	}
10944:     }
10945:     return $thisfn;
10946: }
10947: 
10948: sub clutter_with_no_wrapper {
10949:     my $uri = &clutter(shift);
10950:     if ($uri =~ m-^/adm/-) {
10951: 	$uri =~ s-^/adm/wrapper/-/-;
10952: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
10953:     }
10954:     return $uri;
10955: }
10956: 
10957: sub freeze_escape {
10958:     my ($value)=@_;
10959:     if (ref($value)) {
10960: 	$value=&nfreeze($value);
10961: 	return '__FROZEN__'.&escape($value);
10962:     }
10963:     return &escape($value);
10964: }
10965: 
10966: 
10967: sub thaw_unescape {
10968:     my ($value)=@_;
10969:     if ($value =~ /^__FROZEN__/) {
10970: 	substr($value,0,10,undef);
10971: 	$value=&unescape($value);
10972: 	return &thaw($value);
10973:     }
10974:     return &unescape($value);
10975: }
10976: 
10977: sub correct_line_ends {
10978:     my ($result)=@_;
10979:     $$result =~s/\r\n/\n/mg;
10980:     $$result =~s/\r/\n/mg;
10981: }
10982: # ================================================================ Main Program
10983: 
10984: sub goodbye {
10985:    &logthis("Starting Shut down");
10986: #not converted to using infrastruture and probably shouldn't be
10987:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
10988: #converted
10989: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
10990:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
10991: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
10992: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
10993: #1.1 only
10994: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
10995: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
10996: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
10997: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
10998:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
10999:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
11000:    &logthis(sprintf("%-20s is %s",'hits',$hits));
11001:    &flushcourselogs();
11002:    &logthis("Shutting down");
11003: }
11004: 
11005: sub get_dns {
11006:     my ($url,$func,$ignore_cache) = @_;
11007:     if (!$ignore_cache) {
11008: 	my ($content,$cached)=
11009: 	    &Apache::lonnet::is_cached_new('dns',$url);
11010: 	if ($cached) {
11011: 	    &$func($content);
11012: 	    return;
11013: 	}
11014:     }
11015: 
11016:     my %alldns;
11017:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11018:     foreach my $dns (<$config>) {
11019: 	next if ($dns !~ /^\^(\S*)/x);
11020:         my $line = $1;
11021:         my ($host,$protocol) = split(/:/,$line);
11022:         if ($protocol ne 'https') {
11023:             $protocol = 'http';
11024:         }
11025: 	$alldns{$host} = $protocol;
11026:     }
11027:     while (%alldns) {
11028: 	my ($dns) = keys(%alldns);
11029: 	my $ua=new LWP::UserAgent;
11030:         $ua->timeout(30);
11031: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
11032: 	my $response=$ua->request($request);
11033:         delete($alldns{$dns});
11034: 	next if ($response->is_error());
11035: 	my @content = split("\n",$response->content);
11036: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
11037: 	&$func(\@content);
11038: 	return;
11039:     }
11040:     close($config);
11041:     my $which = (split('/',$url))[3];
11042:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
11043:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
11044:     my @content = <$config>;
11045:     &$func(\@content);
11046:     return;
11047: }
11048: # ------------------------------------------------------------ Read domain file
11049: {
11050:     my $loaded;
11051:     my %domain;
11052: 
11053:     sub parse_domain_tab {
11054: 	my ($lines) = @_;
11055: 	foreach my $line (@$lines) {
11056: 	    next if ($line =~ /^(\#|\s*$ )/x);
11057: 
11058: 	    chomp($line);
11059: 	    my ($name,@elements) = split(/:/,$line,9);
11060: 	    my %this_domain;
11061: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
11062: 			       'lang_def', 'city', 'longi', 'lati',
11063: 			       'primary') {
11064: 		$this_domain{$field} = shift(@elements);
11065: 	    }
11066: 	    $domain{$name} = \%this_domain;
11067: 	}
11068:     }
11069: 
11070:     sub reset_domain_info {
11071: 	undef($loaded);
11072: 	undef(%domain);
11073:     }
11074: 
11075:     sub load_domain_tab {
11076: 	my ($ignore_cache) = @_;
11077: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
11078: 	my $fh;
11079: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
11080: 	    my @lines = <$fh>;
11081: 	    &parse_domain_tab(\@lines);
11082: 	}
11083: 	close($fh);
11084: 	$loaded = 1;
11085:     }
11086: 
11087:     sub domain {
11088: 	&load_domain_tab() if (!$loaded);
11089: 
11090: 	my ($name,$what) = @_;
11091: 	return if ( !exists($domain{$name}) );
11092: 
11093: 	if (!$what) {
11094: 	    return $domain{$name}{'description'};
11095: 	}
11096: 	return $domain{$name}{$what};
11097:     }
11098: 
11099:     sub domain_info {
11100:         &load_domain_tab() if (!$loaded);
11101:         return %domain;
11102:     }
11103: 
11104: }
11105: 
11106: 
11107: # ------------------------------------------------------------- Read hosts file
11108: {
11109:     my %hostname;
11110:     my %hostdom;
11111:     my %libserv;
11112:     my $loaded;
11113:     my %name_to_host;
11114:     my %internetdom;
11115:     my %LC_dns_serv;
11116: 
11117:     sub parse_hosts_tab {
11118: 	my ($file) = @_;
11119: 	foreach my $configline (@$file) {
11120: 	    next if ($configline =~ /^(\#|\s*$ )/x);
11121:             chomp($configline);
11122: 	    if ($configline =~ /^\^/) {
11123:                 if ($configline =~ /^\^([\w.\-]+)/) {
11124:                     $LC_dns_serv{$1} = 1;
11125:                 }
11126:                 next;
11127:             }
11128: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
11129: 	    $name=~s/\s//g;
11130: 	    if ($id && $domain && $role && $name) {
11131: 		$hostname{$id}=$name;
11132: 		push(@{$name_to_host{$name}}, $id);
11133: 		$hostdom{$id}=$domain;
11134: 		if ($role eq 'library') { $libserv{$id}=$name; }
11135:                 if (defined($protocol)) {
11136:                     if ($protocol eq 'https') {
11137:                         $protocol{$id} = $protocol;
11138:                     } else {
11139:                         $protocol{$id} = 'http'; 
11140:                     }
11141:                 } else {
11142:                     $protocol{$id} = 'http';
11143:                 }
11144:                 if (defined($intdom)) {
11145:                     $internetdom{$id} = $intdom;
11146:                 }
11147: 	    }
11148: 	}
11149:     }
11150:     
11151:     sub reset_hosts_info {
11152: 	&purge_remembered();
11153: 	&reset_domain_info();
11154: 	&reset_hosts_ip_info();
11155: 	undef(%name_to_host);
11156: 	undef(%hostname);
11157: 	undef(%hostdom);
11158: 	undef(%libserv);
11159: 	undef($loaded);
11160:     }
11161: 
11162:     sub load_hosts_tab {
11163: 	my ($ignore_cache) = @_;
11164: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
11165: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11166: 	my @config = <$config>;
11167: 	&parse_hosts_tab(\@config);
11168: 	close($config);
11169: 	$loaded=1;
11170:     }
11171: 
11172:     sub hostname {
11173: 	&load_hosts_tab() if (!$loaded);
11174: 
11175: 	my ($lonid) = @_;
11176: 	return $hostname{$lonid};
11177:     }
11178: 
11179:     sub all_hostnames {
11180: 	&load_hosts_tab() if (!$loaded);
11181: 
11182: 	return %hostname;
11183:     }
11184: 
11185:     sub all_names {
11186: 	&load_hosts_tab() if (!$loaded);
11187: 
11188: 	return %name_to_host;
11189:     }
11190: 
11191:     sub all_host_domain {
11192:         &load_hosts_tab() if (!$loaded);
11193:         return %hostdom;
11194:     }
11195: 
11196:     sub is_library {
11197: 	&load_hosts_tab() if (!$loaded);
11198: 
11199: 	return exists($libserv{$_[0]});
11200:     }
11201: 
11202:     sub all_library {
11203: 	&load_hosts_tab() if (!$loaded);
11204: 
11205: 	return %libserv;
11206:     }
11207: 
11208:     sub unique_library {
11209: 	#2x reverse removes all hostnames that appear more than once
11210:         my %unique = reverse &all_library();
11211:         return reverse %unique;
11212:     }
11213: 
11214:     sub get_servers {
11215: 	&load_hosts_tab() if (!$loaded);
11216: 
11217: 	my ($domain,$type) = @_;
11218: 	my %possible_hosts = ($type eq 'library') ? %libserv
11219: 	                                          : %hostname;
11220: 	my %result;
11221: 	if (ref($domain) eq 'ARRAY') {
11222: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
11223: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
11224: 		    $result{$host} = $hostname;
11225: 		}
11226: 	    }
11227: 	} else {
11228: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
11229: 		if ($hostdom{$host} eq $domain) {
11230: 		    $result{$host} = $hostname;
11231: 		}
11232: 	    }
11233: 	}
11234: 	return %result;
11235:     }
11236: 
11237:     sub get_unique_servers {
11238:         my %unique = reverse &get_servers(@_);
11239: 	return reverse %unique;
11240:     }
11241: 
11242:     sub host_domain {
11243: 	&load_hosts_tab() if (!$loaded);
11244: 
11245: 	my ($lonid) = @_;
11246: 	return $hostdom{$lonid};
11247:     }
11248: 
11249:     sub all_domains {
11250: 	&load_hosts_tab() if (!$loaded);
11251: 
11252: 	my %seen;
11253: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
11254: 	return @uniq;
11255:     }
11256: 
11257:     sub internet_dom {
11258:         &load_hosts_tab() if (!$loaded);
11259: 
11260:         my ($lonid) = @_;
11261:         return $internetdom{$lonid};
11262:     }
11263: 
11264:     sub is_LC_dns {
11265:         &load_hosts_tab() if (!$loaded);
11266: 
11267:         my ($hostname) = @_;
11268:         return exists($LC_dns_serv{$hostname});
11269:     }
11270: 
11271: }
11272: 
11273: { 
11274:     my %iphost;
11275:     my %name_to_ip;
11276:     my %lonid_to_ip;
11277: 
11278:     sub get_hosts_from_ip {
11279: 	my ($ip) = @_;
11280: 	my %iphosts = &get_iphost();
11281: 	if (ref($iphosts{$ip})) {
11282: 	    return @{$iphosts{$ip}};
11283: 	}
11284: 	return;
11285:     }
11286:     
11287:     sub reset_hosts_ip_info {
11288: 	undef(%iphost);
11289: 	undef(%name_to_ip);
11290: 	undef(%lonid_to_ip);
11291:     }
11292: 
11293:     sub get_host_ip {
11294: 	my ($lonid) = @_;
11295: 	if (exists($lonid_to_ip{$lonid})) {
11296: 	    return $lonid_to_ip{$lonid};
11297: 	}
11298: 	my $name=&hostname($lonid);
11299:    	my $ip = gethostbyname($name);
11300: 	return if (!$ip || length($ip) ne 4);
11301: 	$ip=inet_ntoa($ip);
11302: 	$name_to_ip{$name}   = $ip;
11303: 	$lonid_to_ip{$lonid} = $ip;
11304: 	return $ip;
11305:     }
11306:     
11307:     sub get_iphost {
11308: 	my ($ignore_cache) = @_;
11309: 
11310: 	if (!$ignore_cache) {
11311: 	    if (%iphost) {
11312: 		return %iphost;
11313: 	    }
11314: 	    my ($ip_info,$cached)=
11315: 		&Apache::lonnet::is_cached_new('iphost','iphost');
11316: 	    if ($cached) {
11317: 		%iphost      = %{$ip_info->[0]};
11318: 		%name_to_ip  = %{$ip_info->[1]};
11319: 		%lonid_to_ip = %{$ip_info->[2]};
11320: 		return %iphost;
11321: 	    }
11322: 	}
11323: 
11324: 	# get yesterday's info for fallback
11325: 	my %old_name_to_ip;
11326: 	my ($ip_info,$cached)=
11327: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
11328: 	if ($cached) {
11329: 	    %old_name_to_ip = %{$ip_info->[1]};
11330: 	}
11331: 
11332: 	my %name_to_host = &all_names();
11333: 	foreach my $name (keys(%name_to_host)) {
11334: 	    my $ip;
11335: 	    if (!exists($name_to_ip{$name})) {
11336: 		$ip = gethostbyname($name);
11337: 		if (!$ip || length($ip) ne 4) {
11338: 		    if (defined($old_name_to_ip{$name})) {
11339: 			$ip = $old_name_to_ip{$name};
11340: 			&logthis("Can't find $name defaulting to old $ip");
11341: 		    } else {
11342: 			&logthis("Name $name no IP found");
11343: 			next;
11344: 		    }
11345: 		} else {
11346: 		    $ip=inet_ntoa($ip);
11347: 		}
11348: 		$name_to_ip{$name} = $ip;
11349: 	    } else {
11350: 		$ip = $name_to_ip{$name};
11351: 	    }
11352: 	    foreach my $id (@{ $name_to_host{$name} }) {
11353: 		$lonid_to_ip{$id} = $ip;
11354: 	    }
11355: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
11356: 	}
11357: 	&Apache::lonnet::do_cache_new('iphost','iphost',
11358: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
11359: 				      48*60*60);
11360: 
11361: 	return %iphost;
11362:     }
11363: 
11364:     #
11365:     #  Given a DNS returns the loncapa host name for that DNS 
11366:     # 
11367:     sub host_from_dns {
11368:         my ($dns) = @_;
11369:         my @hosts;
11370:         my $ip;
11371: 
11372:         if (exists($name_to_ip{$dns})) {
11373:             $ip = $name_to_ip{$dns};
11374:         }
11375:         if (!$ip) {
11376:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
11377:             if (length($ip) == 4) { 
11378: 	        $ip   = &IO::Socket::inet_ntoa($ip);
11379:             }
11380:         }
11381:         if ($ip) {
11382: 	    @hosts = get_hosts_from_ip($ip);
11383: 	    return $hosts[0];
11384:         }
11385:         return undef;
11386:     }
11387: 
11388:     sub get_internet_names {
11389:         my ($lonid) = @_;
11390:         return if ($lonid eq '');
11391:         my ($idnref,$cached)=
11392:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
11393:         if ($cached) {
11394:             return $idnref;
11395:         }
11396:         my $ip = &get_host_ip($lonid);
11397:         my @hosts = &get_hosts_from_ip($ip);
11398:         my %iphost = &get_iphost();
11399:         my (@idns,%seen);
11400:         foreach my $id (@hosts) {
11401:             my $dom = &host_domain($id);
11402:             my $prim_id = &domain($dom,'primary');
11403:             my $prim_ip = &get_host_ip($prim_id);
11404:             next if ($seen{$prim_ip});
11405:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
11406:                 foreach my $id (@{$iphost{$prim_ip}}) {
11407:                     my $intdom = &internet_dom($id);
11408:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
11409:                         push(@idns,$intdom);
11410:                     }
11411:                 }
11412:             }
11413:             $seen{$prim_ip} = 1;
11414:         }
11415:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
11416:     }
11417: 
11418: }
11419: 
11420: sub all_loncaparevs {
11421:     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);
11422: }
11423: 
11424: BEGIN {
11425: 
11426: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
11427:     unless ($readit) {
11428: {
11429:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
11430:     %perlvar = (%perlvar,%{$configvars});
11431: }
11432: 
11433: 
11434: # ------------------------------------------------------ Read spare server file
11435: {
11436:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
11437: 
11438:     while (my $configline=<$config>) {
11439:        chomp($configline);
11440:        if ($configline) {
11441: 	   my ($host,$type) = split(':',$configline,2);
11442: 	   if (!defined($type) || $type eq '') { $type = 'default' };
11443: 	   push(@{ $spareid{$type} }, $host);
11444:        }
11445:     }
11446:     close($config);
11447: }
11448: # ------------------------------------------------------------ Read permissions
11449: {
11450:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
11451: 
11452:     while (my $configline=<$config>) {
11453: 	chomp($configline);
11454: 	if ($configline) {
11455: 	    my ($role,$perm)=split(/ /,$configline);
11456: 	    if ($perm ne '') { $pr{$role}=$perm; }
11457: 	}
11458:     }
11459:     close($config);
11460: }
11461: 
11462: # -------------------------------------------- Read plain texts for permissions
11463: {
11464:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
11465: 
11466:     while (my $configline=<$config>) {
11467: 	chomp($configline);
11468: 	if ($configline) {
11469: 	    my ($short,@plain)=split(/:/,$configline);
11470:             %{$prp{$short}} = ();
11471: 	    if (@plain > 0) {
11472:                 $prp{$short}{'std'} = $plain[0];
11473:                 for (my $i=1; $i<@plain; $i++) {
11474:                     $prp{$short}{'alt'.$i} = $plain[$i];  
11475:                 }
11476:             }
11477: 	}
11478:     }
11479:     close($config);
11480: }
11481: 
11482: # ---------------------------------------------------------- Read package table
11483: {
11484:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
11485: 
11486:     while (my $configline=<$config>) {
11487: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
11488: 	chomp($configline);
11489: 	my ($short,$plain)=split(/:/,$configline);
11490: 	my ($pack,$name)=split(/\&/,$short);
11491: 	if ($plain ne '') {
11492: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
11493: 	    $packagetab{$short}=$plain; 
11494: 	}
11495:     }
11496:     close($config);
11497: }
11498: 
11499: # ---------------------------------------------------------- Read loncaparev table
11500: {
11501:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
11502:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
11503:             while (my $configline=<$config>) {
11504:                 chomp($configline);
11505:                 my ($hostid,$loncaparev)=split(/:/,$configline);
11506:                 $loncaparevs{$hostid}=$loncaparev;
11507:             }
11508:             close($config);
11509:         }
11510:     }
11511: }
11512: 
11513: # ---------------------------------------------------------- Read serverhostID table
11514: {
11515:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
11516:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
11517:             while (my $configline=<$config>) {
11518:                 chomp($configline);
11519:                 my ($name,$id)=split(/:/,$configline);
11520:                 $serverhomeIDs{$name}=$id;
11521:             }
11522:             close($config);
11523:         }
11524:     }
11525: }
11526: 
11527: {
11528:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
11529:     if (-e $file) {
11530:         my $parser = HTML::LCParser->new($file);
11531:         while (my $token = $parser->get_token()) {
11532:             if ($token->[0] eq 'S') {
11533:                 my $item = $token->[1];
11534:                 my $name = $token->[2]{'name'};
11535:                 my $value = $token->[2]{'value'};
11536:                 if ($item ne '' && $name ne '' && $value ne '') {
11537:                     my $release = $parser->get_text();
11538:                     $release =~ s/(^\s*|\s*$ )//gx;
11539:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
11540:                 }
11541:             }
11542:         }
11543:     }
11544: }
11545: 
11546: # ---------------------------------------------------------- Read managers table
11547: {
11548:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
11549:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
11550:             while (my $configline=<$config>) {
11551:                 chomp($configline);
11552:                 next if ($configline =~ /^\#/);
11553:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
11554:                     $managerstab{$configline} = 1;
11555:                 }
11556:             }
11557:             close($config);
11558:         }
11559:     }
11560: }
11561: 
11562: # ------------- set up temporary directory
11563: {
11564:     $tmpdir = LONCAPA::tempdir();
11565: 
11566: }
11567: 
11568: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
11569: 				'compress_threshold'=> 20_000,
11570:  			        });
11571: 
11572: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
11573: $dumpcount=0;
11574: $locknum=0;
11575: 
11576: &logtouch();
11577: &logthis('<font color="yellow">INFO: Read configuration</font>');
11578: $readit=1;
11579:     {
11580: 	use integer;
11581: 	my $test=(2**32)+1;
11582: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
11583: 	&logthis(" Detected 64bit platform ($_64bit)");
11584:     }
11585: }
11586: }
11587: 
11588: 1;
11589: __END__
11590: 
11591: =pod
11592: 
11593: =head1 NAME
11594: 
11595: Apache::lonnet - Subroutines to ask questions about things in the network.
11596: 
11597: =head1 SYNOPSIS
11598: 
11599: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
11600: 
11601:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
11602: 
11603: Common parameters:
11604: 
11605: =over 4
11606: 
11607: =item *
11608: 
11609: $uname : an internal username (if $cname expecting a course Id specifically)
11610: 
11611: =item *
11612: 
11613: $udom : a domain (if $cdom expecting a course's domain specifically)
11614: 
11615: =item *
11616: 
11617: $symb : a resource instance identifier
11618: 
11619: =item *
11620: 
11621: $namespace : the name of a .db file that contains the data needed or
11622: being set.
11623: 
11624: =back
11625: 
11626: =head1 OVERVIEW
11627: 
11628: lonnet provides subroutines which interact with the
11629: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
11630: about classes, users, and resources.
11631: 
11632: For many of these objects you can also use this to store data about
11633: them or modify them in various ways.
11634: 
11635: =head2 Symbs
11636: 
11637: To identify a specific instance of a resource, LON-CAPA uses symbols
11638: or "symbs"X<symb>. These identifiers are built from the URL of the
11639: map, the resource number of the resource in the map, and the URL of
11640: the resource itself. The latter is somewhat redundant, but might help
11641: if maps change.
11642: 
11643: An example is
11644: 
11645:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
11646: 
11647: The respective map entry is
11648: 
11649:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
11650:   title="Problem 2">
11651:  </resource>
11652: 
11653: Symbs are used by the random number generator, as well as to store and
11654: restore data specific to a certain instance of for example a problem.
11655: 
11656: =head2 Storing And Retrieving Data
11657: 
11658: X<store()>X<cstore()>X<restore()>Three of the most important functions
11659: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
11660: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
11661: is is the non-critical message twin of cstore. These functions are for
11662: handlers to store a perl hash to a user's permanent data space in an
11663: easy manner, and to retrieve it again on another call. It is expected
11664: that a handler would use this once at the beginning to retrieve data,
11665: and then again once at the end to send only the new data back.
11666: 
11667: The data is stored in the user's data directory on the user's
11668: homeserver under the ID of the course.
11669: 
11670: The hash that is returned by restore will have all of the previous
11671: value for all of the elements of the hash.
11672: 
11673: Example:
11674: 
11675:  #creating a hash
11676:  my %hash;
11677:  $hash{'foo'}='bar';
11678: 
11679:  #storing it
11680:  &Apache::lonnet::cstore(\%hash);
11681: 
11682:  #changing a value
11683:  $hash{'foo'}='notbar';
11684: 
11685:  #adding a new value
11686:  $hash{'bar'}='foo';
11687:  &Apache::lonnet::cstore(\%hash);
11688: 
11689:  #retrieving the hash
11690:  my %history=&Apache::lonnet::restore();
11691: 
11692:  #print the hash
11693:  foreach my $key (sort(keys(%history))) {
11694:    print("\%history{$key} = $history{$key}");
11695:  }
11696: 
11697: Will print out:
11698: 
11699:  %history{1:foo} = bar
11700:  %history{1:keys} = foo:timestamp
11701:  %history{1:timestamp} = 990455579
11702:  %history{2:bar} = foo
11703:  %history{2:foo} = notbar
11704:  %history{2:keys} = foo:bar:timestamp
11705:  %history{2:timestamp} = 990455580
11706:  %history{bar} = foo
11707:  %history{foo} = notbar
11708:  %history{timestamp} = 990455580
11709:  %history{version} = 2
11710: 
11711: Note that the special hash entries C<keys>, C<version> and
11712: C<timestamp> were added to the hash. C<version> will be equal to the
11713: total number of versions of the data that have been stored. The
11714: C<timestamp> attribute will be the UNIX time the hash was
11715: stored. C<keys> is available in every historical section to list which
11716: keys were added or changed at a specific historical revision of a
11717: hash.
11718: 
11719: B<Warning>: do not store the hash that restore returns directly. This
11720: will cause a mess since it will restore the historical keys as if the
11721: were new keys. I.E. 1:foo will become 1:1:foo etc.
11722: 
11723: Calling convention:
11724: 
11725:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
11726:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
11727: 
11728: For more detailed information, see lonnet specific documentation.
11729: 
11730: =head1 RETURN MESSAGES
11731: 
11732: =over 4
11733: 
11734: =item * B<con_lost>: unable to contact remote host
11735: 
11736: =item * B<con_delayed>: unable to contact remote host, message will be delivered
11737: when the connection is brought back up
11738: 
11739: =item * B<con_failed>: unable to contact remote host and unable to save message
11740: for later delivery
11741: 
11742: =item * B<error:>: an error a occurred, a description of the error follows the :
11743: 
11744: =item * B<no_such_host>: unable to fund a host associated with the user/domain
11745: that was requested
11746: 
11747: =back
11748: 
11749: =head1 PUBLIC SUBROUTINES
11750: 
11751: =head2 Session Environment Functions
11752: 
11753: =over 4
11754: 
11755: =item * 
11756: X<appenv()>
11757: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
11758: the user envirnoment file, and will be restored for each access this
11759: user makes during this session, also modifies the %env for the current
11760: process. Optional rolesarrayref - if defined contains a reference to an array
11761: of roles which are exempt from the restriction on modifying user.role entries 
11762: in the user's environment.db and in %env.    
11763: 
11764: =item *
11765: X<delenv()>
11766: B<delenv($delthis,$regexp)>: removes all items from the session
11767: environment file that begin with $delthis. If the 
11768: optional second arg - $regexp - is true, $delthis is treated as a 
11769: regular expression, otherwise \Q$delthis\E is used. 
11770: The values are also deleted from the current processes %env.
11771: 
11772: =item * get_env_multiple($name) 
11773: 
11774: gets $name from the %env hash, it seemlessly handles the cases where multiple
11775: values may be defined and end up as an array ref.
11776: 
11777: returns an array of values
11778: 
11779: =back
11780: 
11781: =head2 User Information
11782: 
11783: =over 4
11784: 
11785: =item *
11786: X<queryauthenticate()>
11787: B<queryauthenticate($uname,$udom)>: try to determine user's current 
11788: authentication scheme
11789: 
11790: =item *
11791: X<authenticate()>
11792: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
11793: authenticate user from domain's lib servers (first use the current
11794: one). C<$upass> should be the users password.
11795: $checkdefauth is optional (value is 1 if a check should be made to
11796:    authenticate user using default authentication method, and allow
11797:    account creation if username does not have account in the domain).
11798: $clientcancheckhost is optional (value is 1 if checking whether the
11799:    server can host will occur on the client side in lonauth.pm).   
11800: 
11801: =item *
11802: X<homeserver()>
11803: B<homeserver($uname,$udom)>: find the server which has
11804: the user's directory and files (there must be only one), this caches
11805: the answer, and also caches if there is a borken connection.
11806: 
11807: =item *
11808: X<idget()>
11809: B<idget($udom,@ids)>: find the usernames behind a list of IDs
11810: (IDs are a unique resource in a domain, there must be only 1 ID per
11811: username, and only 1 username per ID in a specific domain) (returns
11812: hash: id=>name,id=>name)
11813: 
11814: =item *
11815: X<idrget()>
11816: B<idrget($udom,@unames)>: find the IDs behind a list of
11817: usernames (returns hash: name=>id,name=>id)
11818: 
11819: =item *
11820: X<idput()>
11821: B<idput($udom,%ids)>: store away a list of names and associated IDs
11822: 
11823: =item *
11824: X<rolesinit()>
11825: B<rolesinit($udom,$username)>: get user privileges.
11826: returns user role, first access and timer interval hashes
11827: 
11828: =item *
11829: X<privileged()>
11830: B<privileged($username,$domain)>: returns a true if user has a
11831: privileged and active role (i.e. su or dc), false otherwise.
11832: 
11833: =item *
11834: X<getsection()>
11835: B<getsection($udom,$uname,$cname)>: finds the section of student in the
11836: course $cname, return section name/number or '' for "not in course"
11837: and '-1' for "no section"
11838: 
11839: =item *
11840: X<userenvironment()>
11841: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
11842: passed in @what from the requested user's environment, returns a hash
11843: 
11844: =item * 
11845: X<userlog_query()>
11846: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
11847: activity.log file. %filters defines filters applied when parsing the
11848: log file. These can be start or end timestamps, or the type of action
11849: - log to look for Login or Logout events, check for Checkin or
11850: Checkout, role for role selection. The response is in the form
11851: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
11852: escaped strings of the action recorded in the activity.log file.
11853: 
11854: =back
11855: 
11856: =head2 User Roles
11857: 
11858: =over 4
11859: 
11860: =item *
11861: 
11862: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
11863:  F: full access
11864:  U,I,K: authentication modes (cxx only)
11865:  '': forbidden
11866:  1: user needs to choose course
11867:  2: browse allowed
11868:  A: passphrase authentication needed
11869: 
11870: =item *
11871: 
11872: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
11873: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
11874: and course level
11875: 
11876: =item *
11877: 
11878: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
11879: (rolesplain.tab); plain text explanation of a user role term.
11880: $type is Course (default) or Community.
11881: If $forcedefault evaluates to true, text returned will be default 
11882: text for $type. Otherwise, if this is a course, the text returned 
11883: will be a custom name for the role (if defined in the course's 
11884: environment).  If no custom name is defined the default is returned.
11885:    
11886: =item *
11887: 
11888: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
11889: All arguments are optional. Returns a hash of a roles, either for
11890: co-author/assistant author roles for a user's Construction Space
11891: (default), or if $context is 'userroles', roles for the user himself,
11892: In the hash, keys are set to colon-separated $uname,$udom,$role, and
11893: (optionally) if $withsec is true, a fourth colon-separated item - $section.
11894: For each key, value is set to colon-separated start and end times for
11895: the role.  If no username and domain are specified, will default to
11896: current user/domain. Types, roles, and roledoms are references to arrays
11897: of role statuses (active, future or previous), roles 
11898: (e.g., cc,in, st etc.) and domains of the roles which can be used
11899: to restrict the list of roles reported. If no array ref is 
11900: provided for types, will default to return only active roles.
11901: 
11902: =back
11903: 
11904: =head2 User Modification
11905: 
11906: =over 4
11907: 
11908: =item *
11909: 
11910: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
11911: user for the level given by URL.  Optional start and end dates (leave empty
11912: string or zero for "no date")
11913: 
11914: =item *
11915: 
11916: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
11917: change a users, password, possible return values are: ok,
11918: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
11919: refused
11920: 
11921: =item *
11922: 
11923: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
11924: 
11925: =item *
11926: 
11927: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
11928:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
11929: 
11930: will update user information (firstname,middlename,lastname,generation,
11931: permanentemail), and if forceid is true, student/employee ID also.
11932: A user's institutional affiliation(s) can also be updated.
11933: User information fields will not be overwritten with empty entries 
11934: unless the field is included in the $candelete array reference.
11935: This array is included when a single user is modified via "Manage Users",
11936: or when Autoupdate.pl is run by cron in a domain.
11937: 
11938: =item *
11939: 
11940: modifystudent
11941: 
11942: modify a student's enrollment and identification information.
11943: The course id is resolved based on the current users environment.  
11944: This means the envoking user must be a course coordinator or otherwise
11945: associated with a course.
11946: 
11947: This call is essentially a wrapper for lonnet::modifyuser and
11948: lonnet::modify_student_enrollment
11949: 
11950: Inputs: 
11951: 
11952: =over 4
11953: 
11954: =item B<$udom> Student's loncapa domain
11955: 
11956: =item B<$uname> Student's loncapa login name
11957: 
11958: =item B<$uid> Student/Employee ID
11959: 
11960: =item B<$umode> Student's authentication mode
11961: 
11962: =item B<$upass> Student's password
11963: 
11964: =item B<$first> Student's first name
11965: 
11966: =item B<$middle> Student's middle name
11967: 
11968: =item B<$last> Student's last name
11969: 
11970: =item B<$gene> Student's generation
11971: 
11972: =item B<$usec> Student's section in course
11973: 
11974: =item B<$end> Unix time of the roles expiration
11975: 
11976: =item B<$start> Unix time of the roles start date
11977: 
11978: =item B<$forceid> If defined, allow $uid to be changed
11979: 
11980: =item B<$desiredhome> server to use as home server for student
11981: 
11982: =item B<$email> Student's permanent e-mail address
11983: 
11984: =item B<$type> Type of enrollment (auto or manual)
11985: 
11986: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
11987: 
11988: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
11989: 
11990: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
11991: 
11992: =item B<$context> role change context (shown in User Management Logs display in a course)
11993: 
11994: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
11995: 
11996: =back
11997: 
11998: =item *
11999: 
12000: modify_student_enrollment
12001: 
12002: Change a students enrollment status in a class.  The environment variable
12003: 'role.request.course' must be defined for this function to proceed.
12004: 
12005: Inputs:
12006: 
12007: =over 4
12008: 
12009: =item $udom, students domain
12010: 
12011: =item $uname, students name
12012: 
12013: =item $uid, students user id
12014: 
12015: =item $first, students first name
12016: 
12017: =item $middle
12018: 
12019: =item $last
12020: 
12021: =item $gene
12022: 
12023: =item $usec
12024: 
12025: =item $end
12026: 
12027: =item $start
12028: 
12029: =item $type
12030: 
12031: =item $locktype
12032: 
12033: =item $cid
12034: 
12035: =item $selfenroll
12036: 
12037: =item $context
12038: 
12039: =back
12040: 
12041: 
12042: =item *
12043: 
12044: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
12045: custom role; give a custom role to a user for the level given by URL.  Specify
12046: name and domain of role author, and role name
12047: 
12048: =item *
12049: 
12050: revokerole($udom,$uname,$url,$role) : revoke a role for url
12051: 
12052: =item *
12053: 
12054: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
12055: 
12056: =back
12057: 
12058: =head2 Course Infomation
12059: 
12060: =over 4
12061: 
12062: =item *
12063: 
12064: coursedescription($courseid,$options) : returns a hash of information about the
12065: specified course id, including all environment settings for the
12066: course, the description of the course will be in the hash under the
12067: key 'description'
12068: 
12069: $options is an optional parameter that if supplied is a hash reference that controls
12070: what how this function works.  It has the following key/values:
12071: 
12072: =over 4
12073: 
12074: =item freshen_cache
12075: 
12076: If defined, and the environment cache for the course is valid, it is 
12077: returned in the returned hash.
12078: 
12079: =item one_time
12080: 
12081: If defined, the last cache time is set to _now_
12082: 
12083: =item user
12084: 
12085: If defined, the supplied username is used instead of the current user.
12086: 
12087: 
12088: =back
12089: 
12090: =item *
12091: 
12092: resdata($name,$domain,$type,@which) : request for current parameter
12093: setting for a specific $type, where $type is either 'course' or 'user',
12094: @what should be a list of parameters to ask about. This routine caches
12095: answers for 5 minutes.
12096: 
12097: =item *
12098: 
12099: get_courseresdata($courseid, $domain) : dump the entire course resource
12100: data base, returning a hash that is keyed by the resource name and has
12101: values that are the resource value.  I believe that the timestamps and
12102: versions are also returned.
12103: 
12104: 
12105: =back
12106: 
12107: =head2 Course Modification
12108: 
12109: =over 4
12110: 
12111: =item *
12112: 
12113: writecoursepref($courseid,%prefs) : write preferences (environment
12114: database) for a course
12115: 
12116: =item *
12117: 
12118: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
12119: 
12120: =item *
12121: 
12122: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
12123: 
12124: =item *
12125: 
12126: is_course($courseid), is_course($cdom, $cnum)
12127: 
12128: Accepts either a combined $courseid (in the form of domain_courseid) or the
12129: two component version $cdom, $cnum. It checks if the specified course exists.
12130: 
12131: Returns:
12132:     undef if the course doesn't exist, otherwise
12133:     in scalar context the combined courseid.
12134:     in list context the two components of the course identifier, domain and 
12135:     courseid.    
12136: 
12137: =back
12138: 
12139: =head2 Resource Subroutines
12140: 
12141: =over 4
12142: 
12143: =item *
12144: 
12145: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
12146: 
12147: =item *
12148: 
12149: repcopy($filename) : subscribes to the requested file, and attempts to
12150: replicate from the owning library server, Might return
12151: 'unavailable', 'not_found', 'forbidden', 'ok', or
12152: 'bad_request', also attempts to grab the metadata for the
12153: resource. Expects the local filesystem pathname
12154: (/home/httpd/html/res/....)
12155: 
12156: =back
12157: 
12158: =head2 Resource Information
12159: 
12160: =over 4
12161: 
12162: =item *
12163: 
12164: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
12165: a vairety of different possible values, $varname should be a request
12166: string, and the other parameters can be used to specify who and what
12167: one is asking about.
12168: 
12169: Possible values for $varname are environment.lastname (or other item
12170: from the envirnment hash), user.name (or someother aspect about the
12171: user), resource.0.maxtries (or some other part and parameter of a
12172: resource)
12173: 
12174: =item *
12175: 
12176: directcondval($number) : get current value of a condition; reads from a state
12177: string
12178: 
12179: =item *
12180: 
12181: condval($condidx) : value of condition index based on state
12182: 
12183: =item *
12184: 
12185: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
12186: resource's metadata, $what should be either a specific key, or either
12187: 'keys' (to get a list of possible keys) or 'packages' to get a list of
12188: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
12189: 
12190: this function automatically caches all requests
12191: 
12192: =item *
12193: 
12194: metadata_query($query,$custom,$customshow) : make a metadata query against the
12195: network of library servers; returns file handle of where SQL and regex results
12196: will be stored for query
12197: 
12198: =item *
12199: 
12200: symbread($filename) : return symbolic list entry (filename argument optional);
12201: returns the data handle
12202: 
12203: =item *
12204: 
12205: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
12206: a possible symb for the URL in $thisfn, and if is an encryypted
12207: resource that the user accessed using /enc/ returns a 1 on success, 0
12208: on failure, user must be in a course, as it assumes the existance of
12209: the course initial hash, and uses $env('request.course.id'}
12210: 
12211: 
12212: =item *
12213: 
12214: symbclean($symb) : removes versions numbers from a symb, returns the
12215: cleaned symb
12216: 
12217: =item *
12218: 
12219: is_on_map($uri) : checks if the $uri is somewhere on the current
12220: course map, user must be in a course for it to work.
12221: 
12222: =item *
12223: 
12224: numval($salt) : return random seed value (addend for rndseed)
12225: 
12226: =item *
12227: 
12228: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
12229: a random seed, all arguments are optional, if they aren't sent it uses the
12230: environment to derive them. Note: if symb isn't sent and it can't get one
12231: from &symbread it will use the current time as its return value
12232: 
12233: =item *
12234: 
12235: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
12236: unfakeable, receipt
12237: 
12238: =item *
12239: 
12240: receipt() : API to ireceipt working off of env values; given out to users
12241: 
12242: =item *
12243: 
12244: countacc($url) : count the number of accesses to a given URL
12245: 
12246: =item *
12247: 
12248: 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
12249: 
12250: =item *
12251: 
12252: 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)
12253: 
12254: =item *
12255: 
12256: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
12257: 
12258: =item *
12259: 
12260: devalidate($symb) : devalidate temporary spreadsheet calculations,
12261: forcing spreadsheet to reevaluate the resource scores next time.
12262: 
12263: =back
12264: 
12265: =head2 Storing/Retreiving Data
12266: 
12267: =over 4
12268: 
12269: =item *
12270: 
12271: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
12272: for this url; hashref needs to be given and should be a \%hashname; the
12273: remaining args aren't required and if they aren't passed or are '' they will
12274: be derived from the env
12275: 
12276: =item *
12277: 
12278: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
12279: uses critical subroutine
12280: 
12281: =item *
12282: 
12283: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
12284: all args are optional
12285: 
12286: =item *
12287: 
12288: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
12289: dumps the complete (or key matching regexp) namespace into a hash
12290: ($udom, $uname, $regexp, $range are optional) for a namespace that is
12291: normally &store()ed into
12292: 
12293: $range should be either an integer '100' (give me the first 100
12294:                                            matching records)
12295:               or be  two integers sperated by a - with no spaces
12296:                  '30-50' (give me the 30th through the 50th matching
12297:                           records)
12298: 
12299: 
12300: =item *
12301: 
12302: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
12303: replaces a &store() version of data with a replacement set of data
12304: for a particular resource in a namespace passed in the $storehash hash 
12305: reference
12306: 
12307: =item *
12308: 
12309: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
12310: works very similar to store/cstore, but all data is stored in a
12311: temporary location and can be reset using tmpreset, $storehash should
12312: be a hash reference, returns nothing on success
12313: 
12314: =item *
12315: 
12316: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
12317: similar to restore, but all data is stored in a temporary location and
12318: can be reset using tmpreset. Returns a hash of values on success,
12319: error string otherwise.
12320: 
12321: =item *
12322: 
12323: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
12324: deltes all keys for $symb form the temporary storage hash.
12325: 
12326: =item *
12327: 
12328: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
12329: reference filled in from namesp ($udom and $uname are optional)
12330: 
12331: =item *
12332: 
12333: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
12334: namesp ($udom and $uname are optional)
12335: 
12336: =item *
12337: 
12338: dump($namespace,$udom,$uname,$regexp,$range) : 
12339: dumps the complete (or key matching regexp) namespace into a hash
12340: ($udom, $uname, $regexp, $range are optional)
12341: 
12342: $range should be either an integer '100' (give me the first 100
12343:                                            matching records)
12344:               or be  two integers sperated by a - with no spaces
12345:                  '30-50' (give me the 30th through the 50th matching
12346:                           records)
12347: =item *
12348: 
12349: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
12350: $store can be a scalar, an array reference, or if the amount to be 
12351: incremented is > 1, a hash reference.
12352: 
12353: ($udom and $uname are optional)
12354: 
12355: =item *
12356: 
12357: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
12358: ($udom and $uname are optional)
12359: 
12360: =item *
12361: 
12362: cput($namespace,$storehash,$udom,$uname) : critical put
12363: ($udom and $uname are optional)
12364: 
12365: =item *
12366: 
12367: newput($namespace,$storehash,$udom,$uname) :
12368: 
12369: Attempts to store the items in the $storehash, but only if they don't
12370: currently exist, if this succeeds you can be certain that you have 
12371: successfully created a new key value pair in the $namespace db.
12372: 
12373: 
12374: Args:
12375:  $namespace: name of database to store values to
12376:  $storehash: hashref to store to the db
12377:  $udom: (optional) domain of user containing the db
12378:  $uname: (optional) name of user caontaining the db
12379: 
12380: Returns:
12381:  'ok' -> succeeded in storing all keys of $storehash
12382:  'key_exists: <key>' -> failed to anything out of $storehash, as at
12383:                         least <key> already existed in the db (other
12384:                         requested keys may also already exist)
12385:  'error: <msg>' -> unable to tie the DB or other error occurred
12386:  'con_lost' -> unable to contact request server
12387:  'refused' -> action was not allowed by remote machine
12388: 
12389: 
12390: =item *
12391: 
12392: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
12393: reference filled in from namesp (encrypts the return communication)
12394: ($udom and $uname are optional)
12395: 
12396: =item *
12397: 
12398: log($udom,$name,$home,$message) : write to permanent log for user; use
12399: critical subroutine
12400: 
12401: =item *
12402: 
12403: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
12404: array reference filled in from namespace found in domain level on either
12405: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
12406: 
12407: =item *
12408: 
12409: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
12410: domain level either on specified domain server ($uhome) or primary domain 
12411: server ($udom and $uhome are optional)
12412: 
12413: =item * 
12414: 
12415: get_domain_defaults($target_domain) : returns hash with defaults for
12416: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
12417: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
12418: or localauth), initial password or a kerberos realm, language (e.g., en-us).
12419: Values are retrieved from cache (if current), or from domain's configuration.db
12420: (if available), or lastly from values in lonTabs/dns_domain,tab, 
12421: or lonTabs/domain.tab. 
12422: 
12423: %domdefaults = &get_auth_defaults($target_domain);
12424: 
12425: =back
12426: 
12427: =head2 Network Status Functions
12428: 
12429: =over 4
12430: 
12431: =item *
12432: 
12433: dirlist() : return directory list based on URI (first arg).
12434: 
12435: Inputs: 1 required, 5 optional.
12436: 
12437: =over
12438: 
12439: =item 
12440: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
12441: 
12442: =item
12443: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
12444: 
12445: =item
12446: $username -  username of user/course to be listed. Extracted from $uri if absent. 
12447: 
12448: =item
12449: $getpropath - boolean: 1 if prepend path using &propath(). 
12450: 
12451: =item
12452: $getuserdir - boolean: 1 if prepend path for "userfiles".
12453: 
12454: =item 
12455: $alternateRoot - path to prepend in place of path from $uri.
12456: 
12457: =back
12458: 
12459: Returns: Array of up to two items.
12460: 
12461: =over
12462: 
12463: a reference to an array of files/subdirectories
12464: 
12465: =over
12466: 
12467: Each element in the array of files/subdirectories is a & separated list of
12468: item name and the result of running stat on the item.  If dirlist was requested
12469: for a file instead of a directory, the item name will be ''. For a directory 
12470: listing, if the item is a metadata file, the element will end &N&M 
12471: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
12472: default copyright set (1).  
12473: 
12474: =back
12475: 
12476: a scalar containing error condition (if encountered).
12477: 
12478: =over
12479: 
12480: =item 
12481: no_host (no homeserver identified for $username:$domain).
12482: 
12483: =item 
12484: no_such_host (server contacted for listing not identified as valid host).
12485: 
12486: =item 
12487: con_lost (connection to remote server failed).
12488: 
12489: =item 
12490: refused (invalid $username:$domain received on lond side).
12491: 
12492: =item 
12493: no_such_dir (directory at specified path on lond side does not exist). 
12494: 
12495: =item 
12496: empty (directory at specified path on lond side is empty).
12497: 
12498: =over
12499: 
12500: This is currently not encountered because the &ls3, &ls2, 
12501: &ls (_handler) routines on the lond side do not filter out
12502: . and .. from a directory listing. 
12503: 
12504: =back
12505: 
12506: =back
12507: 
12508: =back
12509: 
12510: =item *
12511: 
12512: spareserver() : find server with least workload from spare.tab
12513: 
12514: 
12515: =item *
12516: 
12517: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
12518: if there is no corresponding loncapa host.
12519: 
12520: =back
12521: 
12522: 
12523: =head2 Apache Request
12524: 
12525: =over 4
12526: 
12527: =item *
12528: 
12529: ssi($url,%hash) : server side include, does a complete request cycle on url to
12530: localhost, posts hash
12531: 
12532: =back
12533: 
12534: =head2 Data to String to Data
12535: 
12536: =over 4
12537: 
12538: =item *
12539: 
12540: hash2str(%hash) : convert a hash into a string complete with escaping and '='
12541: and '&' separators, supports elements that are arrayrefs and hashrefs
12542: 
12543: =item *
12544: 
12545: hashref2str($hashref) : convert a hashref into a string complete with
12546: escaping and '=' and '&' separators, supports elements that are
12547: arrayrefs and hashrefs
12548: 
12549: =item *
12550: 
12551: arrayref2str($arrayref) : convert an arrayref into a string complete
12552: with escaping and '&' separators, supports elements that are arrayrefs
12553: and hashrefs
12554: 
12555: =item *
12556: 
12557: str2hash($string) : convert string to hash using unescaping and
12558: splitting on '=' and '&', supports elements that are arrayrefs and
12559: hashrefs
12560: 
12561: =item *
12562: 
12563: str2array($string) : convert string to hash using unescaping and
12564: splitting on '&', supports elements that are arrayrefs and hashrefs
12565: 
12566: =back
12567: 
12568: =head2 Logging Routines
12569: 
12570: 
12571: These routines allow one to make log messages in the lonnet.log and
12572: lonnet.perm logfiles.
12573: 
12574: =over 4
12575: 
12576: =item *
12577: 
12578: logtouch() : make sure the logfile, lonnet.log, exists
12579: 
12580: =item *
12581: 
12582: logthis() : append message to the normal lonnet.log file, it gets
12583: preiodically rolled over and deleted.
12584: 
12585: =item *
12586: 
12587: logperm() : append a permanent message to lonnet.perm.log, this log
12588: file never gets deleted by any automated portion of the system, only
12589: messages of critical importance should go in here.
12590: 
12591: 
12592: =back
12593: 
12594: =head2 General File Helper Routines
12595: 
12596: =over 4
12597: 
12598: =item *
12599: 
12600: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
12601: (a) files in /uploaded
12602:   (i) If a local copy of the file exists - 
12603:       compares modification date of local copy with last-modified date for 
12604:       definitive version stored on home server for course. If local copy is 
12605:       stale, requests a new version from the home server and stores it. 
12606:       If the original has been removed from the home server, then local copy 
12607:       is unlinked.
12608:   (ii) If local copy does not exist -
12609:       requests the file from the home server and stores it. 
12610:   
12611:   If $caller is 'uploadrep':  
12612:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
12613:     for request for files originally uploaded via DOCS. 
12614:      - returns 'ok' if fresh local copy now available, -1 otherwise.
12615:   
12616:   Otherwise:
12617:      This indicates a call from the content generation phase of the request.
12618:      -  returns the entire contents of the file or -1.
12619:      
12620: (b) files in /res
12621:    - returns the entire contents of a file or -1; 
12622:    it properly subscribes to and replicates the file if neccessary.
12623: 
12624: 
12625: =item *
12626: 
12627: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
12628:                   reference
12629: 
12630: returns either a stat() list of data about the file or an empty list
12631: if the file doesn't exist or couldn't find out about it (connection
12632: problems or user unknown)
12633: 
12634: =item *
12635: 
12636: filelocation($dir,$file) : returns file system location of a file
12637: based on URI; meant to be "fairly clean" absolute reference, $dir is a
12638: directory that relative $file lookups are to looked in ($dir of /a/dir
12639: and a file of ../bob will become /a/bob)
12640: 
12641: =item *
12642: 
12643: hreflocation($dir,$file) : returns file system location or a URL; same as
12644: filelocation except for hrefs
12645: 
12646: =item *
12647: 
12648: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
12649: 
12650: =back
12651: 
12652: =head2 Usererfile file routines (/uploaded*)
12653: 
12654: =over 4
12655: 
12656: =item *
12657: 
12658: userfileupload(): main rotine for putting a file in a user or course's
12659:                   filespace, arguments are,
12660: 
12661:  formname - required - this is the name of the element in $env where the
12662:            filename, and the contents of the file to create/modifed exist
12663:            the filename is in $env{'form.'.$formname.'.filename'} and the
12664:            contents of the file is located in $env{'form.'.$formname}
12665:  context - if coursedoc, store the file in the course of the active role
12666:              of the current user; 
12667:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
12668:            if 'canceloverwrite': delete file in tmp/overwrites directory
12669:  subdir - required - subdirectory to put the file in under ../userfiles/
12670:          if undefined, it will be placed in "unknown"
12671: 
12672:  (This routine calls clean_filename() to remove any dangerous
12673:  characters from the filename, and then calls finuserfileupload() to
12674:  complete the transaction)
12675: 
12676:  returns either the url of the uploaded file (/uploaded/....) if successful
12677:  and /adm/notfound.html if unsuccessful
12678: 
12679: =item *
12680: 
12681: clean_filename(): routine for cleaing a filename up for storage in
12682:                  userfile space, argument is:
12683: 
12684:  filename - proposed filename
12685: 
12686: returns: the new clean filename
12687: 
12688: =item *
12689: 
12690: finishuserfileupload(): routine that creates and sends the file to
12691: userspace, probably shouldn't be called directly
12692: 
12693:   docuname: username or courseid of destination for the file
12694:   docudom: domain of user/course of destination for the file
12695:   formname: same as for userfileupload()
12696:   fname: filename (including subdirectories) for the file
12697:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
12698:   allfiles: reference to hash used to store objects found by parser
12699:   codebase: reference to hash used for codebases of java objects found by parser
12700:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
12701:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
12702:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
12703:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
12704:   context: if 'overwrite', will move the uploaded file from its temporary location to
12705:             userfiles to facilitate overwriting a previously uploaded file with same name.
12706:   mimetype: reference to scalar to accommodate mime type determined
12707:             from File::MMagic if $parser = parse.
12708: 
12709:  returns either the url of the uploaded file (/uploaded/....) if successful
12710:  and /adm/notfound.html if unsuccessful (or an error message if context 
12711:  was 'overwrite').
12712:  
12713: 
12714: =item *
12715: 
12716: renameuserfile(): renames an existing userfile to a new name
12717: 
12718:   Args:
12719:    docuname: username or courseid of destination for the file
12720:    docudom: domain of user/course of destination for the file
12721:    old: current file name (including any subdirs under userfiles)
12722:    new: desired file name (including any subdirs under userfiles)
12723: 
12724: =item *
12725: 
12726: mkdiruserfile(): creates a directory is a userfiles dir
12727: 
12728:   Args:
12729:    docuname: username or courseid of destination for the file
12730:    docudom: domain of user/course of destination for the file
12731:    dir: dir to create (including any subdirs under userfiles)
12732: 
12733: =item *
12734: 
12735: removeuserfile(): removes a file that exists in userfiles
12736: 
12737:   Args:
12738:    docuname: username or courseid of destination for the file
12739:    docudom: domain of user/course of destination for the file
12740:    fname: filname to delete (including any subdirs under userfiles)
12741: 
12742: =item *
12743: 
12744: removeuploadedurl(): convience function for removeuserfile()
12745: 
12746:   Args:
12747:    url:  a full /uploaded/... url to delete
12748: 
12749: =item * 
12750: 
12751: get_portfile_permissions():
12752:   Args:
12753:     domain: domain of user or course contain the portfolio files
12754:     user: name of user or num of course contain the portfolio files
12755:   Returns:
12756:     hashref of a dump of the proper file_permissions.db
12757:    
12758: 
12759: =item * 
12760: 
12761: get_access_controls():
12762: 
12763: Args:
12764:   current_permissions: the hash ref returned from get_portfile_permissions()
12765:   group: (optional) the group you want the files associated with
12766:   file: (optional) the file you want access info on
12767: 
12768: Returns:
12769:     a hash (keys are file names) of hashes containing
12770:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
12771:         values are XML containing access control settings (see below) 
12772: 
12773: Internal notes:
12774: 
12775:  access controls are stored in file_permissions.db as key=value pairs.
12776:     key -> path to file/file_name\0uniqueID:scope_end_start
12777:         where scope -> public,guest,course,group,domains or users.
12778:               end -> UNIX time for end of access (0 -> no end date)
12779:               start -> UNIX time for start of access
12780: 
12781:     value -> XML description of access control
12782:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
12783:             <start></start>
12784:             <end></end>
12785: 
12786:             <password></password>  for scope type = guest
12787: 
12788:             <domain></domain>     for scope type = course or group
12789:             <number></number>
12790:             <roles id="">
12791:              <role></role>
12792:              <access></access>
12793:              <section></section>
12794:              <group></group>
12795:             </roles>
12796: 
12797:             <dom></dom>         for scope type = domains
12798: 
12799:             <users>             for scope type = users
12800:              <user>
12801:               <uname></uname>
12802:               <udom></udom>
12803:              </user>
12804:             </users>
12805:            </scope> 
12806:               
12807:  Access data is also aggregated for each file in an additional key=value pair:
12808:  key -> path to file/file_name\0accesscontrol 
12809:  value -> reference to hash
12810:           hash contains key = value pairs
12811:           where key = uniqueID:scope_end_start
12812:                 value = UNIX time record was last updated
12813: 
12814:           Used to improve speed of look-ups of access controls for each file.  
12815:  
12816:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
12817: 
12818: modify_access_controls():
12819: 
12820: Modifies access controls for a portfolio file
12821: Args
12822: 1. file name
12823: 2. reference to hash of required changes,
12824: 3. domain
12825: 4. username
12826:   where domain,username are the domain of the portfolio owner 
12827:   (either a user or a course) 
12828: 
12829: Returns:
12830: 1. result of additions or updates ('ok' or 'error', with error message). 
12831: 2. result of deletions ('ok' or 'error', with error message).
12832: 3. reference to hash of any new or updated access controls.
12833: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
12834:    key = integer (inbound ID)
12835:    value = uniqueID  
12836: 
12837: =back
12838: 
12839: =head2 HTTP Helper Routines
12840: 
12841: =over 4
12842: 
12843: =item *
12844: 
12845: escape() : unpack non-word characters into CGI-compatible hex codes
12846: 
12847: =item *
12848: 
12849: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
12850: 
12851: =back
12852: 
12853: =head1 PRIVATE SUBROUTINES
12854: 
12855: =head2 Underlying communication routines (Shouldn't call)
12856: 
12857: =over 4
12858: 
12859: =item *
12860: 
12861: subreply() : tries to pass a message to lonc, returns con_lost if incapable
12862: 
12863: =item *
12864: 
12865: reply() : uses subreply to send a message to remote machine, logs all failures
12866: 
12867: =item *
12868: 
12869: critical() : passes a critical message to another server; if cannot
12870: get through then place message in connection buffer directory and
12871: returns con_delayed, if incapable of saving message, returns
12872: con_failed
12873: 
12874: =item *
12875: 
12876: reconlonc() : tries to reconnect lonc client processes.
12877: 
12878: =back
12879: 
12880: =head2 Resource Access Logging
12881: 
12882: =over 4
12883: 
12884: =item *
12885: 
12886: flushcourselogs() : flush (save) buffer logs and access logs
12887: 
12888: =item *
12889: 
12890: courselog($what) : save message for course in hash
12891: 
12892: =item *
12893: 
12894: courseacclog($what) : save message for course using &courselog().  Perform
12895: special processing for specific resource types (problems, exams, quizzes, etc).
12896: 
12897: =item *
12898: 
12899: goodbye() : flush course logs and log shutting down; it is called in srm.conf
12900: as a PerlChildExitHandler
12901: 
12902: =back
12903: 
12904: =head2 Other
12905: 
12906: =over 4
12907: 
12908: =item *
12909: 
12910: symblist($mapname,%newhash) : update symbolic storage links
12911: 
12912: =back
12913: 
12914: =cut
12915: 

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