File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1077: download - view: text, annotated - select for diffs
Sun Jul 25 02:58:05 2010 UTC (13 years, 11 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Correct subroutine name.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1077 2010/07/25 02:58:05 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: ###
   29: 
   30: =pod
   31: 
   32: =head1 NAME
   33: 
   34: Apache::lonnet.pm
   35: 
   36: =head1 SYNOPSIS
   37: 
   38: This file is an interface to the lonc processes of
   39: the LON-CAPA network as well as set of elaborated functions for handling information
   40: necessary for navigating through a given cluster of LON-CAPA machines within a
   41: domain. There are over 40 specialized functions in this module which handle the
   42: reading and transmission of metadata, user information (ids, names, environments, roles,
   43: logs), file information (storage, reading, directories, extensions, replication, embedded
   44: styles and descriptors), educational resources (course descriptions, section names and
   45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
   46: and from more descriptive phrases or explanations.
   47: 
   48: This is part of the LearningOnline Network with CAPA project
   49: described at http://www.lon-capa.org.
   50: 
   51: =head1 Package Variables
   52: 
   53: These are largely undocumented, so if you decipher one please note it here.
   54: 
   55: =over 4
   56: 
   57: =item $processmarker
   58: 
   59: Contains the time this process was started and this servers host id.
   60: 
   61: =item $dumpcount
   62: 
   63: Counts the number of times a message log flush has been attempted (regardless
   64: of success) by this process.  Used as part of the filename when messages are
   65: delayed.
   66: 
   67: =back
   68: 
   69: =cut
   70: 
   71: package Apache::lonnet;
   72: 
   73: use strict;
   74: use LWP::UserAgent();
   75: use HTTP::Date;
   76: use Image::Magick;
   77: 
   78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
   79:             $_64bit %env %protocol %loncaparevs %serverhomeIDs);
   80: 
   81: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   82:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   83:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   84:     %courseownerbuf, %coursetypebuf,$locknum);
   85: 
   86: use IO::Socket;
   87: use GDBM_File;
   88: use HTML::LCParser;
   89: use Fcntl qw(:flock);
   90: use Storable qw(thaw nfreeze);
   91: use Time::HiRes qw( gettimeofday tv_interval );
   92: use Cache::Memcached;
   93: use Digest::MD5;
   94: use Math::Random;
   95: use File::MMagic;
   96: use LONCAPA qw(:DEFAULT :match);
   97: use LONCAPA::Configuration;
   98: 
   99: my $readit;
  100: my $max_connection_retries = 10;     # Or some such value.
  101: 
  102: require Exporter;
  103: 
  104: our @ISA = qw (Exporter);
  105: our @EXPORT = qw(%env);
  106: 
  107: 
  108: # --------------------------------------------------------------------- Logging
  109: {
  110:     my $logid;
  111:     sub instructor_log {
  112: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  113:         if (($cnum eq '') || ($cdom eq '')) {
  114:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  115:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  116:         }
  117: 	$logid++;
  118:         my $now = time();
  119: 	my $id=$now.'00000'.$$.'00000'.$logid;
  120: 	return &Apache::lonnet::put('nohist_'.$hash_name,
  121: 				    { $id => {
  122: 					'exe_uname' => $env{'user.name'},
  123: 					'exe_udom'  => $env{'user.domain'},
  124: 					'exe_time'  => $now,
  125: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
  126: 					'delflag'   => $delflag,
  127: 					'logentry'  => $storehash,
  128: 					'uname'     => $uname,
  129: 					'udom'      => $udom,
  130: 				    }
  131: 				  },$cdom,$cnum);
  132:     }
  133: }
  134: 
  135: sub logtouch {
  136:     my $execdir=$perlvar{'lonDaemons'};
  137:     unless (-e "$execdir/logs/lonnet.log") {	
  138: 	open(my $fh,">>$execdir/logs/lonnet.log");
  139: 	close $fh;
  140:     }
  141:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  142:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  143: }
  144: 
  145: sub logthis {
  146:     my $message=shift;
  147:     my $execdir=$perlvar{'lonDaemons'};
  148:     my $now=time;
  149:     my $local=localtime($now);
  150:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  151: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
  152: 	print $fh $logstring;
  153: 	close($fh);
  154:     }
  155:     return 1;
  156: }
  157: 
  158: sub logperm {
  159:     my $message=shift;
  160:     my $execdir=$perlvar{'lonDaemons'};
  161:     my $now=time;
  162:     my $local=localtime($now);
  163:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  164: 	print $fh "$now:$message:$local\n";
  165: 	close($fh);
  166:     }
  167:     return 1;
  168: }
  169: 
  170: sub create_connection {
  171:     my ($hostname,$lonid) = @_;
  172:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  173: 				     Type    => SOCK_STREAM,
  174: 				     Timeout => 10);
  175:     return 0 if (!$client);
  176:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  177:     my $result = <$client>;
  178:     chomp($result);
  179:     return 1 if ($result eq 'done');
  180:     return 0;
  181: }
  182: 
  183: sub get_server_timezone {
  184:     my ($cnum,$cdom) = @_;
  185:     my $home=&homeserver($cnum,$cdom);
  186:     if ($home ne 'no_host') {
  187:         my $cachetime = 24*3600;
  188:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  189:         if (defined($cached)) {
  190:             return $timezone;
  191:         } else {
  192:             my $timezone = &reply('servertimezone',$home);
  193:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  194:         }
  195:     }
  196: }
  197: 
  198: sub get_server_loncaparev {
  199:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
  200:     if (defined($lonhost)) {
  201:         if (!defined(&hostname($lonhost))) {
  202:             undef($lonhost);
  203:         }
  204:     }
  205:     if (!defined($lonhost)) {
  206:         if (defined(&domain($dom,'primary'))) {
  207:             $lonhost=&domain($dom,'primary');
  208:             if ($lonhost eq 'no_host') {
  209:                 undef($lonhost);
  210:             }
  211:         }
  212:     }
  213:     if (defined($lonhost)) {
  214:         my $cachetime = 12*3600;
  215:         if (!$ignore_cache) {
  216:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
  217:             if (defined($cached)) {
  218:                 return $loncaparev;
  219:             }
  220:         }
  221:         my ($answer,$loncaparev);
  222:         my @ids=&current_machine_ids();
  223:         if (grep(/^\Q$lonhost\E$/,@ids)) {
  224:             $answer = $perlvar{'lonVersion'};
  225:             if ($answer =~ /^[\'\"]?([\d.\-]+)[\'\"]?$/) {
  226:                 $loncaparev = $1;
  227:             }
  228:         } else {
  229:             $answer = &reply('serverloncaparev',$lonhost);
  230:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
  231:                 if ($caller eq 'loncron') {
  232:                     my $ua=new LWP::UserAgent;
  233:                     $ua->timeout(20);
  234:                     my $protocol = $protocol{$lonhost};
  235:                     $protocol = 'http' if ($protocol ne 'https');
  236:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
  237:                     my $request=new HTTP::Request('GET',$url);
  238:                     my $response=$ua->request($request);
  239:                     unless ($response->is_error()) {
  240:                         my $content = $response->content;
  241:                         if ($content =~ /<p>VERSION\:\s*([\d.\-]+)<\/p>/) {
  242:                             $loncaparev = $1;
  243:                         }
  244:                     }
  245:                 } else {
  246:                     $loncaparev = $loncaparevs{$lonhost};
  247:                 }
  248:             } elsif ($answer =~ /^[\'\"]?([\d.\-]+)[\'\"]?$/) {
  249:                 $loncaparev = $1;
  250:             }
  251:         }
  252:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
  253:     }
  254: }
  255: 
  256: sub get_server_homeID {
  257:     my ($hostname,$ignore_cache,$caller) = @_;
  258:     unless ($ignore_cache) {
  259:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
  260:         if (defined($cached)) {
  261:             return $serverhomeID;
  262:         }
  263:     }
  264:     my $cachetime = 12*3600;
  265:     my $serverhomeID;
  266:     if ($caller eq 'loncron') { 
  267:         my @machine_ids = &machine_ids($hostname);
  268:         foreach my $id (@machine_ids) {
  269:             my $response = &reply('serverhomeID',$id);
  270:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
  271:                 $serverhomeID = $response;
  272:                 last;
  273:             }
  274:         }
  275:         if ($serverhomeID eq '') {
  276:             $serverhomeID = $machine_ids[-1];
  277:         }
  278:     } else {
  279:         $serverhomeID = $serverhomeIDs{$hostname};
  280:     }
  281:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
  282: }
  283: 
  284: # -------------------------------------------------- Non-critical communication
  285: sub subreply {
  286:     my ($cmd,$server)=@_;
  287:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  288:     #
  289:     #  With loncnew process trimming, there's a timing hole between lonc server
  290:     #  process exit and the master server picking up the listen on the AF_UNIX
  291:     #  socket.  In that time interval, a lock file will exist:
  292: 
  293:     my $lockfile=$peerfile.".lock";
  294:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  295: 	sleep(1);
  296:     }
  297:     # At this point, either a loncnew parent is listening or an old lonc
  298:     # or loncnew child is listening so we can connect or everything's dead.
  299:     #
  300:     #   We'll give the connection a few tries before abandoning it.  If
  301:     #   connection is not possible, we'll con_lost back to the client.
  302:     #   
  303:     my $client;
  304:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  305: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  306: 				      Type    => SOCK_STREAM,
  307: 				      Timeout => 10);
  308: 	if ($client) {
  309: 	    last;		# Connected!
  310: 	} else {
  311: 	    &create_connection(&hostname($server),$server);
  312: 	}
  313:         sleep(1);		# Try again later if failed connection.
  314:     }
  315:     my $answer;
  316:     if ($client) {
  317: 	print $client "sethost:$server:$cmd\n";
  318: 	$answer=<$client>;
  319: 	if (!$answer) { $answer="con_lost"; }
  320: 	chomp($answer);
  321:     } else {
  322: 	$answer = 'con_lost';	# Failed connection.
  323:     }
  324:     return $answer;
  325: }
  326: 
  327: sub reply {
  328:     my ($cmd,$server)=@_;
  329:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  330:     my $answer=subreply($cmd,$server);
  331:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  332:        &logthis("<font color=\"blue\">WARNING:".
  333:                 " $cmd to $server returned $answer</font>");
  334:     }
  335:     return $answer;
  336: }
  337: 
  338: # ----------------------------------------------------------- Send USR1 to lonc
  339: 
  340: sub reconlonc {
  341:     my ($lonid) = @_;
  342:     my $hostname = &hostname($lonid);
  343:     if ($lonid) {
  344: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  345: 	if ($hostname && -e $peerfile) {
  346: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  347: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  348: 					     Type    => SOCK_STREAM,
  349: 					     Timeout => 10);
  350: 	    if ($client) {
  351: 		print $client ("reset_retries\n");
  352: 		my $answer=<$client>;
  353: 		#reset just this one.
  354: 	    }
  355: 	}
  356: 	return;
  357:     }
  358: 
  359:     &logthis("Trying to reconnect lonc");
  360:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  361:     if (open(my $fh,"<$loncfile")) {
  362: 	my $loncpid=<$fh>;
  363:         chomp($loncpid);
  364:         if (kill 0 => $loncpid) {
  365: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  366:             kill USR1 => $loncpid;
  367:             sleep 1;
  368:          } else {
  369: 	    &logthis(
  370:                "<font color=\"blue\">WARNING:".
  371:                " lonc at pid $loncpid not responding, giving up</font>");
  372:         }
  373:     } else {
  374: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  375:     }
  376: }
  377: 
  378: # ------------------------------------------------------ Critical communication
  379: 
  380: sub critical {
  381:     my ($cmd,$server)=@_;
  382:     unless (&hostname($server)) {
  383:         &logthis("<font color=\"blue\">WARNING:".
  384:                " Critical message to unknown server ($server)</font>");
  385:         return 'no_such_host';
  386:     }
  387:     my $answer=reply($cmd,$server);
  388:     if ($answer eq 'con_lost') {
  389: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  390: 	my $answer=reply($cmd,$server);
  391:         if ($answer eq 'con_lost') {
  392:             my $now=time;
  393:             my $middlename=$cmd;
  394:             $middlename=substr($middlename,0,16);
  395:             $middlename=~s/\W//g;
  396:             my $dfilename=
  397:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  398:             $dumpcount++;
  399:             {
  400: 		my $dfh;
  401: 		if (open($dfh,">$dfilename")) {
  402: 		    print $dfh "$cmd\n"; 
  403: 		    close($dfh);
  404: 		}
  405:             }
  406:             sleep 2;
  407:             my $wcmd='';
  408:             {
  409: 		my $dfh;
  410: 		if (open($dfh,"<$dfilename")) {
  411: 		    $wcmd=<$dfh>; 
  412: 		    close($dfh);
  413: 		}
  414:             }
  415:             chomp($wcmd);
  416:             if ($wcmd eq $cmd) {
  417: 		&logthis("<font color=\"blue\">WARNING: ".
  418:                          "Connection buffer $dfilename: $cmd</font>");
  419:                 &logperm("D:$server:$cmd");
  420: 	        return 'con_delayed';
  421:             } else {
  422:                 &logthis("<font color=\"red\">CRITICAL:"
  423:                         ." Critical connection failed: $server $cmd</font>");
  424:                 &logperm("F:$server:$cmd");
  425:                 return 'con_failed';
  426:             }
  427:         }
  428:     }
  429:     return $answer;
  430: }
  431: 
  432: # ------------------------------------------- check if return value is an error
  433: 
  434: sub error {
  435:     my ($result) = @_;
  436:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  437: 	if ($2 == 2) { return undef; }
  438: 	return $1;
  439:     }
  440:     return undef;
  441: }
  442: 
  443: sub convert_and_load_session_env {
  444:     my ($lonidsdir,$handle)=@_;
  445:     my @profile;
  446:     {
  447: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  448: 	if (!$opened) {
  449: 	    return 0;
  450: 	}
  451: 	flock($idf,LOCK_SH);
  452: 	@profile=<$idf>;
  453: 	close($idf);
  454:     }
  455:     my %temp_env;
  456:     foreach my $line (@profile) {
  457: 	if ($line !~ m/=/) {
  458: 	    return 0;
  459: 	}
  460: 	chomp($line);
  461: 	my ($envname,$envvalue)=split(/=/,$line,2);
  462: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  463:     }
  464:     unlink("$lonidsdir/$handle.id");
  465:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  466: 	    0640)) {
  467: 	%disk_env = %temp_env;
  468: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  469: 	untie(%disk_env);
  470:     }
  471:     return 1;
  472: }
  473: 
  474: # ------------------------------------------- Transfer profile into environment
  475: my $env_loaded;
  476: sub transfer_profile_to_env {
  477:     my ($lonidsdir,$handle,$force_transfer) = @_;
  478:     if (!$force_transfer && $env_loaded) { return; } 
  479: 
  480:     if (!defined($lonidsdir)) {
  481: 	$lonidsdir = $perlvar{'lonIDsDir'};
  482:     }
  483:     if (!defined($handle)) {
  484:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  485:     }
  486: 
  487:     my $convert;
  488:     {
  489:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  490: 	if (!$opened) {
  491: 	    return;
  492: 	}
  493: 	flock($idf,LOCK_SH);
  494: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  495: 		&GDBM_READER(),0640)) {
  496: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  497: 	    untie(%disk_env);
  498: 	} else {
  499: 	    $convert = 1;
  500: 	}
  501:     }
  502:     if ($convert) {
  503: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  504: 	    &logthis("Failed to load session, or convert session.");
  505: 	}
  506:     }
  507: 
  508:     my %remove;
  509:     while ( my $envname = each(%env) ) {
  510:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  511:             if ($time < time-300) {
  512:                 $remove{$key}++;
  513:             }
  514:         }
  515:     }
  516: 
  517:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  518:     $env_loaded=1;
  519:     foreach my $expired_key (keys(%remove)) {
  520:         &delenv($expired_key);
  521:     }
  522: }
  523: 
  524: # ---------------------------------------------------- Check for valid session 
  525: sub check_for_valid_session {
  526:     my ($r) = @_;
  527:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  528:     my $lonid=$cookies{'lonID'};
  529:     return undef if (!$lonid);
  530: 
  531:     my $handle=&LONCAPA::clean_handle($lonid->value);
  532:     my $lonidsdir=$r->dir_config('lonIDsDir');
  533:     return undef if (!-e "$lonidsdir/$handle.id");
  534: 
  535:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  536:     return undef if (!$opened);
  537: 
  538:     flock($idf,LOCK_SH);
  539:     my %disk_env;
  540:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  541: 	    &GDBM_READER(),0640)) {
  542: 	return undef;	
  543:     }
  544: 
  545:     if (!defined($disk_env{'user.name'})
  546: 	|| !defined($disk_env{'user.domain'})) {
  547: 	return undef;
  548:     }
  549:     return $handle;
  550: }
  551: 
  552: sub timed_flock {
  553:     my ($file,$lock_type) = @_;
  554:     my $failed=0;
  555:     eval {
  556: 	local $SIG{__DIE__}='DEFAULT';
  557: 	local $SIG{ALRM}=sub {
  558: 	    $failed=1;
  559: 	    die("failed lock");
  560: 	};
  561: 	alarm(13);
  562: 	flock($file,$lock_type);
  563: 	alarm(0);
  564:     };
  565:     if ($failed) {
  566: 	return undef;
  567:     } else {
  568: 	return 1;
  569:     }
  570: }
  571: 
  572: # ---------------------------------------------------------- Append Environment
  573: 
  574: sub appenv {
  575:     my ($newenv,$roles) = @_;
  576:     if (ref($newenv) eq 'HASH') {
  577:         foreach my $key (keys(%{$newenv})) {
  578:             my $refused = 0;
  579: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  580:                 $refused = 1;
  581:                 if (ref($roles) eq 'ARRAY') {
  582:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
  583:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  584:                         $refused = 0;
  585:                     }
  586:                 }
  587:             }
  588:             if ($refused) {
  589:                 &logthis("<font color=\"blue\">WARNING: ".
  590:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  591:                          .'</font>');
  592: 	        delete($newenv->{$key});
  593:             } else {
  594:                 $env{$key}=$newenv->{$key};
  595:             }
  596:         }
  597:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  598:         if ($opened
  599: 	    && &timed_flock($env_file,LOCK_EX)
  600: 	    &&
  601: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  602: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  603: 	    while (my ($key,$value) = each(%{$newenv})) {
  604: 	        $disk_env{$key} = $value;
  605: 	    }
  606: 	    untie(%disk_env);
  607:         }
  608:     }
  609:     return 'ok';
  610: }
  611: # ----------------------------------------------------- Delete from Environment
  612: 
  613: sub delenv {
  614:     my ($delthis,$regexp) = @_;
  615:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
  616:         &logthis("<font color=\"blue\">WARNING: ".
  617:                 "Attempt to delete from environment ".$delthis);
  618:         return 'error';
  619:     }
  620:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  621:     if ($opened
  622: 	&& &timed_flock($env_file,LOCK_EX)
  623: 	&&
  624: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  625: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  626: 	foreach my $key (keys(%disk_env)) {
  627: 	    if ($regexp) {
  628:                 if ($key=~/^$delthis/) {
  629:                     delete($env{$key});
  630:                     delete($disk_env{$key});
  631:                 } 
  632:             } else {
  633:                 if ($key=~/^\Q$delthis\E/) {
  634: 		    delete($env{$key});
  635: 		    delete($disk_env{$key});
  636: 	        }
  637:             }
  638: 	}
  639: 	untie(%disk_env);
  640:     }
  641:     return 'ok';
  642: }
  643: 
  644: sub get_env_multiple {
  645:     my ($name) = @_;
  646:     my @values;
  647:     if (defined($env{$name})) {
  648:         # exists is it an array
  649:         if (ref($env{$name})) {
  650:             @values=@{ $env{$name} };
  651:         } else {
  652:             $values[0]=$env{$name};
  653:         }
  654:     }
  655:     return(@values);
  656: }
  657: 
  658: # ------------------------------------------------------------------- Locking
  659: 
  660: sub set_lock {
  661:     my ($text)=@_;
  662:     $locknum++;
  663:     my $id=$$.'-'.$locknum;
  664:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  665:              'session.lock.'.$id => $text});
  666:     return $id;
  667: }
  668: 
  669: sub get_locks {
  670:     my $num=0;
  671:     my %texts=();
  672:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  673:        if ($lock=~/\w/) {
  674:           $num++;
  675:           $texts{$lock}=$env{'session.lock.'.$lock};
  676:        }
  677:    }
  678:    return ($num,%texts);
  679: }
  680: 
  681: sub remove_lock {
  682:     my ($id)=@_;
  683:     my $newlocks='';
  684:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  685:        if (($lock=~/\w/) && ($lock ne $id)) {
  686:           $newlocks.=','.$lock;
  687:        }
  688:     }
  689:     &appenv({'session.locks' => $newlocks});
  690:     &delenv('session.lock.'.$id);
  691: }
  692: 
  693: sub remove_all_locks {
  694:     my $activelocks=$env{'session.locks'};
  695:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  696:        if ($lock=~/\w/) {
  697:           &remove_lock($lock);
  698:        }
  699:     }
  700: }
  701: 
  702: 
  703: # ------------------------------------------ Find out current server userload
  704: sub userload {
  705:     my $numusers=0;
  706:     {
  707: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  708: 	my $filename;
  709: 	my $curtime=time;
  710: 	while ($filename=readdir(LONIDS)) {
  711: 	    next if ($filename eq '.' || $filename eq '..');
  712: 	    next if ($filename =~ /publicuser_\d+\.id/);
  713: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  714: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  715: 	}
  716: 	closedir(LONIDS);
  717:     }
  718:     my $userloadpercent=0;
  719:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  720:     if ($maxuserload) {
  721: 	$userloadpercent=100*$numusers/$maxuserload;
  722:     }
  723:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  724:     return $userloadpercent;
  725: }
  726: 
  727: # ------------------------------ Find server with least workload from spare.tab
  728: 
  729: sub spareserver {
  730:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
  731:     my $spare_server;
  732:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  733:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  734:                                                      :  $userloadpercent;
  735:     
  736:     foreach my $try_server (@{ $spareid{'primary'} }) {
  737: 	($spare_server, $lowest_load) =
  738: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
  739:     }
  740: 
  741:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
  742: 
  743:     if (!$found_server) {
  744: 	foreach my $try_server (@{ $spareid{'default'} }) {
  745: 	    ($spare_server, $lowest_load) =
  746: 		&compare_server_load($try_server, $spare_server, $lowest_load);
  747: 	}
  748:     }
  749: 
  750:     if (!$want_server_name) {
  751:         my $protocol = 'http';
  752:         if ($protocol{$spare_server} eq 'https') {
  753:             $protocol = $protocol{$spare_server};
  754:         }
  755:         if (defined($spare_server)) {
  756:             my $hostname = &hostname($spare_server);
  757:             if (defined($hostname)) {  
  758: 	        $spare_server = $protocol.'://'.$hostname;
  759:             }
  760:         }
  761:     }
  762:     return $spare_server;
  763: }
  764: 
  765: sub compare_server_load {
  766:     my ($try_server, $spare_server, $lowest_load) = @_;
  767: 
  768:     my $loadans     = &reply('load',    $try_server);
  769:     my $userloadans = &reply('userload',$try_server);
  770: 
  771:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  772: 	return; #didn't get a number from the server
  773:     }
  774: 
  775:     my $load;
  776:     if ($loadans =~ /\d/) {
  777: 	if ($userloadans =~ /\d/) {
  778: 	    #both are numbers, pick the bigger one
  779: 	    $load = ($loadans > $userloadans) ? $loadans 
  780: 		                              : $userloadans;
  781: 	} else {
  782: 	    $load = $loadans;
  783: 	}
  784:     } else {
  785: 	$load = $userloadans;
  786:     }
  787: 
  788:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  789: 	$spare_server = $try_server;
  790: 	$lowest_load  = $load;
  791:     }
  792:     return ($spare_server,$lowest_load);
  793: }
  794: 
  795: # --------------------------- ask offload servers if user already has a session
  796: sub find_existing_session {
  797:     my ($udom,$uname) = @_;
  798:     foreach my $try_server (@{ $spareid{'primary'} },
  799: 			    @{ $spareid{'default'} }) {
  800: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
  801:     }
  802:     return;
  803: }
  804: 
  805: # -------------------------------- ask if server already has a session for user
  806: sub has_user_session {
  807:     my ($lonid,$udom,$uname) = @_;
  808:     my $result = &reply(join(':','userhassession',
  809: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  810:     return 1 if ($result eq 'ok');
  811: 
  812:     return 0;
  813: }
  814: 
  815: # --------- determine least loaded server in a user's domain which allows login
  816: 
  817: sub choose_server {
  818:     my ($udom) = @_;
  819:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
  820:     my %servers = &get_servers($udom);
  821:     my $lowest_load = 30000;
  822:     my ($login_host,$hostname);
  823:     foreach my $lonhost (keys(%servers)) {
  824:         my $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
  825:         if ($loginvia eq '') {
  826:             ($login_host, $lowest_load) =
  827:             &compare_server_load($lonhost, $login_host, $lowest_load);
  828:         }
  829:     }
  830:     if ($login_host ne '') {
  831:         $hostname = $servers{$login_host};
  832:     }
  833:     return ($login_host,$hostname);
  834: }
  835: 
  836: # --------------------------------------------- Try to change a user's password
  837: 
  838: sub changepass {
  839:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  840:     $currentpass = &escape($currentpass);
  841:     $newpass     = &escape($newpass);
  842:     my $lonhost = $perlvar{'lonHostID'};
  843:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
  844: 		       $server);
  845:     if (! $answer) {
  846: 	&logthis("No reply on password change request to $server ".
  847: 		 "by $uname in domain $udom.");
  848:     } elsif ($answer =~ "^ok") {
  849:         &logthis("$uname in $udom successfully changed their password ".
  850: 		 "on $server.");
  851:     } elsif ($answer =~ "^pwchange_failure") {
  852: 	&logthis("$uname in $udom was unable to change their password ".
  853: 		 "on $server.  The action was blocked by either lcpasswd ".
  854: 		 "or pwchange");
  855:     } elsif ($answer =~ "^non_authorized") {
  856:         &logthis("$uname in $udom did not get their password correct when ".
  857: 		 "attempting to change it on $server.");
  858:     } elsif ($answer =~ "^auth_mode_error") {
  859:         &logthis("$uname in $udom attempted to change their password despite ".
  860: 		 "not being locally or internally authenticated on $server.");
  861:     } elsif ($answer =~ "^unknown_user") {
  862:         &logthis("$uname in $udom attempted to change their password ".
  863: 		 "on $server but were unable to because $server is not ".
  864: 		 "their home server.");
  865:     } elsif ($answer =~ "^refused") {
  866: 	&logthis("$server refused to change $uname in $udom password because ".
  867: 		 "it was sent an unencrypted request to change the password.");
  868:     } elsif ($answer =~ "invalid_client") {
  869:         &logthis("$server refused to change $uname in $udom password because ".
  870:                  "it was a reset by e-mail originating from an invalid server.");
  871:     }
  872:     return $answer;
  873: }
  874: 
  875: # ----------------------- Try to determine user's current authentication scheme
  876: 
  877: sub queryauthenticate {
  878:     my ($uname,$udom)=@_;
  879:     my $uhome=&homeserver($uname,$udom);
  880:     if (!$uhome) {
  881: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
  882: 	return 'no_host';
  883:     }
  884:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
  885:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
  886: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  887:     }
  888:     return $answer;
  889: }
  890: 
  891: # --------- Try to authenticate user from domain's lib servers (first this one)
  892: 
  893: sub authenticate {
  894:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
  895:     $upass=&escape($upass);
  896:     $uname= &LONCAPA::clean_username($uname);
  897:     my $uhome=&homeserver($uname,$udom,1);
  898:     my $newhome;
  899:     if ((!$uhome) || ($uhome eq 'no_host')) {
  900: # Maybe the machine was offline and only re-appeared again recently?
  901:         &reconlonc();
  902: # One more
  903: 	$uhome=&homeserver($uname,$udom,1);
  904:         if (($uhome eq 'no_host') && $checkdefauth) {
  905:             if (defined(&domain($udom,'primary'))) {
  906:                 $newhome=&domain($udom,'primary');
  907:             }
  908:             if ($newhome ne '') {
  909:                 $uhome = $newhome;
  910:             }
  911:         }
  912: 	if ((!$uhome) || ($uhome eq 'no_host')) {
  913: 	    &logthis("User $uname at $udom is unknown in authenticate");
  914: 	    return 'no_host';
  915:         }
  916:     }
  917:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
  918:     if ($answer eq 'authorized') {
  919:         if ($newhome) {
  920:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
  921:             return 'no_account_on_host'; 
  922:         } else {
  923:             &logthis("User $uname at $udom authorized by $uhome");
  924:             return $uhome;
  925:         }
  926:     }
  927:     if ($answer eq 'non_authorized') {
  928: 	&logthis("User $uname at $udom rejected by $uhome");
  929: 	return 'no_host'; 
  930:     }
  931:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  932:     return 'no_host';
  933: }
  934: 
  935: sub can_host_session {
  936:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
  937:     my $canhost = 1;
  938:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
  939:     if (ref($remotesessions) eq 'HASH') {
  940:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
  941:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
  942:                 $canhost = 0;
  943:             } else {
  944:                 $canhost = 1;
  945:             }
  946:         }
  947:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
  948:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
  949:                 $canhost = 1;
  950:             } else {
  951:                 $canhost = 0;
  952:             }
  953:         }
  954:         if ($canhost) {
  955:             if ($remotesessions->{'version'} ne '') {
  956:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
  957:                 if ($reqmajor ne '' && $reqminor ne '') {
  958:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
  959:                         my $major = $1;
  960:                         my $minor = $2;
  961:                         if (($major < $reqmajor ) ||
  962:                             (($major == $reqmajor) && ($minor < $reqminor))) {
  963:                             $canhost = 0;
  964:                         }
  965:                     } else {
  966:                         $canhost = 0;
  967:                     }
  968:                 }
  969:             }
  970:         }
  971:     }
  972:     if ($canhost) {
  973:         if (ref($hostedsessions) eq 'HASH') {
  974:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
  975:                 if (grep(/^\Q$udom\E$/,@{$hostedsessions->{'excludedomain'}})) {
  976:                     $canhost = 0;
  977:                 } else {
  978:                     $canhost = 1;
  979:                 }
  980:             }
  981:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
  982:                 if (grep(/^\Q$udom\E$/,@{$hostedsessions->{'includedomain'}})) {
  983:                     $canhost = 1;
  984:                 } else {
  985:                     $canhost = 0;
  986:                 }
  987:             }
  988:         }
  989:     }
  990:     return $canhost;
  991: }
  992: 
  993: # ---------------------- Find the homebase for a user from domain's lib servers
  994: 
  995: my %homecache;
  996: sub homeserver {
  997:     my ($uname,$udom,$ignoreBadCache)=@_;
  998:     my $index="$uname:$udom";
  999: 
 1000:     if (exists($homecache{$index})) { return $homecache{$index}; }
 1001: 
 1002:     my %servers = &get_servers($udom,'library');
 1003:     foreach my $tryserver (keys(%servers)) {
 1004:         next if ($ignoreBadCache ne 'true' && 
 1005: 		 exists($badServerCache{$tryserver}));
 1006: 
 1007: 	my $answer=reply("home:$udom:$uname",$tryserver);
 1008: 	if ($answer eq 'found') {
 1009: 	    delete($badServerCache{$tryserver}); 
 1010: 	    return $homecache{$index}=$tryserver;
 1011: 	} elsif ($answer eq 'no_host') {
 1012: 	    $badServerCache{$tryserver}=1;
 1013: 	}
 1014:     }    
 1015:     return 'no_host';
 1016: }
 1017: 
 1018: # ------------------------------------- Find the usernames behind a list of IDs
 1019: 
 1020: sub idget {
 1021:     my ($udom,@ids)=@_;
 1022:     my %returnhash=();
 1023:     
 1024:     my %servers = &get_servers($udom,'library');
 1025:     foreach my $tryserver (keys(%servers)) {
 1026: 	my $idlist=join('&',@ids);
 1027: 	$idlist=~tr/A-Z/a-z/; 
 1028: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
 1029: 	my @answer=();
 1030: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
 1031: 	    @answer=split(/\&/,$reply);
 1032: 	}                    ;
 1033: 	my $i;
 1034: 	for ($i=0;$i<=$#ids;$i++) {
 1035: 	    if ($answer[$i]) {
 1036: 		$returnhash{$ids[$i]}=$answer[$i];
 1037: 	    } 
 1038: 	}
 1039:     } 
 1040:     return %returnhash;
 1041: }
 1042: 
 1043: # ------------------------------------- Find the IDs behind a list of usernames
 1044: 
 1045: sub idrget {
 1046:     my ($udom,@unames)=@_;
 1047:     my %returnhash=();
 1048:     foreach my $uname (@unames) {
 1049:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
 1050:     }
 1051:     return %returnhash;
 1052: }
 1053: 
 1054: # ------------------------------- Store away a list of names and associated IDs
 1055: 
 1056: sub idput {
 1057:     my ($udom,%ids)=@_;
 1058:     my %servers=();
 1059:     foreach my $uname (keys(%ids)) {
 1060: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
 1061:         my $uhom=&homeserver($uname,$udom);
 1062:         if ($uhom ne 'no_host') {
 1063:             my $id=&escape($ids{$uname});
 1064:             $id=~tr/A-Z/a-z/;
 1065:             my $esc_unam=&escape($uname);
 1066: 	    if ($servers{$uhom}) {
 1067: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
 1068:             } else {
 1069:                 $servers{$uhom}=$id.'='.$esc_unam;
 1070:             }
 1071:         }
 1072:     }
 1073:     foreach my $server (keys(%servers)) {
 1074:         &critical('idput:'.$udom.':'.$servers{$server},$server);
 1075:     }
 1076: }
 1077: 
 1078: # ------------------------------dump from db file owned by domainconfig user
 1079: sub dump_dom {
 1080:     my ($namespace,$udom,$regexp,$range)=@_;
 1081:     if (!$udom) {
 1082:         $udom=$env{'user.domain'};
 1083:     }
 1084:     my %returnhash;
 1085:     if ($udom) {
 1086:         my $uname = &get_domainconfiguser($udom);
 1087:         %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
 1088:     }
 1089:     return %returnhash;
 1090: }
 1091: 
 1092: # ------------------------------------------ get items from domain db files   
 1093: 
 1094: sub get_dom {
 1095:     my ($namespace,$storearr,$udom,$uhome)=@_;
 1096:     my $items='';
 1097:     foreach my $item (@$storearr) {
 1098:         $items.=&escape($item).'&';
 1099:     }
 1100:     $items=~s/\&$//;
 1101:     if (!$udom) {
 1102:         $udom=$env{'user.domain'};
 1103:         if (defined(&domain($udom,'primary'))) {
 1104:             $uhome=&domain($udom,'primary');
 1105:         } else {
 1106:             undef($uhome);
 1107:         }
 1108:     } else {
 1109:         if (!$uhome) {
 1110:             if (defined(&domain($udom,'primary'))) {
 1111:                 $uhome=&domain($udom,'primary');
 1112:             }
 1113:         }
 1114:     }
 1115:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1116:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
 1117:         my %returnhash;
 1118:         if ($rep eq '' || $rep =~ /^error: 2 /) {
 1119:             return %returnhash;
 1120:         }
 1121:         my @pairs=split(/\&/,$rep);
 1122:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 1123:             return @pairs;
 1124:         }
 1125:         my $i=0;
 1126:         foreach my $item (@$storearr) {
 1127:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
 1128:             $i++;
 1129:         }
 1130:         return %returnhash;
 1131:     } else {
 1132:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
 1133:     }
 1134: }
 1135: 
 1136: # -------------------------------------------- put items in domain db files 
 1137: 
 1138: sub put_dom {
 1139:     my ($namespace,$storehash,$udom,$uhome)=@_;
 1140:     if (!$udom) {
 1141:         $udom=$env{'user.domain'};
 1142:         if (defined(&domain($udom,'primary'))) {
 1143:             $uhome=&domain($udom,'primary');
 1144:         } else {
 1145:             undef($uhome);
 1146:         }
 1147:     } else {
 1148:         if (!$uhome) {
 1149:             if (defined(&domain($udom,'primary'))) {
 1150:                 $uhome=&domain($udom,'primary');
 1151:             }
 1152:         }
 1153:     } 
 1154:     if ($udom && $uhome && ($uhome ne 'no_host')) {
 1155:         my $items='';
 1156:         foreach my $item (keys(%$storehash)) {
 1157:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 1158:         }
 1159:         $items=~s/\&$//;
 1160:         return &reply("putdom:$udom:$namespace:$items",$uhome);
 1161:     } else {
 1162:         &logthis("put_dom failed - no homeserver and/or domain");
 1163:     }
 1164: }
 1165: 
 1166: # --------------------- newput for items in db file owned by domainconfig user
 1167: sub newput_dom {
 1168:     my ($namespace,$storehash,$udom) = @_;
 1169:     my $result;
 1170:     if (!$udom) {
 1171:         $udom=$env{'user.domain'};
 1172:     }
 1173:     if ($udom) {
 1174:         my $uname = &get_domainconfiguser($udom);
 1175:         $result = &newput($namespace,$storehash,$udom,$uname);
 1176:     }
 1177:     return $result;
 1178: }
 1179: 
 1180: # --------------------- delete for items in db file owned by domainconfig user
 1181: sub del_dom {
 1182:     my ($namespace,$storearr,$udom)=@_;
 1183:     if (ref($storearr) eq 'ARRAY') {
 1184:         if (!$udom) {
 1185:             $udom=$env{'user.domain'};
 1186:         }
 1187:         if ($udom) {
 1188:             my $uname = &get_domainconfiguser($udom); 
 1189:             return &del($namespace,$storearr,$udom,$uname);
 1190:         }
 1191:     }
 1192: }
 1193: 
 1194: # ----------------------------------construct domainconfig user for a domain 
 1195: sub get_domainconfiguser {
 1196:     my ($udom) = @_;
 1197:     return $udom.'-domainconfig';
 1198: }
 1199: 
 1200: sub retrieve_inst_usertypes {
 1201:     my ($udom) = @_;
 1202:     my (%returnhash,@order);
 1203:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
 1204:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
 1205:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
 1206:         %returnhash = %{$domdefs{'inststatustypes'}};
 1207:         @order = @{$domdefs{'inststatusorder'}};
 1208:     } else {
 1209:         if (defined(&domain($udom,'primary'))) {
 1210:             my $uhome=&domain($udom,'primary');
 1211:             my $rep=&reply("inst_usertypes:$udom",$uhome);
 1212:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 1213:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
 1214:                 return (\%returnhash,\@order);
 1215:             }
 1216:             my ($hashitems,$orderitems) = split(/:/,$rep); 
 1217:             my @pairs=split(/\&/,$hashitems);
 1218:             foreach my $item (@pairs) {
 1219:                 my ($key,$value)=split(/=/,$item,2);
 1220:                 $key = &unescape($key);
 1221:                 next if ($key =~ /^error: 2 /);
 1222:                 $returnhash{$key}=&thaw_unescape($value);
 1223:             }
 1224:             my @esc_order = split(/\&/,$orderitems);
 1225:             foreach my $item (@esc_order) {
 1226:                 push(@order,&unescape($item));
 1227:             }
 1228:         } else {
 1229:             &logthis("get_dom failed - no primary domain server for $udom");
 1230:         }
 1231:     }
 1232:     return (\%returnhash,\@order);
 1233: }
 1234: 
 1235: sub is_domainimage {
 1236:     my ($url) = @_;
 1237:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1238:         if (&domain($1) ne '') {
 1239:             return '1';
 1240:         }
 1241:     }
 1242:     return;
 1243: }
 1244: 
 1245: sub inst_directory_query {
 1246:     my ($srch) = @_;
 1247:     my $udom = $srch->{'srchdomain'};
 1248:     my %results;
 1249:     my $homeserver = &domain($udom,'primary');
 1250:     my $outcome;
 1251:     if ($homeserver ne '') {
 1252: 	my $queryid=&reply("querysend:instdirsearch:".
 1253: 			   &escape($srch->{'srchby'}).':'.
 1254: 			   &escape($srch->{'srchterm'}).':'.
 1255: 			   &escape($srch->{'srchtype'}),$homeserver);
 1256: 	my $host=&hostname($homeserver);
 1257: 	if ($queryid !~/^\Q$host\E\_/) {
 1258: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1259: 	    return;
 1260: 	}
 1261: 	my $response = &get_query_reply($queryid);
 1262: 	my $maxtries = 5;
 1263: 	my $tries = 1;
 1264: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1265: 	    $response = &get_query_reply($queryid);
 1266: 	    $tries ++;
 1267: 	}
 1268: 
 1269:         if (!&error($response) && $response ne 'refused') {
 1270:             if ($response eq 'unavailable') {
 1271:                 $outcome = $response;
 1272:             } else {
 1273:                 $outcome = 'ok';
 1274:                 my @matches = split(/\n/,$response);
 1275:                 foreach my $match (@matches) {
 1276:                     my ($key,$value) = split(/=/,$match);
 1277:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1278:                 }
 1279:             }
 1280:         }
 1281:     }
 1282:     return ($outcome,%results);
 1283: }
 1284: 
 1285: sub usersearch {
 1286:     my ($srch) = @_;
 1287:     my $dom = $srch->{'srchdomain'};
 1288:     my %results;
 1289:     my %libserv = &all_library();
 1290:     my $query = 'usersearch';
 1291:     foreach my $tryserver (keys(%libserv)) {
 1292:         if (&host_domain($tryserver) eq $dom) {
 1293:             my $host=&hostname($tryserver);
 1294:             my $queryid=
 1295:                 &reply("querysend:".&escape($query).':'.
 1296:                        &escape($srch->{'srchby'}).':'.
 1297:                        &escape($srch->{'srchtype'}).':'.
 1298:                        &escape($srch->{'srchterm'}),$tryserver);
 1299:             if ($queryid !~/^\Q$host\E\_/) {
 1300:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1301:                 next;
 1302:             }
 1303:             my $reply = &get_query_reply($queryid);
 1304:             my $maxtries = 1;
 1305:             my $tries = 1;
 1306:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1307:                 $reply = &get_query_reply($queryid);
 1308:                 $tries ++;
 1309:             }
 1310:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1311:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1312:             } else {
 1313:                 my @matches;
 1314:                 if ($reply =~ /\n/) {
 1315:                     @matches = split(/\n/,$reply);
 1316:                 } else {
 1317:                     @matches = split(/\&/,$reply);
 1318:                 }
 1319:                 foreach my $match (@matches) {
 1320:                     my ($uname,$udom,%userhash);
 1321:                     foreach my $entry (split(/:/,$match)) {
 1322:                         my ($key,$value) =
 1323:                             map {&unescape($_);} split(/=/,$entry);
 1324:                         $userhash{$key} = $value;
 1325:                         if ($key eq 'username') {
 1326:                             $uname = $value;
 1327:                         } elsif ($key eq 'domain') {
 1328:                             $udom = $value;
 1329:                         }
 1330:                     }
 1331:                     $results{$uname.':'.$udom} = \%userhash;
 1332:                 }
 1333:             }
 1334:         }
 1335:     }
 1336:     return %results;
 1337: }
 1338: 
 1339: sub get_instuser {
 1340:     my ($udom,$uname,$id) = @_;
 1341:     my $homeserver = &domain($udom,'primary');
 1342:     my ($outcome,%results);
 1343:     if ($homeserver ne '') {
 1344:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1345:                            &escape($id).':'.&escape($udom),$homeserver);
 1346:         my $host=&hostname($homeserver);
 1347:         if ($queryid !~/^\Q$host\E\_/) {
 1348:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1349:             return;
 1350:         }
 1351:         my $response = &get_query_reply($queryid);
 1352:         my $maxtries = 5;
 1353:         my $tries = 1;
 1354:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1355:             $response = &get_query_reply($queryid);
 1356:             $tries ++;
 1357:         }
 1358:         if (!&error($response) && $response ne 'refused') {
 1359:             if ($response eq 'unavailable') {
 1360:                 $outcome = $response;
 1361:             } else {
 1362:                 $outcome = 'ok';
 1363:                 my @matches = split(/\n/,$response);
 1364:                 foreach my $match (@matches) {
 1365:                     my ($key,$value) = split(/=/,$match);
 1366:                     $results{&unescape($key)} = &thaw_unescape($value);
 1367:                 }
 1368:             }
 1369:         }
 1370:     }
 1371:     my %userinfo;
 1372:     if (ref($results{$uname}) eq 'HASH') {
 1373:         %userinfo = %{$results{$uname}};
 1374:     } 
 1375:     return ($outcome,%userinfo);
 1376: }
 1377: 
 1378: sub inst_rulecheck {
 1379:     my ($udom,$uname,$id,$item,$rules) = @_;
 1380:     my %returnhash;
 1381:     if ($udom ne '') {
 1382:         if (ref($rules) eq 'ARRAY') {
 1383:             @{$rules} = map {&escape($_);} (@{$rules});
 1384:             my $rulestr = join(':',@{$rules});
 1385:             my $homeserver=&domain($udom,'primary');
 1386:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1387:                 my $response;
 1388:                 if ($item eq 'username') {                
 1389:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1390:                                               ':'.&escape($uname).':'.$rulestr,
 1391:                                               $homeserver));
 1392:                 } elsif ($item eq 'id') {
 1393:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1394:                                               ':'.&escape($id).':'.$rulestr,
 1395:                                               $homeserver));
 1396:                 } elsif ($item eq 'selfcreate') {
 1397:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1398:                                                &escape($udom).':'.&escape($uname).
 1399:                                               ':'.$rulestr,$homeserver));
 1400:                 }
 1401:                 if ($response ne 'refused') {
 1402:                     my @pairs=split(/\&/,$response);
 1403:                     foreach my $item (@pairs) {
 1404:                         my ($key,$value)=split(/=/,$item,2);
 1405:                         $key = &unescape($key);
 1406:                         next if ($key =~ /^error: 2 /);
 1407:                         $returnhash{$key}=&thaw_unescape($value);
 1408:                     }
 1409:                 }
 1410:             }
 1411:         }
 1412:     }
 1413:     return %returnhash;
 1414: }
 1415: 
 1416: sub inst_userrules {
 1417:     my ($udom,$check) = @_;
 1418:     my (%ruleshash,@ruleorder);
 1419:     if ($udom ne '') {
 1420:         my $homeserver=&domain($udom,'primary');
 1421:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1422:             my $response;
 1423:             if ($check eq 'id') {
 1424:                 $response=&reply('instidrules:'.&escape($udom),
 1425:                                  $homeserver);
 1426:             } elsif ($check eq 'email') {
 1427:                 $response=&reply('instemailrules:'.&escape($udom),
 1428:                                  $homeserver);
 1429:             } else {
 1430:                 $response=&reply('instuserrules:'.&escape($udom),
 1431:                                  $homeserver);
 1432:             }
 1433:             if (($response ne 'refused') && ($response ne 'error') && 
 1434:                 ($response ne 'unknown_cmd') && 
 1435:                 ($response ne 'no_such_host')) {
 1436:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1437:                 my @pairs=split(/\&/,$hashitems);
 1438:                 foreach my $item (@pairs) {
 1439:                     my ($key,$value)=split(/=/,$item,2);
 1440:                     $key = &unescape($key);
 1441:                     next if ($key =~ /^error: 2 /);
 1442:                     $ruleshash{$key}=&thaw_unescape($value);
 1443:                 }
 1444:                 my @esc_order = split(/\&/,$orderitems);
 1445:                 foreach my $item (@esc_order) {
 1446:                     push(@ruleorder,&unescape($item));
 1447:                 }
 1448:             }
 1449:         }
 1450:     }
 1451:     return (\%ruleshash,\@ruleorder);
 1452: }
 1453: 
 1454: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 1455: 
 1456: sub get_domain_defaults {
 1457:     my ($domain) = @_;
 1458:     my $cachetime = 60*60*24;
 1459:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 1460:     if (defined($cached)) {
 1461:         if (ref($result) eq 'HASH') {
 1462:             return %{$result};
 1463:         }
 1464:     }
 1465:     my %domdefaults;
 1466:     my %domconfig =
 1467:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
 1468:                                   'requestcourses','inststatus',
 1469:                                   'coursedefaults','usersessions'],$domain);
 1470:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 1471:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 1472:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 1473:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 1474:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 1475:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 1476:     } else {
 1477:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 1478:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 1479:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 1480:     }
 1481:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 1482:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 1483:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 1484:         } else {
 1485:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 1486:         } 
 1487:         my @usertools = ('aboutme','blog','portfolio');
 1488:         foreach my $item (@usertools) {
 1489:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 1490:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 1491:             }
 1492:         }
 1493:     }
 1494:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
 1495:         foreach my $item ('official','unofficial','community') {
 1496:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
 1497:         }
 1498:     }
 1499:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
 1500:         foreach my $item ('inststatustypes','inststatusorder') {
 1501:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
 1502:         }
 1503:     }
 1504:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
 1505:         foreach my $item ('canuse_pdfforms') {
 1506:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
 1507:         }
 1508:     }
 1509:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
 1510:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
 1511:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
 1512:         }
 1513:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
 1514:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
 1515:         }
 1516:     }
 1517:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
 1518:                                   $cachetime);
 1519:     return %domdefaults;
 1520: }
 1521: 
 1522: # --------------------------------------------------- Assign a key to a student
 1523: 
 1524: sub assign_access_key {
 1525: #
 1526: # a valid key looks like uname:udom#comments
 1527: # comments are being appended
 1528: #
 1529:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 1530:     $kdom=
 1531:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 1532:     $knum=
 1533:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 1534:     $cdom=
 1535:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1536:     $cnum=
 1537:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1538:     $udom=$env{'user.name'} unless (defined($udom));
 1539:     $uname=$env{'user.domain'} unless (defined($uname));
 1540:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 1541:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 1542:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 1543:                                                   # assigned to this person
 1544:                                                   # - this should not happen,
 1545:                                                   # unless something went wrong
 1546:                                                   # the first time around
 1547: # ready to assign
 1548:         $logentry=$1.'; '.$logentry;
 1549:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 1550:                                                  $kdom,$knum) eq 'ok') {
 1551: # key now belongs to user
 1552: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 1553:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 1554:                 &appenv({'environment.'.$envkey => $ckey});
 1555:                 return 'ok';
 1556:             } else {
 1557:                 return 
 1558:   'error: Count not permanently assign key, will need to be re-entered later.';
 1559: 	    }
 1560:         } else {
 1561:             return 'error: Could not assign key, try again later.';
 1562:         }
 1563:     } elsif (!$existing{$ckey}) {
 1564: # the key does not exist
 1565: 	return 'error: The key does not exist';
 1566:     } else {
 1567: # the key is somebody else's
 1568: 	return 'error: The key is already in use';
 1569:     }
 1570: }
 1571: 
 1572: # ------------------------------------------ put an additional comment on a key
 1573: 
 1574: sub comment_access_key {
 1575: #
 1576: # a valid key looks like uname:udom#comments
 1577: # comments are being appended
 1578: #
 1579:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 1580:     $cdom=
 1581:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1582:     $cnum=
 1583:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1584:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1585:     if ($existing{$ckey}) {
 1586:         $existing{$ckey}.='; '.$logentry;
 1587: # ready to assign
 1588:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 1589:                                                  $cdom,$cnum) eq 'ok') {
 1590: 	    return 'ok';
 1591:         } else {
 1592: 	    return 'error: Count not store comment.';
 1593:         }
 1594:     } else {
 1595: # the key does not exist
 1596: 	return 'error: The key does not exist';
 1597:     }
 1598: }
 1599: 
 1600: # ------------------------------------------------------ Generate a set of keys
 1601: 
 1602: sub generate_access_keys {
 1603:     my ($number,$cdom,$cnum,$logentry)=@_;
 1604:     $cdom=
 1605:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1606:     $cnum=
 1607:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1608:     unless (&allowed('mky',$cdom)) { return 0; }
 1609:     unless (($cdom) && ($cnum)) { return 0; }
 1610:     if ($number>10000) { return 0; }
 1611:     sleep(2); # make sure don't get same seed twice
 1612:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 1613:     my $total=0;
 1614:     for (my $i=1;$i<=$number;$i++) {
 1615:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 1616:                   sprintf("%lx",int(100000*rand)).'-'.
 1617:                   sprintf("%lx",int(100000*rand));
 1618:        $newkey=~s/1/g/g; # folks mix up 1 and l
 1619:        $newkey=~s/0/h/g; # and also 0 and O
 1620:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 1621:        if ($existing{$newkey}) {
 1622:            $i--;
 1623:        } else {
 1624: 	  if (&put('accesskeys',
 1625:               { $newkey => '# generated '.localtime().
 1626:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 1627:                            '; '.$logentry },
 1628: 		   $cdom,$cnum) eq 'ok') {
 1629:               $total++;
 1630: 	  }
 1631:        }
 1632:     }
 1633:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 1634:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 1635:     return $total;
 1636: }
 1637: 
 1638: # ------------------------------------------------------- Validate an accesskey
 1639: 
 1640: sub validate_access_key {
 1641:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 1642:     $cdom=
 1643:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1644:     $cnum=
 1645:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1646:     $udom=$env{'user.domain'} unless (defined($udom));
 1647:     $uname=$env{'user.name'} unless (defined($uname));
 1648:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1649:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 1650: }
 1651: 
 1652: # ------------------------------------- Find the section of student in a course
 1653: sub devalidate_getsection_cache {
 1654:     my ($udom,$unam,$courseid)=@_;
 1655:     my $hashid="$udom:$unam:$courseid";
 1656:     &devalidate_cache_new('getsection',$hashid);
 1657: }
 1658: 
 1659: sub courseid_to_courseurl {
 1660:     my ($courseid) = @_;
 1661:     #already url style courseid
 1662:     return $courseid if ($courseid =~ m{^/});
 1663: 
 1664:     if (exists($env{'course.'.$courseid.'.num'})) {
 1665: 	my $cnum = $env{'course.'.$courseid.'.num'};
 1666: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 1667: 	return "/$cdom/$cnum";
 1668:     }
 1669: 
 1670:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 1671:     if (exists($courseinfo{'num'})) {
 1672: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 1673:     }
 1674: 
 1675:     return undef;
 1676: }
 1677: 
 1678: sub getsection {
 1679:     my ($udom,$unam,$courseid)=@_;
 1680:     my $cachetime=1800;
 1681: 
 1682:     my $hashid="$udom:$unam:$courseid";
 1683:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 1684:     if (defined($cached)) { return $result; }
 1685: 
 1686:     my %Pending; 
 1687:     my %Expired;
 1688:     #
 1689:     # Each role can either have not started yet (pending), be active, 
 1690:     #    or have expired.
 1691:     #
 1692:     # If there is an active role, we are done.
 1693:     #
 1694:     # If there is more than one role which has not started yet, 
 1695:     #     choose the one which will start sooner
 1696:     # If there is one role which has not started yet, return it.
 1697:     #
 1698:     # If there is more than one expired role, choose the one which ended last.
 1699:     # If there is a role which has expired, return it.
 1700:     #
 1701:     $courseid = &courseid_to_courseurl($courseid);
 1702:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 1703:     foreach my $key (keys(%roleshash)) {
 1704:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 1705:         my $section=$1;
 1706:         if ($key eq $courseid.'_st') { $section=''; }
 1707:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 1708:         my $now=time;
 1709:         if (defined($end) && $end && ($now > $end)) {
 1710:             $Expired{$end}=$section;
 1711:             next;
 1712:         }
 1713:         if (defined($start) && $start && ($now < $start)) {
 1714:             $Pending{$start}=$section;
 1715:             next;
 1716:         }
 1717:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 1718:     }
 1719:     #
 1720:     # Presumedly there will be few matching roles from the above
 1721:     # loop and the sorting time will be negligible.
 1722:     if (scalar(keys(%Pending))) {
 1723:         my ($time) = sort {$a <=> $b} keys(%Pending);
 1724:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 1725:     } 
 1726:     if (scalar(keys(%Expired))) {
 1727:         my @sorted = sort {$a <=> $b} keys(%Expired);
 1728:         my $time = pop(@sorted);
 1729:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 1730:     }
 1731:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 1732: }
 1733: 
 1734: sub save_cache {
 1735:     &purge_remembered();
 1736:     #&Apache::loncommon::validate_page();
 1737:     undef(%env);
 1738:     undef($env_loaded);
 1739: }
 1740: 
 1741: my $to_remember=-1;
 1742: my %remembered;
 1743: my %accessed;
 1744: my $kicks=0;
 1745: my $hits=0;
 1746: sub make_key {
 1747:     my ($name,$id) = @_;
 1748:     if (length($id) > 65 
 1749: 	&& length(&escape($id)) > 200) {
 1750: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 1751:     }
 1752:     return &escape($name.':'.$id);
 1753: }
 1754: 
 1755: sub devalidate_cache_new {
 1756:     my ($name,$id,$debug) = @_;
 1757:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 1758:     $id=&make_key($name,$id);
 1759:     $memcache->delete($id);
 1760:     delete($remembered{$id});
 1761:     delete($accessed{$id});
 1762: }
 1763: 
 1764: sub is_cached_new {
 1765:     my ($name,$id,$debug) = @_;
 1766:     $id=&make_key($name,$id);
 1767:     if (exists($remembered{$id})) {
 1768: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
 1769: 	$accessed{$id}=[&gettimeofday()];
 1770: 	$hits++;
 1771: 	return ($remembered{$id},1);
 1772:     }
 1773:     my $value = $memcache->get($id);
 1774:     if (!(defined($value))) {
 1775: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 1776: 	return (undef,undef);
 1777:     }
 1778:     if ($value eq '__undef__') {
 1779: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 1780: 	$value=undef;
 1781:     }
 1782:     &make_room($id,$value,$debug);
 1783:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 1784:     return ($value,1);
 1785: }
 1786: 
 1787: sub do_cache_new {
 1788:     my ($name,$id,$value,$time,$debug) = @_;
 1789:     $id=&make_key($name,$id);
 1790:     my $setvalue=$value;
 1791:     if (!defined($setvalue)) {
 1792: 	$setvalue='__undef__';
 1793:     }
 1794:     if (!defined($time) ) {
 1795: 	$time=600;
 1796:     }
 1797:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 1798:     my $result = $memcache->set($id,$setvalue,$time);
 1799:     if (! $result) {
 1800: 	&logthis("caching of id -> $id  failed");
 1801: 	$memcache->disconnect_all();
 1802:     }
 1803:     # need to make a copy of $value
 1804:     &make_room($id,$value,$debug);
 1805:     return $value;
 1806: }
 1807: 
 1808: sub make_room {
 1809:     my ($id,$value,$debug)=@_;
 1810: 
 1811:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 1812:                                     : $value;
 1813:     if ($to_remember<0) { return; }
 1814:     $accessed{$id}=[&gettimeofday()];
 1815:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 1816:     my $to_kick;
 1817:     my $max_time=0;
 1818:     foreach my $other (keys(%accessed)) {
 1819: 	if (&tv_interval($accessed{$other}) > $max_time) {
 1820: 	    $to_kick=$other;
 1821: 	    $max_time=&tv_interval($accessed{$other});
 1822: 	}
 1823:     }
 1824:     delete($remembered{$to_kick});
 1825:     delete($accessed{$to_kick});
 1826:     $kicks++;
 1827:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 1828:     return;
 1829: }
 1830: 
 1831: sub purge_remembered {
 1832:     #&logthis("Tossing ".scalar(keys(%remembered)));
 1833:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 1834:     undef(%remembered);
 1835:     undef(%accessed);
 1836: }
 1837: # ------------------------------------- Read an entry from a user's environment
 1838: 
 1839: sub userenvironment {
 1840:     my ($udom,$unam,@what)=@_;
 1841:     my $items;
 1842:     foreach my $item (@what) {
 1843:         $items.=&escape($item).'&';
 1844:     }
 1845:     $items=~s/\&$//;
 1846:     my %returnhash=();
 1847:     my $uhome = &homeserver($unam,$udom);
 1848:     unless ($uhome eq 'no_host') {
 1849:         my @answer=split(/\&/, 
 1850:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
 1851:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
 1852:             return %returnhash;
 1853:         }
 1854:         my $i;
 1855:         for ($i=0;$i<=$#what;$i++) {
 1856: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
 1857:         }
 1858:     }
 1859:     return %returnhash;
 1860: }
 1861: 
 1862: # ---------------------------------------------------------- Get a studentphoto
 1863: sub studentphoto {
 1864:     my ($udom,$unam,$ext) = @_;
 1865:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1866:     if (defined($env{'request.course.id'})) {
 1867:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 1868:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 1869:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 1870:             } else {
 1871:                 my ($result,$perm_reqd)=
 1872: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1873:                 if ($result eq 'ok') {
 1874:                     if (!($perm_reqd eq 'yes')) {
 1875:                         return(&retrievestudentphoto($udom,$unam,$ext));
 1876:                     }
 1877:                 }
 1878:             }
 1879:         }
 1880:     } else {
 1881:         my ($result,$perm_reqd) = 
 1882: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1883:         if ($result eq 'ok') {
 1884:             if (!($perm_reqd eq 'yes')) {
 1885:                 return(&retrievestudentphoto($udom,$unam,$ext));
 1886:             }
 1887:         }
 1888:     }
 1889:     return '/adm/lonKaputt/lonlogo_broken.gif';
 1890: }
 1891: 
 1892: sub retrievestudentphoto {
 1893:     my ($udom,$unam,$ext,$type) = @_;
 1894:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1895:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 1896:     if ($ret eq 'ok') {
 1897:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 1898:         if ($type eq 'thumbnail') {
 1899:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 1900:         }
 1901:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 1902:         return $tokenurl;
 1903:     } else {
 1904:         if ($type eq 'thumbnail') {
 1905:             return '/adm/lonKaputt/genericstudent_tn.gif';
 1906:         } else { 
 1907:             return '/adm/lonKaputt/lonlogo_broken.gif';
 1908:         }
 1909:     }
 1910: }
 1911: 
 1912: # -------------------------------------------------------------------- New chat
 1913: 
 1914: sub chatsend {
 1915:     my ($newentry,$anon,$group)=@_;
 1916:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 1917:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1918:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 1919:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 1920: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 1921: 		   &escape($newentry)).':'.$group,$chome);
 1922: }
 1923: 
 1924: # ------------------------------------------ Find current version of a resource
 1925: 
 1926: sub getversion {
 1927:     my $fname=&clutter(shift);
 1928:     unless ($fname=~/^\/res\//) { return -1; }
 1929:     return &currentversion(&filelocation('',$fname));
 1930: }
 1931: 
 1932: sub currentversion {
 1933:     my $fname=shift;
 1934:     my ($result,$cached)=&is_cached_new('resversion',$fname);
 1935:     if (defined($cached)) { return $result; }
 1936:     my $author=$fname;
 1937:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1938:     my ($udom,$uname)=split(/\//,$author);
 1939:     my $home=homeserver($uname,$udom);
 1940:     if ($home eq 'no_host') { 
 1941:         return -1; 
 1942:     }
 1943:     my $answer=reply("currentversion:$fname",$home);
 1944:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1945: 	return -1;
 1946:     }
 1947:     return &do_cache_new('resversion',$fname,$answer,600);
 1948: }
 1949: 
 1950: # ----------------------------- Subscribe to a resource, return URL if possible
 1951: 
 1952: sub subscribe {
 1953:     my $fname=shift;
 1954:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 1955:     $fname=~s/[\n\r]//g;
 1956:     my $author=$fname;
 1957:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1958:     my ($udom,$uname)=split(/\//,$author);
 1959:     my $home=homeserver($uname,$udom);
 1960:     if ($home eq 'no_host') {
 1961:         return 'not_found';
 1962:     }
 1963:     my $answer=reply("sub:$fname",$home);
 1964:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1965: 	$answer.=' by '.$home;
 1966:     }
 1967:     return $answer;
 1968: }
 1969:     
 1970: # -------------------------------------------------------------- Replicate file
 1971: 
 1972: sub repcopy {
 1973:     my $filename=shift;
 1974:     $filename=~s/\/+/\//g;
 1975:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
 1976:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 1977:     if ($filename=~m|^/home/httpd/html/userfiles/| or
 1978: 	$filename=~m -^/*(uploaded|editupload)/-) { 
 1979: 	return &repcopy_userfile($filename);
 1980:     }
 1981:     $filename=~s/[\n\r]//g;
 1982:     my $transname="$filename.in.transfer";
 1983: # FIXME: this should flock
 1984:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 1985:     my $remoteurl=subscribe($filename);
 1986:     if ($remoteurl =~ /^con_lost by/) {
 1987: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1988:            return 'unavailable';
 1989:     } elsif ($remoteurl eq 'not_found') {
 1990: 	   #&logthis("Subscribe returned not_found: $filename");
 1991: 	   return 'not_found';
 1992:     } elsif ($remoteurl =~ /^rejected by/) {
 1993: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1994:            return 'forbidden';
 1995:     } elsif ($remoteurl eq 'directory') {
 1996:            return 'ok';
 1997:     } else {
 1998:         my $author=$filename;
 1999:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 2000:         my ($udom,$uname)=split(/\//,$author);
 2001:         my $home=homeserver($uname,$udom);
 2002:         unless ($home eq $perlvar{'lonHostID'}) {
 2003:            my @parts=split(/\//,$filename);
 2004:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 2005:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
 2006:                &logthis("Malconfiguration for replication: $filename");
 2007: 	       return 'bad_request';
 2008:            }
 2009:            my $count;
 2010:            for ($count=5;$count<$#parts;$count++) {
 2011:                $path.="/$parts[$count]";
 2012:                if ((-e $path)!=1) {
 2013: 		   mkdir($path,0777);
 2014:                }
 2015:            }
 2016:            my $ua=new LWP::UserAgent;
 2017:            my $request=new HTTP::Request('GET',"$remoteurl");
 2018:            my $response=$ua->request($request,$transname);
 2019:            if ($response->is_error()) {
 2020: 	       unlink($transname);
 2021:                my $message=$response->status_line;
 2022:                &logthis("<font color=\"blue\">WARNING:"
 2023:                        ." LWP get: $message: $filename</font>");
 2024:                return 'unavailable';
 2025:            } else {
 2026: 	       if ($remoteurl!~/\.meta$/) {
 2027:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 2028:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 2029:                   if ($mresponse->is_error()) {
 2030: 		      unlink($filename.'.meta');
 2031:                       &logthis(
 2032:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 2033:                   }
 2034: 	       }
 2035:                rename($transname,$filename);
 2036:                return 'ok';
 2037:            }
 2038:        }
 2039:     }
 2040: }
 2041: 
 2042: # ------------------------------------------------ Get server side include body
 2043: sub ssi_body {
 2044:     my ($filelink,%form)=@_;
 2045:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 2046:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 2047:     }
 2048:     my $output='';
 2049:     my $response;
 2050:     if ($filelink=~/^https?\:/) {
 2051:        ($output,$response)=&externalssi($filelink);
 2052:     } else {
 2053:        $filelink .= $filelink=~/\?/ ? '&' : '?';
 2054:        $filelink .= 'inhibitmenu=yes';
 2055:        ($output,$response)=&ssi($filelink,%form);
 2056:     }
 2057:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 2058:     $output=~s/^.*?\<body[^\>]*\>//si;
 2059:     $output=~s/\<\/body\s*\>.*?$//si;
 2060:     if (wantarray) {
 2061:         return ($output, $response);
 2062:     } else {
 2063:         return $output;
 2064:     }
 2065: }
 2066: 
 2067: # --------------------------------------------------------- Server Side Include
 2068: 
 2069: sub absolute_url {
 2070:     my ($host_name) = @_;
 2071:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 2072:     if ($host_name eq '') {
 2073: 	$host_name = $ENV{'SERVER_NAME'};
 2074:     }
 2075:     return $protocol.$host_name;
 2076: }
 2077: 
 2078: #
 2079: #   Server side include.
 2080: # Parameters:
 2081: #  fn     Possibly encrypted resource name/id.
 2082: #  form   Hash that describes how the rendering should be done
 2083: #         and other things.
 2084: # Returns:
 2085: #   Scalar context: The content of the response.
 2086: #   Array context:  2 element list of the content and the full response object.
 2087: #     
 2088: sub ssi {
 2089: 
 2090:     my ($fn,%form)=@_;
 2091:     my $ua=new LWP::UserAgent;
 2092:     my $request;
 2093: 
 2094:     $form{'no_update_last_known'}=1;
 2095:     &Apache::lonenc::check_encrypt(\$fn);
 2096:     if (%form) {
 2097:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 2098:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
 2099:     } else {
 2100:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 2101:     }
 2102: 
 2103:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 2104:     my $response=$ua->request($request);
 2105: 
 2106:     if (wantarray) {
 2107: 	return ($response->content, $response);
 2108:     } else {
 2109: 	return $response->content;
 2110:     }
 2111: }
 2112: 
 2113: sub externalssi {
 2114:     my ($url)=@_;
 2115:     my $ua=new LWP::UserAgent;
 2116:     my $request=new HTTP::Request('GET',$url);
 2117:     my $response=$ua->request($request);
 2118:     if (wantarray) {
 2119:         return ($response->content, $response);
 2120:     } else {
 2121:         return $response->content;
 2122:     }
 2123: }
 2124: 
 2125: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 2126: 
 2127: sub allowuploaded {
 2128:     my ($srcurl,$url)=@_;
 2129:     $url=&clutter(&declutter($url));
 2130:     my $dir=$url;
 2131:     $dir=~s/\/[^\/]+$//;
 2132:     my %httpref=();
 2133:     my $httpurl=&hreflocation('',$url);
 2134:     $httpref{'httpref.'.$httpurl}=$srcurl;
 2135:     &Apache::lonnet::appenv(\%httpref);
 2136: }
 2137: 
 2138: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 2139: # input: action, courseID, current domain, intended
 2140: #        path to file, source of file, instruction to parse file for objects,
 2141: #        ref to hash for embedded objects,
 2142: #        ref to hash for codebase of java objects.
 2143: #
 2144: # output: url to file (if action was uploaddoc), 
 2145: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 2146: #
 2147: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 2148: # course.
 2149: #
 2150: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2151: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 2152: #          course's home server.
 2153: #
 2154: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 2155: #          be copied from $source (current location) to 
 2156: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2157: #         and will then be copied to
 2158: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 2159: #         course's home server.
 2160: #
 2161: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2162: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 2163: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 2164: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 2165: #         in course's home server.
 2166: #
 2167: 
 2168: sub process_coursefile {
 2169:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
 2170:     my $fetchresult;
 2171:     my $home=&homeserver($docuname,$docudom);
 2172:     if ($action eq 'propagate') {
 2173:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2174: 			     $home);
 2175:     } else {
 2176:         my $fpath = '';
 2177:         my $fname = $file;
 2178:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2179:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2180:         my $filepath = &build_filepath($fpath);
 2181:         if ($action eq 'copy') {
 2182:             if ($source eq '') {
 2183:                 $fetchresult = 'no source file';
 2184:                 return $fetchresult;
 2185:             } else {
 2186:                 my $destination = $filepath.'/'.$fname;
 2187:                 rename($source,$destination);
 2188:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2189:                                  $home);
 2190:             }
 2191:         } elsif ($action eq 'uploaddoc') {
 2192:             open(my $fh,'>'.$filepath.'/'.$fname);
 2193:             print $fh $env{'form.'.$source};
 2194:             close($fh);
 2195:             if ($parser eq 'parse') {
 2196:                 my $mm = new File::MMagic;
 2197:                 my $mime_type = $mm->checktype_filename($filepath.'/'.$fname);
 2198:                 if ($mime_type eq 'text/html') {
 2199:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 2200:                     unless ($parse_result eq 'ok') {
 2201:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 2202:                     }
 2203:                 }
 2204:             }
 2205:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2206:                                  $home);
 2207:             if ($fetchresult eq 'ok') {
 2208:                 return '/uploaded/'.$fpath.'/'.$fname;
 2209:             } else {
 2210:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2211:                         ' to host '.$home.': '.$fetchresult);
 2212:                 return '/adm/notfound.html';
 2213:             }
 2214:         }
 2215:     }
 2216:     unless ( $fetchresult eq 'ok') {
 2217:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2218:              ' to host '.$home.': '.$fetchresult);
 2219:     }
 2220:     return $fetchresult;
 2221: }
 2222: 
 2223: sub build_filepath {
 2224:     my ($fpath) = @_;
 2225:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 2226:     unless ($fpath eq '') {
 2227:         my @parts=split('/',$fpath);
 2228:         foreach my $part (@parts) {
 2229:             $filepath.= '/'.$part;
 2230:             if ((-e $filepath)!=1) {
 2231:                 mkdir($filepath,0777);
 2232:             }
 2233:         }
 2234:     }
 2235:     return $filepath;
 2236: }
 2237: 
 2238: sub store_edited_file {
 2239:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 2240:     my $file = $primary_url;
 2241:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 2242:     my $fpath = '';
 2243:     my $fname = $file;
 2244:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2245:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2246:     my $filepath = &build_filepath($fpath);
 2247:     open(my $fh,'>'.$filepath.'/'.$fname);
 2248:     print $fh $content;
 2249:     close($fh);
 2250:     my $home=&homeserver($docuname,$docudom);
 2251:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2252: 			  $home);
 2253:     if ($$fetchresult eq 'ok') {
 2254:         return '/uploaded/'.$fpath.'/'.$fname;
 2255:     } else {
 2256:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2257: 		 ' to host '.$home.': '.$$fetchresult);
 2258:         return '/adm/notfound.html';
 2259:     }
 2260: }
 2261: 
 2262: sub clean_filename {
 2263:     my ($fname,$args)=@_;
 2264: # Replace Windows backslashes by forward slashes
 2265:     $fname=~s/\\/\//g;
 2266:     if (!$args->{'keep_path'}) {
 2267:         # Get rid of everything but the actual filename
 2268: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 2269:     }
 2270: # Replace spaces by underscores
 2271:     $fname=~s/\s+/\_/g;
 2272: # Replace all other weird characters by nothing
 2273:     $fname=~s{[^/\w\.\-]}{}g;
 2274: # Replace all .\d. sequences with _\d. so they no longer look like version
 2275: # numbers
 2276:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 2277:     return $fname;
 2278: }
 2279: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
 2280: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
 2281: # image with the same aspect ratio as the original, but with dimensions which do 
 2282: # not exceed $resizewidth and $resizeheight.
 2283:  
 2284: sub resizeImage {
 2285:     my ($img_path,$resizewidth,$resizeheight) = @_;
 2286:     my $ima = Image::Magick->new;
 2287:     my $resized;
 2288:     if (-e $img_path) {
 2289:         $ima->Read($img_path);
 2290:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
 2291:             my $width = $ima->Get('width');
 2292:             my $height = $ima->Get('height');
 2293:             if ($width > $resizewidth) {
 2294: 	        my $factor = $width/$resizewidth;
 2295:                 my $newheight = $height/$factor;
 2296:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
 2297:                 $resized = 1;
 2298:             }
 2299:         }
 2300:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
 2301:             my $width = $ima->Get('width');
 2302:             my $height = $ima->Get('height');
 2303:             if ($height > $resizeheight) {
 2304:                 my $factor = $height/$resizeheight;
 2305:                 my $newwidth = $width/$factor;
 2306:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
 2307:                 $resized = 1;
 2308:             }
 2309:         }
 2310:         if ($resized) {
 2311:             $ima->Write($img_path);
 2312:         }
 2313:     }
 2314:     return;
 2315: }
 2316: 
 2317: # --------------- Take an uploaded file and put it into the userfiles directory
 2318: # input: $formname - the contents of the file are in $env{"form.$formname"}
 2319: #                    the desired filenam is in $env{"form.$formname.filename"}
 2320: #        $coursedoc - if true up to the current course
 2321: #                     if false
 2322: #        $subdir - directory in userfile to store the file into
 2323: #        $parser - instruction to parse file for objects ($parser = parse)    
 2324: #        $allfiles - reference to hash for embedded objects
 2325: #        $codebase - reference to hash for codebase of java objects
 2326: #        $desuname - username for permanent storage of uploaded file
 2327: #        $dsetudom - domain for permanaent storage of uploaded file
 2328: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 2329: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 2330: #        $resizewidth - width (pixels) to which to resize uploaded image
 2331: #        $resizeheight - height (pixels) to which to resize uploaded image
 2332: # 
 2333: # output: url of file in userspace, or error: <message> 
 2334: #             or /adm/notfound.html if failure to upload occurse
 2335: 
 2336: sub userfileupload {
 2337:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
 2338:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight)=@_;
 2339:     if (!defined($subdir)) { $subdir='unknown'; }
 2340:     my $fname=$env{'form.'.$formname.'.filename'};
 2341:     $fname=&clean_filename($fname);
 2342: # See if there is anything left
 2343:     unless ($fname) { return 'error: no uploaded file'; }
 2344:     chop($env{'form.'.$formname});
 2345:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
 2346:         my $now = time;
 2347:         my $filepath = 'tmp/helprequests/'.$now;
 2348:         my @parts=split(/\//,$filepath);
 2349:         my $fullpath = $perlvar{'lonDaemons'};
 2350:         for (my $i=0;$i<@parts;$i++) {
 2351:             $fullpath .= '/'.$parts[$i];
 2352:             if ((-e $fullpath)!=1) {
 2353:                 mkdir($fullpath,0777);
 2354:             }
 2355:         }
 2356:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2357:         print $fh $env{'form.'.$formname};
 2358:         close($fh);
 2359:         return $fullpath.'/'.$fname;
 2360:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
 2361:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 2362:                        '_'.$env{'user.domain'}.'/pending';
 2363:         my @parts=split(/\//,$filepath);
 2364:         my $fullpath = $perlvar{'lonDaemons'};
 2365:         for (my $i=0;$i<@parts;$i++) {
 2366:             $fullpath .= '/'.$parts[$i];
 2367:             if ((-e $fullpath)!=1) {
 2368:                 mkdir($fullpath,0777);
 2369:             }
 2370:         }
 2371:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2372:         print $fh $env{'form.'.$formname};
 2373:         close($fh);
 2374:         return $fullpath.'/'.$fname;
 2375:     }
 2376:     if ($subdir eq 'scantron') {
 2377:         $fname = 'scantron_orig_'.$fname;
 2378:     } else {   
 2379: # Create the directory if not present
 2380:         $fname="$subdir/$fname";
 2381:     }
 2382:     if ($coursedoc) {
 2383: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2384: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2385:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 2386:             return &finishuserfileupload($docuname,$docudom,
 2387: 					 $formname,$fname,$parser,$allfiles,
 2388: 					 $codebase,$thumbwidth,$thumbheight,
 2389:                                          $resizewidth,$resizeheight);
 2390:         } else {
 2391:             $fname=$env{'form.folder'}.'/'.$fname;
 2392:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 2393: 				       $fname,$formname,$parser,
 2394: 				       $allfiles,$codebase);
 2395:         }
 2396:     } elsif (defined($destuname)) {
 2397:         my $docuname=$destuname;
 2398:         my $docudom=$destudom;
 2399: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2400: 				     $parser,$allfiles,$codebase,
 2401:                                      $thumbwidth,$thumbheight,
 2402:                                      $resizewidth,$resizeheight);
 2403:         
 2404:     } else {
 2405:         my $docuname=$env{'user.name'};
 2406:         my $docudom=$env{'user.domain'};
 2407:         if (exists($env{'form.group'})) {
 2408:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2409:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2410:         }
 2411: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2412: 				     $parser,$allfiles,$codebase,
 2413:                                      $thumbwidth,$thumbheight,
 2414:                                      $resizewidth,$resizeheight);
 2415:     }
 2416: }
 2417: 
 2418: sub finishuserfileupload {
 2419:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 2420:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight) = @_;
 2421:     my $path=$docudom.'/'.$docuname.'/';
 2422:     my $filepath=$perlvar{'lonDocRoot'};
 2423:   
 2424:     my ($fnamepath,$file,$fetchthumb);
 2425:     $file=$fname;
 2426:     if ($fname=~m|/|) {
 2427:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 2428: 	$path.=$fnamepath.'/';
 2429:     }
 2430:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 2431:     my $count;
 2432:     for ($count=4;$count<=$#parts;$count++) {
 2433:         $filepath.="/$parts[$count]";
 2434:         if ((-e $filepath)!=1) {
 2435: 	    mkdir($filepath,0777);
 2436:         }
 2437:     }
 2438: 
 2439: # Save the file
 2440:     {
 2441: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 2442: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 2443: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 2444: 	    return '/adm/notfound.html';
 2445: 	}
 2446: 	if (!print FH ($env{'form.'.$formname})) {
 2447: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 2448: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 2449: 	    return '/adm/notfound.html';
 2450: 	}
 2451: 	close(FH);
 2452:         if ($resizewidth && $resizeheight) {
 2453:             my $mm = new File::MMagic;
 2454:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 2455:             if ($mime_type =~ m{^image/}) {
 2456: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
 2457:             }  
 2458: 	}
 2459:     }
 2460:     if ($parser eq 'parse') {
 2461:         my $mm = new File::MMagic;
 2462:         my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
 2463:         if ($mime_type eq 'text/html') {
 2464:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
 2465:                                                        $allfiles,$codebase);
 2466:             unless ($parse_result eq 'ok') {
 2467:                 &logthis('Failed to parse '.$filepath.$file.
 2468: 	   	         ' for embedded media: '.$parse_result); 
 2469:             }
 2470:         }
 2471:     }
 2472:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 2473:         my $input = $filepath.'/'.$file;
 2474:         my $output = $filepath.'/'.'tn-'.$file;
 2475:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 2476:         system("convert -sample $thumbsize $input $output");
 2477:         if (-e $filepath.'/'.'tn-'.$file) {
 2478:             $fetchthumb  = 1; 
 2479:         }
 2480:     }
 2481:  
 2482: # Notify homeserver to grep it
 2483: #
 2484:     my $docuhome=&homeserver($docuname,$docudom);	
 2485:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 2486:     if ($fetchresult eq 'ok') {
 2487:         if ($fetchthumb) {
 2488:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 2489:             if ($thumbresult ne 'ok') {
 2490:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 2491:                          $docuhome.': '.$thumbresult);
 2492:             }
 2493:         }
 2494: #
 2495: # Return the URL to it
 2496:         return '/uploaded/'.$path.$file;
 2497:     } else {
 2498:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 2499: 		 ': '.$fetchresult);
 2500:         return '/adm/notfound.html';
 2501:     }
 2502: }
 2503: 
 2504: sub extract_embedded_items {
 2505:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 2506:     my @state = ();
 2507:     my %javafiles = (
 2508:                       codebase => '',
 2509:                       code => '',
 2510:                       archive => ''
 2511:                     );
 2512:     my %mediafiles = (
 2513:                       src => '',
 2514:                       movie => '',
 2515:                      );
 2516:     my $p;
 2517:     if ($content) {
 2518:         $p = HTML::LCParser->new($content);
 2519:     } else {
 2520:         $p = HTML::LCParser->new($fullpath);
 2521:     }
 2522:     while (my $t=$p->get_token()) {
 2523: 	if ($t->[0] eq 'S') {
 2524: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 2525: 	    push(@state, $tagname);
 2526:             if (lc($tagname) eq 'allow') {
 2527:                 &add_filetype($allfiles,$attr->{'src'},'src');
 2528:             }
 2529: 	    if (lc($tagname) eq 'img') {
 2530: 		&add_filetype($allfiles,$attr->{'src'},'src');
 2531: 	    }
 2532: 	    if (lc($tagname) eq 'a') {
 2533: 		&add_filetype($allfiles,$attr->{'href'},'href');
 2534: 	    }
 2535:             if (lc($tagname) eq 'script') {
 2536:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 2537:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 2538:                 } else {
 2539:                     &add_filetype($allfiles,$attr->{'src'},'src');
 2540:                 }
 2541:             }
 2542:             if (lc($tagname) eq 'link') {
 2543:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 2544:                     &add_filetype($allfiles,$attr->{'href'},'href');
 2545:                 }
 2546:             }
 2547: 	    if (lc($tagname) eq 'object' ||
 2548: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 2549: 		foreach my $item (keys(%javafiles)) {
 2550: 		    $javafiles{$item} = '';
 2551: 		}
 2552: 	    }
 2553: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 2554: 		my $name = lc($attr->{'name'});
 2555: 		foreach my $item (keys(%javafiles)) {
 2556: 		    if ($name eq $item) {
 2557: 			$javafiles{$item} = $attr->{'value'};
 2558: 			last;
 2559: 		    }
 2560: 		}
 2561: 		foreach my $item (keys(%mediafiles)) {
 2562: 		    if ($name eq $item) {
 2563: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 2564: 			last;
 2565: 		    }
 2566: 		}
 2567: 	    }
 2568: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 2569: 		foreach my $item (keys(%javafiles)) {
 2570: 		    if ($attr->{$item}) {
 2571: 			$javafiles{$item} = $attr->{$item};
 2572: 			last;
 2573: 		    }
 2574: 		}
 2575: 		foreach my $item (keys(%mediafiles)) {
 2576: 		    if ($attr->{$item}) {
 2577: 			&add_filetype($allfiles,$attr->{$item},$item);
 2578: 			last;
 2579: 		    }
 2580: 		}
 2581: 	    }
 2582: 	} elsif ($t->[0] eq 'E') {
 2583: 	    my ($tagname) = ($t->[1]);
 2584: 	    if ($javafiles{'codebase'} ne '') {
 2585: 		$javafiles{'codebase'} .= '/';
 2586: 	    }  
 2587: 	    if (lc($tagname) eq 'applet' ||
 2588: 		lc($tagname) eq 'object' ||
 2589: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 2590: 		) {
 2591: 		foreach my $item (keys(%javafiles)) {
 2592: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 2593: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 2594: 			&add_filetype($allfiles,$file,$item);
 2595: 		    }
 2596: 		}
 2597: 	    } 
 2598: 	    pop @state;
 2599: 	}
 2600:     }
 2601:     return 'ok';
 2602: }
 2603: 
 2604: sub add_filetype {
 2605:     my ($allfiles,$file,$type)=@_;
 2606:     if (exists($allfiles->{$file})) {
 2607: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 2608: 	    push(@{$allfiles->{$file}}, &escape($type));
 2609: 	}
 2610:     } else {
 2611: 	@{$allfiles->{$file}} = (&escape($type));
 2612:     }
 2613: }
 2614: 
 2615: sub removeuploadedurl {
 2616:     my ($url)=@_;	
 2617:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
 2618:     return &removeuserfile($uname,$udom,$fname);
 2619: }
 2620: 
 2621: sub removeuserfile {
 2622:     my ($docuname,$docudom,$fname)=@_;
 2623:     my $home=&homeserver($docuname,$docudom);    
 2624:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 2625:     if ($result eq 'ok') {	
 2626:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 2627:             my $metafile = $fname.'.meta';
 2628:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 2629: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 2630:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
 2631:             my $sqlresult = 
 2632:                 &update_portfolio_table($docuname,$docudom,$file,
 2633:                                         'portfolio_metadata',$group,
 2634:                                         'delete');
 2635:         }
 2636:     }
 2637:     return $result;
 2638: }
 2639: 
 2640: sub mkdiruserfile {
 2641:     my ($docuname,$docudom,$dir)=@_;
 2642:     my $home=&homeserver($docuname,$docudom);
 2643:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 2644: }
 2645: 
 2646: sub renameuserfile {
 2647:     my ($docuname,$docudom,$old,$new)=@_;
 2648:     my $home=&homeserver($docuname,$docudom);
 2649:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 2650:                         &escape("$old").':'.&escape("$new"),$home);
 2651:     if ($result eq 'ok') {
 2652:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 2653:             my $oldmeta = $old.'.meta';
 2654:             my $newmeta = $new.'.meta';
 2655:             my $metaresult = 
 2656:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 2657: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 2658:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 2659:             my $sqlresult = 
 2660:                 &update_portfolio_table($docuname,$docudom,$file,
 2661:                                         'portfolio_metadata',$group,
 2662:                                         'delete');
 2663:         }
 2664:     }
 2665:     return $result;
 2666: }
 2667: 
 2668: # ------------------------------------------------------------------------- Log
 2669: 
 2670: sub log {
 2671:     my ($dom,$nam,$hom,$what)=@_;
 2672:     return critical("log:$dom:$nam:$what",$hom);
 2673: }
 2674: 
 2675: # ------------------------------------------------------------------ Course Log
 2676: #
 2677: # This routine flushes several buffers of non-mission-critical nature
 2678: #
 2679: 
 2680: sub flushcourselogs {
 2681:     &logthis('Flushing log buffers');
 2682: #
 2683: # course logs
 2684: # This is a log of all transactions in a course, which can be used
 2685: # for data mining purposes
 2686: #
 2687: # It also collects the courseid database, which lists last transaction
 2688: # times and course titles for all courseids
 2689: #
 2690:     my %courseidbuffer=();
 2691:     foreach my $crsid (keys(%courselogs)) {
 2692:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 2693: 		          &escape($courselogs{$crsid}),
 2694: 		          $coursehombuf{$crsid}) eq 'ok') {
 2695: 	    delete $courselogs{$crsid};
 2696:         } else {
 2697:             &logthis('Failed to flush log buffer for '.$crsid);
 2698:             if (length($courselogs{$crsid})>40000) {
 2699:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 2700:                         " exceeded maximum size, deleting.</font>");
 2701:                delete $courselogs{$crsid};
 2702:             }
 2703:         }
 2704:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 2705:             'description' => $coursedescrbuf{$crsid},
 2706:             'inst_code'    => $courseinstcodebuf{$crsid},
 2707:             'type'        => $coursetypebuf{$crsid},
 2708:             'owner'       => $courseownerbuf{$crsid},
 2709:         };
 2710:     }
 2711: #
 2712: # Write course id database (reverse lookup) to homeserver of courses 
 2713: # Is used in pickcourse
 2714: #
 2715:     foreach my $crs_home (keys(%courseidbuffer)) {
 2716:         my $response = &courseidput(&host_domain($crs_home),
 2717:                                     $courseidbuffer{$crs_home},
 2718:                                     $crs_home,'timeonly');
 2719:     }
 2720: #
 2721: # File accesses
 2722: # Writes to the dynamic metadata of resources to get hit counts, etc.
 2723: #
 2724:     foreach my $entry (keys(%accesshash)) {
 2725:         if ($entry =~ /___count$/) {
 2726:             my ($dom,$name);
 2727:             ($dom,$name,undef)=
 2728: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 2729:             if (! defined($dom) || $dom eq '' || 
 2730:                 ! defined($name) || $name eq '') {
 2731:                 my $cid = $env{'request.course.id'};
 2732:                 $dom  = $env{'request.'.$cid.'.domain'};
 2733:                 $name = $env{'request.'.$cid.'.num'};
 2734:             }
 2735:             my $value = $accesshash{$entry};
 2736:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 2737:             my %temphash=($url => $value);
 2738:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 2739:             if ($result eq 'ok') {
 2740:                 delete $accesshash{$entry};
 2741:             } elsif ($result eq 'unknown_cmd') {
 2742:                 # Target server has old code running on it.
 2743:                 my %temphash=($entry => $value);
 2744:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2745:                     delete $accesshash{$entry};
 2746:                 }
 2747:             }
 2748:         } else {
 2749:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 2750:             my %temphash=($entry => $accesshash{$entry});
 2751:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2752:                 delete $accesshash{$entry};
 2753:             }
 2754:         }
 2755:     }
 2756: #
 2757: # Roles
 2758: # Reverse lookup of user roles for course faculty/staff and co-authorship
 2759: #
 2760:     foreach my $entry (keys(%userrolehash)) {
 2761:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 2762: 	    split(/\:/,$entry);
 2763:         if (&Apache::lonnet::put('nohist_userroles',
 2764:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 2765:                 $rudom,$runame) eq 'ok') {
 2766: 	    delete $userrolehash{$entry};
 2767:         }
 2768:     }
 2769: #
 2770: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 2771: #
 2772:     my %domrolebuffer = ();
 2773:     foreach my $entry (keys(%domainrolehash)) {
 2774:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 2775:         if ($domrolebuffer{$rudom}) {
 2776:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 2777:                       '='.&escape($domainrolehash{$entry});
 2778:         } else {
 2779:             $domrolebuffer{$rudom}.=&escape($entry).
 2780:                       '='.&escape($domainrolehash{$entry});
 2781:         }
 2782:         delete $domainrolehash{$entry};
 2783:     }
 2784:     foreach my $dom (keys(%domrolebuffer)) {
 2785: 	my %servers = &get_servers($dom,'library');
 2786: 	foreach my $tryserver (keys(%servers)) {
 2787: 	    unless (&reply('domroleput:'.$dom.':'.
 2788: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 2789: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 2790: 	    }
 2791:         }
 2792:     }
 2793:     $dumpcount++;
 2794: }
 2795: 
 2796: sub courselog {
 2797:     my $what=shift;
 2798:     $what=time.':'.$what;
 2799:     unless ($env{'request.course.id'}) { return ''; }
 2800:     $coursedombuf{$env{'request.course.id'}}=
 2801:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 2802:     $coursenumbuf{$env{'request.course.id'}}=
 2803:        $env{'course.'.$env{'request.course.id'}.'.num'};
 2804:     $coursehombuf{$env{'request.course.id'}}=
 2805:        $env{'course.'.$env{'request.course.id'}.'.home'};
 2806:     $coursedescrbuf{$env{'request.course.id'}}=
 2807:        $env{'course.'.$env{'request.course.id'}.'.description'};
 2808:     $courseinstcodebuf{$env{'request.course.id'}}=
 2809:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 2810:     $courseownerbuf{$env{'request.course.id'}}=
 2811:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 2812:     $coursetypebuf{$env{'request.course.id'}}=
 2813:        $env{'course.'.$env{'request.course.id'}.'.type'};
 2814:     if (defined $courselogs{$env{'request.course.id'}}) {
 2815: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 2816:     } else {
 2817: 	$courselogs{$env{'request.course.id'}}.=$what;
 2818:     }
 2819:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 2820: 	&flushcourselogs();
 2821:     }
 2822: }
 2823: 
 2824: sub courseacclog {
 2825:     my $fnsymb=shift;
 2826:     unless ($env{'request.course.id'}) { return ''; }
 2827:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 2828:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
 2829:         $what.=':POST';
 2830:         # FIXME: Probably ought to escape things....
 2831: 	foreach my $key (keys(%env)) {
 2832:             if ($key=~/^form\.(.*)/) {
 2833:                 my $formitem = $1;
 2834:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 2835:                     $what.=':'.$formitem.'='.$env{$key};
 2836:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 2837:                     $what.=':'.$formitem.'='.$env{$key};
 2838:                 }
 2839:             }
 2840:         }
 2841:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 2842:         # FIXME: We should not be depending on a form parameter that someone
 2843:         # editing lonsearchcat.pm might change in the future.
 2844:         if ($env{'form.phase'} eq 'course_search') {
 2845:             $what.= ':POST';
 2846:             # FIXME: Probably ought to escape things....
 2847:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 2848:                                  'crsdiscuss') {
 2849:                 $what.=':'.$element.'='.$env{'form.'.$element};
 2850:             }
 2851:         }
 2852:     }
 2853:     &courselog($what);
 2854: }
 2855: 
 2856: sub countacc {
 2857:     my $url=&declutter(shift);
 2858:     return if (! defined($url) || $url eq '');
 2859:     unless ($env{'request.course.id'}) { return ''; }
 2860:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 2861:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 2862:     $accesshash{$key}++;
 2863: }
 2864: 
 2865: sub linklog {
 2866:     my ($from,$to)=@_;
 2867:     $from=&declutter($from);
 2868:     $to=&declutter($to);
 2869:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 2870:     $accesshash{$to.'___'.$from.'___goto'}=1;
 2871: }
 2872:   
 2873: sub userrolelog {
 2874:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 2875:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 2876:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 2877:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 2878:         ($trole=~/^ta/) || ($trole=~/^co/)) {
 2879:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2880:        $userrolehash
 2881:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2882:                     =$tend.':'.$tstart;
 2883:     }
 2884:     if (($env{'request.role'} =~ /dc\./) &&
 2885: 	(($trole=~/^au/) || ($trole=~/^in/) ||
 2886: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
 2887: 	 ($trole=~/^cr/) || ($trole=~/^ta/) ||
 2888:          ($trole=~/^co/))) {
 2889:        $userrolehash
 2890:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 2891:                     =$tend.':'.$tstart;
 2892:     }
 2893:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 2894:         ($trole=~/^li/) || ($trole=~/^li/) ||
 2895:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 2896:         ($trole=~/^sc/)) {
 2897:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2898:        $domainrolehash
 2899:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2900:                     = $tend.':'.$tstart;
 2901:     }
 2902: }
 2903: 
 2904: sub courserolelog {
 2905:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 2906:     if (($trole eq 'cc') || ($trole eq 'in') ||
 2907:         ($trole eq 'ep') || ($trole eq 'ad') ||
 2908:         ($trole eq 'ta') || ($trole eq 'st') ||
 2909:         ($trole=~/^cr/) || ($trole eq 'gr') ||
 2910:         ($trole eq 'co')) {
 2911:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 2912:             my $cdom = $1;
 2913:             my $cnum = $2;
 2914:             my $sec = $3;
 2915:             my $namespace = 'rolelog';
 2916:             my %storehash = (
 2917:                                role    => $trole,
 2918:                                start   => $tstart,
 2919:                                end     => $tend,
 2920:                                selfenroll => $selfenroll,
 2921:                                context    => $context,
 2922:                             );
 2923:             if ($trole eq 'gr') {
 2924:                 $namespace = 'groupslog';
 2925:                 $storehash{'group'} = $sec;
 2926:             } else {
 2927:                 $storehash{'section'} = $sec;
 2928:             }
 2929:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
 2930:             if (($trole ne 'st') || ($sec ne '')) {
 2931:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
 2932:             }
 2933:         }
 2934:     }
 2935:     return;
 2936: }
 2937: 
 2938: sub get_course_adv_roles {
 2939:     my ($cid,$codes) = @_;
 2940:     $cid=$env{'request.course.id'} unless (defined($cid));
 2941:     my %coursehash=&coursedescription($cid);
 2942:     my $crstype = &Apache::loncommon::course_type($cid);
 2943:     my %nothide=();
 2944:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2945:         if ($user !~ /:/) {
 2946: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 2947:         } else {
 2948:             $nothide{$user}=1;
 2949:         }
 2950:     }
 2951:     my %returnhash=();
 2952:     my %dumphash=
 2953:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 2954:     my $now=time;
 2955:     my %privileged;
 2956:     foreach my $entry (keys(%dumphash)) {
 2957: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2958:         if (($tstart) && ($tstart<0)) { next; }
 2959:         if (($tend) && ($tend<$now)) { next; }
 2960:         if (($tstart) && ($now<$tstart)) { next; }
 2961:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 2962: 	if ($username eq '' || $domain eq '') { next; }
 2963:         unless (ref($privileged{$domain}) eq 'HASH') {
 2964:             my %dompersonnel =
 2965:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 2966:             $privileged{$domain} = {};
 2967:             foreach my $server (keys(%dompersonnel)) {
 2968:                 if (ref($dompersonnel{$server}) eq 'HASH') {
 2969:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
 2970:                         my ($trole,$uname,$udom) = split(/:/,$user);
 2971:                         $privileged{$udom}{$uname} = 1;
 2972:                     }
 2973:                 }
 2974:             }
 2975:         }
 2976:         if ((exists($privileged{$domain}{$username})) && 
 2977:             (!$nothide{$username.':'.$domain})) { next; }
 2978: 	if ($role eq 'cr') { next; }
 2979:         if ($codes) {
 2980:             if ($section) { $role .= ':'.$section; }
 2981:             if ($returnhash{$role}) {
 2982:                 $returnhash{$role}.=','.$username.':'.$domain;
 2983:             } else {
 2984:                 $returnhash{$role}=$username.':'.$domain;
 2985:             }
 2986:         } else {
 2987:             my $key=&plaintext($role,$crstype);
 2988:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 2989:             if ($returnhash{$key}) {
 2990: 	        $returnhash{$key}.=','.$username.':'.$domain;
 2991:             } else {
 2992:                 $returnhash{$key}=$username.':'.$domain;
 2993:             }
 2994:         }
 2995:     }
 2996:     return %returnhash;
 2997: }
 2998: 
 2999: sub get_my_roles {
 3000:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 3001:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 3002:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 3003:     my (%dumphash,%nothide);
 3004:     if ($context eq 'userroles') { 
 3005:         %dumphash = &dump('roles',$udom,$uname);
 3006:     } else {
 3007:         %dumphash=
 3008:             &dump('nohist_userroles',$udom,$uname);
 3009:         if ($hidepriv) {
 3010:             my %coursehash=&coursedescription($udom.'_'.$uname);
 3011:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 3012:                 if ($user !~ /:/) {
 3013:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 3014:                 } else {
 3015:                     $nothide{$user} = 1;
 3016:                 }
 3017:             }
 3018:         }
 3019:     }
 3020:     my %returnhash=();
 3021:     my $now=time;
 3022:     my %privileged;
 3023:     foreach my $entry (keys(%dumphash)) {
 3024:         my ($role,$tend,$tstart);
 3025:         if ($context eq 'userroles') {
 3026: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 3027:         } else {
 3028:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 3029:         }
 3030:         if (($tstart) && ($tstart<0)) { next; }
 3031:         my $status = 'active';
 3032:         if (($tend) && ($tend<=$now)) {
 3033:             $status = 'previous';
 3034:         } 
 3035:         if (($tstart) && ($now<$tstart)) {
 3036:             $status = 'future';
 3037:         }
 3038:         if (ref($types) eq 'ARRAY') {
 3039:             if (!grep(/^\Q$status\E$/,@{$types})) {
 3040:                 next;
 3041:             } 
 3042:         } else {
 3043:             if ($status ne 'active') {
 3044:                 next;
 3045:             }
 3046:         }
 3047:         my ($rolecode,$username,$domain,$section,$area);
 3048:         if ($context eq 'userroles') {
 3049:             ($area,$rolecode) = split(/_/,$entry);
 3050:             (undef,$domain,$username,$section) = split(/\//,$area);
 3051:         } else {
 3052:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 3053:         }
 3054:         if (ref($roledoms) eq 'ARRAY') {
 3055:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 3056:                 next;
 3057:             }
 3058:         }
 3059:         if (ref($roles) eq 'ARRAY') {
 3060:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 3061:                 if ($role =~ /^cr\//) {
 3062:                     if (!grep(/^cr$/,@{$roles})) {
 3063:                         next;
 3064:                     }
 3065:                 } else {
 3066:                     next;
 3067:                 }
 3068:             }
 3069:         }
 3070:         if ($hidepriv) {
 3071:             if ($context eq 'userroles') {
 3072:                 if ((&privileged($username,$domain)) &&
 3073:                     (!$nothide{$username.':'.$domain})) {
 3074:                     next;
 3075:                 }
 3076:             } else {
 3077:                 unless (ref($privileged{$domain}) eq 'HASH') {
 3078:                     my %dompersonnel =
 3079:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
 3080:                     $privileged{$domain} = {};
 3081:                     if (keys(%dompersonnel)) {
 3082:                         foreach my $server (keys(%dompersonnel)) {
 3083:                             if (ref($dompersonnel{$server}) eq 'HASH') {
 3084:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
 3085:                                     my ($trole,$uname,$udom) = split(/:/,$user);
 3086:                                     $privileged{$udom}{$uname} = $trole;
 3087:                                 }
 3088:                             }
 3089:                         }
 3090:                     }
 3091:                 }
 3092:                 if (exists($privileged{$domain}{$username})) {
 3093:                     if (!$nothide{$username.':'.$domain}) {
 3094:                         next;
 3095:                     }
 3096:                 }
 3097:             }
 3098:         }
 3099:         if ($withsec) {
 3100:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 3101:                 $tstart.':'.$tend;
 3102:         } else {
 3103:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 3104:         }
 3105:     }
 3106:     return %returnhash;
 3107: }
 3108: 
 3109: # ----------------------------------------------------- Frontpage Announcements
 3110: #
 3111: #
 3112: 
 3113: sub postannounce {
 3114:     my ($server,$text)=@_;
 3115:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 3116:     unless ($text=~/\w/) { $text=''; }
 3117:     return &reply('setannounce:'.&escape($text),$server);
 3118: }
 3119: 
 3120: sub getannounce {
 3121: 
 3122:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 3123: 	my $announcement='';
 3124: 	while (my $line = <$fh>) { $announcement .= $line; }
 3125: 	close($fh);
 3126: 	if ($announcement=~/\w/) { 
 3127: 	    return 
 3128:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 3129:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 3130: 	} else {
 3131: 	    return '';
 3132: 	}
 3133:     } else {
 3134: 	return '';
 3135:     }
 3136: }
 3137: 
 3138: # ---------------------------------------------------------- Course ID routines
 3139: # Deal with domain's nohist_courseid.db files
 3140: #
 3141: 
 3142: sub courseidput {
 3143:     my ($domain,$storehash,$coursehome,$caller) = @_;
 3144:     return unless (ref($storehash) eq 'HASH');
 3145:     my $outcome;
 3146:     if ($caller eq 'timeonly') {
 3147:         my $cids = '';
 3148:         foreach my $item (keys(%$storehash)) {
 3149:             $cids.=&escape($item).'&';
 3150:         }
 3151:         $cids=~s/\&$//;
 3152:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 3153:                           $coursehome);       
 3154:     } else {
 3155:         my $items = '';
 3156:         foreach my $item (keys(%$storehash)) {
 3157:             $items.= &escape($item).'='.
 3158:                      &freeze_escape($$storehash{$item}).'&';
 3159:         }
 3160:         $items=~s/\&$//;
 3161:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 3162:                           $coursehome);
 3163:     }
 3164:     if ($outcome eq 'unknown_cmd') {
 3165:         my $what;
 3166:         foreach my $cid (keys(%$storehash)) {
 3167:             $what .= &escape($cid).'=';
 3168:             foreach my $item ('description','inst_code','owner','type') {
 3169:                 $what .= &escape($storehash->{$cid}{$item}).':';
 3170:             }
 3171:             $what =~ s/\:$/&/;
 3172:         }
 3173:         $what =~ s/\&$//;  
 3174:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 3175:     } else {
 3176:         return $outcome;
 3177:     }
 3178: }
 3179: 
 3180: sub courseiddump {
 3181:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 3182:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 3183:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
 3184:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
 3185:     my $as_hash = 1;
 3186:     my %returnhash;
 3187:     if (!$domfilter) { $domfilter=''; }
 3188:     my %libserv = &all_library();
 3189:     foreach my $tryserver (keys(%libserv)) {
 3190:         if ( (  $hostidflag == 1 
 3191: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 3192: 	     || (!defined($hostidflag)) ) {
 3193: 
 3194: 	    if (($domfilter eq '') ||
 3195: 		(&host_domain($tryserver) eq $domfilter)) {
 3196:                 my $rep = 
 3197:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
 3198:                          $sincefilter.':'.&escape($descfilter).':'.
 3199:                          &escape($instcodefilter).':'.&escape($ownerfilter).
 3200:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
 3201:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
 3202:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
 3203:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
 3204:                          &escape($cc_clone).':'.$cloneonly.':'.
 3205:                          &escape($createdbefore).':'.&escape($createdafter).':'.
 3206:                          &escape($creationcontext).':'.$domcloner,
 3207:                          $tryserver);
 3208:                 my @pairs=split(/\&/,$rep);
 3209:                 foreach my $item (@pairs) {
 3210:                     my ($key,$value)=split(/\=/,$item,2);
 3211:                     $key = &unescape($key);
 3212:                     next if ($key =~ /^error: 2 /);
 3213:                     my $result = &thaw_unescape($value);
 3214:                     if (ref($result) eq 'HASH') {
 3215:                         $returnhash{$key}=$result;
 3216:                     } else {
 3217:                         my @responses = split(/:/,$value);
 3218:                         my @items = ('description','inst_code','owner','type');
 3219:                         for (my $i=0; $i<@responses; $i++) {
 3220:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 3221:                         }
 3222:                     }
 3223:                 }
 3224:             }
 3225:         }
 3226:     }
 3227:     return %returnhash;
 3228: }
 3229: 
 3230: sub courselastaccess {
 3231:     my ($cdom,$cnum,$hostidref) = @_;
 3232:     my %returnhash;
 3233:     if ($cdom && $cnum) {
 3234:         my $chome = &homeserver($cnum,$cdom);
 3235:         if ($chome ne 'no_host') {
 3236:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
 3237:             &extract_lastaccess(\%returnhash,$rep);
 3238:         }
 3239:     } else {
 3240:         if (!$cdom) { $cdom=''; }
 3241:         my %libserv = &all_library();
 3242:         foreach my $tryserver (keys(%libserv)) {
 3243:             if (ref($hostidref) eq 'ARRAY') {
 3244:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
 3245:             } 
 3246:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
 3247:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
 3248:                 &extract_lastaccess(\%returnhash,$rep);
 3249:             }
 3250:         }
 3251:     }
 3252:     return %returnhash;
 3253: }
 3254: 
 3255: sub extract_lastaccess {
 3256:     my ($returnhash,$rep) = @_;
 3257:     if (ref($returnhash) eq 'HASH') {
 3258:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
 3259:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
 3260:                  $rep eq '') {
 3261:             my @pairs=split(/\&/,$rep);
 3262:             foreach my $item (@pairs) {
 3263:                 my ($key,$value)=split(/\=/,$item,2);
 3264:                 $key = &unescape($key);
 3265:                 next if ($key =~ /^error: 2 /);
 3266:                 $returnhash->{$key} = &thaw_unescape($value);
 3267:             }
 3268:         }
 3269:     }
 3270:     return;
 3271: }
 3272: 
 3273: # ---------------------------------------------------------- DC e-mail
 3274: 
 3275: sub dcmailput {
 3276:     my ($domain,$msgid,$message,$server)=@_;
 3277:     my $status = &Apache::lonnet::critical(
 3278:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 3279:        &escape($message),$server);
 3280:     return $status;
 3281: }
 3282: 
 3283: sub dcmaildump {
 3284:     my ($dom,$startdate,$enddate,$senders) = @_;
 3285:     my %returnhash=();
 3286: 
 3287:     if (defined(&domain($dom,'primary'))) {
 3288:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 3289:                                                          &escape($enddate).':';
 3290: 	my @esc_senders=map { &escape($_)} @$senders;
 3291: 	$cmd.=&escape(join('&',@esc_senders));
 3292: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 3293:             my ($key,$value) = split(/\=/,$line,2);
 3294:             if (($key) && ($value)) {
 3295:                 $returnhash{&unescape($key)} = &unescape($value);
 3296:             }
 3297:         }
 3298:     }
 3299:     return %returnhash;
 3300: }
 3301: # ---------------------------------------------------------- Domain roles
 3302: 
 3303: sub get_domain_roles {
 3304:     my ($dom,$roles,$startdate,$enddate)=@_;
 3305:     if ((!defined($startdate)) || ($startdate eq '')) {
 3306:         $startdate = '.';
 3307:     }
 3308:     if ((!defined($enddate)) || ($enddate eq '')) {
 3309:         $enddate = '.';
 3310:     }
 3311:     my $rolelist;
 3312:     if (ref($roles) eq 'ARRAY') {
 3313:         $rolelist = join(':',@{$roles});
 3314:     }
 3315:     my %personnel = ();
 3316: 
 3317:     my %servers = &get_servers($dom,'library');
 3318:     foreach my $tryserver (keys(%servers)) {
 3319: 	%{$personnel{$tryserver}}=();
 3320: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 3321: 					    &escape($startdate).':'.
 3322: 					    &escape($enddate).':'.
 3323: 					    &escape($rolelist), $tryserver))) {
 3324: 	    my ($key,$value) = split(/\=/,$line,2);
 3325: 	    if (($key) && ($value)) {
 3326: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 3327: 	    }
 3328: 	}
 3329:     }
 3330:     return %personnel;
 3331: }
 3332: 
 3333: # ----------------------------------------------------------- Interval timing 
 3334: 
 3335: sub get_first_access {
 3336:     my ($type,$argsymb)=@_;
 3337:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 3338:     if ($argsymb) { $symb=$argsymb; }
 3339:     my ($map,$id,$res)=&decode_symb($symb);
 3340:     if ($type eq 'course') {
 3341: 	$res='course';
 3342:     } elsif ($type eq 'map') {
 3343: 	$res=&symbread($map);
 3344:     } else {
 3345: 	$res=$symb;
 3346:     }
 3347:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 3348:     return $times{"$courseid\0$res"};
 3349: }
 3350: 
 3351: sub set_first_access {
 3352:     my ($type)=@_;
 3353:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 3354:     my ($map,$id,$res)=&decode_symb($symb);
 3355:     if ($type eq 'course') {
 3356: 	$res='course';
 3357:     } elsif ($type eq 'map') {
 3358: 	$res=&symbread($map);
 3359:     } else {
 3360: 	$res=$symb;
 3361:     }
 3362:     my $firstaccess=&get_first_access($type,$symb);
 3363:     if (!$firstaccess) {
 3364: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 3365:     }
 3366:     return 'already_set';
 3367: }
 3368: 
 3369: # --------------------------------------------- Set Expire Date for Spreadsheet
 3370: 
 3371: sub expirespread {
 3372:     my ($uname,$udom,$stype,$usymb)=@_;
 3373:     my $cid=$env{'request.course.id'}; 
 3374:     if ($cid) {
 3375:        my $now=time;
 3376:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 3377:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 3378:                             $env{'course.'.$cid.'.num'}.
 3379: 	        	    ':nohist_expirationdates:'.
 3380:                             &escape($key).'='.$now,
 3381:                             $env{'course.'.$cid.'.home'})
 3382:     }
 3383:     return 'ok';
 3384: }
 3385: 
 3386: # ----------------------------------------------------- Devalidate Spreadsheets
 3387: 
 3388: sub devalidate {
 3389:     my ($symb,$uname,$udom)=@_;
 3390:     my $cid=$env{'request.course.id'}; 
 3391:     if ($cid) {
 3392:         # delete the stored spreadsheets for
 3393:         # - the student level sheet of this user in course's homespace
 3394:         # - the assessment level sheet for this resource 
 3395:         #   for this user in user's homespace
 3396: 	# - current conditional state info
 3397: 	my $key=$uname.':'.$udom.':';
 3398:         my $status=
 3399: 	    &del('nohist_calculatedsheets',
 3400: 		 [$key.'studentcalc:'],
 3401: 		 $env{'course.'.$cid.'.domain'},
 3402: 		 $env{'course.'.$cid.'.num'})
 3403: 		.' '.
 3404: 	    &del('nohist_calculatedsheets_'.$cid,
 3405: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 3406:         unless ($status eq 'ok ok') {
 3407:            &logthis('Could not devalidate spreadsheet '.
 3408:                     $uname.' at '.$udom.' for '.
 3409: 		    $symb.': '.$status);
 3410:         }
 3411: 	&delenv('user.state.'.$cid);
 3412:     }
 3413: }
 3414: 
 3415: sub get_scalar {
 3416:     my ($string,$end) = @_;
 3417:     my $value;
 3418:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 3419: 	$value = $1;
 3420:     } elsif ($$string =~ s/^([^&]*?)&//) {
 3421: 	$value = $1;
 3422:     }
 3423:     return &unescape($value);
 3424: }
 3425: 
 3426: sub array2str {
 3427:   my (@array) = @_;
 3428:   my $result=&arrayref2str(\@array);
 3429:   $result=~s/^__ARRAY_REF__//;
 3430:   $result=~s/__END_ARRAY_REF__$//;
 3431:   return $result;
 3432: }
 3433: 
 3434: sub arrayref2str {
 3435:   my ($arrayref) = @_;
 3436:   my $result='__ARRAY_REF__';
 3437:   foreach my $elem (@$arrayref) {
 3438:     if(ref($elem) eq 'ARRAY') {
 3439:       $result.=&arrayref2str($elem).'&';
 3440:     } elsif(ref($elem) eq 'HASH') {
 3441:       $result.=&hashref2str($elem).'&';
 3442:     } elsif(ref($elem)) {
 3443:       #print("Got a ref of ".(ref($elem))." skipping.");
 3444:     } else {
 3445:       $result.=&escape($elem).'&';
 3446:     }
 3447:   }
 3448:   $result=~s/\&$//;
 3449:   $result .= '__END_ARRAY_REF__';
 3450:   return $result;
 3451: }
 3452: 
 3453: sub hash2str {
 3454:   my (%hash) = @_;
 3455:   my $result=&hashref2str(\%hash);
 3456:   $result=~s/^__HASH_REF__//;
 3457:   $result=~s/__END_HASH_REF__$//;
 3458:   return $result;
 3459: }
 3460: 
 3461: sub hashref2str {
 3462:   my ($hashref)=@_;
 3463:   my $result='__HASH_REF__';
 3464:   foreach my $key (sort(keys(%$hashref))) {
 3465:     if (ref($key) eq 'ARRAY') {
 3466:       $result.=&arrayref2str($key).'=';
 3467:     } elsif (ref($key) eq 'HASH') {
 3468:       $result.=&hashref2str($key).'=';
 3469:     } elsif (ref($key)) {
 3470:       $result.='=';
 3471:       #print("Got a ref of ".(ref($key))." skipping.");
 3472:     } else {
 3473: 	if ($key) {$result.=&escape($key).'=';} else { last; }
 3474:     }
 3475: 
 3476:     if(ref($hashref->{$key}) eq 'ARRAY') {
 3477:       $result.=&arrayref2str($hashref->{$key}).'&';
 3478:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 3479:       $result.=&hashref2str($hashref->{$key}).'&';
 3480:     } elsif(ref($hashref->{$key})) {
 3481:        $result.='&';
 3482:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 3483:     } else {
 3484:       $result.=&escape($hashref->{$key}).'&';
 3485:     }
 3486:   }
 3487:   $result=~s/\&$//;
 3488:   $result .= '__END_HASH_REF__';
 3489:   return $result;
 3490: }
 3491: 
 3492: sub str2hash {
 3493:     my ($string)=@_;
 3494:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 3495:     return %$hash;
 3496: }
 3497: 
 3498: sub str2hashref {
 3499:   my ($string) = @_;
 3500: 
 3501:   my %hash;
 3502: 
 3503:   if($string !~ /^__HASH_REF__/) {
 3504:       if (! ($string eq '' || !defined($string))) {
 3505: 	  $hash{'error'}='Not hash reference';
 3506:       }
 3507:       return (\%hash, $string);
 3508:   }
 3509: 
 3510:   $string =~ s/^__HASH_REF__//;
 3511: 
 3512:   while($string !~ /^__END_HASH_REF__/) {
 3513:       #key
 3514:       my $key='';
 3515:       if($string =~ /^__HASH_REF__/) {
 3516:           ($key, $string)=&str2hashref($string);
 3517:           if(defined($key->{'error'})) {
 3518:               $hash{'error'}='Bad data';
 3519:               return (\%hash, $string);
 3520:           }
 3521:       } elsif($string =~ /^__ARRAY_REF__/) {
 3522:           ($key, $string)=&str2arrayref($string);
 3523:           if($key->[0] eq 'Array reference error') {
 3524:               $hash{'error'}='Bad data';
 3525:               return (\%hash, $string);
 3526:           }
 3527:       } else {
 3528:           $string =~ s/^(.*?)=//;
 3529: 	  $key=&unescape($1);
 3530:       }
 3531:       $string =~ s/^=//;
 3532: 
 3533:       #value
 3534:       my $value='';
 3535:       if($string =~ /^__HASH_REF__/) {
 3536:           ($value, $string)=&str2hashref($string);
 3537:           if(defined($value->{'error'})) {
 3538:               $hash{'error'}='Bad data';
 3539:               return (\%hash, $string);
 3540:           }
 3541:       } elsif($string =~ /^__ARRAY_REF__/) {
 3542:           ($value, $string)=&str2arrayref($string);
 3543:           if($value->[0] eq 'Array reference error') {
 3544:               $hash{'error'}='Bad data';
 3545:               return (\%hash, $string);
 3546:           }
 3547:       } else {
 3548: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 3549:       }
 3550:       $string =~ s/^&//;
 3551: 
 3552:       $hash{$key}=$value;
 3553:   }
 3554: 
 3555:   $string =~ s/^__END_HASH_REF__//;
 3556: 
 3557:   return (\%hash, $string);
 3558: }
 3559: 
 3560: sub str2array {
 3561:     my ($string)=@_;
 3562:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 3563:     return @$array;
 3564: }
 3565: 
 3566: sub str2arrayref {
 3567:   my ($string) = @_;
 3568:   my @array;
 3569: 
 3570:   if($string !~ /^__ARRAY_REF__/) {
 3571:       if (! ($string eq '' || !defined($string))) {
 3572: 	  $array[0]='Array reference error';
 3573:       }
 3574:       return (\@array, $string);
 3575:   }
 3576: 
 3577:   $string =~ s/^__ARRAY_REF__//;
 3578: 
 3579:   while($string !~ /^__END_ARRAY_REF__/) {
 3580:       my $value='';
 3581:       if($string =~ /^__HASH_REF__/) {
 3582:           ($value, $string)=&str2hashref($string);
 3583:           if(defined($value->{'error'})) {
 3584:               $array[0] ='Array reference error';
 3585:               return (\@array, $string);
 3586:           }
 3587:       } elsif($string =~ /^__ARRAY_REF__/) {
 3588:           ($value, $string)=&str2arrayref($string);
 3589:           if($value->[0] eq 'Array reference error') {
 3590:               $array[0] ='Array reference error';
 3591:               return (\@array, $string);
 3592:           }
 3593:       } else {
 3594: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 3595:       }
 3596:       $string =~ s/^&//;
 3597: 
 3598:       push(@array, $value);
 3599:   }
 3600: 
 3601:   $string =~ s/^__END_ARRAY_REF__//;
 3602: 
 3603:   return (\@array, $string);
 3604: }
 3605: 
 3606: # -------------------------------------------------------------------Temp Store
 3607: 
 3608: sub tmpreset {
 3609:   my ($symb,$namespace,$domain,$stuname) = @_;
 3610:   if (!$symb) {
 3611:     $symb=&symbread();
 3612:     if (!$symb) { $symb= $env{'request.url'}; }
 3613:   }
 3614:   $symb=escape($symb);
 3615: 
 3616:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3617:   $namespace=~s/\//\_/g;
 3618:   $namespace=~s/\W//g;
 3619: 
 3620:   if (!$domain) { $domain=$env{'user.domain'}; }
 3621:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3622:   if ($domain eq 'public' && $stuname eq 'public') {
 3623:       $stuname=$ENV{'REMOTE_ADDR'};
 3624:   }
 3625:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3626:   my %hash;
 3627:   if (tie(%hash,'GDBM_File',
 3628: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3629: 	  &GDBM_WRCREAT(),0640)) {
 3630:     foreach my $key (keys(%hash)) {
 3631:       if ($key=~ /:$symb/) {
 3632: 	delete($hash{$key});
 3633:       }
 3634:     }
 3635:   }
 3636: }
 3637: 
 3638: sub tmpstore {
 3639:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3640: 
 3641:   if (!$symb) {
 3642:     $symb=&symbread();
 3643:     if (!$symb) { $symb= $env{'request.url'}; }
 3644:   }
 3645:   $symb=escape($symb);
 3646: 
 3647:   if (!$namespace) {
 3648:     # I don't think we would ever want to store this for a course.
 3649:     # it seems this will only be used if we don't have a course.
 3650:     #$namespace=$env{'request.course.id'};
 3651:     #if (!$namespace) {
 3652:       $namespace=$env{'request.state'};
 3653:     #}
 3654:   }
 3655:   $namespace=~s/\//\_/g;
 3656:   $namespace=~s/\W//g;
 3657:   if (!$domain) { $domain=$env{'user.domain'}; }
 3658:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3659:   if ($domain eq 'public' && $stuname eq 'public') {
 3660:       $stuname=$ENV{'REMOTE_ADDR'};
 3661:   }
 3662:   my $now=time;
 3663:   my %hash;
 3664:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3665:   if (tie(%hash,'GDBM_File',
 3666: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3667: 	  &GDBM_WRCREAT(),0640)) {
 3668:     $hash{"version:$symb"}++;
 3669:     my $version=$hash{"version:$symb"};
 3670:     my $allkeys=''; 
 3671:     foreach my $key (keys(%$storehash)) {
 3672:       $allkeys.=$key.':';
 3673:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 3674:     }
 3675:     $hash{"$version:$symb:timestamp"}=$now;
 3676:     $allkeys.='timestamp';
 3677:     $hash{"$version:keys:$symb"}=$allkeys;
 3678:     if (untie(%hash)) {
 3679:       return 'ok';
 3680:     } else {
 3681:       return "error:$!";
 3682:     }
 3683:   } else {
 3684:     return "error:$!";
 3685:   }
 3686: }
 3687: 
 3688: # -----------------------------------------------------------------Temp Restore
 3689: 
 3690: sub tmprestore {
 3691:   my ($symb,$namespace,$domain,$stuname) = @_;
 3692: 
 3693:   if (!$symb) {
 3694:     $symb=&symbread();
 3695:     if (!$symb) { $symb= $env{'request.url'}; }
 3696:   }
 3697:   $symb=escape($symb);
 3698: 
 3699:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3700: 
 3701:   if (!$domain) { $domain=$env{'user.domain'}; }
 3702:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3703:   if ($domain eq 'public' && $stuname eq 'public') {
 3704:       $stuname=$ENV{'REMOTE_ADDR'};
 3705:   }
 3706:   my %returnhash;
 3707:   $namespace=~s/\//\_/g;
 3708:   $namespace=~s/\W//g;
 3709:   my %hash;
 3710:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3711:   if (tie(%hash,'GDBM_File',
 3712: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3713: 	  &GDBM_READER(),0640)) {
 3714:     my $version=$hash{"version:$symb"};
 3715:     $returnhash{'version'}=$version;
 3716:     my $scope;
 3717:     for ($scope=1;$scope<=$version;$scope++) {
 3718:       my $vkeys=$hash{"$scope:keys:$symb"};
 3719:       my @keys=split(/:/,$vkeys);
 3720:       my $key;
 3721:       $returnhash{"$scope:keys"}=$vkeys;
 3722:       foreach $key (@keys) {
 3723: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3724: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3725:       }
 3726:     }
 3727:     if (!(untie(%hash))) {
 3728:       return "error:$!";
 3729:     }
 3730:   } else {
 3731:     return "error:$!";
 3732:   }
 3733:   return %returnhash;
 3734: }
 3735: 
 3736: # ----------------------------------------------------------------------- Store
 3737: 
 3738: sub store {
 3739:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3740:     my $home='';
 3741: 
 3742:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3743: 
 3744:     $symb=&symbclean($symb);
 3745:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3746: 
 3747:     if (!$domain) { $domain=$env{'user.domain'}; }
 3748:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3749: 
 3750:     &devalidate($symb,$stuname,$domain);
 3751: 
 3752:     $symb=escape($symb);
 3753:     if (!$namespace) { 
 3754:        unless ($namespace=$env{'request.course.id'}) { 
 3755:           return ''; 
 3756:        } 
 3757:     }
 3758:     if (!$home) { $home=$env{'user.home'}; }
 3759: 
 3760:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3761:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3762: 
 3763:     my $namevalue='';
 3764:     foreach my $key (keys(%$storehash)) {
 3765:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3766:     }
 3767:     $namevalue=~s/\&$//;
 3768:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 3769:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3770: }
 3771: 
 3772: # -------------------------------------------------------------- Critical Store
 3773: 
 3774: sub cstore {
 3775:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3776:     my $home='';
 3777: 
 3778:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3779: 
 3780:     $symb=&symbclean($symb);
 3781:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3782: 
 3783:     if (!$domain) { $domain=$env{'user.domain'}; }
 3784:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3785: 
 3786:     &devalidate($symb,$stuname,$domain);
 3787: 
 3788:     $symb=escape($symb);
 3789:     if (!$namespace) { 
 3790:        unless ($namespace=$env{'request.course.id'}) { 
 3791:           return ''; 
 3792:        } 
 3793:     }
 3794:     if (!$home) { $home=$env{'user.home'}; }
 3795: 
 3796:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3797:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3798: 
 3799:     my $namevalue='';
 3800:     foreach my $key (keys(%$storehash)) {
 3801:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3802:     }
 3803:     $namevalue=~s/\&$//;
 3804:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 3805:     return critical
 3806:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3807: }
 3808: 
 3809: # --------------------------------------------------------------------- Restore
 3810: 
 3811: sub restore {
 3812:     my ($symb,$namespace,$domain,$stuname) = @_;
 3813:     my $home='';
 3814: 
 3815:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3816: 
 3817:     if (!$symb) {
 3818:       unless ($symb=escape(&symbread())) { return ''; }
 3819:     } else {
 3820:       $symb=&escape(&symbclean($symb));
 3821:     }
 3822:     if (!$namespace) { 
 3823:        unless ($namespace=$env{'request.course.id'}) { 
 3824:           return ''; 
 3825:        } 
 3826:     }
 3827:     if (!$domain) { $domain=$env{'user.domain'}; }
 3828:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3829:     if (!$home) { $home=$env{'user.home'}; }
 3830:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 3831: 
 3832:     my %returnhash=();
 3833:     foreach my $line (split(/\&/,$answer)) {
 3834: 	my ($name,$value)=split(/\=/,$line);
 3835:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 3836:     }
 3837:     my $version;
 3838:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 3839:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 3840:           $returnhash{$item}=$returnhash{$version.':'.$item};
 3841:        }
 3842:     }
 3843:     return %returnhash;
 3844: }
 3845: 
 3846: # ---------------------------------------------------------- Course Description
 3847: 
 3848: sub coursedescription {
 3849:     my ($courseid,$args)=@_;
 3850:     $courseid=~s/^\///;
 3851:     $courseid=~s/\_/\//g;
 3852:     my ($cdomain,$cnum)=split(/\//,$courseid);
 3853:     my $chome=&homeserver($cnum,$cdomain);
 3854:     my $normalid=$cdomain.'_'.$cnum;
 3855:     # need to always cache even if we get errors otherwise we keep 
 3856:     # trying and trying and trying to get the course description.
 3857:     my %envhash=();
 3858:     my %returnhash=();
 3859:     
 3860:     my $expiretime=600;
 3861:     if ($env{'request.course.id'} eq $normalid) {
 3862: 	$expiretime=120;
 3863:     }
 3864: 
 3865:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 3866:     if (!$args->{'freshen_cache'}
 3867: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 3868: 	foreach my $key (keys(%env)) {
 3869: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 3870: 	    my ($setting) = $1;
 3871: 	    $returnhash{$setting} = $env{$key};
 3872: 	}
 3873: 	return %returnhash;
 3874:     }
 3875: 
 3876:     # get the data agin
 3877:     if (!$args->{'one_time'}) {
 3878: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 3879:     }
 3880: 
 3881:     if ($chome ne 'no_host') {
 3882:        %returnhash=&dump('environment',$cdomain,$cnum);
 3883:        if (!exists($returnhash{'con_lost'})) {
 3884:            $returnhash{'home'}= $chome;
 3885: 	   $returnhash{'domain'} = $cdomain;
 3886: 	   $returnhash{'num'} = $cnum;
 3887:            if (!defined($returnhash{'type'})) {
 3888:                $returnhash{'type'} = 'Course';
 3889:            }
 3890:            while (my ($name,$value) = each %returnhash) {
 3891:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 3892:            }
 3893:            $returnhash{'url'}=&clutter($returnhash{'url'});
 3894:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 3895: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
 3896:            $envhash{'course.'.$normalid.'.home'}=$chome;
 3897:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 3898:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 3899:        }
 3900:     }
 3901:     if (!$args->{'one_time'}) {
 3902: 	&appenv(\%envhash);
 3903:     }
 3904:     return %returnhash;
 3905: }
 3906: 
 3907: # -------------------------------------------------See if a user is privileged
 3908: 
 3909: sub privileged {
 3910:     my ($username,$domain)=@_;
 3911:     my $rolesdump=&reply("dump:$domain:$username:roles",
 3912: 			&homeserver($username,$domain));
 3913:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
 3914:         ($rolesdump =~ /^error:/)) {
 3915:         return 0;
 3916:     }
 3917:     my $now=time;
 3918:     if ($rolesdump ne '') {
 3919:         foreach my $entry (split(/&/,$rolesdump)) {
 3920: 	    if ($entry!~/^rolesdef_/) {
 3921: 		my ($area,$role)=split(/=/,$entry);
 3922: 		$area=~s/\_\w\w$//;
 3923: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 3924: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 3925: 		    my $active=1;
 3926: 		    if ($tend) {
 3927: 			if ($tend<$now) { $active=0; }
 3928: 		    }
 3929: 		    if ($tstart) {
 3930: 			if ($tstart>$now) { $active=0; }
 3931: 		    }
 3932: 		    if ($active) { return 1; }
 3933: 		}
 3934: 	    }
 3935: 	}
 3936:     }
 3937:     return 0;
 3938: }
 3939: 
 3940: # -------------------------------------------------------- Get user privileges
 3941: 
 3942: sub rolesinit {
 3943:     my ($domain,$username,$authhost)=@_;
 3944:     my $now=time;
 3945:     my %userroles = ('user.login.time' => $now);
 3946:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 3947:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
 3948:         ($rolesdump =~ /^error:/)) { 
 3949:         return \%userroles;
 3950:     }
 3951:     my %allroles=();
 3952:     my %allgroups=();   
 3953:     my $group_privs;
 3954: 
 3955:     if ($rolesdump ne '') {
 3956:         foreach my $entry (split(/&/,$rolesdump)) {
 3957: 	  if ($entry!~/^rolesdef_/) {
 3958:             my ($area,$role)=split(/=/,$entry);
 3959: 	    $area=~s/\_\w\w$//;
 3960:             my ($trole,$tend,$tstart,$group_privs);
 3961: 	    if ($role=~/^cr/) { 
 3962: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 3963: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
 3964: 		    ($tend,$tstart)=split('_',$trest);
 3965: 		} else {
 3966: 		    $trole=$role;
 3967: 		}
 3968:             } elsif ($role =~ m|^gr/|) {
 3969:                 ($trole,$tend,$tstart) = split(/_/,$role);
 3970:                 ($trole,$group_privs) = split(/\//,$trole);
 3971:                 $group_privs = &unescape($group_privs);
 3972: 	    } else {
 3973: 		($trole,$tend,$tstart)=split(/_/,$role);
 3974: 	    }
 3975: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 3976: 					 $username);
 3977: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 3978:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 3979:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 3980:             if (($area ne '') && ($trole ne '')) {
 3981: 		my $spec=$trole.'.'.$area;
 3982: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 3983: 		if ($trole =~ /^cr\//) {
 3984:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 3985:                 } elsif ($trole eq 'gr') {
 3986:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 3987: 		} else {
 3988:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 3989: 		}
 3990:             }
 3991:           }
 3992:         }
 3993:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 3994:         $userroles{'user.adv'}    = $adv;
 3995: 	$userroles{'user.author'} = $author;
 3996:         $env{'user.adv'}=$adv;
 3997:     }
 3998:     return \%userroles;  
 3999: }
 4000: 
 4001: sub set_arearole {
 4002:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 4003: # log the associated role with the area
 4004:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 4005:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 4006: }
 4007: 
 4008: sub custom_roleprivs {
 4009:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 4010:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 4011:     my $homsvr=homeserver($rauthor,$rdomain);
 4012:     if (&hostname($homsvr) ne '') {
 4013:         my ($rdummy,$roledef)=
 4014:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 4015:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4016:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 4017:             if (defined($syspriv)) {
 4018:                 if ($trest =~ /^$match_community$/) {
 4019:                     $syspriv =~ s/bre\&S//; 
 4020:                 }
 4021:                 $$allroles{'cm./'}.=':'.$syspriv;
 4022:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 4023:             }
 4024:             if ($tdomain ne '') {
 4025:                 if (defined($dompriv)) {
 4026:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 4027:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 4028:                 }
 4029:                 if (($trest ne '') && (defined($coursepriv))) {
 4030:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 4031:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 4032:                 }
 4033:             }
 4034:         }
 4035:     }
 4036: }
 4037: 
 4038: sub group_roleprivs {
 4039:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 4040:     my $access = 1;
 4041:     my $now = time;
 4042:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 4043:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 4044:     if ($access) {
 4045:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 4046:         $$allgroups{$course}{$group} .=':'.$group_privs;
 4047:     }
 4048: }
 4049: 
 4050: sub standard_roleprivs {
 4051:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 4052:     if (defined($pr{$trole.':s'})) {
 4053:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 4054:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 4055:     }
 4056:     if ($tdomain ne '') {
 4057:         if (defined($pr{$trole.':d'})) {
 4058:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 4059:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 4060:         }
 4061:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 4062:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 4063:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 4064:         }
 4065:     }
 4066: }
 4067: 
 4068: sub set_userprivs {
 4069:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 4070:     my $author=0;
 4071:     my $adv=0;
 4072:     my %grouproles = ();
 4073:     if (keys(%{$allgroups}) > 0) {
 4074:         my @groupkeys; 
 4075:         foreach my $role (keys(%{$allroles})) {
 4076:             push(@groupkeys,$role);
 4077:         }
 4078:         if (ref($groups_roles) eq 'HASH') {
 4079:             foreach my $key (keys(%{$groups_roles})) {
 4080:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 4081:                     push(@groupkeys,$key);
 4082:                 }
 4083:             }
 4084:         }
 4085:         if (@groupkeys > 0) {
 4086:             foreach my $role (@groupkeys) {
 4087:                 my ($trole,$area,$sec,$extendedarea);
 4088:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 4089:                     $trole = $1;
 4090:                     $area = $2;
 4091:                     $sec = $3;
 4092:                     $extendedarea = $area.$sec;
 4093:                     if (exists($$allgroups{$area})) {
 4094:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 4095:                             my $spec = $trole.'.'.$extendedarea;
 4096:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 4097:                                                 $$allgroups{$area}{$group};
 4098:                         }
 4099:                     }
 4100:                 }
 4101:             }
 4102:         }
 4103:     }
 4104:     foreach my $group (keys(%grouproles)) {
 4105:         $$allroles{$group} = $grouproles{$group};
 4106:     }
 4107:     foreach my $role (keys(%{$allroles})) {
 4108:         my %thesepriv;
 4109:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 4110:         foreach my $item (split(/:/,$$allroles{$role})) {
 4111:             if ($item ne '') {
 4112:                 my ($privilege,$restrictions)=split(/&/,$item);
 4113:                 if ($restrictions eq '') {
 4114:                     $thesepriv{$privilege}='F';
 4115:                 } elsif ($thesepriv{$privilege} ne 'F') {
 4116:                     $thesepriv{$privilege}.=$restrictions;
 4117:                 }
 4118:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 4119:             }
 4120:         }
 4121:         my $thesestr='';
 4122:         foreach my $priv (keys(%thesepriv)) {
 4123: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 4124: 	}
 4125:         $userroles->{'user.priv.'.$role} = $thesestr;
 4126:     }
 4127:     return ($author,$adv);
 4128: }
 4129: 
 4130: sub role_status {
 4131:     my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 4132:     my @pwhere = ();
 4133:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 4134:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
 4135:         unless (!defined($$role) || $$role eq '') {
 4136:             $$where=join('.',@pwhere);
 4137:             $$trolecode=$$role.'.'.$$where;
 4138:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 4139:             $$tstatus='is';
 4140:             if ($$tstart && $$tstart>$then) {
 4141:                 $$tstatus='future';
 4142:                 if ($$tstart<$now) {
 4143:                     if ($$tstart && $$tstart>$refresh) {
 4144:                         if (($$where ne '') && ($$role ne '')) {
 4145:                             my (%allroles,%allgroups,$group_privs,
 4146:                                 %groups_roles,@rolecodes);
 4147:                             my %userroles = (
 4148:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 4149:                             );
 4150:                             @rolecodes = ('cm'); 
 4151:                             my $spec=$$role.'.'.$$where;
 4152:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 4153:                             if ($$role =~ /^cr\//) {
 4154:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 4155:                                 push(@rolecodes,'cr');
 4156:                             } elsif ($$role eq 'gr') {
 4157:                                 push(@rolecodes,$$role);
 4158:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 4159:                                                     $env{'user.name'});
 4160:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 4161:                                 (undef,my $group_privs) = split(/\//,$trole);
 4162:                                 $group_privs = &unescape($group_privs);
 4163:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 4164:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 4165:                                 if (keys(%course_roles) > 0) {
 4166:                                     my ($tnum) = ($trest =~ /^($match_courseid)/);
 4167:                                     if ($tdomain ne '' && $tnum ne '') { 
 4168:                                         foreach my $key (keys(%course_roles)) {
 4169:                                             if ($key =~ /^\Q$tnum\E:\Q$tdomain\E:([^:]+):?([^:]*)/) {
 4170:                                                 my $crsrole = $1;
 4171:                                                 my $crssec = $2;
 4172:                                                 if ($crsrole =~ /^cr/) {
 4173:                                                     unless (grep(/^cr$/,@rolecodes)) {
 4174:                                                         push(@rolecodes,'cr');
 4175:                                                     }
 4176:                                                 } else {
 4177:                                                     unless(grep(/^\Q$crsrole\E$/,@rolecodes)) {
 4178:                                                         push(@rolecodes,$crsrole);
 4179:                                                     }
 4180:                                                 }
 4181:                                                 my $rolekey = $crsrole.'./'.$tdomain.'/'.$tnum;
 4182:                                                 if ($crssec ne '') {
 4183:                                                     $rolekey .= '/'.$crssec;
 4184:                                                 }
 4185:                                                 $rolekey .= './';
 4186:                                                 $groups_roles{$rolekey} = \@rolecodes;
 4187:                                             }
 4188:                                         }
 4189:                                     }
 4190:                                 }
 4191:                             } else {
 4192:                                 push(@rolecodes,$$role);
 4193:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 4194:                             }
 4195:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
 4196:                             &appenv(\%userroles,\@rolecodes);
 4197:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 4198:                         }
 4199:                     }
 4200:                     $$tstatus = 'is';
 4201:                 }
 4202:             }
 4203:             if ($$tend) {
 4204:                 if ($$tend<$then) {
 4205:                     $$tstatus='expired';
 4206:                 } elsif ($$tend<$now) {
 4207:                     $$tstatus='will_not';
 4208:                 }
 4209:             }
 4210:         }
 4211:     }
 4212: }
 4213: 
 4214: sub check_adhoc_privs {
 4215:     my ($cdom,$cnum,$then,$refresh,$now,$checkrole) = @_;
 4216:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 4217:     if ($env{$cckey}) {
 4218:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 4219:         &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 4220:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 4221:             &set_adhoc_privileges($cdom,$cnum,$checkrole);
 4222:         }
 4223:     } else {
 4224:         &set_adhoc_privileges($cdom,$cnum,$checkrole);
 4225:     }
 4226: }
 4227: 
 4228: sub set_adhoc_privileges {
 4229: # role can be cc or ca
 4230:     my ($dcdom,$pickedcourse,$role) = @_;
 4231:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 4232:     my $spec = $role.'.'.$area;
 4233:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 4234:                                   $env{'user.name'});
 4235:     my %ccrole = ();
 4236:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
 4237:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
 4238:     &appenv(\%userroles,[$role,'cm']);
 4239:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 4240:     &appenv( {'request.role'        => $spec,
 4241:               'request.role.domain' => $dcdom,
 4242:               'request.course.sec'  => ''
 4243:              }
 4244:            );
 4245:     my $tadv=0;
 4246:     if (&allowed('adv') eq 'F') { $tadv=1; }
 4247:     &appenv({'request.role.adv'    => $tadv});
 4248: }
 4249: 
 4250: # --------------------------------------------------------------- get interface
 4251: 
 4252: sub get {
 4253:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4254:    my $items='';
 4255:    foreach my $item (@$storearr) {
 4256:        $items.=&escape($item).'&';
 4257:    }
 4258:    $items=~s/\&$//;
 4259:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4260:    if (!$uname) { $uname=$env{'user.name'}; }
 4261:    my $uhome=&homeserver($uname,$udomain);
 4262: 
 4263:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 4264:    my @pairs=split(/\&/,$rep);
 4265:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 4266:      return @pairs;
 4267:    }
 4268:    my %returnhash=();
 4269:    my $i=0;
 4270:    foreach my $item (@$storearr) {
 4271:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 4272:       $i++;
 4273:    }
 4274:    return %returnhash;
 4275: }
 4276: 
 4277: # --------------------------------------------------------------- del interface
 4278: 
 4279: sub del {
 4280:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4281:    my $items='';
 4282:    foreach my $item (@$storearr) {
 4283:        $items.=&escape($item).'&';
 4284:    }
 4285: 
 4286:    $items=~s/\&$//;
 4287:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4288:    if (!$uname) { $uname=$env{'user.name'}; }
 4289:    my $uhome=&homeserver($uname,$udomain);
 4290:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 4291: }
 4292: 
 4293: # -------------------------------------------------------------- dump interface
 4294: 
 4295: sub dump {
 4296:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 4297:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4298:     if (!$uname) { $uname=$env{'user.name'}; }
 4299:     my $uhome=&homeserver($uname,$udomain);
 4300:     if ($regexp) {
 4301: 	$regexp=&escape($regexp);
 4302:     } else {
 4303: 	$regexp='.';
 4304:     }
 4305:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 4306:     my @pairs=split(/\&/,$rep);
 4307:     my %returnhash=();
 4308:     foreach my $item (@pairs) {
 4309: 	my ($key,$value)=split(/=/,$item,2);
 4310: 	$key = &unescape($key);
 4311: 	next if ($key =~ /^error: 2 /);
 4312: 	$returnhash{$key}=&thaw_unescape($value);
 4313:     }
 4314:     return %returnhash;
 4315: }
 4316: 
 4317: # --------------------------------------------------------- dumpstore interface
 4318: 
 4319: sub dumpstore {
 4320:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 4321:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4322:    if (!$uname) { $uname=$env{'user.name'}; }
 4323:    my $uhome=&homeserver($uname,$udomain);
 4324:    if ($regexp) {
 4325:        $regexp=&escape($regexp);
 4326:    } else {
 4327:        $regexp='.';
 4328:    }
 4329:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 4330:    my @pairs=split(/\&/,$rep);
 4331:    my %returnhash=();
 4332:    foreach my $item (@pairs) {
 4333:        my ($key,$value)=split(/=/,$item,2);
 4334:        next if ($key =~ /^error: 2 /);
 4335:        $returnhash{$key}=&thaw_unescape($value);
 4336:    }
 4337:    return %returnhash;
 4338: }
 4339: 
 4340: # -------------------------------------------------------------- keys interface
 4341: 
 4342: sub getkeys {
 4343:    my ($namespace,$udomain,$uname)=@_;
 4344:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4345:    if (!$uname) { $uname=$env{'user.name'}; }
 4346:    my $uhome=&homeserver($uname,$udomain);
 4347:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 4348:    my @keyarray=();
 4349:    foreach my $key (split(/\&/,$rep)) {
 4350:       next if ($key =~ /^error: 2 /);
 4351:       push(@keyarray,&unescape($key));
 4352:    }
 4353:    return @keyarray;
 4354: }
 4355: 
 4356: # --------------------------------------------------------------- currentdump
 4357: sub currentdump {
 4358:    my ($courseid,$sdom,$sname)=@_;
 4359:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 4360:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 4361:    $sname    = $env{'user.name'}         if (! defined($sname));
 4362:    my $uhome = &homeserver($sname,$sdom);
 4363:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 4364:    return if ($rep =~ /^(error:|no_such_host)/);
 4365:    #
 4366:    my %returnhash=();
 4367:    #
 4368:    if ($rep eq "unknown_cmd") { 
 4369:        # an old lond will not know currentdump
 4370:        # Do a dump and make it look like a currentdump
 4371:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 4372:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 4373:        my %hash = @tmp;
 4374:        @tmp=();
 4375:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 4376:    } else {
 4377:        my @pairs=split(/\&/,$rep);
 4378:        foreach my $pair (@pairs) {
 4379:            my ($key,$value)=split(/=/,$pair,2);
 4380:            my ($symb,$param) = split(/:/,$key);
 4381:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 4382:                                                         &thaw_unescape($value);
 4383:        }
 4384:    }
 4385:    return %returnhash;
 4386: }
 4387: 
 4388: sub convert_dump_to_currentdump{
 4389:     my %hash = %{shift()};
 4390:     my %returnhash;
 4391:     # Code ripped from lond, essentially.  The only difference
 4392:     # here is the unescaping done by lonnet::dump().  Conceivably
 4393:     # we might run in to problems with parameter names =~ /^v\./
 4394:     while (my ($key,$value) = each(%hash)) {
 4395:         my ($v,$symb,$param) = split(/:/,$key);
 4396: 	$symb  = &unescape($symb);
 4397: 	$param = &unescape($param);
 4398:         next if ($v eq 'version' || $symb eq 'keys');
 4399:         next if (exists($returnhash{$symb}) &&
 4400:                  exists($returnhash{$symb}->{$param}) &&
 4401:                  $returnhash{$symb}->{'v.'.$param} > $v);
 4402:         $returnhash{$symb}->{$param}=$value;
 4403:         $returnhash{$symb}->{'v.'.$param}=$v;
 4404:     }
 4405:     #
 4406:     # Remove all of the keys in the hashes which keep track of
 4407:     # the version of the parameter.
 4408:     while (my ($symb,$param_hash) = each(%returnhash)) {
 4409:         # use a foreach because we are going to delete from the hash.
 4410:         foreach my $key (keys(%$param_hash)) {
 4411:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 4412:         }
 4413:     }
 4414:     return \%returnhash;
 4415: }
 4416: 
 4417: # ------------------------------------------------------ critical inc interface
 4418: 
 4419: sub cinc {
 4420:     return &inc(@_,'critical');
 4421: }
 4422: 
 4423: # --------------------------------------------------------------- inc interface
 4424: 
 4425: sub inc {
 4426:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 4427:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4428:     if (!$uname) { $uname=$env{'user.name'}; }
 4429:     my $uhome=&homeserver($uname,$udomain);
 4430:     my $items='';
 4431:     if (! ref($store)) {
 4432:         # got a single value, so use that instead
 4433:         $items = &escape($store).'=&';
 4434:     } elsif (ref($store) eq 'SCALAR') {
 4435:         $items = &escape($$store).'=&';        
 4436:     } elsif (ref($store) eq 'ARRAY') {
 4437:         $items = join('=&',map {&escape($_);} @{$store});
 4438:     } elsif (ref($store) eq 'HASH') {
 4439:         while (my($key,$value) = each(%{$store})) {
 4440:             $items.= &escape($key).'='.&escape($value).'&';
 4441:         }
 4442:     }
 4443:     $items=~s/\&$//;
 4444:     if ($critical) {
 4445: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 4446:     } else {
 4447: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 4448:     }
 4449: }
 4450: 
 4451: # --------------------------------------------------------------- put interface
 4452: 
 4453: sub put {
 4454:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4455:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4456:    if (!$uname) { $uname=$env{'user.name'}; }
 4457:    my $uhome=&homeserver($uname,$udomain);
 4458:    my $items='';
 4459:    foreach my $item (keys(%$storehash)) {
 4460:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4461:    }
 4462:    $items=~s/\&$//;
 4463:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 4464: }
 4465: 
 4466: # ------------------------------------------------------------ newput interface
 4467: 
 4468: sub newput {
 4469:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4470:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4471:    if (!$uname) { $uname=$env{'user.name'}; }
 4472:    my $uhome=&homeserver($uname,$udomain);
 4473:    my $items='';
 4474:    foreach my $key (keys(%$storehash)) {
 4475:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4476:    }
 4477:    $items=~s/\&$//;
 4478:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 4479: }
 4480: 
 4481: # ---------------------------------------------------------  putstore interface
 4482: 
 4483: sub putstore {
 4484:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 4485:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4486:    if (!$uname) { $uname=$env{'user.name'}; }
 4487:    my $uhome=&homeserver($uname,$udomain);
 4488:    my $items='';
 4489:    foreach my $key (keys(%$storehash)) {
 4490:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 4491:    }
 4492:    $items=~s/\&$//;
 4493:    my $esc_symb=&escape($symb);
 4494:    my $esc_v=&escape($version);
 4495:    my $reply =
 4496:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 4497: 	      $uhome);
 4498:    if ($reply eq 'unknown_cmd') {
 4499:        # gfall back to way things use to be done
 4500:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 4501: 			    $uname);
 4502:    }
 4503:    return $reply;
 4504: }
 4505: 
 4506: sub old_putstore {
 4507:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 4508:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4509:     if (!$uname) { $uname=$env{'user.name'}; }
 4510:     my $uhome=&homeserver($uname,$udomain);
 4511:     my %newstorehash;
 4512:     foreach my $item (keys(%$storehash)) {
 4513: 	my $key = $version.':'.&escape($symb).':'.$item;
 4514: 	$newstorehash{$key} = $storehash->{$item};
 4515:     }
 4516:     my $items='';
 4517:     my %allitems = ();
 4518:     foreach my $item (keys(%newstorehash)) {
 4519: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 4520: 	    my $key = $1.':keys:'.$2;
 4521: 	    $allitems{$key} .= $3.':';
 4522: 	}
 4523: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 4524:     }
 4525:     foreach my $item (keys(%allitems)) {
 4526: 	$allitems{$item} =~ s/\:$//;
 4527: 	$items.= $item.'='.$allitems{$item}.'&';
 4528:     }
 4529:     $items=~s/\&$//;
 4530:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 4531: }
 4532: 
 4533: # ------------------------------------------------------ critical put interface
 4534: 
 4535: sub cput {
 4536:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4537:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4538:    if (!$uname) { $uname=$env{'user.name'}; }
 4539:    my $uhome=&homeserver($uname,$udomain);
 4540:    my $items='';
 4541:    foreach my $item (keys(%$storehash)) {
 4542:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4543:    }
 4544:    $items=~s/\&$//;
 4545:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 4546: }
 4547: 
 4548: # -------------------------------------------------------------- eget interface
 4549: 
 4550: sub eget {
 4551:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4552:    my $items='';
 4553:    foreach my $item (@$storearr) {
 4554:        $items.=&escape($item).'&';
 4555:    }
 4556:    $items=~s/\&$//;
 4557:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4558:    if (!$uname) { $uname=$env{'user.name'}; }
 4559:    my $uhome=&homeserver($uname,$udomain);
 4560:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 4561:    my @pairs=split(/\&/,$rep);
 4562:    my %returnhash=();
 4563:    my $i=0;
 4564:    foreach my $item (@$storearr) {
 4565:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 4566:       $i++;
 4567:    }
 4568:    return %returnhash;
 4569: }
 4570: 
 4571: # ------------------------------------------------------------ tmpput interface
 4572: sub tmpput {
 4573:     my ($storehash,$server,$context)=@_;
 4574:     my $items='';
 4575:     foreach my $item (keys(%$storehash)) {
 4576: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4577:     }
 4578:     $items=~s/\&$//;
 4579:     if (defined($context)) {
 4580:         $items .= ':'.&escape($context);
 4581:     }
 4582:     return &reply("tmpput:$items",$server);
 4583: }
 4584: 
 4585: # ------------------------------------------------------------ tmpget interface
 4586: sub tmpget {
 4587:     my ($token,$server)=@_;
 4588:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 4589:     my $rep=&reply("tmpget:$token",$server);
 4590:     my %returnhash;
 4591:     foreach my $item (split(/\&/,$rep)) {
 4592: 	my ($key,$value)=split(/=/,$item);
 4593:         next if ($key =~ /^error: 2 /);
 4594: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 4595:     }
 4596:     return %returnhash;
 4597: }
 4598: 
 4599: # ------------------------------------------------------------ tmpget interface
 4600: sub tmpdel {
 4601:     my ($token,$server)=@_;
 4602:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 4603:     return &reply("tmpdel:$token",$server);
 4604: }
 4605: 
 4606: # -------------------------------------------------- portfolio access checking
 4607: 
 4608: sub portfolio_access {
 4609:     my ($requrl) = @_;
 4610:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 4611:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 4612:     if ($result) {
 4613:         my %setters;
 4614:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4615:             my ($startblock,$endblock) =
 4616:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 4617:             if ($startblock && $endblock) {
 4618:                 return 'B';
 4619:             }
 4620:         } else {
 4621:             my ($startblock,$endblock) =
 4622:                 &Apache::loncommon::blockcheck(\%setters,'port');
 4623:             if ($startblock && $endblock) {
 4624:                 return 'B';
 4625:             }
 4626:         }
 4627:     }
 4628:     if ($result eq 'ok') {
 4629:        return 'F';
 4630:     } elsif ($result =~ /^[^:]+:guest_/) {
 4631:        return 'A';
 4632:     }
 4633:     return '';
 4634: }
 4635: 
 4636: sub get_portfolio_access {
 4637:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 4638: 
 4639:     if (!ref($access_hash)) {
 4640: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 4641: 	my %access_controls = &get_access_controls($current_perms,$group,
 4642: 						   $file_name);
 4643: 	$access_hash = $access_controls{$file_name};
 4644:     }
 4645: 
 4646:     my ($public,$guest,@domains,@users,@courses,@groups);
 4647:     my $now = time;
 4648:     if (ref($access_hash) eq 'HASH') {
 4649:         foreach my $key (keys(%{$access_hash})) {
 4650:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 4651:             if ($start > $now) {
 4652:                 next;
 4653:             }
 4654:             if ($end && $end<$now) {
 4655:                 next;
 4656:             }
 4657:             if ($scope eq 'public') {
 4658:                 $public = $key;
 4659:                 last;
 4660:             } elsif ($scope eq 'guest') {
 4661:                 $guest = $key;
 4662:             } elsif ($scope eq 'domains') {
 4663:                 push(@domains,$key);
 4664:             } elsif ($scope eq 'users') {
 4665:                 push(@users,$key);
 4666:             } elsif ($scope eq 'course') {
 4667:                 push(@courses,$key);
 4668:             } elsif ($scope eq 'group') {
 4669:                 push(@groups,$key);
 4670:             }
 4671:         }
 4672:         if ($public) {
 4673:             return 'ok';
 4674:         }
 4675:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4676:             if ($guest) {
 4677:                 return $guest;
 4678:             }
 4679:         } else {
 4680:             if (@domains > 0) {
 4681:                 foreach my $domkey (@domains) {
 4682:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 4683:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 4684:                             return 'ok';
 4685:                         }
 4686:                     }
 4687:                 }
 4688:             }
 4689:             if (@users > 0) {
 4690:                 foreach my $userkey (@users) {
 4691:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 4692:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 4693:                             if (ref($item) eq 'HASH') {
 4694:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 4695:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 4696:                                     return 'ok';
 4697:                                 }
 4698:                             }
 4699:                         }
 4700:                     } 
 4701:                 }
 4702:             }
 4703:             my %roleshash;
 4704:             my @courses_and_groups = @courses;
 4705:             push(@courses_and_groups,@groups); 
 4706:             if (@courses_and_groups > 0) {
 4707:                 my (%allgroups,%allroles); 
 4708:                 my ($start,$end,$role,$sec,$group);
 4709:                 foreach my $envkey (%env) {
 4710:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4711:                         my $cid = $2.'_'.$3; 
 4712:                         if ($1 eq 'gr') {
 4713:                             $group = $4;
 4714:                             $allgroups{$cid}{$group} = $env{$envkey};
 4715:                         } else {
 4716:                             if ($4 eq '') {
 4717:                                 $sec = 'none';
 4718:                             } else {
 4719:                                 $sec = $4;
 4720:                             }
 4721:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4722:                         }
 4723:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4724:                         my $cid = $2.'_'.$3;
 4725:                         if ($4 eq '') {
 4726:                             $sec = 'none';
 4727:                         } else {
 4728:                             $sec = $4;
 4729:                         }
 4730:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4731:                     }
 4732:                 }
 4733:                 if (keys(%allroles) == 0) {
 4734:                     return;
 4735:                 }
 4736:                 foreach my $key (@courses_and_groups) {
 4737:                     my %content = %{$$access_hash{$key}};
 4738:                     my $cnum = $content{'number'};
 4739:                     my $cdom = $content{'domain'};
 4740:                     my $cid = $cdom.'_'.$cnum;
 4741:                     if (!exists($allroles{$cid})) {
 4742:                         next;
 4743:                     }    
 4744:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 4745:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 4746:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 4747:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 4748:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 4749:                         foreach my $role (keys(%{$allroles{$cid}})) {
 4750:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 4751:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 4752:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 4753:                                         if (grep/^all$/,@sections) {
 4754:                                             return 'ok';
 4755:                                         } else {
 4756:                                             if (grep/^$sec$/,@sections) {
 4757:                                                 return 'ok';
 4758:                                             }
 4759:                                         }
 4760:                                     }
 4761:                                 }
 4762:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 4763:                                     if (grep/^none$/,@groups) {
 4764:                                         return 'ok';
 4765:                                     }
 4766:                                 } else {
 4767:                                     if (grep/^all$/,@groups) {
 4768:                                         return 'ok';
 4769:                                     } 
 4770:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 4771:                                         if (grep/^$group$/,@groups) {
 4772:                                             return 'ok';
 4773:                                         }
 4774:                                     }
 4775:                                 } 
 4776:                             }
 4777:                         }
 4778:                     }
 4779:                 }
 4780:             }
 4781:             if ($guest) {
 4782:                 return $guest;
 4783:             }
 4784:         }
 4785:     }
 4786:     return;
 4787: }
 4788: 
 4789: sub course_group_datechecker {
 4790:     my ($dates,$now,$status) = @_;
 4791:     my ($start,$end) = split(/\./,$dates);
 4792:     if (!$start && !$end) {
 4793:         return 'ok';
 4794:     }
 4795:     if (grep/^active$/,@{$status}) {
 4796:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 4797:             return 'ok';
 4798:         }
 4799:     }
 4800:     if (grep/^previous$/,@{$status}) {
 4801:         if ($end > $now ) {
 4802:             return 'ok';
 4803:         }
 4804:     }
 4805:     if (grep/^future$/,@{$status}) {
 4806:         if ($start > $now) {
 4807:             return 'ok';
 4808:         }
 4809:     }
 4810:     return; 
 4811: }
 4812: 
 4813: sub parse_portfolio_url {
 4814:     my ($url) = @_;
 4815: 
 4816:     my ($type,$udom,$unum,$group,$file_name);
 4817:     
 4818:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 4819: 	$type = 1;
 4820:         $udom = $1;
 4821:         $unum = $2;
 4822:         $file_name = $3;
 4823:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 4824: 	$type = 2;
 4825:         $udom = $1;
 4826:         $unum = $2;
 4827:         $group = $3;
 4828:         $file_name = $3.'/'.$4;
 4829:     }
 4830:     if (wantarray) {
 4831: 	return ($type,$udom,$unum,$file_name,$group);
 4832:     }
 4833:     return $type;
 4834: }
 4835: 
 4836: sub is_portfolio_url {
 4837:     my ($url) = @_;
 4838:     return scalar(&parse_portfolio_url($url));
 4839: }
 4840: 
 4841: sub is_portfolio_file {
 4842:     my ($file) = @_;
 4843:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 4844:         return 1;
 4845:     }
 4846:     return;
 4847: }
 4848: 
 4849: sub usertools_access {
 4850:     my ($uname,$udom,$tool,$action,$context) = @_;
 4851:     my ($access,%tools);
 4852:     if ($context eq '') {
 4853:         $context = 'tools';
 4854:     }
 4855:     if ($context eq 'requestcourses') {
 4856:         %tools = (
 4857:                       official   => 1,
 4858:                       unofficial => 1,
 4859:                       community  => 1,
 4860:                  );
 4861:     } else {
 4862:         %tools = (
 4863:                       aboutme   => 1,
 4864:                       blog      => 1,
 4865:                       portfolio => 1,
 4866:                  );
 4867:     }
 4868:     return if (!defined($tools{$tool}));
 4869: 
 4870:     if ((!defined($udom)) || (!defined($uname))) {
 4871:         $udom = $env{'user.domain'};
 4872:         $uname = $env{'user.name'};
 4873:     }
 4874: 
 4875:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 4876:         if ($action ne 'reload') {
 4877:             if ($context eq 'requestcourses') {
 4878:                 return $env{'environment.canrequest.'.$tool};
 4879:             } else {
 4880:                 return $env{'environment.availabletools.'.$tool};
 4881:             }
 4882:         }
 4883:     }
 4884: 
 4885:     my ($toolstatus,$inststatus);
 4886: 
 4887:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 4888:          ($action ne 'reload')) {
 4889:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
 4890:         $inststatus = $env{'environment.inststatus'};
 4891:     } else {
 4892:         my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
 4893:         $toolstatus = $userenv{$context.'.'.$tool};
 4894:         $inststatus = $userenv{'inststatus'};
 4895:     }
 4896: 
 4897:     if ($toolstatus ne '') {
 4898:         if ($toolstatus) {
 4899:             $access = 1;
 4900:         } else {
 4901:             $access = 0;
 4902:         }
 4903:         return $access;
 4904:     }
 4905: 
 4906:     my $is_adv = &is_advanced_user($udom,$uname);
 4907:     my %domdef = &get_domain_defaults($udom);
 4908:     if (ref($domdef{$tool}) eq 'HASH') {
 4909:         if ($is_adv) {
 4910:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 4911:                 if ($domdef{$tool}{'_LC_adv'}) { 
 4912:                     $access = 1;
 4913:                 } else {
 4914:                     $access = 0;
 4915:                 }
 4916:                 return $access;
 4917:             }
 4918:         }
 4919:         if ($inststatus ne '') {
 4920:             my ($hasaccess,$hasnoaccess);
 4921:             foreach my $affiliation (split(/:/,$inststatus)) {
 4922:                 if ($domdef{$tool}{$affiliation} ne '') { 
 4923:                     if ($domdef{$tool}{$affiliation}) {
 4924:                         $hasaccess = 1;
 4925:                     } else {
 4926:                         $hasnoaccess = 1;
 4927:                     }
 4928:                 }
 4929:             }
 4930:             if ($hasaccess || $hasnoaccess) {
 4931:                 if ($hasaccess) {
 4932:                     $access = 1;
 4933:                 } elsif ($hasnoaccess) {
 4934:                     $access = 0; 
 4935:                 }
 4936:                 return $access;
 4937:             }
 4938:         } else {
 4939:             if ($domdef{$tool}{'default'} ne '') {
 4940:                 if ($domdef{$tool}{'default'}) {
 4941:                     $access = 1;
 4942:                 } elsif ($domdef{$tool}{'default'} == 0) {
 4943:                     $access = 0;
 4944:                 }
 4945:                 return $access;
 4946:             }
 4947:         }
 4948:     } else {
 4949:         if ($context eq 'tools') {
 4950:             $access = 1;
 4951:         } else {
 4952:             $access = 0;
 4953:         }
 4954:         return $access;
 4955:     }
 4956: }
 4957: 
 4958: sub is_course_owner {
 4959:     my ($cdom,$cnum,$udom,$uname) = @_;
 4960:     if (($udom eq '') || ($uname eq '')) {
 4961:         $udom = $env{'user.domain'};
 4962:         $uname = $env{'user.name'};
 4963:     }
 4964:     unless (($udom eq '') || ($uname eq '')) {
 4965:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 4966:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 4967:                 return 1;
 4968:             } else {
 4969:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 4970:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 4971:                     return 1;
 4972:                 }
 4973:             }
 4974:         }
 4975:     }
 4976:     return;
 4977: }
 4978: 
 4979: sub is_advanced_user {
 4980:     my ($udom,$uname) = @_;
 4981:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 4982:     my %allroles;
 4983:     my $is_adv;
 4984:     foreach my $role (keys(%roleshash)) {
 4985:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 4986:         my $area = '/'.$tdomain.'/'.$trest;
 4987:         if ($sec ne '') {
 4988:             $area .= '/'.$sec;
 4989:         }
 4990:         if (($area ne '') && ($trole ne '')) {
 4991:             my $spec=$trole.'.'.$area;
 4992:             if ($trole =~ /^cr\//) {
 4993:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 4994:             } elsif ($trole ne 'gr') {
 4995:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 4996:             }
 4997:         }
 4998:     }
 4999:     foreach my $role (keys(%allroles)) {
 5000:         last if ($is_adv);
 5001:         foreach my $item (split(/:/,$allroles{$role})) {
 5002:             if ($item ne '') {
 5003:                 my ($privilege,$restrictions)=split(/&/,$item);
 5004:                 if ($privilege eq 'adv') {
 5005:                     $is_adv = 1;
 5006:                     last;
 5007:                 }
 5008:             }
 5009:         }
 5010:     }
 5011:     return $is_adv;
 5012: }
 5013: 
 5014: sub check_can_request {
 5015:     my ($dom,$can_request,$request_domains) = @_;
 5016:     my $canreq = 0;
 5017:     my ($types,$typename) = &Apache::loncommon::course_types();
 5018:     my @options = ('approval','validate','autolimit');
 5019:     my $optregex = join('|',@options);
 5020:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 5021:         foreach my $type (@{$types}) {
 5022:             if (&usertools_access($env{'user.name'},
 5023:                                   $env{'user.domain'},
 5024:                                   $type,undef,'requestcourses')) {
 5025:                 $canreq ++;
 5026:                 if (ref($request_domains) eq 'HASH') {
 5027:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 5028:                 }
 5029:                 if ($dom eq $env{'user.domain'}) {
 5030:                     $can_request->{$type} = 1;
 5031:                 }
 5032:             }
 5033:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 5034:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 5035:                 if (@curr > 0) {
 5036:                     foreach my $item (@curr) {
 5037:                         if (ref($request_domains) eq 'HASH') {
 5038:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 5039:                             if ($otherdom ne '') {
 5040:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 5041:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 5042:                                         push(@{$request_domains->{$type}},$otherdom);
 5043:                                     }
 5044:                                 } else {
 5045:                                     push(@{$request_domains->{$type}},$otherdom);
 5046:                                 }
 5047:                             }
 5048:                         }
 5049:                     }
 5050:                     unless($dom eq $env{'user.domain'}) {
 5051:                         $canreq ++;
 5052:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 5053:                             $can_request->{$type} = 1;
 5054:                         }
 5055:                     }
 5056:                 }
 5057:             }
 5058:         }
 5059:     }
 5060:     return $canreq;
 5061: }
 5062: 
 5063: # ---------------------------------------------- Custom access rule evaluation
 5064: 
 5065: sub customaccess {
 5066:     my ($priv,$uri)=@_;
 5067:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 5068:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 5069:     $udom = &LONCAPA::clean_domain($udom);
 5070:     $ucrs = &LONCAPA::clean_username($ucrs);
 5071:     my $access=0;
 5072:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 5073: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 5074: 	if ($type eq 'user') {
 5075: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 5076: 		my ($tdom,$tuname)=split(m{/},$scope);
 5077: 		if ($tdom) {
 5078: 		    if ($tdom ne $env{'user.domain'}) { next; }
 5079: 		}
 5080: 		if ($tuname) {
 5081: 		    if ($tuname ne $env{'user.name'}) { next; }
 5082: 		}
 5083: 		$access=($effect eq 'allow');
 5084: 		last;
 5085: 	    }
 5086: 	} else {
 5087: 	    if ($role) {
 5088: 		if ($role ne $urole) { next; }
 5089: 	    }
 5090: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 5091: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 5092: 		if ($tdom) {
 5093: 		    if ($tdom ne $udom) { next; }
 5094: 		}
 5095: 		if ($tcrs) {
 5096: 		    if ($tcrs ne $ucrs) { next; }
 5097: 		}
 5098: 		if ($tsec) {
 5099: 		    if ($tsec ne $usec) { next; }
 5100: 		}
 5101: 		$access=($effect eq 'allow');
 5102: 		last;
 5103: 	    }
 5104: 	    if ($realm eq '' && $role eq '') {
 5105: 		$access=($effect eq 'allow');
 5106: 	    }
 5107: 	}
 5108:     }
 5109:     return $access;
 5110: }
 5111: 
 5112: # ------------------------------------------------- Check for a user privilege
 5113: 
 5114: sub allowed {
 5115:     my ($priv,$uri,$symb,$role)=@_;
 5116:     my $ver_orguri=$uri;
 5117:     $uri=&deversion($uri);
 5118:     my $orguri=$uri;
 5119:     $uri=&declutter($uri);
 5120: 
 5121:     if ($priv eq 'evb') {
 5122: # Evade communication block restrictions for specified role in a course
 5123:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 5124:             return $1;
 5125:         } else {
 5126:             return;
 5127:         }
 5128:     }
 5129: 
 5130:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 5131: # Free bre access to adm and meta resources
 5132:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 5133: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 5134: 	&& ($priv eq 'bre')) {
 5135: 	return 'F';
 5136:     }
 5137: 
 5138: # Free bre access to user's own portfolio contents
 5139:     my ($space,$domain,$name,@dir)=split('/',$uri);
 5140:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 5141: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 5142:         my %setters;
 5143:         my ($startblock,$endblock) = 
 5144:             &Apache::loncommon::blockcheck(\%setters,'port');
 5145:         if ($startblock && $endblock) {
 5146:             return 'B';
 5147:         } else {
 5148:             return 'F';
 5149:         }
 5150:     }
 5151: 
 5152: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 5153:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 5154:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 5155:         if (exists($env{'request.course.id'})) {
 5156:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5157:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5158:             if (($domain eq $cdom) && ($name eq $cnum)) {
 5159:                 my $courseprivid=$env{'request.course.id'};
 5160:                 $courseprivid=~s/\_/\//;
 5161:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 5162:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 5163:                     return $1; 
 5164:                 } else {
 5165:                     if ($env{'request.course.sec'}) {
 5166:                         $courseprivid.='/'.$env{'request.course.sec'};
 5167:                     }
 5168:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 5169:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 5170:                         return $2;
 5171:                     }
 5172:                 }
 5173:             }
 5174:         }
 5175:     }
 5176: 
 5177: # Free bre to public access
 5178: 
 5179:     if ($priv eq 'bre') {
 5180:         my $copyright=&metadata($uri,'copyright');
 5181: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 5182:            return 'F'; 
 5183:         }
 5184:         if ($copyright eq 'priv') {
 5185:             $uri=~/([^\/]+)\/([^\/]+)\//;
 5186: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 5187: 		return '';
 5188:             }
 5189:         }
 5190:         if ($copyright eq 'domain') {
 5191:             $uri=~/([^\/]+)\/([^\/]+)\//;
 5192: 	    unless (($env{'user.domain'} eq $1) ||
 5193:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 5194: 		return '';
 5195:             }
 5196:         }
 5197:         if ($env{'request.role'}=~ /li\.\//) {
 5198:             # Library role, so allow browsing of resources in this domain.
 5199:             return 'F';
 5200:         }
 5201:         if ($copyright eq 'custom') {
 5202: 	    unless (&customaccess($priv,$uri)) { return ''; }
 5203:         }
 5204:     }
 5205:     # Domain coordinator is trying to create a course
 5206:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 5207:         # uri is the requested domain in this case.
 5208:         # comparison to 'request.role.domain' shows if the user has selected
 5209:         # a role of dc for the domain in question.
 5210:         return 'F' if ($uri eq $env{'request.role.domain'});
 5211:     }
 5212: 
 5213:     my $thisallowed='';
 5214:     my $statecond=0;
 5215:     my $courseprivid='';
 5216: 
 5217:     my $ownaccess;
 5218:     # Community Coordinator or Assistant Co-author browsing resource space.
 5219:     if (($priv eq 'bro') && ($env{'user.author'})) {
 5220:         if ($uri eq '') {
 5221:             $ownaccess = 1;
 5222:         } else {
 5223:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 5224:                 my $udom = $env{'user.domain'};
 5225:                 my $uname = $env{'user.name'};
 5226:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 5227:                     $ownaccess = 1;
 5228:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 5229:                     unless ($uri =~ m{\.\./}) {
 5230:                         $ownaccess = 1;
 5231:                     }
 5232:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 5233:                     my $now = time;
 5234:                     if ($uri =~ m{^([^/]+)/?$}) {
 5235:                         my $adom = $1;
 5236:                         foreach my $key (keys(%env)) {
 5237:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 5238:                                 my ($start,$end) = split('.',$env{$key});
 5239:                                 if (($now >= $start) && (!$end || $end < $now)) {
 5240:                                     $ownaccess = 1;
 5241:                                     last;
 5242:                                 }
 5243:                             }
 5244:                         }
 5245:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 5246:                         my $adom = $1;
 5247:                         my $aname = $2;
 5248:                         foreach my $role ('ca','aa') { 
 5249:                             if ($env{"user.role.$role./$adom/$aname"}) {
 5250:                                 my ($start,$end) =
 5251:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 5252:                                 if (($now >= $start) && (!$end || $end < $now)) {
 5253:                                     $ownaccess = 1;
 5254:                                     last;
 5255:                                 }
 5256:                             }
 5257:                         }
 5258:                     }
 5259:                 }
 5260:             }
 5261:         }
 5262:     }
 5263: 
 5264: # Course
 5265: 
 5266:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 5267:         unless (($priv eq 'bro') && (!$ownaccess)) {
 5268:             $thisallowed.=$1;
 5269:         }
 5270:     }
 5271: 
 5272: # Domain
 5273: 
 5274:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 5275:        =~/\Q$priv\E\&([^\:]*)/) {
 5276:         unless (($priv eq 'bro') && (!$ownaccess)) {
 5277:             $thisallowed.=$1;
 5278:         }
 5279:     }
 5280: 
 5281: # Course: uri itself is a course
 5282:     my $courseuri=$uri;
 5283:     $courseuri=~s/\_(\d)/\/$1/;
 5284:     $courseuri=~s/^([^\/])/\/$1/;
 5285: 
 5286:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 5287:        =~/\Q$priv\E\&([^\:]*)/) {
 5288:         unless (($priv eq 'bro') && (!$ownaccess)) {
 5289:             $thisallowed.=$1;
 5290:         }
 5291:     }
 5292: 
 5293: # URI is an uploaded document for this course, default permissions don't matter
 5294: # not allowing 'edit' access (editupload) to uploaded course docs
 5295:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 5296: 	$thisallowed='';
 5297:         my ($match)=&is_on_map($uri);
 5298:         if ($match) {
 5299:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 5300:                   =~/\Q$priv\E\&([^\:]*)/) {
 5301:                 $thisallowed.=$1;
 5302:             }
 5303:         } else {
 5304:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 5305:             if ($refuri) {
 5306:                 if ($refuri =~ m|^/adm/|) {
 5307:                     $thisallowed='F';
 5308:                 } else {
 5309:                     $refuri=&declutter($refuri);
 5310:                     my ($match) = &is_on_map($refuri);
 5311:                     if ($match) {
 5312:                         $thisallowed='F';
 5313:                     }
 5314:                 }
 5315:             }
 5316:         }
 5317:     }
 5318: 
 5319:     if ($priv eq 'bre'
 5320: 	&& $thisallowed ne 'F' 
 5321: 	&& $thisallowed ne '2'
 5322: 	&& &is_portfolio_url($uri)) {
 5323: 	$thisallowed = &portfolio_access($uri);
 5324:     }
 5325:     
 5326: # Full access at system, domain or course-wide level? Exit.
 5327:     if ($thisallowed=~/F/) {
 5328: 	return 'F';
 5329:     }
 5330: 
 5331: # If this is generating or modifying users, exit with special codes
 5332: 
 5333:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 5334: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 5335: 	    my ($audom,$auname)=split('/',$uri);
 5336: # no author name given, so this just checks on the general right to make a co-author in this domain
 5337: 	    unless ($auname) { return $thisallowed; }
 5338: # an author name is given, so we are about to actually make a co-author for a certain account
 5339: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 5340: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 5341: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 5342: 	}
 5343: 	return $thisallowed;
 5344:     }
 5345: #
 5346: # Gathered so far: system, domain and course wide privileges
 5347: #
 5348: # Course: See if uri or referer is an individual resource that is part of 
 5349: # the course
 5350: 
 5351:     if ($env{'request.course.id'}) {
 5352: 
 5353:        $courseprivid=$env{'request.course.id'};
 5354:        if ($env{'request.course.sec'}) {
 5355:           $courseprivid.='/'.$env{'request.course.sec'};
 5356:        }
 5357:        $courseprivid=~s/\_/\//;
 5358:        my $checkreferer=1;
 5359:        my ($match,$cond)=&is_on_map($uri);
 5360:        if ($match) {
 5361:            $statecond=$cond;
 5362:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 5363:                =~/\Q$priv\E\&([^\:]*)/) {
 5364:                $thisallowed.=$1;
 5365:                $checkreferer=0;
 5366:            }
 5367:        }
 5368:        
 5369:        if ($checkreferer) {
 5370: 	  my $refuri=$env{'httpref.'.$orguri};
 5371:             unless ($refuri) {
 5372:                 foreach my $key (keys(%env)) {
 5373: 		    if ($key=~/^httpref\..*\*/) {
 5374: 			my $pattern=$key;
 5375:                         $pattern=~s/^httpref\.\/res\///;
 5376:                         $pattern=~s/\*/\[\^\/\]\+/g;
 5377:                         $pattern=~s/\//\\\//g;
 5378:                         if ($orguri=~/$pattern/) {
 5379: 			    $refuri=$env{$key};
 5380:                         }
 5381:                     }
 5382:                 }
 5383:             }
 5384: 
 5385:          if ($refuri) { 
 5386: 	  $refuri=&declutter($refuri);
 5387:           my ($match,$cond)=&is_on_map($refuri);
 5388:             if ($match) {
 5389:               my $refstatecond=$cond;
 5390:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 5391:                   =~/\Q$priv\E\&([^\:]*)/) {
 5392:                   $thisallowed.=$1;
 5393:                   $uri=$refuri;
 5394:                   $statecond=$refstatecond;
 5395:               }
 5396:           }
 5397:         }
 5398:        }
 5399:    }
 5400: 
 5401: #
 5402: # Gathered now: all privileges that could apply, and condition number
 5403: # 
 5404: #
 5405: # Full or no access?
 5406: #
 5407: 
 5408:     if ($thisallowed=~/F/) {
 5409: 	return 'F';
 5410:     }
 5411: 
 5412:     unless ($thisallowed) {
 5413:         return '';
 5414:     }
 5415: 
 5416: # Restrictions exist, deal with them
 5417: #
 5418: #   C:according to course preferences
 5419: #   R:according to resource settings
 5420: #   L:unless locked
 5421: #   X:according to user session state
 5422: #
 5423: 
 5424: # Possibly locked functionality, check all courses
 5425: # Locks might take effect only after 10 minutes cache expiration for other
 5426: # courses, and 2 minutes for current course
 5427: 
 5428:     my $envkey;
 5429:     if ($thisallowed=~/L/) {
 5430:         foreach $envkey (keys(%env)) {
 5431:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 5432:                my $courseid=$2;
 5433:                my $roleid=$1.'.'.$2;
 5434:                $courseid=~s/^\///;
 5435:                my $expiretime=600;
 5436:                if ($env{'request.role'} eq $roleid) {
 5437: 		  $expiretime=120;
 5438:                }
 5439: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 5440:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 5441:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 5442: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 5443:                }
 5444:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 5445:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 5446: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 5447:                        &log($env{'user.domain'},$env{'user.name'},
 5448:                             $env{'user.home'},
 5449:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 5450:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 5451:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 5452: 		       return '';
 5453:                    }
 5454:                }
 5455:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 5456:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 5457: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 5458:                        &log($env{'user.domain'},$env{'user.name'},
 5459:                             $env{'user.home'},
 5460:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 5461:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 5462:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 5463: 		       return '';
 5464:                    }
 5465:                }
 5466: 	   }
 5467:        }
 5468:     }
 5469:    
 5470: #
 5471: # Rest of the restrictions depend on selected course
 5472: #
 5473: 
 5474:     unless ($env{'request.course.id'}) {
 5475: 	if ($thisallowed eq 'A') {
 5476: 	    return 'A';
 5477:         } elsif ($thisallowed eq 'B') {
 5478:             return 'B';
 5479: 	} else {
 5480: 	    return '1';
 5481: 	}
 5482:     }
 5483: 
 5484: #
 5485: # Now user is definitely in a course
 5486: #
 5487: 
 5488: 
 5489: # Course preferences
 5490: 
 5491:    if ($thisallowed=~/C/) {
 5492:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 5493:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 5494:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 5495: 	   =~/\Q$rolecode\E/) {
 5496: 	   if ($priv ne 'pch') { 
 5497: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 5498: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 5499: 			$env{'request.course.id'});
 5500: 	   }
 5501:            return '';
 5502:        }
 5503: 
 5504:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 5505: 	   =~/\Q$unamedom\E/) {
 5506: 	   if ($priv ne 'pch') { 
 5507: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 5508: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 5509: 			$env{'request.course.id'});
 5510: 	   }
 5511:            return '';
 5512:        }
 5513:    }
 5514: 
 5515: # Resource preferences
 5516: 
 5517:    if ($thisallowed=~/R/) {
 5518:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 5519:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 5520: 	   if ($priv ne 'pch') { 
 5521: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 5522: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 5523: 	   }
 5524: 	   return '';
 5525:        }
 5526:    }
 5527: 
 5528: # Restricted by state or randomout?
 5529: 
 5530:    if ($thisallowed=~/X/) {
 5531:       if ($env{'acc.randomout'}) {
 5532: 	 if (!$symb) { $symb=&symbread($uri,1); }
 5533:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 5534:             return ''; 
 5535:          }
 5536:       }
 5537:       if (&condval($statecond)) {
 5538: 	 return '2';
 5539:       } else {
 5540:          return '';
 5541:       }
 5542:    }
 5543: 
 5544:     if ($thisallowed eq 'A') {
 5545: 	return 'A';
 5546:     } elsif ($thisallowed eq 'B') {
 5547:         return 'B';
 5548:     }
 5549:    return 'F';
 5550: }
 5551: 
 5552: sub split_uri_for_cond {
 5553:     my $uri=&deversion(&declutter(shift));
 5554:     my @uriparts=split(/\//,$uri);
 5555:     my $filename=pop(@uriparts);
 5556:     my $pathname=join('/',@uriparts);
 5557:     return ($pathname,$filename);
 5558: }
 5559: # --------------------------------------------------- Is a resource on the map?
 5560: 
 5561: sub is_on_map {
 5562:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 5563:     #Trying to find the conditional for the file
 5564:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 5565: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 5566:     if ($match) {
 5567: 	return (1,$1);
 5568:     } else {
 5569: 	return (0,0);
 5570:     }
 5571: }
 5572: 
 5573: # --------------------------------------------------------- Get symb from alias
 5574: 
 5575: sub get_symb_from_alias {
 5576:     my $symb=shift;
 5577:     my ($map,$resid,$url)=&decode_symb($symb);
 5578: # Already is a symb
 5579:     if ($url) { return $symb; }
 5580: # Must be an alias
 5581:     my $aliassymb='';
 5582:     my %bighash;
 5583:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 5584:                             &GDBM_READER(),0640)) {
 5585:         my $rid=$bighash{'mapalias_'.$symb};
 5586: 	if ($rid) {
 5587: 	    my ($mapid,$resid)=split(/\./,$rid);
 5588: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 5589: 				    $resid,$bighash{'src_'.$rid});
 5590: 	}
 5591:         untie %bighash;
 5592:     }
 5593:     return $aliassymb;
 5594: }
 5595: 
 5596: # ----------------------------------------------------------------- Define Role
 5597: 
 5598: sub definerole {
 5599:   if (allowed('mcr','/')) {
 5600:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 5601:     foreach my $role (split(':',$sysrole)) {
 5602: 	my ($crole,$cqual)=split(/\&/,$role);
 5603:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 5604:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 5605: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 5606:                return "refused:s:$crole&$cqual"; 
 5607:             }
 5608:         }
 5609:     }
 5610:     foreach my $role (split(':',$domrole)) {
 5611: 	my ($crole,$cqual)=split(/\&/,$role);
 5612:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 5613:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 5614: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 5615:                return "refused:d:$crole&$cqual"; 
 5616:             }
 5617:         }
 5618:     }
 5619:     foreach my $role (split(':',$courole)) {
 5620: 	my ($crole,$cqual)=split(/\&/,$role);
 5621:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 5622:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 5623: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 5624:                return "refused:c:$crole&$cqual"; 
 5625:             }
 5626:         }
 5627:     }
 5628:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 5629:                 "$env{'user.domain'}:$env{'user.name'}:".
 5630: 	        "rolesdef_$rolename=".
 5631:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 5632:     return reply($command,$env{'user.home'});
 5633:   } else {
 5634:     return 'refused';
 5635:   }
 5636: }
 5637: 
 5638: # ---------------- Make a metadata query against the network of library servers
 5639: 
 5640: sub metadata_query {
 5641:     my ($query,$custom,$customshow,$server_array)=@_;
 5642:     my %rhash;
 5643:     my %libserv = &all_library();
 5644:     my @server_list = (defined($server_array) ? @$server_array
 5645:                                               : keys(%libserv) );
 5646:     for my $server (@server_list) {
 5647: 	unless ($custom or $customshow) {
 5648: 	    my $reply=&reply("querysend:".&escape($query),$server);
 5649: 	    $rhash{$server}=$reply;
 5650: 	}
 5651: 	else {
 5652: 	    my $reply=&reply("querysend:".&escape($query).':'.
 5653: 			     &escape($custom).':'.&escape($customshow),
 5654: 			     $server);
 5655: 	    $rhash{$server}=$reply;
 5656: 	}
 5657:     }
 5658:     return \%rhash;
 5659: }
 5660: 
 5661: # ----------------------------------------- Send log queries and wait for reply
 5662: 
 5663: sub log_query {
 5664:     my ($uname,$udom,$query,%filters)=@_;
 5665:     my $uhome=&homeserver($uname,$udom);
 5666:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 5667:     my $uhost=&hostname($uhome);
 5668:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 5669:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 5670:                        $uhome);
 5671:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 5672:     return get_query_reply($queryid);
 5673: }
 5674: 
 5675: # -------------------------- Update MySQL table for portfolio file
 5676: 
 5677: sub update_portfolio_table {
 5678:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 5679:     if ($group ne '') {
 5680:         $file_name =~s /^\Q$group\E//;
 5681:     }
 5682:     my $homeserver = &homeserver($uname,$udom);
 5683:     my $queryid=
 5684:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 5685:                ':'.&escape($file_name).':'.$action,$homeserver);
 5686:     my $reply = &get_query_reply($queryid);
 5687:     return $reply;
 5688: }
 5689: 
 5690: # -------------------------- Update MySQL allusers table
 5691: 
 5692: sub update_allusers_table {
 5693:     my ($uname,$udom,$names) = @_;
 5694:     my $homeserver = &homeserver($uname,$udom);
 5695:     my $queryid=
 5696:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 5697:                'lastname='.&escape($names->{'lastname'}).'%%'.
 5698:                'firstname='.&escape($names->{'firstname'}).'%%'.
 5699:                'middlename='.&escape($names->{'middlename'}).'%%'.
 5700:                'generation='.&escape($names->{'generation'}).'%%'.
 5701:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 5702:                'id='.&escape($names->{'id'}),$homeserver);
 5703:     return;
 5704: }
 5705: 
 5706: # ------- Request retrieval of institutional classlists for course(s)
 5707: 
 5708: sub fetch_enrollment_query {
 5709:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 5710:     my $homeserver;
 5711:     my $maxtries = 1;
 5712:     if ($context eq 'automated') {
 5713:         $homeserver = $perlvar{'lonHostID'};
 5714:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 5715:     } else {
 5716:         $homeserver = &homeserver($cnum,$dom);
 5717:     }
 5718:     my $host=&hostname($homeserver);
 5719:     my $cmd = '';
 5720:     foreach my $affiliate (keys(%{$affiliatesref})) {
 5721:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5722:     }
 5723:     $cmd =~ s/%%$//;
 5724:     $cmd = &escape($cmd);
 5725:     my $query = 'fetchenrollment';
 5726:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 5727:     unless ($queryid=~/^\Q$host\E\_/) { 
 5728:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 5729:         return 'error: '.$queryid;
 5730:     }
 5731:     my $reply = &get_query_reply($queryid);
 5732:     my $tries = 1;
 5733:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5734:         $reply = &get_query_reply($queryid);
 5735:         $tries ++;
 5736:     }
 5737:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5738:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5739:     } else {
 5740:         my @responses = split(/:/,$reply);
 5741:         if ($homeserver eq $perlvar{'lonHostID'}) {
 5742:             foreach my $line (@responses) {
 5743:                 my ($key,$value) = split(/=/,$line,2);
 5744:                 $$replyref{$key} = $value;
 5745:             }
 5746:         } else {
 5747:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 5748:             foreach my $line (@responses) {
 5749:                 my ($key,$value) = split(/=/,$line);
 5750:                 $$replyref{$key} = $value;
 5751:                 if ($value > 0) {
 5752:                     foreach my $item (@{$$affiliatesref{$key}}) {
 5753:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 5754:                         my $destname = $pathname.'/'.$filename;
 5755:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 5756:                         if ($xml_classlist =~ /^error/) {
 5757:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 5758:                         } else {
 5759:                             if ( open(FILE,">$destname") ) {
 5760:                                 print FILE &unescape($xml_classlist);
 5761:                                 close(FILE);
 5762:                             } else {
 5763:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 5764:                             }
 5765:                         }
 5766:                     }
 5767:                 }
 5768:             }
 5769:         }
 5770:         return 'ok';
 5771:     }
 5772:     return 'error';
 5773: }
 5774: 
 5775: sub get_query_reply {
 5776:     my $queryid=shift;
 5777:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 5778:     my $reply='';
 5779:     for (1..100) {
 5780: 	sleep 2;
 5781:         if (-e $replyfile.'.end') {
 5782: 	    if (open(my $fh,$replyfile)) {
 5783: 		$reply = join('',<$fh>);
 5784: 		close($fh);
 5785: 	   } else { return 'error: reply_file_error'; }
 5786:            return &unescape($reply);
 5787: 	}
 5788:     }
 5789:     return 'timeout:'.$queryid;
 5790: }
 5791: 
 5792: sub courselog_query {
 5793: #
 5794: # possible filters:
 5795: # url: url or symb
 5796: # username
 5797: # domain
 5798: # action: view, submit, grade
 5799: # start: timestamp
 5800: # end: timestamp
 5801: #
 5802:     my (%filters)=@_;
 5803:     unless ($env{'request.course.id'}) { return 'no_course'; }
 5804:     if ($filters{'url'}) {
 5805: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 5806:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 5807:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 5808:     }
 5809:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5810:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5811:     return &log_query($cname,$cdom,'courselog',%filters);
 5812: }
 5813: 
 5814: sub userlog_query {
 5815: #
 5816: # possible filters:
 5817: # action: log check role
 5818: # start: timestamp
 5819: # end: timestamp
 5820: #
 5821:     my ($uname,$udom,%filters)=@_;
 5822:     return &log_query($uname,$udom,'userlog',%filters);
 5823: }
 5824: 
 5825: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 5826: 
 5827: sub auto_run {
 5828:     my ($cnum,$cdom) = @_;
 5829:     my $response = 0;
 5830:     my $settings;
 5831:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 5832:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 5833:         $settings = $domconfig{'autoenroll'};
 5834:         if ($settings->{'run'} eq '1') {
 5835:             $response = 1;
 5836:         }
 5837:     } else {
 5838:         my $homeserver;
 5839:         if (&is_course($cdom,$cnum)) {
 5840:             $homeserver = &homeserver($cnum,$cdom);
 5841:         } else {
 5842:             $homeserver = &domain($cdom,'primary');
 5843:         }
 5844:         if ($homeserver ne 'no_host') {
 5845:             $response = &reply('autorun:'.$cdom,$homeserver);
 5846:         }
 5847:     }
 5848:     return $response;
 5849: }
 5850: 
 5851: sub auto_get_sections {
 5852:     my ($cnum,$cdom,$inst_coursecode) = @_;
 5853:     my $homeserver;
 5854:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 5855:         $homeserver = &homeserver($cnum,$cdom);
 5856:     }
 5857:     if (!defined($homeserver)) { 
 5858:         if ($cdom =~ /^$match_domain$/) {
 5859:             $homeserver = &domain($cdom,'primary');
 5860:         }
 5861:     }
 5862:     my @secs;
 5863:     if (defined($homeserver)) {
 5864:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 5865:         unless ($response eq 'refused') {
 5866:             @secs = split(/:/,$response);
 5867:         }
 5868:     }
 5869:     return @secs;
 5870: }
 5871: 
 5872: sub auto_new_course {
 5873:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 5874:     my $homeserver = &homeserver($cnum,$cdom);
 5875:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 5876:     return $response;
 5877: }
 5878: 
 5879: sub auto_validate_courseID {
 5880:     my ($cnum,$cdom,$inst_course_id) = @_;
 5881:     my $homeserver = &homeserver($cnum,$cdom);
 5882:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 5883:     return $response;
 5884: }
 5885: 
 5886: sub auto_validate_instcode {
 5887:     my ($cnum,$cdom,$instcode,$owner) = @_;
 5888:     my ($homeserver,$response);
 5889:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 5890:         $homeserver = &homeserver($cnum,$cdom);
 5891:     }
 5892:     if (!defined($homeserver)) {
 5893:         if ($cdom =~ /^$match_domain$/) {
 5894:             $homeserver = &domain($cdom,'primary');
 5895:         }
 5896:     }
 5897:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 5898:                         &escape($instcode).':'.&escape($owner),$homeserver));
 5899:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
 5900:     return ($outcome,$description);
 5901: }
 5902: 
 5903: sub auto_create_password {
 5904:     my ($cnum,$cdom,$authparam,$udom) = @_;
 5905:     my ($homeserver,$response);
 5906:     my $create_passwd = 0;
 5907:     my $authchk = '';
 5908:     if ($udom =~ /^$match_domain$/) {
 5909:         $homeserver = &domain($udom,'primary');
 5910:     }
 5911:     if ($homeserver eq '') {
 5912:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 5913:             $homeserver = &homeserver($cnum,$cdom);
 5914:         }
 5915:     }
 5916:     if ($homeserver eq '') {
 5917:         $authchk = 'nodomain';
 5918:     } else {
 5919:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 5920:         if ($response eq 'refused') {
 5921:             $authchk = 'refused';
 5922:         } else {
 5923:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 5924:         }
 5925:     }
 5926:     return ($authparam,$create_passwd,$authchk);
 5927: }
 5928: 
 5929: sub auto_photo_permission {
 5930:     my ($cnum,$cdom,$students) = @_;
 5931:     my $homeserver = &homeserver($cnum,$cdom);
 5932:     my ($outcome,$perm_reqd,$conditions) = 
 5933: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 5934:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5935: 	return (undef,undef);
 5936:     }
 5937:     return ($outcome,$perm_reqd,$conditions);
 5938: }
 5939: 
 5940: sub auto_checkphotos {
 5941:     my ($uname,$udom,$pid) = @_;
 5942:     my $homeserver = &homeserver($uname,$udom);
 5943:     my ($result,$resulttype);
 5944:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 5945: 				   &escape($uname).':'.&escape($pid),
 5946: 				   $homeserver));
 5947:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5948: 	return (undef,undef);
 5949:     }
 5950:     if ($outcome) {
 5951:         ($result,$resulttype) = split(/:/,$outcome);
 5952:     } 
 5953:     return ($result,$resulttype);
 5954: }
 5955: 
 5956: sub auto_photochoice {
 5957:     my ($cnum,$cdom) = @_;
 5958:     my $homeserver = &homeserver($cnum,$cdom);
 5959:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 5960: 						       &escape($cdom),
 5961: 						       $homeserver)));
 5962:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5963: 	return (undef,undef);
 5964:     }
 5965:     return ($update,$comment);
 5966: }
 5967: 
 5968: sub auto_photoupdate {
 5969:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 5970:     my $homeserver = &homeserver($cnum,$dom);
 5971:     my $host=&hostname($homeserver);
 5972:     my $cmd = '';
 5973:     my $maxtries = 1;
 5974:     foreach my $affiliate (keys(%{$affiliatesref})) {
 5975:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5976:     }
 5977:     $cmd =~ s/%%$//;
 5978:     $cmd = &escape($cmd);
 5979:     my $query = 'institutionalphotos';
 5980:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 5981:     unless ($queryid=~/^\Q$host\E\_/) {
 5982:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 5983:         return 'error: '.$queryid;
 5984:     }
 5985:     my $reply = &get_query_reply($queryid);
 5986:     my $tries = 1;
 5987:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5988:         $reply = &get_query_reply($queryid);
 5989:         $tries ++;
 5990:     }
 5991:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5992:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5993:     } else {
 5994:         my @responses = split(/:/,$reply);
 5995:         my $outcome = shift(@responses); 
 5996:         foreach my $item (@responses) {
 5997:             my ($key,$value) = split(/=/,$item);
 5998:             $$photo{$key} = $value;
 5999:         }
 6000:         return $outcome;
 6001:     }
 6002:     return 'error';
 6003: }
 6004: 
 6005: sub auto_instcode_format {
 6006:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 6007: 	$cat_order) = @_;
 6008:     my $courses = '';
 6009:     my @homeservers;
 6010:     if ($caller eq 'global') {
 6011: 	my %servers = &get_servers($codedom,'library');
 6012: 	foreach my $tryserver (keys(%servers)) {
 6013: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 6014: 		push(@homeservers,$tryserver);
 6015: 	    }
 6016:         }
 6017:     } elsif ($caller eq 'requests') {
 6018:         if ($codedom =~ /^$match_domain$/) {
 6019:             my $chome = &domain($codedom,'primary');
 6020:             unless ($chome eq 'no_host') {
 6021:                 push(@homeservers,$chome);
 6022:             }
 6023:         }
 6024:     } else {
 6025:         push(@homeservers,&homeserver($caller,$codedom));
 6026:     }
 6027:     foreach my $code (keys(%{$instcodes})) {
 6028:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 6029:     }
 6030:     chop($courses);
 6031:     my $ok_response = 0;
 6032:     my $response;
 6033:     while (@homeservers > 0 && $ok_response == 0) {
 6034:         my $server = shift(@homeservers); 
 6035:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 6036:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 6037:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 6038: 		split(/:/,$response);
 6039:             %{$codes} = (%{$codes},&str2hash($codes_str));
 6040:             push(@{$codetitles},&str2array($codetitles_str));
 6041:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 6042:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 6043:             $ok_response = 1;
 6044:         }
 6045:     }
 6046:     if ($ok_response) {
 6047:         return 'ok';
 6048:     } else {
 6049:         return $response;
 6050:     }
 6051: }
 6052: 
 6053: sub auto_instcode_defaults {
 6054:     my ($domain,$returnhash,$code_order) = @_;
 6055:     my @homeservers;
 6056: 
 6057:     my %servers = &get_servers($domain,'library');
 6058:     foreach my $tryserver (keys(%servers)) {
 6059: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 6060: 	    push(@homeservers,$tryserver);
 6061: 	}
 6062:     }
 6063: 
 6064:     my $response;
 6065:     foreach my $server (@homeservers) {
 6066:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 6067:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 6068: 	
 6069: 	foreach my $pair (split(/\&/,$response)) {
 6070: 	    my ($name,$value)=split(/\=/,$pair);
 6071: 	    if ($name eq 'code_order') {
 6072: 		@{$code_order} = split(/\&/,&unescape($value));
 6073: 	    } else {
 6074: 		$returnhash->{&unescape($name)}=&unescape($value);
 6075: 	    }
 6076: 	}
 6077: 	return 'ok';
 6078:     }
 6079: 
 6080:     return $response;
 6081: }
 6082: 
 6083: sub auto_possible_instcodes {
 6084:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 6085:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 6086:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 6087:         return;
 6088:     }
 6089:     my (@homeservers,$uhome);
 6090:     if (defined(&domain($domain,'primary'))) {
 6091:         $uhome=&domain($domain,'primary');
 6092:         push(@homeservers,&domain($domain,'primary'));
 6093:     } else {
 6094:         my %servers = &get_servers($domain,'library');
 6095:         foreach my $tryserver (keys(%servers)) {
 6096:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 6097:                 push(@homeservers,$tryserver);
 6098:             }
 6099:         }
 6100:     }
 6101:     my $response;
 6102:     foreach my $server (@homeservers) {
 6103:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 6104:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 6105:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 6106:             split(':',$response);
 6107:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 6108:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 6109:         foreach my $item (split('&',$cat_title)) {   
 6110:             my ($name,$value)=split('=',$item);
 6111:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 6112:         }
 6113:         foreach my $item (split('&',$cat_order)) {
 6114:             my ($name,$value)=split('=',$item);
 6115:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 6116:         }
 6117:         return 'ok';
 6118:     }
 6119:     return $response;
 6120: }
 6121: 
 6122: sub auto_courserequest_checks {
 6123:     my ($dom) = @_;
 6124:     my ($homeserver,%validations);
 6125:     if ($dom =~ /^$match_domain$/) {
 6126:         $homeserver = &domain($dom,'primary');
 6127:     }
 6128:     unless ($homeserver eq 'no_host') {
 6129:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 6130:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 6131:             my @items = split(/&/,$response);
 6132:             foreach my $item (@items) {
 6133:                 my ($key,$value) = split('=',$item);
 6134:                 $validations{&unescape($key)} = &thaw_unescape($value);
 6135:             }
 6136:         }
 6137:     }
 6138:     return %validations; 
 6139: }
 6140: 
 6141: sub auto_courserequest_validation {
 6142:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
 6143:     my ($homeserver,$response);
 6144:     if ($dom =~ /^$match_domain$/) {
 6145:         $homeserver = &domain($dom,'primary');
 6146:     }
 6147:     unless ($homeserver eq 'no_host') {  
 6148:           
 6149:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 6150:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 6151:                                     ':'.&escape($instcode).':'.&escape($instseclist),
 6152:                                     $homeserver));
 6153:     }
 6154:     return $response;
 6155: }
 6156: 
 6157: sub auto_validate_class_sec {
 6158:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 6159:     my $homeserver = &homeserver($cnum,$cdom);
 6160:     my $ownerlist;
 6161:     if (ref($owners) eq 'ARRAY') {
 6162:         $ownerlist = join(',',@{$owners});
 6163:     } else {
 6164:         $ownerlist = $owners;
 6165:     }
 6166:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 6167:                         &escape($ownerlist).':'.$cdom,$homeserver);
 6168:     return $response;
 6169: }
 6170: 
 6171: # ------------------------------------------------------- Course Group routines
 6172: 
 6173: sub get_coursegroups {
 6174:     my ($cdom,$cnum,$group,$namespace) = @_;
 6175:     return(&dump($namespace,$cdom,$cnum,$group));
 6176: }
 6177: 
 6178: sub modify_coursegroup {
 6179:     my ($cdom,$cnum,$groupsettings) = @_;
 6180:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 6181: }
 6182: 
 6183: sub toggle_coursegroup_status {
 6184:     my ($cdom,$cnum,$group,$action) = @_;
 6185:     my ($from_namespace,$to_namespace);
 6186:     if ($action eq 'delete') {
 6187:         $from_namespace = 'coursegroups';
 6188:         $to_namespace = 'deleted_groups';
 6189:     } else {
 6190:         $from_namespace = 'deleted_groups';
 6191:         $to_namespace = 'coursegroups';
 6192:     }
 6193:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 6194:     if (my $tmp = &error(%curr_group)) {
 6195:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 6196:         return ('read error',$tmp);
 6197:     } else {
 6198:         my %savedsettings = %curr_group; 
 6199:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 6200:         my $deloutcome;
 6201:         if ($result eq 'ok') {
 6202:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 6203:         } else {
 6204:             return ('write error',$result);
 6205:         }
 6206:         if ($deloutcome eq 'ok') {
 6207:             return 'ok';
 6208:         } else {
 6209:             return ('delete error',$deloutcome);
 6210:         }
 6211:     }
 6212: }
 6213: 
 6214: sub modify_group_roles {
 6215:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 6216:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 6217:     my $role = 'gr/'.&escape($userprivs);
 6218:     my ($uname,$udom) = split(/:/,$user);
 6219:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 6220:     if ($result eq 'ok') {
 6221:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 6222:     }
 6223:     return $result;
 6224: }
 6225: 
 6226: sub modify_coursegroup_membership {
 6227:     my ($cdom,$cnum,$membership) = @_;
 6228:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 6229:     return $result;
 6230: }
 6231: 
 6232: sub get_active_groups {
 6233:     my ($udom,$uname,$cdom,$cnum) = @_;
 6234:     my $now = time;
 6235:     my %groups = ();
 6236:     foreach my $key (keys(%env)) {
 6237:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 6238:             my ($start,$end) = split(/\./,$env{$key});
 6239:             if (($end!=0) && ($end<$now)) { next; }
 6240:             if (($start!=0) && ($start>$now)) { next; }
 6241:             if ($1 eq $cdom && $2 eq $cnum) {
 6242:                 $groups{$3} = $env{$key} ;
 6243:             }
 6244:         }
 6245:     }
 6246:     return %groups;
 6247: }
 6248: 
 6249: sub get_group_membership {
 6250:     my ($cdom,$cnum,$group) = @_;
 6251:     return(&dump('groupmembership',$cdom,$cnum,$group));
 6252: }
 6253: 
 6254: sub get_users_groups {
 6255:     my ($udom,$uname,$courseid) = @_;
 6256:     my @usersgroups;
 6257:     my $cachetime=1800;
 6258: 
 6259:     my $hashid="$udom:$uname:$courseid";
 6260:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 6261:     if (defined($cached)) {
 6262:         @usersgroups = split(/:/,$grouplist);
 6263:     } else {  
 6264:         $grouplist = '';
 6265:         my $courseurl = &courseid_to_courseurl($courseid);
 6266:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 6267:         my $access_end = $env{'course.'.$courseid.
 6268:                               '.default_enrollment_end_date'};
 6269:         my $now = time;
 6270:         foreach my $key (keys(%roleshash)) {
 6271:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 6272:                 my $group = $1;
 6273:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 6274:                     my $start = $2;
 6275:                     my $end = $1;
 6276:                     if ($start == -1) { next; } # deleted from group
 6277:                     if (($start!=0) && ($start>$now)) { next; }
 6278:                     if (($end!=0) && ($end<$now)) {
 6279:                         if ($access_end && $access_end < $now) {
 6280:                             if ($access_end - $end < 86400) {
 6281:                                 push(@usersgroups,$group);
 6282:                             }
 6283:                         }
 6284:                         next;
 6285:                     }
 6286:                     push(@usersgroups,$group);
 6287:                 }
 6288:             }
 6289:         }
 6290:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 6291:         $grouplist = join(':',@usersgroups);
 6292:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 6293:     }
 6294:     return @usersgroups;
 6295: }
 6296: 
 6297: sub devalidate_getgroups_cache {
 6298:     my ($udom,$uname,$cdom,$cnum)=@_;
 6299:     my $courseid = $cdom.'_'.$cnum;
 6300: 
 6301:     my $hashid="$udom:$uname:$courseid";
 6302:     &devalidate_cache_new('getgroups',$hashid);
 6303: }
 6304: 
 6305: # ------------------------------------------------------------------ Plain Text
 6306: 
 6307: sub plaintext {
 6308:     my ($short,$type,$cid,$forcedefault) = @_;
 6309:     if ($short =~ m{^cr/}) {
 6310: 	return (split('/',$short))[-1];
 6311:     }
 6312:     if (!defined($cid)) {
 6313:         $cid = $env{'request.course.id'};
 6314:     }
 6315:     my %rolenames = (
 6316:                       Course    => 'std',
 6317:                       Community => 'alt1',
 6318:                     );
 6319:     if ($cid ne '') {
 6320:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 6321:             unless ($forcedefault) {
 6322:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 6323:                 &Apache::lonlocal::mt_escape(\$roletext);
 6324:                 return &Apache::lonlocal::mt($roletext);
 6325:             }
 6326:         }
 6327:     }
 6328:     if ((defined($type)) && (defined($rolenames{$type})) &&
 6329:         (defined($rolenames{$type})) && 
 6330:         (defined($prp{$short}{$rolenames{$type}}))) {
 6331:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 6332:     } elsif ($cid ne '') {
 6333:         my $crstype = $env{'course.'.$cid.'.type'};
 6334:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 6335:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 6336:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 6337:         }
 6338:     }
 6339:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 6340: }
 6341: 
 6342: # ----------------------------------------------------------------- Assign Role
 6343: 
 6344: sub assignrole {
 6345:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 6346:         $context)=@_;
 6347:     my $mrole;
 6348:     if ($role =~ /^cr\//) {
 6349:         my $cwosec=$url;
 6350:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 6351: 	unless (&allowed('ccr',$cwosec)) {
 6352:            my $refused = 1;
 6353:            if ($context eq 'requestcourses') {
 6354:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 6355:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 6356:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 6357:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 6358:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 6359:                            if ($crsenv{'internal.courseowner'} eq
 6360:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 6361:                                $refused = '';
 6362:                            }
 6363:                        }
 6364:                    }
 6365:                }
 6366:            }
 6367:            if ($refused) {
 6368:                &logthis('Refused custom assignrole: '.
 6369:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 6370:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 6371:                return 'refused';
 6372:            }
 6373:         }
 6374:         $mrole='cr';
 6375:     } elsif ($role =~ /^gr\//) {
 6376:         my $cwogrp=$url;
 6377:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 6378:         unless (&allowed('mdg',$cwogrp)) {
 6379:             &logthis('Refused group assignrole: '.
 6380:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 6381:                     $env{'user.name'}.' at '.$env{'user.domain'});
 6382:             return 'refused';
 6383:         }
 6384:         $mrole='gr';
 6385:     } else {
 6386:         my $cwosec=$url;
 6387:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 6388:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 6389:             my $refused;
 6390:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 6391:                 if (!(&allowed('c'.$role,$url))) {
 6392:                     $refused = 1;
 6393:                 }
 6394:             } else {
 6395:                 $refused = 1;
 6396:             }
 6397:             if ($refused) {
 6398:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 6399:                 if (!$selfenroll && $context eq 'course') {
 6400:                     my %crsenv;
 6401:                     if ($role eq 'cc' || $role eq 'co') {
 6402:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 6403:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 6404:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 6405:                                 if ($crsenv{'internal.courseowner'} eq 
 6406:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 6407:                                     $refused = '';
 6408:                                 }
 6409:                             }
 6410:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 6411:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 6412:                                 if ($crsenv{'internal.courseowner'} eq 
 6413:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 6414:                                     $refused = '';
 6415:                                 }
 6416:                             }
 6417:                         }
 6418:                     }
 6419:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6420:                     $refused = '';
 6421:                 } elsif ($context eq 'requestcourses') {
 6422:                     my @possroles = ('st','ta','ep','in','cc','co');
 6423:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 6424:                         my $wrongcc;
 6425:                         if ($cnum =~ /^$match_community$/) {
 6426:                             $wrongcc = 1 if ($role eq 'cc');
 6427:                         } else {
 6428:                             $wrongcc = 1 if ($role eq 'co');
 6429:                         }
 6430:                         unless ($wrongcc) {
 6431:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 6432:                             if ($crsenv{'internal.courseowner'} eq 
 6433:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 6434:                                 $refused = '';
 6435:                             }
 6436:                         }
 6437:                     }
 6438:                 }
 6439:                 if ($refused) {
 6440:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 6441:                              ' '.$role.' '.$end.' '.$start.' by '.
 6442: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 6443:                     return 'refused';
 6444:                 }
 6445:             }
 6446:         }
 6447:         $mrole=$role;
 6448:     }
 6449:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 6450:                 "$udom:$uname:$url".'_'."$mrole=$role";
 6451:     if ($end) { $command.='_'.$end; }
 6452:     if ($start) {
 6453: 	if ($end) { 
 6454:            $command.='_'.$start; 
 6455:         } else {
 6456:            $command.='_0_'.$start;
 6457:         }
 6458:     }
 6459:     my $origstart = $start;
 6460:     my $origend = $end;
 6461:     my $delflag;
 6462: # actually delete
 6463:     if ($deleteflag) {
 6464: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 6465: # modify command to delete the role
 6466:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 6467:                 "$udom:$uname:$url".'_'."$mrole";
 6468: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 6469: # set start and finish to negative values for userrolelog
 6470:            $start=-1;
 6471:            $end=-1;
 6472:            $delflag = 1;
 6473:         }
 6474:     }
 6475: # send command
 6476:     my $answer=&reply($command,&homeserver($uname,$udom));
 6477: # log new user role if status is ok
 6478:     if ($answer eq 'ok') {
 6479: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 6480: # for course roles, perform group memberships changes triggered by role change.
 6481:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
 6482:         unless ($role =~ /^gr/) {
 6483:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 6484:                                              $origstart,$selfenroll,$context);
 6485:         }
 6486:         if ($role eq 'cc') {
 6487:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 6488:         }
 6489:     }
 6490:     return $answer;
 6491: }
 6492: 
 6493: sub autoupdate_coowners {
 6494:     my ($url,$end,$start,$uname,$udom) = @_;
 6495:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 6496:     if (($cdom ne '') && ($cnum ne '')) {
 6497:         my $now = time;
 6498:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 6499:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 6500:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 6501:             my $instcode = $coursehash{'internal.coursecode'};
 6502:             if ($instcode ne '') {
 6503:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 6504:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 6505:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 6506:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 6507:                         if ($result eq 'valid') {
 6508:                             if ($coursehash{'internal.co-owners'}) {
 6509:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 6510:                                     push(@newcoowners,$coowner);
 6511:                                 }
 6512:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 6513:                                     push(@newcoowners,$uname.':'.$udom);
 6514:                                 }
 6515:                                 @newcoowners = sort(@newcoowners);
 6516:                             } else {
 6517:                                 push(@newcoowners,$uname.':'.$udom);
 6518:                             }
 6519:                         } else {
 6520:                             if ($coursehash{'internal.co-owners'}) {
 6521:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 6522:                                     unless ($coowner eq $uname.':'.$udom) {
 6523:                                         push(@newcoowners,$coowner);
 6524:                                     }
 6525:                                 }
 6526:                                 unless (@newcoowners > 0) {
 6527:                                     $delcoowners = 1;
 6528:                                     $coowners = '';
 6529:                                 }
 6530:                             }
 6531:                         }
 6532:                         if (@newcoowners || $delcoowners) {
 6533:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 6534:                                             $delcoowners,@newcoowners);
 6535:                         }
 6536:                     }
 6537:                 }
 6538:             }
 6539:         }
 6540:     }
 6541: }
 6542: 
 6543: sub store_coowners {
 6544:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 6545:     my $cid = $cdom.'_'.$cnum;
 6546:     my ($coowners,$delresult,$putresult);
 6547:     if (@newcoowners) {
 6548:         $coowners = join(',',@newcoowners);
 6549:         my %coownershash = (
 6550:                             'internal.co-owners' => $coowners,
 6551:                            );
 6552:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 6553:         if ($putresult eq 'ok') {
 6554:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 6555:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 6556:             }
 6557:         }
 6558:     }
 6559:     if ($delcoowners) {
 6560:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 6561:         if ($delresult eq 'ok') {
 6562:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 6563:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 6564:             }
 6565:         }
 6566:     }
 6567:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 6568:         my %crsinfo =
 6569:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 6570:         if (ref($crsinfo{$cid}) eq 'HASH') {
 6571:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 6572:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 6573:         }
 6574:     }
 6575: }
 6576: 
 6577: # -------------------------------------------------- Modify user authentication
 6578: # Overrides without validation
 6579: 
 6580: sub modifyuserauth {
 6581:     my ($udom,$uname,$umode,$upass)=@_;
 6582:     my $uhome=&homeserver($uname,$udom);
 6583:     unless (&allowed('mau',$udom)) { return 'refused'; }
 6584:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 6585:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 6586:              ' in domain '.$env{'request.role.domain'});  
 6587:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 6588: 		     &escape($upass),$uhome);
 6589:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 6590:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 6591:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 6592:     &log($udom,,$uname,$uhome,
 6593:         'Authentication changed by '.$env{'user.domain'}.', '.
 6594:                                      $env{'user.name'}.', '.$umode.
 6595:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 6596:     unless ($reply eq 'ok') {
 6597:         &logthis('Authentication mode error: '.$reply);
 6598: 	return 'error: '.$reply;
 6599:     }   
 6600:     return 'ok';
 6601: }
 6602: 
 6603: # --------------------------------------------------------------- Modify a user
 6604: 
 6605: sub modifyuser {
 6606:     my ($udom,    $uname, $uid,
 6607:         $umode,   $upass, $first,
 6608:         $middle,  $last,  $gene,
 6609:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 6610:     $udom= &LONCAPA::clean_domain($udom);
 6611:     $uname=&LONCAPA::clean_username($uname);
 6612:     my $showcandelete = 'none';
 6613:     if (ref($candelete) eq 'ARRAY') {
 6614:         if (@{$candelete} > 0) {
 6615:             $showcandelete = join(', ',@{$candelete});
 6616:         }
 6617:     }
 6618:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 6619:              $umode.', '.$first.', '.$middle.', '.
 6620: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 6621:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 6622:                                      ' desiredhome not specified'). 
 6623:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 6624:              ' in domain '.$env{'request.role.domain'});
 6625:     my $uhome=&homeserver($uname,$udom,'true');
 6626:     my $newuser;
 6627:     if ($uhome eq 'no_host') {
 6628:         $newuser = 1;
 6629:     }
 6630: # ----------------------------------------------------------------- Create User
 6631:     if (($uhome eq 'no_host') && 
 6632: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 6633:         my $unhome='';
 6634:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 6635:             $unhome = $desiredhome;
 6636: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 6637: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 6638:         } else { # load balancing routine for determining $unhome
 6639:             my $loadm=10000000;
 6640: 	    my %servers = &get_servers($udom,'library');
 6641: 	    foreach my $tryserver (keys(%servers)) {
 6642: 		my $answer=reply('load',$tryserver);
 6643: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 6644: 		    $loadm=$answer;
 6645: 		    $unhome=$tryserver;
 6646: 		}
 6647: 	    }
 6648:         }
 6649:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 6650: 	    return 'error: unable to find a home server for '.$uname.
 6651:                    ' in domain '.$udom;
 6652:         }
 6653:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 6654:                          &escape($upass),$unhome);
 6655: 	unless ($reply eq 'ok') {
 6656:             return 'error: '.$reply;
 6657:         }   
 6658:         $uhome=&homeserver($uname,$udom,'true');
 6659:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 6660: 	    return 'error: unable verify users home machine.';
 6661:         }
 6662:     }   # End of creation of new user
 6663: # ---------------------------------------------------------------------- Add ID
 6664:     if ($uid) {
 6665:        $uid=~tr/A-Z/a-z/;
 6666:        my %uidhash=&idrget($udom,$uname);
 6667:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 6668:          && (!$forceid)) {
 6669: 	  unless ($uid eq $uidhash{$uname}) {
 6670: 	      return 'error: user id "'.$uid.'" does not match '.
 6671:                   'current user id "'.$uidhash{$uname}.'".';
 6672:           }
 6673:        } else {
 6674: 	  &idput($udom,($uname => $uid));
 6675:        }
 6676:     }
 6677: # -------------------------------------------------------------- Add names, etc
 6678:     my @tmp=&get('environment',
 6679: 		   ['firstname','middlename','lastname','generation','id',
 6680:                     'permanentemail','inststatus'],
 6681: 		   $udom,$uname);
 6682:     my (%names,%oldnames);
 6683:     if ($tmp[0] =~ m/^error:.*/) { 
 6684:         %names=(); 
 6685:     } else {
 6686:         %names = @tmp;
 6687:         %oldnames = %names;
 6688:     }
 6689: #
 6690: # If name, email and/or uid are blank (e.g., because an uploaded file
 6691: # of users did not contain them), do not overwrite existing values
 6692: # unless field is in $candelete array ref.  
 6693: #
 6694: 
 6695:     my @fields = ('firstname','middlename','lastname','generation',
 6696:                   'permanentemail','id');
 6697:     my %newvalues;
 6698:     if (ref($candelete) eq 'ARRAY') {
 6699:         foreach my $field (@fields) {
 6700:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 6701:                 if ($field eq 'firstname') {
 6702:                     $names{$field} = $first;
 6703:                 } elsif ($field eq 'middlename') {
 6704:                     $names{$field} = $middle;
 6705:                 } elsif ($field eq 'lastname') {
 6706:                     $names{$field} = $last;
 6707:                 } elsif ($field eq 'generation') { 
 6708:                     $names{$field} = $gene;
 6709:                 } elsif ($field eq 'permanentemail') {
 6710:                     $names{$field} = $email;
 6711:                 } elsif ($field eq 'id') {
 6712:                     $names{$field}  = $uid;
 6713:                 }
 6714:             }
 6715:         }
 6716:     }
 6717:     if ($first)  { $names{'firstname'}  = $first; }
 6718:     if (defined($middle)) { $names{'middlename'} = $middle; }
 6719:     if ($last)   { $names{'lastname'}   = $last; }
 6720:     if (defined($gene))   { $names{'generation'} = $gene; }
 6721:     if ($email) {
 6722:        $email=~s/[^\w\@\.\-\,]//gs;
 6723:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 6724:     }
 6725:     if ($uid) { $names{'id'}  = $uid; }
 6726:     if (defined($inststatus)) {
 6727:         $names{'inststatus'} = '';
 6728:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 6729:         if (ref($usertypes) eq 'HASH') {
 6730:             my @okstatuses; 
 6731:             foreach my $item (split(/:/,$inststatus)) {
 6732:                 if (defined($usertypes->{$item})) {
 6733:                     push(@okstatuses,$item);  
 6734:                 }
 6735:             }
 6736:             if (@okstatuses) {
 6737:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 6738:             }
 6739:         }
 6740:     }
 6741:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 6742:                  $umode.', '.$first.', '.$middle.', '.
 6743:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 6744:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 6745:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 6746:     } else {
 6747:         $logmsg .= ' during self creation';
 6748:     }
 6749:     my $changed;
 6750:     if ($newuser) {
 6751:         $changed = 1;
 6752:     } else {
 6753:         foreach my $field (@fields) {
 6754:             if ($names{$field} ne $oldnames{$field}) {
 6755:                 $changed = 1;
 6756:                 last;
 6757:             }
 6758:         }
 6759:     }
 6760:     unless ($changed) {
 6761:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 6762:         &logthis($logmsg);
 6763:         return 'ok';
 6764:     }
 6765:     my $reply = &put('environment', \%names, $udom,$uname);
 6766:     if ($reply ne 'ok') { 
 6767:         return 'error: '.$reply;
 6768:     }
 6769:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 6770:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 6771:     $logmsg = 'Success modifying user '.$logmsg;
 6772:     &logthis($logmsg);
 6773:     return 'ok';
 6774: }
 6775: 
 6776: # -------------------------------------------------------------- Modify student
 6777: 
 6778: sub modifystudent {
 6779:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 6780:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 6781:         $selfenroll,$context,$inststatus)=@_;
 6782:     if (!$cid) {
 6783: 	unless ($cid=$env{'request.course.id'}) {
 6784: 	    return 'not_in_class';
 6785: 	}
 6786:     }
 6787: # --------------------------------------------------------------- Make the user
 6788:     my $reply=&modifyuser
 6789: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 6790:          $desiredhome,$email,$inststatus);
 6791:     unless ($reply eq 'ok') { return $reply; }
 6792:     # This will cause &modify_student_enrollment to get the uid from the
 6793:     # students environment
 6794:     $uid = undef if (!$forceid);
 6795:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 6796: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
 6797:     return $reply;
 6798: }
 6799: 
 6800: sub modify_student_enrollment {
 6801:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
 6802:     my ($cdom,$cnum,$chome);
 6803:     if (!$cid) {
 6804: 	unless ($cid=$env{'request.course.id'}) {
 6805: 	    return 'not_in_class';
 6806: 	}
 6807: 	$cdom=$env{'course.'.$cid.'.domain'};
 6808: 	$cnum=$env{'course.'.$cid.'.num'};
 6809:     } else {
 6810: 	($cdom,$cnum)=split(/_/,$cid);
 6811:     }
 6812:     $chome=$env{'course.'.$cid.'.home'};
 6813:     if (!$chome) {
 6814: 	$chome=&homeserver($cnum,$cdom);
 6815:     }
 6816:     if (!$chome) { return 'unknown_course'; }
 6817:     # Make sure the user exists
 6818:     my $uhome=&homeserver($uname,$udom);
 6819:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 6820: 	return 'error: no such user';
 6821:     }
 6822:     # Get student data if we were not given enough information
 6823:     if (!defined($first)  || $first  eq '' || 
 6824:         !defined($last)   || $last   eq '' || 
 6825:         !defined($uid)    || $uid    eq '' || 
 6826:         !defined($middle) || $middle eq '' || 
 6827:         !defined($gene)   || $gene   eq '') {
 6828:         # They did not supply us with enough data to enroll the student, so
 6829:         # we need to pick up more information.
 6830:         my %tmp = &get('environment',
 6831:                        ['firstname','middlename','lastname', 'generation','id']
 6832:                        ,$udom,$uname);
 6833: 
 6834:         #foreach my $key (keys(%tmp)) {
 6835:         #    &logthis("key $key = ".$tmp{$key});
 6836:         #}
 6837:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 6838:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 6839:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 6840:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 6841:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 6842:     }
 6843:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 6844:     my $reply=cput('classlist',
 6845: 		   {"$uname:$udom" => 
 6846: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 6847: 		   $cdom,$cnum);
 6848:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 6849: 	return 'error: '.$reply;
 6850:     } else {
 6851: 	&devalidate_getsection_cache($udom,$uname,$cid);
 6852:     }
 6853:     # Add student role to user
 6854:     my $uurl='/'.$cid;
 6855:     $uurl=~s/\_/\//g;
 6856:     if ($usec) {
 6857: 	$uurl.='/'.$usec;
 6858:     }
 6859:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
 6860: }
 6861: 
 6862: sub format_name {
 6863:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 6864:     my $name;
 6865:     if ($first ne 'lastname') {
 6866: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 6867:     } else {
 6868: 	if ($lastname=~/\S/) {
 6869: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 6870: 	    $name=~s/\s+,/,/;
 6871: 	} else {
 6872: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 6873: 	}
 6874:     }
 6875:     $name=~s/^\s+//;
 6876:     $name=~s/\s+$//;
 6877:     $name=~s/\s+/ /g;
 6878:     return $name;
 6879: }
 6880: 
 6881: # ------------------------------------------------- Write to course preferences
 6882: 
 6883: sub writecoursepref {
 6884:     my ($courseid,%prefs)=@_;
 6885:     $courseid=~s/^\///;
 6886:     $courseid=~s/\_/\//g;
 6887:     my ($cdomain,$cnum)=split(/\//,$courseid);
 6888:     my $chome=homeserver($cnum,$cdomain);
 6889:     if (($chome eq '') || ($chome eq 'no_host')) { 
 6890: 	return 'error: no such course';
 6891:     }
 6892:     my $cstring='';
 6893:     foreach my $pref (keys(%prefs)) {
 6894: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 6895:     }
 6896:     $cstring=~s/\&$//;
 6897:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 6898: }
 6899: 
 6900: # ---------------------------------------------------------- Make/modify course
 6901: 
 6902: sub createcourse {
 6903:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 6904:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 6905:     $url=&declutter($url);
 6906:     my $cid='';
 6907:     if ($context eq 'requestcourses') {
 6908:         my $can_create = 0;
 6909:         my ($ownername,$ownerdom) = split(':',$course_owner);
 6910:         if ($udom eq $ownerdom) {
 6911:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 6912:                                   $context)) {
 6913:                 $can_create = 1;
 6914:             }
 6915:         } else {
 6916:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 6917:                                            $category);
 6918:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 6919:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 6920:                 if (@curr > 0) {
 6921:                     my @options = qw(approval validate autolimit);
 6922:                     my $optregex = join('|',@options);
 6923:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 6924:                         $can_create = 1;
 6925:                     }
 6926:                 }
 6927:             }
 6928:         }
 6929:         if ($can_create) {
 6930:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 6931:                 unless (&allowed('ccc',$udom)) {
 6932:                     return 'refused'; 
 6933:                 }
 6934:             }
 6935:         } else {
 6936:             return 'refused';
 6937:         }
 6938:     } elsif (!&allowed('ccc',$udom)) {
 6939:         return 'refused';
 6940:     }
 6941: # --------------------------------------------------------------- Get Unique ID
 6942:     my $uname;
 6943:     if ($cnum =~ /^$match_courseid$/) {
 6944:         my $chome=&homeserver($cnum,$udom,'true');
 6945:         if (($chome eq '') || ($chome eq 'no_host')) {
 6946:             $uname = $cnum;
 6947:         } else {
 6948:             $uname = &generate_coursenum($udom,$crstype);
 6949:         }
 6950:     } else {
 6951:         $uname = &generate_coursenum($udom,$crstype);
 6952:     }
 6953:     return $uname if ($uname =~ /^error/);
 6954: # -------------------------------------------------- Check supplied server name
 6955:     if (!defined($course_server)) {
 6956:         if (defined(&domain($udom,'primary'))) {
 6957:             $course_server = &domain($udom,'primary');
 6958:         } else {
 6959:             $course_server = $env{'user.home'}; 
 6960:         }
 6961:     }
 6962:     my %host_servers =
 6963:         &Apache::lonnet::get_servers($udom,'library');
 6964:     unless ($host_servers{$course_server}) {
 6965:         return 'error: invalid home server for course: '.$course_server;
 6966:     }
 6967: # ------------------------------------------------------------- Make the course
 6968:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 6969:                       $course_server);
 6970:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 6971:     my $uhome=&homeserver($uname,$udom,'true');
 6972:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 6973: 	return 'error: no such course';
 6974:     }
 6975: # ----------------------------------------------------------------- Course made
 6976: # log existence
 6977:     my $now = time;
 6978:     my $newcourse = {
 6979:                     $udom.'_'.$uname => {
 6980:                                      description => $description,
 6981:                                      inst_code   => $inst_code,
 6982:                                      owner       => $course_owner,
 6983:                                      type        => $crstype,
 6984:                                      creator     => $env{'user.name'}.':'.
 6985:                                                     $env{'user.domain'},
 6986:                                      created     => $now,
 6987:                                      context     => $context,
 6988:                                                 },
 6989:                     };
 6990:     &courseidput($udom,$newcourse,$uhome,'notime');
 6991: # set toplevel url
 6992:     my $topurl=$url;
 6993:     unless ($nonstandard) {
 6994: # ------------------------------------------ For standard courses, make top url
 6995:         my $mapurl=&clutter($url);
 6996:         if ($mapurl eq '/res/') { $mapurl=''; }
 6997:         $env{'form.initmap'}=(<<ENDINITMAP);
 6998: <map>
 6999: <resource id="1" type="start"></resource>
 7000: <resource id="2" src="$mapurl"></resource>
 7001: <resource id="3" type="finish"></resource>
 7002: <link index="1" from="1" to="2"></link>
 7003: <link index="2" from="2" to="3"></link>
 7004: </map>
 7005: ENDINITMAP
 7006:         $topurl=&declutter(
 7007:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 7008:                           );
 7009:     }
 7010: # ----------------------------------------------------------- Write preferences
 7011:     &writecoursepref($udom.'_'.$uname,
 7012:                      ('description'              => $description,
 7013:                       'url'                      => $topurl,
 7014:                       'internal.creator'         => $env{'user.name'}.':'.
 7015:                                                     $env{'user.domain'},
 7016:                       'internal.created'         => $now,
 7017:                       'internal.creationcontext' => $context)
 7018:                     );
 7019:     return '/'.$udom.'/'.$uname;
 7020: }
 7021: 
 7022: # ------------------------------------------------------------------- Create ID
 7023: sub generate_coursenum {
 7024:     my ($udom,$crstype) = @_;
 7025:     my $domdesc = &domain($udom);
 7026:     return 'error: invalid domain' if ($domdesc eq '');
 7027:     my $first;
 7028:     if ($crstype eq 'Community') {
 7029:         $first = '0';
 7030:     } else {
 7031:         $first = int(1+rand(9)); 
 7032:     } 
 7033:     my $uname=$first.
 7034:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 7035:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
 7036:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 7037: # ----------------------------------------------- Make sure that does not exist
 7038:     my $uhome=&homeserver($uname,$udom,'true');
 7039:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
 7040:         if ($crstype eq 'Community') {
 7041:             $first = '0';
 7042:         } else {
 7043:             $first = int(1+rand(9));
 7044:         }
 7045:         $uname=$first.
 7046:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 7047:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
 7048:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 7049:         $uhome=&homeserver($uname,$udom,'true');
 7050:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
 7051:             return 'error: unable to generate unique course-ID';
 7052:         }
 7053:     }
 7054:     return $uname;
 7055: }
 7056: 
 7057: sub is_course {
 7058:     my ($cdom,$cnum) = @_;
 7059:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
 7060: 				undef,'.');
 7061:     if (exists($courses{$cdom.'_'.$cnum})) {
 7062:         return 1;
 7063:     }
 7064:     return 0;
 7065: }
 7066: 
 7067: sub store_userdata {
 7068:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
 7069:     my $result;
 7070:     if ($datakey ne '') {
 7071:         if (ref($storehash) eq 'HASH') {
 7072:             if ($udom eq '' || $uname eq '') {
 7073:                 $udom = $env{'user.domain'};
 7074:                 $uname = $env{'user.name'};
 7075:             }
 7076:             my $uhome=&homeserver($uname,$udom);
 7077:             if (($uhome eq '') || ($uhome eq 'no_host')) {
 7078:                 $result = 'error: no_host';
 7079:             } else {
 7080:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
 7081:                 $storehash->{'host'} = $perlvar{'lonHostID'};
 7082: 
 7083:                 my $namevalue='';
 7084:                 foreach my $key (keys(%{$storehash})) {
 7085:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 7086:                 }
 7087:                 $namevalue=~s/\&$//;
 7088:                 $result =  &reply("store:$env{'user.domain'}:$env{'user.name'}:".
 7089:                                   "$namespace:$datakey:$namevalue",$uhome);
 7090:             }
 7091:         } else {
 7092:             $result = 'error: data to store was not a hash reference'; 
 7093:         }
 7094:     } else {
 7095:         $result= 'error: invalid requestkey'; 
 7096:     }
 7097:     return $result;
 7098: }
 7099: 
 7100: # ---------------------------------------------------------- Assign Custom Role
 7101: 
 7102: sub assigncustomrole {
 7103:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 7104:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 7105:                        $end,$start,$deleteflag,$selfenroll,$context);
 7106: }
 7107: 
 7108: # ----------------------------------------------------------------- Revoke Role
 7109: 
 7110: sub revokerole {
 7111:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 7112:     my $now=time;
 7113:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 7114: }
 7115: 
 7116: # ---------------------------------------------------------- Revoke Custom Role
 7117: 
 7118: sub revokecustomrole {
 7119:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 7120:     my $now=time;
 7121:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 7122:            $deleteflag,$selfenroll,$context);
 7123: }
 7124: 
 7125: # ------------------------------------------------------------ Disk usage
 7126: sub diskusage {
 7127:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 7128:     $directorypath =~ s/\/$//;
 7129:     my $listing=&reply('du2:'.&escape($directorypath).':'
 7130:                        .&escape($getpropath).':'.&escape($uname).':'
 7131:                        .&escape($udom),homeserver($uname,$udom));
 7132:     if ($listing eq 'unknown_cmd') {
 7133:         if ($getpropath) {
 7134:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 7135:         }
 7136:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 7137:     }
 7138:     return $listing;
 7139: }
 7140: 
 7141: sub is_locked {
 7142:     my ($file_name, $domain, $user) = @_;
 7143:     my @check;
 7144:     my $is_locked;
 7145:     push @check, $file_name;
 7146:     my %locked = &get('file_permissions',\@check,
 7147: 		      $env{'user.domain'},$env{'user.name'});
 7148:     my ($tmp)=keys(%locked);
 7149:     if ($tmp=~/^error:/) { undef(%locked); }
 7150:     
 7151:     if (ref($locked{$file_name}) eq 'ARRAY') {
 7152:         $is_locked = 'false';
 7153:         foreach my $entry (@{$locked{$file_name}}) {
 7154:            if (ref($entry) eq 'ARRAY') { 
 7155:                $is_locked = 'true';
 7156:                last;
 7157:            }
 7158:        }
 7159:     } else {
 7160:         $is_locked = 'false';
 7161:     }
 7162: }
 7163: 
 7164: sub declutter_portfile {
 7165:     my ($file) = @_;
 7166:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 7167:     return $file;
 7168: }
 7169: 
 7170: # ------------------------------------------------------------- Mark as Read Only
 7171: 
 7172: sub mark_as_readonly {
 7173:     my ($domain,$user,$files,$what) = @_;
 7174:     my %current_permissions = &dump('file_permissions',$domain,$user);
 7175:     my ($tmp)=keys(%current_permissions);
 7176:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 7177:     foreach my $file (@{$files}) {
 7178: 	$file = &declutter_portfile($file);
 7179:         push(@{$current_permissions{$file}},$what);
 7180:     }
 7181:     &put('file_permissions',\%current_permissions,$domain,$user);
 7182:     return;
 7183: }
 7184: 
 7185: # ------------------------------------------------------------Save Selected Files
 7186: 
 7187: sub save_selected_files {
 7188:     my ($user, $path, @files) = @_;
 7189:     my $filename = $user."savedfiles";
 7190:     my @other_files = &files_not_in_path($user, $path);
 7191:     open (OUT, '>'.$tmpdir.$filename);
 7192:     foreach my $file (@files) {
 7193:         print (OUT $env{'form.currentpath'}.$file."\n");
 7194:     }
 7195:     foreach my $file (@other_files) {
 7196:         print (OUT $file."\n");
 7197:     }
 7198:     close (OUT);
 7199:     return 'ok';
 7200: }
 7201: 
 7202: sub clear_selected_files {
 7203:     my ($user) = @_;
 7204:     my $filename = $user."savedfiles";
 7205:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 7206:     print (OUT undef);
 7207:     close (OUT);
 7208:     return ("ok");    
 7209: }
 7210: 
 7211: sub files_in_path {
 7212:     my ($user, $path) = @_;
 7213:     my $filename = $user."savedfiles";
 7214:     my %return_files;
 7215:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 7216:     while (my $line_in = <IN>) {
 7217:         chomp ($line_in);
 7218:         my @paths_and_file = split (m!/!, $line_in);
 7219:         my $file_part = pop (@paths_and_file);
 7220:         my $path_part = join ('/', @paths_and_file);
 7221:         $path_part.='/';
 7222:         my $path_and_file = $path_part.$file_part;
 7223:         if ($path_part eq $path) {
 7224:             $return_files{$file_part}= 'selected';
 7225:         }
 7226:     }
 7227:     close (IN);
 7228:     return (\%return_files);
 7229: }
 7230: 
 7231: # called in portfolio select mode, to show files selected NOT in current directory
 7232: sub files_not_in_path {
 7233:     my ($user, $path) = @_;
 7234:     my $filename = $user."savedfiles";
 7235:     my @return_files;
 7236:     my $path_part;
 7237:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 7238:     while (my $line = <IN>) {
 7239:         #ok, I know it's clunky, but I want it to work
 7240:         my @paths_and_file = split(m|/|, $line);
 7241:         my $file_part = pop(@paths_and_file);
 7242:         chomp($file_part);
 7243:         my $path_part = join('/', @paths_and_file);
 7244:         $path_part .= '/';
 7245:         my $path_and_file = $path_part.$file_part;
 7246:         if ($path_part ne $path) {
 7247:             push(@return_files, ($path_and_file));
 7248:         }
 7249:     }
 7250:     close(OUT);
 7251:     return (@return_files);
 7252: }
 7253: 
 7254: #----------------------------------------------Get portfolio file permissions
 7255: 
 7256: sub get_portfile_permissions {
 7257:     my ($domain,$user) = @_;
 7258:     my %current_permissions = &dump('file_permissions',$domain,$user);
 7259:     my ($tmp)=keys(%current_permissions);
 7260:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 7261:     return \%current_permissions;
 7262: }
 7263: 
 7264: #---------------------------------------------Get portfolio file access controls
 7265: 
 7266: sub get_access_controls {
 7267:     my ($current_permissions,$group,$file) = @_;
 7268:     my %access;
 7269:     my $real_file = $file;
 7270:     $file =~ s/\.meta$//;
 7271:     if (defined($file)) {
 7272:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 7273:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 7274:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 7275:             }
 7276:         }
 7277:     } else {
 7278:         foreach my $key (keys(%{$current_permissions})) {
 7279:             if ($key =~ /\0accesscontrol$/) {
 7280:                 if (defined($group)) {
 7281:                     if ($key !~ m-^\Q$group\E/-) {
 7282:                         next;
 7283:                     }
 7284:                 }
 7285:                 my ($fullpath) = split(/\0/,$key);
 7286:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 7287:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 7288:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 7289:                     }
 7290:                 }
 7291:             }
 7292:         }
 7293:     }
 7294:     return %access;
 7295: }
 7296: 
 7297: sub modify_access_controls {
 7298:     my ($file_name,$changes,$domain,$user)=@_;
 7299:     my ($outcome,$deloutcome);
 7300:     my %store_permissions;
 7301:     my %new_values;
 7302:     my %new_control;
 7303:     my %translation;
 7304:     my @deletions = ();
 7305:     my $now = time;
 7306:     if (exists($$changes{'activate'})) {
 7307:         if (ref($$changes{'activate'}) eq 'HASH') {
 7308:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 7309:             my $numnew = scalar(@newitems);
 7310:             for (my $i=0; $i<$numnew; $i++) {
 7311:                 my $newkey = $newitems[$i];
 7312:                 my $newid = &Apache::loncommon::get_cgi_id();
 7313:                 if ($newkey =~ /^\d+:/) { 
 7314:                     $newkey =~ s/^(\d+)/$newid/;
 7315:                     $translation{$1} = $newid;
 7316:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 7317:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 7318:                     $translation{$1} = $newid;
 7319:                 }
 7320:                 $new_values{$file_name."\0".$newkey} = 
 7321:                                           $$changes{'activate'}{$newitems[$i]};
 7322:                 $new_control{$newkey} = $now;
 7323:             }
 7324:         }
 7325:     }
 7326:     my %todelete;
 7327:     my %changed_items;
 7328:     foreach my $action ('delete','update') {
 7329:         if (exists($$changes{$action})) {
 7330:             if (ref($$changes{$action}) eq 'HASH') {
 7331:                 foreach my $key (keys(%{$$changes{$action}})) {
 7332:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 7333:                     if ($action eq 'delete') { 
 7334:                         $todelete{$itemnum} = 1;
 7335:                     } else {
 7336:                         $changed_items{$itemnum} = $key;
 7337:                     }
 7338:                 }
 7339:             }
 7340:         }
 7341:     }
 7342:     # get lock on access controls for file.
 7343:     my $lockhash = {
 7344:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 7345:                                                        ':'.$env{'user.domain'},
 7346:                    }; 
 7347:     my $tries = 0;
 7348:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 7349:    
 7350:     while (($gotlock ne 'ok') && $tries <3) {
 7351:         $tries ++;
 7352:         sleep 1;
 7353:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 7354:     }
 7355:     if ($gotlock eq 'ok') {
 7356:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 7357:         my ($tmp)=keys(%curr_permissions);
 7358:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 7359:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 7360:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 7361:             if (ref($curr_controls) eq 'HASH') {
 7362:                 foreach my $control_item (keys(%{$curr_controls})) {
 7363:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 7364:                     if (defined($todelete{$itemnum})) {
 7365:                         push(@deletions,$file_name."\0".$control_item);
 7366:                     } else {
 7367:                         if (defined($changed_items{$itemnum})) {
 7368:                             $new_control{$changed_items{$itemnum}} = $now;
 7369:                             push(@deletions,$file_name."\0".$control_item);
 7370:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 7371:                         } else {
 7372:                             $new_control{$control_item} = $$curr_controls{$control_item};
 7373:                         }
 7374:                     }
 7375:                 }
 7376:             }
 7377:         }
 7378:         my ($group);
 7379:         if (&is_course($domain,$user)) {
 7380:             ($group,my $file) = split(/\//,$file_name,2);
 7381:         }
 7382:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 7383:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 7384:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 7385:         #  remove lock
 7386:         my @del_lock = ($file_name."\0".'locked_access_records');
 7387:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 7388:         my $sqlresult =
 7389:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 7390:                                     $group);
 7391:     } else {
 7392:         $outcome = "error: could not obtain lockfile\n";  
 7393:     }
 7394:     return ($outcome,$deloutcome,\%new_values,\%translation);
 7395: }
 7396: 
 7397: sub make_public_indefinitely {
 7398:     my ($requrl) = @_;
 7399:     my $now = time;
 7400:     my $action = 'activate';
 7401:     my $aclnum = 0;
 7402:     if (&is_portfolio_url($requrl)) {
 7403:         my (undef,$udom,$unum,$file_name,$group) =
 7404:             &parse_portfolio_url($requrl);
 7405:         my $current_perms = &get_portfile_permissions($udom,$unum);
 7406:         my %access_controls = &get_access_controls($current_perms,
 7407:                                                    $group,$file_name);
 7408:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 7409:             my ($num,$scope,$end,$start) = 
 7410:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 7411:             if ($scope eq 'public') {
 7412:                 if ($start <= $now && $end == 0) {
 7413:                     $action = 'none';
 7414:                 } else {
 7415:                     $action = 'update';
 7416:                     $aclnum = $num;
 7417:                 }
 7418:                 last;
 7419:             }
 7420:         }
 7421:         if ($action eq 'none') {
 7422:              return 'ok';
 7423:         } else {
 7424:             my %changes;
 7425:             my $newend = 0;
 7426:             my $newstart = $now;
 7427:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 7428:             $changes{$action}{$newkey} = {
 7429:                 type => 'public',
 7430:                 time => {
 7431:                     start => $newstart,
 7432:                     end   => $newend,
 7433:                 },
 7434:             };
 7435:             my ($outcome,$deloutcome,$new_values,$translation) =
 7436:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 7437:             return $outcome;
 7438:         }
 7439:     } else {
 7440:         return 'invalid';
 7441:     }
 7442: }
 7443: 
 7444: #------------------------------------------------------Get Marked as Read Only
 7445: 
 7446: sub get_marked_as_readonly {
 7447:     my ($domain,$user,$what,$group) = @_;
 7448:     my $current_permissions = &get_portfile_permissions($domain,$user);
 7449:     my @readonly_files;
 7450:     my $cmp1=$what;
 7451:     if (ref($what)) { $cmp1=join('',@{$what}) };
 7452:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 7453:         if (defined($group)) {
 7454:             if ($file_name !~ m-^\Q$group\E/-) {
 7455:                 next;
 7456:             }
 7457:         }
 7458:         if (ref($value) eq "ARRAY"){
 7459:             foreach my $stored_what (@{$value}) {
 7460:                 my $cmp2=$stored_what;
 7461:                 if (ref($stored_what) eq 'ARRAY') {
 7462:                     $cmp2=join('',@{$stored_what});
 7463:                 }
 7464:                 if ($cmp1 eq $cmp2) {
 7465:                     push(@readonly_files, $file_name);
 7466:                     last;
 7467:                 } elsif (!defined($what)) {
 7468:                     push(@readonly_files, $file_name);
 7469:                     last;
 7470:                 }
 7471:             }
 7472:         }
 7473:     }
 7474:     return @readonly_files;
 7475: }
 7476: #-----------------------------------------------------------Get Marked as Read Only Hash
 7477: 
 7478: sub get_marked_as_readonly_hash {
 7479:     my ($current_permissions,$group,$what) = @_;
 7480:     my %readonly_files;
 7481:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 7482:         if (defined($group)) {
 7483:             if ($file_name !~ m-^\Q$group\E/-) {
 7484:                 next;
 7485:             }
 7486:         }
 7487:         if (ref($value) eq "ARRAY"){
 7488:             foreach my $stored_what (@{$value}) {
 7489:                 if (ref($stored_what) eq 'ARRAY') {
 7490:                     foreach my $lock_descriptor(@{$stored_what}) {
 7491:                         if ($lock_descriptor eq 'graded') {
 7492:                             $readonly_files{$file_name} = 'graded';
 7493:                         } elsif ($lock_descriptor eq 'handback') {
 7494:                             $readonly_files{$file_name} = 'handback';
 7495:                         } else {
 7496:                             if (!exists($readonly_files{$file_name})) {
 7497:                                 $readonly_files{$file_name} = 'locked';
 7498:                             }
 7499:                         }
 7500:                     }
 7501:                 } 
 7502:             }
 7503:         } 
 7504:     }
 7505:     return %readonly_files;
 7506: }
 7507: # ------------------------------------------------------------ Unmark as Read Only
 7508: 
 7509: sub unmark_as_readonly {
 7510:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 7511:     # for portfolio submissions, $what contains [$symb,$crsid] 
 7512:     my ($domain,$user,$what,$file_name,$group) = @_;
 7513:     $file_name = &declutter_portfile($file_name);
 7514:     my $symb_crs = $what;
 7515:     if (ref($what)) { $symb_crs=join('',@$what); }
 7516:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 7517:     my ($tmp)=keys(%current_permissions);
 7518:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 7519:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 7520:     foreach my $file (@readonly_files) {
 7521: 	my $clean_file = &declutter_portfile($file);
 7522: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 7523: 	my $current_locks = $current_permissions{$file};
 7524:         my @new_locks;
 7525:         my @del_keys;
 7526:         if (ref($current_locks) eq "ARRAY"){
 7527:             foreach my $locker (@{$current_locks}) {
 7528:                 my $compare=$locker;
 7529:                 if (ref($locker) eq 'ARRAY') {
 7530:                     $compare=join('',@{$locker});
 7531:                     if ($compare ne $symb_crs) {
 7532:                         push(@new_locks, $locker);
 7533:                     }
 7534:                 }
 7535:             }
 7536:             if (scalar(@new_locks) > 0) {
 7537:                 $current_permissions{$file} = \@new_locks;
 7538:             } else {
 7539:                 push(@del_keys, $file);
 7540:                 &del('file_permissions',\@del_keys, $domain, $user);
 7541:                 delete($current_permissions{$file});
 7542:             }
 7543:         }
 7544:     }
 7545:     &put('file_permissions',\%current_permissions,$domain,$user);
 7546:     return;
 7547: }
 7548: 
 7549: # ------------------------------------------------------------ Directory lister
 7550: 
 7551: sub dirlist {
 7552:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 7553:     $uri=~s/^\///;
 7554:     $uri=~s/\/$//;
 7555:     my ($udom, $uname);
 7556:     if ($getuserdir) {
 7557:         $udom = $userdomain;
 7558:         $uname = $username;
 7559:     } else {
 7560:         (undef,$udom,$uname)=split(/\//,$uri);
 7561:         if(defined($userdomain)) {
 7562:             $udom = $userdomain;
 7563:         }
 7564:         if(defined($username)) {
 7565:             $uname = $username;
 7566:         }
 7567:     }
 7568:     my ($dirRoot,$listing,@listing_results);
 7569: 
 7570:     $dirRoot = $perlvar{'lonDocRoot'};
 7571:     if (defined($getpropath)) {
 7572:         $dirRoot = &propath($udom,$uname);
 7573:         $dirRoot =~ s/\/$//;
 7574:     } elsif (defined($getuserdir)) {
 7575:         my $subdir=$uname.'__';
 7576:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 7577:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 7578:                    ."/$udom/$subdir/$uname";
 7579:     } elsif (defined($alternateRoot)) {
 7580:         $dirRoot = $alternateRoot;
 7581:     }
 7582: 
 7583:     if($udom) {
 7584:         if($uname) {
 7585:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 7586:                               .$getuserdir.':'.&escape($dirRoot)
 7587:                               .':'.&escape($uname).':'.&escape($udom),
 7588:                               &homeserver($uname,$udom));
 7589:             if ($listing eq 'unknown_cmd') {
 7590:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
 7591:                                   &homeserver($uname,$udom));
 7592:             } else {
 7593:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 7594:             }
 7595:             if ($listing eq 'unknown_cmd') {
 7596:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
 7597: 				  &homeserver($uname,$udom));
 7598:                 @listing_results = split(/:/,$listing);
 7599:             } else {
 7600:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 7601:             }
 7602:             return @listing_results;
 7603:         } elsif(!$alternateRoot) {
 7604:             my %allusers;
 7605: 	    my %servers = &get_servers($udom,'library');
 7606:  	    foreach my $tryserver (keys(%servers)) {
 7607:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 7608:                                   &escape($udom),$tryserver);
 7609:                 if ($listing eq 'unknown_cmd') {
 7610: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 7611: 				      $udom, $tryserver);
 7612:                 } else {
 7613:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 7614:                 }
 7615: 		if ($listing eq 'unknown_cmd') {
 7616: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 7617: 				      $udom, $tryserver);
 7618: 		    @listing_results = split(/:/,$listing);
 7619: 		} else {
 7620: 		    @listing_results =
 7621: 			map { &unescape($_); } split(/:/,$listing);
 7622: 		}
 7623: 		if ($listing_results[0] ne 'no_such_dir' && 
 7624: 		    $listing_results[0] ne 'empty'       &&
 7625: 		    $listing_results[0] ne 'con_lost') {
 7626: 		    foreach my $line (@listing_results) {
 7627: 			my ($entry) = split(/&/,$line,2);
 7628: 			$allusers{$entry} = 1;
 7629: 		    }
 7630: 		}
 7631:             }
 7632:             my $alluserstr='';
 7633:             foreach my $user (sort(keys(%allusers))) {
 7634:                 $alluserstr.=$user.'&user:';
 7635:             }
 7636:             $alluserstr=~s/:$//;
 7637:             return split(/:/,$alluserstr);
 7638:         } else {
 7639:             return ('missing user name');
 7640:         }
 7641:     } elsif(!defined($getpropath)) {
 7642:         my @all_domains = sort(&all_domains());
 7643:         foreach my $domain (@all_domains) {
 7644:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
 7645:         }
 7646:         return @all_domains;
 7647:     } else {
 7648:         return ('missing domain');
 7649:     }
 7650: }
 7651: 
 7652: # --------------------------------------------- GetFileTimestamp
 7653: # This function utilizes dirlist and returns the date stamp for
 7654: # when it was last modified.  It will also return an error of -1
 7655: # if an error occurs
 7656: 
 7657: sub GetFileTimestamp {
 7658:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 7659:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 7660:     $studentName   = &LONCAPA::clean_username($studentName);
 7661:     my ($fileStat) = 
 7662:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
 7663:                                  undef,$getuserdir);
 7664:     my @stats = split('&', $fileStat);
 7665:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 7666:         # @stats contains first the filename, then the stat output
 7667:         return $stats[10]; # so this is 10 instead of 9.
 7668:     } else {
 7669:         return -1;
 7670:     }
 7671: }
 7672: 
 7673: sub stat_file {
 7674:     my ($uri) = @_;
 7675:     $uri = &clutter_with_no_wrapper($uri);
 7676: 
 7677:     my ($udom,$uname,$file);
 7678:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 7679: 	($udom,$uname,$file) =
 7680: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 7681: 	$file = 'userfiles/'.$file;
 7682:     }
 7683:     if ($uri =~ m-^/res/-) {
 7684: 	($udom,$uname) = 
 7685: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 7686: 	$file = $uri;
 7687:     }
 7688: 
 7689:     if (!$udom || !$uname || !$file) {
 7690: 	# unable to handle the uri
 7691: 	return ();
 7692:     }
 7693:     my $getpropath;
 7694:     if ($file =~ /^userfiles\//) {
 7695:         $getpropath = 1;
 7696:     }
 7697:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
 7698:     my @stats = split('&', $result);
 7699:     
 7700:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 7701: 	shift(@stats); #filename is first
 7702: 	return @stats;
 7703:     }
 7704:     return ();
 7705: }
 7706: 
 7707: # -------------------------------------------------------- Value of a Condition
 7708: 
 7709: # gets the value of a specific preevaluated condition
 7710: #    stored in the string  $env{user.state.<cid>}
 7711: # or looks up a condition reference in the bighash and if if hasn't
 7712: # already been evaluated recurses into docondval to get the value of
 7713: # the condition, then memoizing it to 
 7714: #   $env{user.state.<cid>.<condition>}
 7715: sub directcondval {
 7716:     my $number=shift;
 7717:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 7718: 	&Apache::lonuserstate::evalstate();
 7719:     }
 7720:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 7721: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 7722:     } elsif ($number =~ /^_/) {
 7723: 	my $sub_condition;
 7724: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7725: 		&GDBM_READER(),0640)) {
 7726: 	    $sub_condition=$bighash{'conditions'.$number};
 7727: 	    untie(%bighash);
 7728: 	}
 7729: 	my $value = &docondval($sub_condition);
 7730: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 7731: 	return $value;
 7732:     }
 7733:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 7734:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 7735:     } else {
 7736:        return 2;
 7737:     }
 7738: }
 7739: 
 7740: # get the collection of conditions for this resource
 7741: sub condval {
 7742:     my $condidx=shift;
 7743:     my $allpathcond='';
 7744:     foreach my $cond (split(/\|/,$condidx)) {
 7745: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 7746: 	    $allpathcond.=
 7747: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 7748: 	}
 7749:     }
 7750:     $allpathcond=~s/\|$//;
 7751:     return &docondval($allpathcond);
 7752: }
 7753: 
 7754: #evaluates an expression of conditions
 7755: sub docondval {
 7756:     my ($allpathcond) = @_;
 7757:     my $result=0;
 7758:     if ($env{'request.course.id'}
 7759: 	&& defined($allpathcond)) {
 7760: 	my $operand='|';
 7761: 	my @stack;
 7762: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 7763: 	    if ($chunk eq '(') {
 7764: 		push @stack,($operand,$result);
 7765: 	    } elsif ($chunk eq ')') {
 7766: 		my $before=pop @stack;
 7767: 		if (pop @stack eq '&') {
 7768: 		    $result=$result>$before?$before:$result;
 7769: 		} else {
 7770: 		    $result=$result>$before?$result:$before;
 7771: 		}
 7772: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 7773: 		$operand=$chunk;
 7774: 	    } else {
 7775: 		my $new=directcondval($chunk);
 7776: 		if ($operand eq '&') {
 7777: 		    $result=$result>$new?$new:$result;
 7778: 		} else {
 7779: 		    $result=$result>$new?$result:$new;
 7780: 		}
 7781: 	    }
 7782: 	}
 7783:     }
 7784:     return $result;
 7785: }
 7786: 
 7787: # ---------------------------------------------------- Devalidate courseresdata
 7788: 
 7789: sub devalidatecourseresdata {
 7790:     my ($coursenum,$coursedomain)=@_;
 7791:     my $hashid=$coursenum.':'.$coursedomain;
 7792:     &devalidate_cache_new('courseres',$hashid);
 7793: }
 7794: 
 7795: 
 7796: # --------------------------------------------------- Course Resourcedata Query
 7797: #
 7798: #  Parameters:
 7799: #      $coursenum    - Number of the course.
 7800: #      $coursedomain - Domain at which the course was created.
 7801: #  Returns:
 7802: #     A hash of the course parameters along (I think) with timestamps
 7803: #     and version info.
 7804: 
 7805: sub get_courseresdata {
 7806:     my ($coursenum,$coursedomain)=@_;
 7807:     my $coursehom=&homeserver($coursenum,$coursedomain);
 7808:     my $hashid=$coursenum.':'.$coursedomain;
 7809:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 7810:     my %dumpreply;
 7811:     unless (defined($cached)) {
 7812: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 7813: 	$result=\%dumpreply;
 7814: 	my ($tmp) = keys(%dumpreply);
 7815: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 7816: 	    &do_cache_new('courseres',$hashid,$result,600);
 7817: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 7818: 	    return $tmp;
 7819: 	} elsif ($tmp =~ /^(error)/) {
 7820: 	    $result=undef;
 7821: 	    &do_cache_new('courseres',$hashid,$result,600);
 7822: 	}
 7823:     }
 7824:     return $result;
 7825: }
 7826: 
 7827: sub devalidateuserresdata {
 7828:     my ($uname,$udom)=@_;
 7829:     my $hashid="$udom:$uname";
 7830:     &devalidate_cache_new('userres',$hashid);
 7831: }
 7832: 
 7833: sub get_userresdata {
 7834:     my ($uname,$udom)=@_;
 7835:     #most student don\'t have any data set, check if there is some data
 7836:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 7837: 
 7838:     my $hashid="$udom:$uname";
 7839:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 7840:     if (!defined($cached)) {
 7841: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 7842: 	$result=\%resourcedata;
 7843: 	&do_cache_new('userres',$hashid,$result,600);
 7844:     }
 7845:     my ($tmp)=keys(%$result);
 7846:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 7847: 	return $result;
 7848:     }
 7849:     #error 2 occurs when the .db doesn't exist
 7850:     if ($tmp!~/error: 2 /) {
 7851: 	&logthis("<font color=\"blue\">WARNING:".
 7852: 		 " Trying to get resource data for ".
 7853: 		 $uname." at ".$udom.": ".
 7854: 		 $tmp."</font>");
 7855:     } elsif ($tmp=~/error: 2 /) {
 7856: 	#&EXT_cache_set($udom,$uname);
 7857: 	&do_cache_new('userres',$hashid,undef,600);
 7858: 	undef($tmp); # not really an error so don't send it back
 7859:     }
 7860:     return $tmp;
 7861: }
 7862: #----------------------------------------------- resdata - return resource data
 7863: #  Purpose:
 7864: #    Return resource data for either users or for a course.
 7865: #  Parameters:
 7866: #     $name      - Course/user name.
 7867: #     $domain    - Name of the domain the user/course is registered on.
 7868: #     $type      - Type of thing $name is (must be 'course' or 'user'
 7869: #     @which     - Array of names of resources desired.
 7870: #  Returns:
 7871: #     The value of the first reasource in @which that is found in the
 7872: #     resource hash.
 7873: #  Exceptional Conditions:
 7874: #     If the $type passed in is not valid (not the string 'course' or 
 7875: #     'user', an undefined  reference is returned.
 7876: #     If none of the resources are found, an undef is returned
 7877: sub resdata {
 7878:     my ($name,$domain,$type,@which)=@_;
 7879:     my $result;
 7880:     if ($type eq 'course') {
 7881: 	$result=&get_courseresdata($name,$domain);
 7882:     } elsif ($type eq 'user') {
 7883: 	$result=&get_userresdata($name,$domain);
 7884:     }
 7885:     if (!ref($result)) { return $result; }    
 7886:     foreach my $item (@which) {
 7887: 	if (defined($result->{$item->[0]})) {
 7888: 	    return [$result->{$item->[0]},$item->[1]];
 7889: 	}
 7890:     }
 7891:     return undef;
 7892: }
 7893: 
 7894: #
 7895: # EXT resource caching routines
 7896: #
 7897: 
 7898: sub clear_EXT_cache_status {
 7899:     &delenv('cache.EXT.');
 7900: }
 7901: 
 7902: sub EXT_cache_status {
 7903:     my ($target_domain,$target_user) = @_;
 7904:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 7905:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 7906:         # We know already the user has no data
 7907:         return 1;
 7908:     } else {
 7909:         return 0;
 7910:     }
 7911: }
 7912: 
 7913: sub EXT_cache_set {
 7914:     my ($target_domain,$target_user) = @_;
 7915:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 7916:     #&appenv({$cachename => time});
 7917: }
 7918: 
 7919: # --------------------------------------------------------- Value of a Variable
 7920: sub EXT {
 7921: 
 7922:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 7923:     unless ($varname) { return ''; }
 7924:     #get real user name/domain, courseid and symb
 7925:     my $courseid;
 7926:     my $publicuser;
 7927:     if ($symbparm) {
 7928: 	$symbparm=&get_symb_from_alias($symbparm);
 7929:     }
 7930:     if (!($uname && $udom)) {
 7931:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 7932:       if (!$symbparm) {	$symbparm=$cursymb; }
 7933:     } else {
 7934: 	$courseid=$env{'request.course.id'};
 7935:     }
 7936:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 7937:     my $rest;
 7938:     if (defined($therest[0])) {
 7939:        $rest=join('.',@therest);
 7940:     } else {
 7941:        $rest='';
 7942:     }
 7943: 
 7944:     my $qualifierrest=$qualifier;
 7945:     if ($rest) { $qualifierrest.='.'.$rest; }
 7946:     my $spacequalifierrest=$space;
 7947:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 7948:     if ($realm eq 'user') {
 7949: # --------------------------------------------------------------- user.resource
 7950: 	if ($space eq 'resource') {
 7951: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 7952: 		  || defined($Apache::lonhomework::parsing_a_task))
 7953: 		 &&
 7954: 		 ($symbparm eq &symbread()) ) {	
 7955: 		# if we are in the middle of processing the resource the
 7956: 		# get the value we are planning on committing
 7957:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 7958:                     return $Apache::lonhomework::results{$qualifierrest};
 7959:                 } else {
 7960:                     return $Apache::lonhomework::history{$qualifierrest};
 7961:                 }
 7962: 	    } else {
 7963: 		my %restored;
 7964: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 7965: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 7966: 		} else {
 7967: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 7968: 		}
 7969: 		return $restored{$qualifierrest};
 7970: 	    }
 7971: # ----------------------------------------------------------------- user.access
 7972:         } elsif ($space eq 'access') {
 7973: 	    # FIXME - not supporting calls for a specific user
 7974:             return &allowed($qualifier,$rest);
 7975: # ------------------------------------------ user.preferences, user.environment
 7976:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 7977: 	    if (($uname eq $env{'user.name'}) &&
 7978: 		($udom eq $env{'user.domain'})) {
 7979: 		return $env{join('.',('environment',$qualifierrest))};
 7980: 	    } else {
 7981: 		my %returnhash;
 7982: 		if (!$publicuser) {
 7983: 		    %returnhash=&userenvironment($udom,$uname,
 7984: 						 $qualifierrest);
 7985: 		}
 7986: 		return $returnhash{$qualifierrest};
 7987: 	    }
 7988: # ----------------------------------------------------------------- user.course
 7989:         } elsif ($space eq 'course') {
 7990: 	    # FIXME - not supporting calls for a specific user
 7991:             return $env{join('.',('request.course',$qualifier))};
 7992: # ------------------------------------------------------------------- user.role
 7993:         } elsif ($space eq 'role') {
 7994: 	    # FIXME - not supporting calls for a specific user
 7995:             my ($role,$where)=split(/\./,$env{'request.role'});
 7996:             if ($qualifier eq 'value') {
 7997: 		return $role;
 7998:             } elsif ($qualifier eq 'extent') {
 7999:                 return $where;
 8000:             }
 8001: # ----------------------------------------------------------------- user.domain
 8002:         } elsif ($space eq 'domain') {
 8003:             return $udom;
 8004: # ------------------------------------------------------------------- user.name
 8005:         } elsif ($space eq 'name') {
 8006:             return $uname;
 8007: # ---------------------------------------------------- Any other user namespace
 8008:         } else {
 8009: 	    my %reply;
 8010: 	    if (!$publicuser) {
 8011: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 8012: 	    }
 8013: 	    return $reply{$qualifierrest};
 8014:         }
 8015:     } elsif ($realm eq 'query') {
 8016: # ---------------------------------------------- pull stuff out of query string
 8017:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 8018: 						[$spacequalifierrest]);
 8019: 	return $env{'form.'.$spacequalifierrest}; 
 8020:    } elsif ($realm eq 'request') {
 8021: # ------------------------------------------------------------- request.browser
 8022:         if ($space eq 'browser') {
 8023: 	    if ($qualifier eq 'textremote') {
 8024: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
 8025: 		    return 1;
 8026: 		} else {
 8027: 		    return 0;
 8028: 		}
 8029: 	    } else {
 8030: 		return $env{'browser.'.$qualifier};
 8031: 	    }
 8032: # ------------------------------------------------------------ request.filename
 8033:         } else {
 8034:             return $env{'request.'.$spacequalifierrest};
 8035:         }
 8036:     } elsif ($realm eq 'course') {
 8037: # ---------------------------------------------------------- course.description
 8038:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 8039:     } elsif ($realm eq 'resource') {
 8040: 
 8041: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 8042: 	    if (!$symbparm) { $symbparm=&symbread(); }
 8043: 	}
 8044: 
 8045: 	if ($space eq 'title') {
 8046: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 8047: 	    return &gettitle($symbparm);
 8048: 	}
 8049: 	
 8050: 	if ($space eq 'map') {
 8051: 	    my ($map) = &decode_symb($symbparm);
 8052: 	    return &symbread($map);
 8053: 	}
 8054: 	if ($space eq 'filename') {
 8055: 	    if ($symbparm) {
 8056: 		return &clutter((&decode_symb($symbparm))[2]);
 8057: 	    }
 8058: 	    return &hreflocation('',$env{'request.filename'});
 8059: 	}
 8060: 
 8061: 	my ($section, $group, @groups);
 8062: 	my ($courselevelm,$courselevel);
 8063: 	if ($symbparm && defined($courseid) && 
 8064: 	    $courseid eq $env{'request.course.id'}) {
 8065: 
 8066: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 8067: 
 8068: # ----------------------------------------------------- Cascading lookup scheme
 8069: 	    my $symbp=$symbparm;
 8070: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 8071: 
 8072: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 8073: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 8074: 
 8075: 	    if (($env{'user.name'} eq $uname) &&
 8076: 		($env{'user.domain'} eq $udom)) {
 8077: 		$section=$env{'request.course.sec'};
 8078:                 @groups = split(/:/,$env{'request.course.groups'});  
 8079:                 @groups=&sort_course_groups($courseid,@groups); 
 8080: 	    } else {
 8081: 		if (! defined($usection)) {
 8082: 		    $section=&getsection($udom,$uname,$courseid);
 8083: 		} else {
 8084: 		    $section = $usection;
 8085: 		}
 8086:                 @groups = &get_users_groups($udom,$uname,$courseid);
 8087: 	    }
 8088: 
 8089: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 8090: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 8091: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 8092: 
 8093: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 8094: 	    my $courselevelr=$courseid.'.'.$symbparm;
 8095: 	    $courselevelm=$courseid.'.'.$mapparm;
 8096: 
 8097: # ----------------------------------------------------------- first, check user
 8098: 
 8099: 	    my $userreply=&resdata($uname,$udom,'user',
 8100: 				       ([$courselevelr,'resource'],
 8101: 					[$courselevelm,'map'     ],
 8102: 					[$courselevel, 'course'  ]));
 8103: 	    if (defined($userreply)) { return &get_reply($userreply); }
 8104: 
 8105: # ------------------------------------------------ second, check some of course
 8106:             my $coursereply;
 8107:             if (@groups > 0) {
 8108:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 8109:                                        $mapparm,$spacequalifierrest);
 8110:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 8111:             }
 8112: 
 8113: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 8114: 				  $env{'course.'.$courseid.'.domain'},
 8115: 				  'course',
 8116: 				  ([$seclevelr,   'resource'],
 8117: 				   [$seclevelm,   'map'     ],
 8118: 				   [$seclevel,    'course'  ],
 8119: 				   [$courselevelr,'resource']));
 8120: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 8121: 
 8122: # ------------------------------------------------------ third, check map parms
 8123: 	    my %parmhash=();
 8124: 	    my $thisparm='';
 8125: 	    if (tie(%parmhash,'GDBM_File',
 8126: 		    $env{'request.course.fn'}.'_parms.db',
 8127: 		    &GDBM_READER(),0640)) {
 8128: 		$thisparm=$parmhash{$symbparm};
 8129: 		untie(%parmhash);
 8130: 	    }
 8131: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 8132: 	}
 8133: # ------------------------------------------ fourth, look in resource metadata
 8134: 
 8135: 	$spacequalifierrest=~s/\./\_/;
 8136: 	my $filename;
 8137: 	if (!$symbparm) { $symbparm=&symbread(); }
 8138: 	if ($symbparm) {
 8139: 	    $filename=(&decode_symb($symbparm))[2];
 8140: 	} else {
 8141: 	    $filename=$env{'request.filename'};
 8142: 	}
 8143: 	my $metadata=&metadata($filename,$spacequalifierrest);
 8144: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 8145: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 8146: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 8147: 
 8148: # ---------------------------------------------- fourth, look in rest of course
 8149: 	if ($symbparm && defined($courseid) && 
 8150: 	    $courseid eq $env{'request.course.id'}) {
 8151: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 8152: 				     $env{'course.'.$courseid.'.domain'},
 8153: 				     'course',
 8154: 				     ([$courselevelm,'map'   ],
 8155: 				      [$courselevel, 'course']));
 8156: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 8157: 	}
 8158: # ------------------------------------------------------------------ Cascade up
 8159: 	unless ($space eq '0') {
 8160: 	    my @parts=split(/_/,$space);
 8161: 	    my $id=pop(@parts);
 8162: 	    my $part=join('_',@parts);
 8163: 	    if ($part eq '') { $part='0'; }
 8164: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 8165: 				 $symbparm,$udom,$uname,$section,1);
 8166: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 8167: 	}
 8168: 	if ($recurse) { return undef; }
 8169: 	my $pack_def=&packages_tab_default($filename,$varname);
 8170: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 8171: # ---------------------------------------------------- Any other user namespace
 8172:     } elsif ($realm eq 'environment') {
 8173: # ----------------------------------------------------------------- environment
 8174: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 8175: 	    return $env{'environment.'.$spacequalifierrest};
 8176: 	} else {
 8177: 	    if ($uname eq 'anonymous' && $udom eq '') {
 8178: 		return '';
 8179: 	    }
 8180: 	    my %returnhash=&userenvironment($udom,$uname,
 8181: 					    $spacequalifierrest);
 8182: 	    return $returnhash{$spacequalifierrest};
 8183: 	}
 8184:     } elsif ($realm eq 'system') {
 8185: # ----------------------------------------------------------------- system.time
 8186: 	if ($space eq 'time') {
 8187: 	    return time;
 8188:         }
 8189:     } elsif ($realm eq 'server') {
 8190: # ----------------------------------------------------------------- system.time
 8191: 	if ($space eq 'name') {
 8192: 	    return $ENV{'SERVER_NAME'};
 8193:         }
 8194:     }
 8195:     return '';
 8196: }
 8197: 
 8198: sub get_reply {
 8199:     my ($reply_value) = @_;
 8200:     if (ref($reply_value) eq 'ARRAY') {
 8201:         if (wantarray) {
 8202: 	    return @$reply_value;
 8203:         }
 8204:         return $reply_value->[0];
 8205:     } else {
 8206:         return $reply_value;
 8207:     }
 8208: }
 8209: 
 8210: sub check_group_parms {
 8211:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 8212:     my @groupitems = ();
 8213:     my $resultitem;
 8214:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 8215:     foreach my $group (@{$groups}) {
 8216:         foreach my $level (@levels) {
 8217:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 8218:              push(@groupitems,[$item,$level->[1]]);
 8219:         }
 8220:     }
 8221:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 8222:                             $env{'course.'.$courseid.'.domain'},
 8223:                                      'course',@groupitems);
 8224:     return $coursereply;
 8225: }
 8226: 
 8227: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 8228:     my ($courseid,@groups) = @_;
 8229:     @groups = sort(@groups);
 8230:     return @groups;
 8231: }
 8232: 
 8233: sub packages_tab_default {
 8234:     my ($uri,$varname)=@_;
 8235:     my (undef,$part,$name)=split(/\./,$varname);
 8236: 
 8237:     my (@extension,@specifics,$do_default);
 8238:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 8239: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 8240: 	if ($pack_type eq 'default') {
 8241: 	    $do_default=1;
 8242: 	} elsif ($pack_type eq 'extension') {
 8243: 	    push(@extension,[$package,$pack_type,$pack_part]);
 8244: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 8245: 	    # only look at packages defaults for packages that this id is
 8246: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 8247: 	}
 8248:     }
 8249:     # first look for a package that matches the requested part id
 8250:     foreach my $package (@specifics) {
 8251: 	my (undef,$pack_type,$pack_part)=@{$package};
 8252: 	next if ($pack_part ne $part);
 8253: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 8254: 	    return $packagetab{"$pack_type&$name&default"};
 8255: 	}
 8256:     }
 8257:     # look for any possible matching non extension_ package
 8258:     foreach my $package (@specifics) {
 8259: 	my (undef,$pack_type,$pack_part)=@{$package};
 8260: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 8261: 	    return $packagetab{"$pack_type&$name&default"};
 8262: 	}
 8263: 	if ($pack_type eq 'part') { $pack_part='0'; }
 8264: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 8265: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 8266: 	}
 8267:     }
 8268:     # look for any posible extension_ match
 8269:     foreach my $package (@extension) {
 8270: 	my ($package,$pack_type)=@{$package};
 8271: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 8272: 	    return $packagetab{"$pack_type&$name&default"};
 8273: 	}
 8274: 	if (defined($packagetab{$package."&$name&default"})) {
 8275: 	    return $packagetab{$package."&$name&default"};
 8276: 	}
 8277:     }
 8278:     # look for a global default setting
 8279:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 8280: 	return $packagetab{"default&$name&default"};
 8281:     }
 8282:     return undef;
 8283: }
 8284: 
 8285: sub add_prefix_and_part {
 8286:     my ($prefix,$part)=@_;
 8287:     my $keyroot;
 8288:     if (defined($prefix) && $prefix !~ /^__/) {
 8289: 	# prefix that has a part already
 8290: 	$keyroot=$prefix;
 8291:     } elsif (defined($prefix)) {
 8292: 	# prefix that is missing a part
 8293: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 8294:     } else {
 8295: 	# no prefix at all
 8296: 	if (defined($part)) { $keyroot='_'.$part; }
 8297:     }
 8298:     return $keyroot;
 8299: }
 8300: 
 8301: # ---------------------------------------------------------------- Get metadata
 8302: 
 8303: my %metaentry;
 8304: my %importedpartids;
 8305: sub metadata {
 8306:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 8307:     $uri=&declutter($uri);
 8308:     # if it is a non metadata possible uri return quickly
 8309:     if (($uri eq '') || 
 8310: 	(($uri =~ m|^/*adm/|) && 
 8311: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 8312:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
 8313: 	return undef;
 8314:     }
 8315:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
 8316: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
 8317: 	return undef;
 8318:     }
 8319:     my $filename=$uri;
 8320:     $uri=~s/\.meta$//;
 8321: #
 8322: # Is the metadata already cached?
 8323: # Look at timestamp of caching
 8324: # Everything is cached by the main uri, libraries are never directly cached
 8325: #
 8326:     if (!defined($liburi)) {
 8327: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 8328: 	if (defined($cached)) { return $result->{':'.$what}; }
 8329:     }
 8330:     {
 8331: # Imported parts would go here
 8332:         my %importedids=();
 8333:         my @origfileimportpartids=();
 8334:         my $importedparts=0;
 8335: #
 8336: # Is this a recursive call for a library?
 8337: #
 8338: #	if (! exists($metacache{$uri})) {
 8339: #	    $metacache{$uri}={};
 8340: #	}
 8341: 	my $cachetime = 60*60;
 8342:         if ($liburi) {
 8343: 	    $liburi=&declutter($liburi);
 8344:             $filename=$liburi;
 8345:         } else {
 8346: 	    &devalidate_cache_new('meta',$uri);
 8347: 	    undef(%metaentry);
 8348: 	}
 8349:         my %metathesekeys=();
 8350:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 8351: 	my $metastring;
 8352: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
 8353: 	    my $which = &hreflocation('','/'.($liburi || $uri));
 8354: 	    $metastring = 
 8355: 		&Apache::lonnet::ssi_body($which,
 8356: 					  ('grade_target' => 'meta'));
 8357: 	    $cachetime = 1; # only want this cached in the child not long term
 8358: 	} elsif ($uri !~ m -^(editupload)/-) {
 8359: 	    my $file=&filelocation('',&clutter($filename));
 8360: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 8361: 	    $metastring=&getfile($file);
 8362: 	}
 8363:         my $parser=HTML::LCParser->new(\$metastring);
 8364:         my $token;
 8365:         undef %metathesekeys;
 8366:         while ($token=$parser->get_token) {
 8367: 	    if ($token->[0] eq 'S') {
 8368: 		if (defined($token->[2]->{'package'})) {
 8369: #
 8370: # This is a package - get package info
 8371: #
 8372: 		    my $package=$token->[2]->{'package'};
 8373: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 8374: 		    if (defined($token->[2]->{'id'})) { 
 8375: 			$keyroot.='_'.$token->[2]->{'id'}; 
 8376: 		    }
 8377: 		    if ($metaentry{':packages'}) {
 8378: 			$metaentry{':packages'}.=','.$package.$keyroot;
 8379: 		    } else {
 8380: 			$metaentry{':packages'}=$package.$keyroot;
 8381: 		    }
 8382: 		    foreach my $pack_entry (keys(%packagetab)) {
 8383: 			my $part=$keyroot;
 8384: 			$part=~s/^\_//;
 8385: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 8386: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 8387: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 8388: 			    # ignore package.tab specified default values
 8389:                             # here &package_tab_default() will fetch those
 8390: 			    if ($subp eq 'default') { next; }
 8391: 			    my $value=$packagetab{$pack_entry};
 8392: 			    my $unikey;
 8393: 			    if ($pack =~ /_0$/) {
 8394: 				$unikey='parameter_0_'.$name;
 8395: 				$part=0;
 8396: 			    } else {
 8397: 				$unikey='parameter'.$keyroot.'_'.$name;
 8398: 			    }
 8399: 			    if ($subp eq 'display') {
 8400: 				$value.=' [Part: '.$part.']';
 8401: 			    }
 8402: 			    $metaentry{':'.$unikey.'.part'}=$part;
 8403: 			    $metathesekeys{$unikey}=1;
 8404: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 8405: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 8406: 			    }
 8407: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 8408: 				$metaentry{':'.$unikey}=
 8409: 				    $metaentry{':'.$unikey.'.default'};
 8410: 			    }
 8411: 			}
 8412: 		    }
 8413: 		} else {
 8414: #
 8415: # This is not a package - some other kind of start tag
 8416: #
 8417: 		    my $entry=$token->[1];
 8418: 		    my $unikey='';
 8419: 
 8420: 		    if ($entry eq 'import') {
 8421: #
 8422: # Importing a library here
 8423: #
 8424:                         my $location=$parser->get_text('/import');
 8425:                         my $dir=$filename;
 8426:                         $dir=~s|[^/]*$||;
 8427:                         $location=&filelocation($dir,$location);
 8428:                        
 8429:                         my $importmode=$token->[2]->{'importmode'};
 8430:                         if ($importmode eq 'problem') {
 8431: # Import as problem/response
 8432:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 8433:                         } elsif ($importmode eq 'part') {
 8434: # Import as part(s)
 8435:                            $importedparts=1;
 8436: # We need to get the original file and the imported file to get the part order correct
 8437: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
 8438: # Load and inspect original file
 8439:                            if ($#origfileimportpartids<0) {
 8440:                               undef(%importedpartids);
 8441:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
 8442:                               my $origfile=&getfile($origfilelocation);
 8443:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
 8444:                            }
 8445: 
 8446: # Load and inspect imported file
 8447:                            my $impfile=&getfile($location);
 8448:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
 8449:                            if ($#impfilepartids>=0) {
 8450: # This problem had parts
 8451:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
 8452:                            } else {
 8453: # Importing by turning a single problem into a problem part
 8454: # It gets the import-tags ID as part-ID
 8455:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
 8456:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
 8457:                            }
 8458:                         } else {
 8459: # Normal import
 8460:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 8461:                            if (defined($token->[2]->{'id'})) {
 8462:                               $unikey.='_'.$token->[2]->{'id'};
 8463:                            }
 8464:                         }
 8465: 
 8466: 			if ($depthcount<20) {
 8467: 			    my $metadata = 
 8468: 				&metadata($uri,'keys', $location,$unikey,
 8469: 					  $depthcount+1);
 8470: 			    foreach my $meta (split(',',$metadata)) {
 8471: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 8472: 				$metathesekeys{$meta}=1;
 8473: 			    }
 8474: 			
 8475:                         }
 8476: 		    } else {
 8477: #
 8478: # Not importing, some other kind of non-package, non-library start tag
 8479: # 
 8480:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
 8481:                         if (defined($token->[2]->{'id'})) {
 8482:                             $unikey.='_'.$token->[2]->{'id'};
 8483:                         }
 8484: 			if (defined($token->[2]->{'name'})) { 
 8485: 			    $unikey.='_'.$token->[2]->{'name'}; 
 8486: 			}
 8487: 			$metathesekeys{$unikey}=1;
 8488: 			foreach my $param (@{$token->[3]}) {
 8489: 			    $metaentry{':'.$unikey.'.'.$param} =
 8490: 				$token->[2]->{$param};
 8491: 			}
 8492: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 8493: 			my $default=$metaentry{':'.$unikey.'.default'};
 8494: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 8495: 		 # only ws inside the tag, and not in default, so use default
 8496: 		 # as value
 8497: 			    $metaentry{':'.$unikey}=$default;
 8498: 			} elsif ( $internaltext =~ /\S/ ) {
 8499: 		  # something interesting inside the tag
 8500: 			    $metaentry{':'.$unikey}=$internaltext;
 8501: 			} else {
 8502: 		  # no interesting values, don't set a default
 8503: 			}
 8504: # end of not-a-package not-a-library import
 8505: 		    }
 8506: # end of not-a-package start tag
 8507: 		}
 8508: # the next is the end of "start tag"
 8509: 	    }
 8510: 	}
 8511: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 8512: 	$extension = lc($extension);
 8513: 	if ($extension eq 'htm') { $extension='html'; }
 8514: 
 8515: 	foreach my $key (keys(%packagetab)) {
 8516: 	    #no specific packages #how's our extension
 8517: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 8518: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 8519: 					 \%metathesekeys);
 8520: 	}
 8521: 
 8522: 	if (!exists($metaentry{':packages'})
 8523: 	    || $packagetab{"import_defaults&extension_$extension"}) {
 8524: 	    foreach my $key (keys(%packagetab)) {
 8525: 		#no specific packages well let's get default then
 8526: 		if ($key!~/^default&/) { next; }
 8527: 		&metadata_create_package_def($uri,$key,'default',
 8528: 					     \%metathesekeys);
 8529: 	    }
 8530: 	}
 8531: # are there custom rights to evaluate
 8532: 	if ($metaentry{':copyright'} eq 'custom') {
 8533: 
 8534:     #
 8535:     # Importing a rights file here
 8536:     #
 8537: 	    unless ($depthcount) {
 8538: 		my $location=$metaentry{':customdistributionfile'};
 8539: 		my $dir=$filename;
 8540: 		$dir=~s|[^/]*$||;
 8541: 		$location=&filelocation($dir,$location);
 8542: 		my $rights_metadata =
 8543: 		    &metadata($uri,'keys',$location,'_rights',
 8544: 			      $depthcount+1);
 8545: 		foreach my $rights (split(',',$rights_metadata)) {
 8546: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 8547: 		    $metathesekeys{$rights}=1;
 8548: 		}
 8549: 	    }
 8550: 	}
 8551: 	# uniqifiy package listing
 8552: 	my %seen;
 8553: 	my @uniq_packages =
 8554: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 8555: 	$metaentry{':packages'} = join(',',@uniq_packages);
 8556: 
 8557:         if ($importedparts) {
 8558: # We had imported parts and need to rebuild partorder
 8559:            $metaentry{':partorder'}='';
 8560:            $metathesekeys{'partorder'}=1;
 8561:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
 8562:                if ($origfileimportpartids[$index] eq 'part') {
 8563: # original part, part of the problem
 8564:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
 8565:                } else {
 8566: # we have imported parts at this position
 8567:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
 8568:                }
 8569:            }
 8570:            $metaentry{':partorder'}=~s/^\,//;
 8571:         }
 8572: 
 8573: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 8574: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 8575: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 8576: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
 8577: # this is the end of "was not already recently cached
 8578:     }
 8579:     return $metaentry{':'.$what};
 8580: }
 8581: 
 8582: sub metadata_create_package_def {
 8583:     my ($uri,$key,$package,$metathesekeys)=@_;
 8584:     my ($pack,$name,$subp)=split(/\&/,$key);
 8585:     if ($subp eq 'default') { next; }
 8586:     
 8587:     if (defined($metaentry{':packages'})) {
 8588: 	$metaentry{':packages'}.=','.$package;
 8589:     } else {
 8590: 	$metaentry{':packages'}=$package;
 8591:     }
 8592:     my $value=$packagetab{$key};
 8593:     my $unikey;
 8594:     $unikey='parameter_0_'.$name;
 8595:     $metaentry{':'.$unikey.'.part'}=0;
 8596:     $$metathesekeys{$unikey}=1;
 8597:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 8598: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 8599:     }
 8600:     if (defined($metaentry{':'.$unikey.'.default'})) {
 8601: 	$metaentry{':'.$unikey}=
 8602: 	    $metaentry{':'.$unikey.'.default'};
 8603:     }
 8604: }
 8605: 
 8606: sub metadata_generate_part0 {
 8607:     my ($metadata,$metacache,$uri) = @_;
 8608:     my %allnames;
 8609:     foreach my $metakey (keys(%$metadata)) {
 8610: 	if ($metakey=~/^parameter\_(.*)/) {
 8611: 	  my $part=$$metacache{':'.$metakey.'.part'};
 8612: 	  my $name=$$metacache{':'.$metakey.'.name'};
 8613: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 8614: 	    $allnames{$name}=$part;
 8615: 	  }
 8616: 	}
 8617:     }
 8618:     foreach my $name (keys(%allnames)) {
 8619:       $$metadata{"parameter_0_$name"}=1;
 8620:       my $key=":parameter_0_$name";
 8621:       $$metacache{"$key.part"}='0';
 8622:       $$metacache{"$key.name"}=$name;
 8623:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 8624: 					   $allnames{$name}.'_'.$name.
 8625: 					   '.type'};
 8626:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 8627: 			     '.display'};
 8628:       my $expr='[Part: '.$allnames{$name}.']';
 8629:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 8630:       $$metacache{"$key.display"}=$olddis;
 8631:     }
 8632: }
 8633: 
 8634: # ------------------------------------------------------ Devalidate title cache
 8635: 
 8636: sub devalidate_title_cache {
 8637:     my ($url)=@_;
 8638:     if (!$env{'request.course.id'}) { return; }
 8639:     my $symb=&symbread($url);
 8640:     if (!$symb) { return; }
 8641:     my $key=$env{'request.course.id'}."\0".$symb;
 8642:     &devalidate_cache_new('title',$key);
 8643: }
 8644: 
 8645: # ------------------------------------------------- Get the title of a course
 8646: 
 8647: sub current_course_title {
 8648:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
 8649: }
 8650: # ------------------------------------------------- Get the title of a resource
 8651: 
 8652: sub gettitle {
 8653:     my $urlsymb=shift;
 8654:     my $symb=&symbread($urlsymb);
 8655:     if ($symb) {
 8656: 	my $key=$env{'request.course.id'}."\0".$symb;
 8657: 	my ($result,$cached)=&is_cached_new('title',$key);
 8658: 	if (defined($cached)) { 
 8659: 	    return $result;
 8660: 	}
 8661: 	my ($map,$resid,$url)=&decode_symb($symb);
 8662: 	my $title='';
 8663: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
 8664: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
 8665: 	} else {
 8666: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8667: 		    &GDBM_READER(),0640)) {
 8668: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
 8669: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
 8670: 		untie(%bighash);
 8671: 	    }
 8672: 	}
 8673: 	$title=~s/\&colon\;/\:/gs;
 8674: 	if ($title) {
 8675: 	    return &do_cache_new('title',$key,$title,600);
 8676: 	}
 8677: 	$urlsymb=$url;
 8678:     }
 8679:     my $title=&metadata($urlsymb,'title');
 8680:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 8681:     return $title;
 8682: }
 8683: 
 8684: sub get_slot {
 8685:     my ($which,$cnum,$cdom)=@_;
 8686:     if (!$cnum || !$cdom) {
 8687: 	(undef,my $courseid)=&whichuser();
 8688: 	$cdom=$env{'course.'.$courseid.'.domain'};
 8689: 	$cnum=$env{'course.'.$courseid.'.num'};
 8690:     }
 8691:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 8692:     my %slotinfo;
 8693:     if (exists($remembered{$key})) {
 8694: 	$slotinfo{$which} = $remembered{$key};
 8695:     } else {
 8696: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 8697: 	&Apache::lonhomework::showhash(%slotinfo);
 8698: 	my ($tmp)=keys(%slotinfo);
 8699: 	if ($tmp=~/^error:/) { return (); }
 8700: 	$remembered{$key} = $slotinfo{$which};
 8701:     }
 8702:     if (ref($slotinfo{$which}) eq 'HASH') {
 8703: 	return %{$slotinfo{$which}};
 8704:     }
 8705:     return $slotinfo{$which};
 8706: }
 8707: # ------------------------------------------------- Update symbolic store links
 8708: 
 8709: sub symblist {
 8710:     my ($mapname,%newhash)=@_;
 8711:     $mapname=&deversion(&declutter($mapname));
 8712:     my %hash;
 8713:     if (($env{'request.course.fn'}) && (%newhash)) {
 8714:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 8715:                       &GDBM_WRCREAT(),0640)) {
 8716: 	    foreach my $url (keys(%newhash)) {
 8717: 		next if ($url eq 'last_known'
 8718: 			 && $env{'form.no_update_last_known'});
 8719: 		$hash{declutter($url)}=&encode_symb($mapname,
 8720: 						    $newhash{$url}->[1],
 8721: 						    $newhash{$url}->[0]);
 8722:             }
 8723:             if (untie(%hash)) {
 8724: 		return 'ok';
 8725:             }
 8726:         }
 8727:     }
 8728:     return 'error';
 8729: }
 8730: 
 8731: # --------------------------------------------------------------- Verify a symb
 8732: 
 8733: sub symbverify {
 8734:     my ($symb,$thisurl)=@_;
 8735:     my $thisfn=$thisurl;
 8736:     $thisfn=&declutter($thisfn);
 8737: # direct jump to resource in page or to a sequence - will construct own symbs
 8738:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 8739: # check URL part
 8740:     my ($map,$resid,$url)=&decode_symb($symb);
 8741: 
 8742:     unless ($url eq $thisfn) { return 0; }
 8743: 
 8744:     $symb=&symbclean($symb);
 8745:     $thisurl=&deversion($thisurl);
 8746:     $thisfn=&deversion($thisfn);
 8747: 
 8748:     my %bighash;
 8749:     my $okay=0;
 8750: 
 8751:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8752:                             &GDBM_READER(),0640)) {
 8753:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
 8754:             $thisurl =~ s/\?.+$//;
 8755:         }
 8756:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 8757:         unless ($ids) { 
 8758:            $ids=$bighash{'ids_/'.$thisurl};
 8759:         }
 8760:         if ($ids) {
 8761: # ------------------------------------------------------------------- Has ID(s)
 8762: 	    foreach my $id (split(/\,/,$ids)) {
 8763: 	       my ($mapid,$resid)=split(/\./,$id);
 8764:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
 8765:                    $symb =~ s/\?.+$//;
 8766:                }
 8767:                if (
 8768:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 8769:    eq $symb) { 
 8770: 		   if (($env{'request.role.adv'}) ||
 8771: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
 8772: 		       $okay=1; 
 8773: 		   }
 8774: 	       }
 8775: 	   }
 8776:         }
 8777: 	untie(%bighash);
 8778:     }
 8779:     return $okay;
 8780: }
 8781: 
 8782: # --------------------------------------------------------------- Clean-up symb
 8783: 
 8784: sub symbclean {
 8785:     my $symb=shift;
 8786:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 8787: # remove version from map
 8788:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 8789: 
 8790: # remove version from URL
 8791:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 8792: 
 8793: # remove wrapper
 8794: 
 8795:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 8796:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 8797:     return $symb;
 8798: }
 8799: 
 8800: # ---------------------------------------------- Split symb to find map and url
 8801: 
 8802: sub encode_symb {
 8803:     my ($map,$resid,$url)=@_;
 8804:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 8805: }
 8806: 
 8807: sub decode_symb {
 8808:     my $symb=shift;
 8809:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 8810:     my ($map,$resid,$url)=split(/___/,$symb);
 8811:     return (&fixversion($map),$resid,&fixversion($url));
 8812: }
 8813: 
 8814: sub fixversion {
 8815:     my $fn=shift;
 8816:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 8817:     my %bighash;
 8818:     my $uri=&clutter($fn);
 8819:     my $key=$env{'request.course.id'}.'_'.$uri;
 8820: # is this cached?
 8821:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 8822:     if (defined($cached)) { return $result; }
 8823: # unfortunately not cached, or expired
 8824:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8825: 	    &GDBM_READER(),0640)) {
 8826:  	if ($bighash{'version_'.$uri}) {
 8827:  	    my $version=$bighash{'version_'.$uri};
 8828:  	    unless (($version eq 'mostrecent') || 
 8829: 		    ($version==&getversion($uri))) {
 8830:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 8831:  	    }
 8832:  	}
 8833:  	untie %bighash;
 8834:     }
 8835:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 8836: }
 8837: 
 8838: sub deversion {
 8839:     my $url=shift;
 8840:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 8841:     return $url;
 8842: }
 8843: 
 8844: # ------------------------------------------------------ Return symb list entry
 8845: 
 8846: sub symbread {
 8847:     my ($thisfn,$donotrecurse)=@_;
 8848:     my $cache_str='request.symbread.cached.'.$thisfn;
 8849:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 8850: # no filename provided? try from environment
 8851:     unless ($thisfn) {
 8852:         if ($env{'request.symb'}) {
 8853: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 8854: 	}
 8855: 	$thisfn=$env{'request.filename'};
 8856:     }
 8857:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 8858: # is that filename actually a symb? Verify, clean, and return
 8859:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 8860: 	if (&symbverify($thisfn,$1)) {
 8861: 	    return $env{$cache_str}=&symbclean($thisfn);
 8862: 	}
 8863:     }
 8864:     $thisfn=declutter($thisfn);
 8865:     my %hash;
 8866:     my %bighash;
 8867:     my $syval='';
 8868:     if (($env{'request.course.fn'}) && ($thisfn)) {
 8869:         my $targetfn = $thisfn;
 8870:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 8871:             $targetfn = 'adm/wrapper/'.$thisfn;
 8872:         }
 8873: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 8874: 	    $targetfn=$1;
 8875: 	}
 8876:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 8877:                       &GDBM_READER(),0640)) {
 8878: 	    $syval=$hash{$targetfn};
 8879:             untie(%hash);
 8880:         }
 8881: # ---------------------------------------------------------- There was an entry
 8882:         if ($syval) {
 8883: 	    #unless ($syval=~/\_\d+$/) {
 8884: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 8885: 		    #&appenv({'request.ambiguous' => $thisfn});
 8886: 		    #return $env{$cache_str}='';
 8887: 		#}    
 8888: 		#$syval.=$1;
 8889: 	    #}
 8890:         } else {
 8891: # ------------------------------------------------------- Was not in symb table
 8892:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8893:                             &GDBM_READER(),0640)) {
 8894: # ---------------------------------------------- Get ID(s) for current resource
 8895:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 8896:               unless ($ids) { 
 8897:                  $ids=$bighash{'ids_/'.$thisfn};
 8898:               }
 8899:               unless ($ids) {
 8900: # alias?
 8901: 		  $ids=$bighash{'mapalias_'.$thisfn};
 8902:               }
 8903:               if ($ids) {
 8904: # ------------------------------------------------------------------- Has ID(s)
 8905:                  my @possibilities=split(/\,/,$ids);
 8906:                  if ($#possibilities==0) {
 8907: # ----------------------------------------------- There is only one possibility
 8908: 		     my ($mapid,$resid)=split(/\./,$ids);
 8909: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 8910: 						    $resid,$thisfn);
 8911:                  } elsif (!$donotrecurse) {
 8912: # ------------------------------------------ There is more than one possibility
 8913:                      my $realpossible=0;
 8914:                      foreach my $id (@possibilities) {
 8915: 			 my $file=$bighash{'src_'.$id};
 8916:                          if (&allowed('bre',$file)) {
 8917:          		    my ($mapid,$resid)=split(/\./,$id);
 8918:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 8919: 				$realpossible++;
 8920:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 8921: 						    $resid,$thisfn);
 8922:                             }
 8923: 			 }
 8924:                      }
 8925: 		     if ($realpossible!=1) { $syval=''; }
 8926:                  } else {
 8927:                      $syval='';
 8928:                  }
 8929: 	      }
 8930:               untie(%bighash)
 8931:            }
 8932:         }
 8933:         if ($syval) {
 8934: 	    return $env{$cache_str}=$syval;
 8935:         }
 8936:     }
 8937:     &appenv({'request.ambiguous' => $thisfn});
 8938:     return $env{$cache_str}='';
 8939: }
 8940: 
 8941: # ---------------------------------------------------------- Return random seed
 8942: 
 8943: sub numval {
 8944:     my $txt=shift;
 8945:     $txt=~tr/A-J/0-9/;
 8946:     $txt=~tr/a-j/0-9/;
 8947:     $txt=~tr/K-T/0-9/;
 8948:     $txt=~tr/k-t/0-9/;
 8949:     $txt=~tr/U-Z/0-5/;
 8950:     $txt=~tr/u-z/0-5/;
 8951:     $txt=~s/\D//g;
 8952:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 8953:     return int($txt);
 8954: }
 8955: 
 8956: sub numval2 {
 8957:     my $txt=shift;
 8958:     $txt=~tr/A-J/0-9/;
 8959:     $txt=~tr/a-j/0-9/;
 8960:     $txt=~tr/K-T/0-9/;
 8961:     $txt=~tr/k-t/0-9/;
 8962:     $txt=~tr/U-Z/0-5/;
 8963:     $txt=~tr/u-z/0-5/;
 8964:     $txt=~s/\D//g;
 8965:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 8966:     my $total;
 8967:     foreach my $val (@txts) { $total+=$val; }
 8968:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 8969:     return int($total);
 8970: }
 8971: 
 8972: sub numval3 {
 8973:     use integer;
 8974:     my $txt=shift;
 8975:     $txt=~tr/A-J/0-9/;
 8976:     $txt=~tr/a-j/0-9/;
 8977:     $txt=~tr/K-T/0-9/;
 8978:     $txt=~tr/k-t/0-9/;
 8979:     $txt=~tr/U-Z/0-5/;
 8980:     $txt=~tr/u-z/0-5/;
 8981:     $txt=~s/\D//g;
 8982:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 8983:     my $total;
 8984:     foreach my $val (@txts) { $total+=$val; }
 8985:     if ($_64bit) { $total=(($total<<32)>>32); }
 8986:     return $total;
 8987: }
 8988: 
 8989: sub digest {
 8990:     my ($data)=@_;
 8991:     my $digest=&Digest::MD5::md5($data);
 8992:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 8993:     my ($e,$f);
 8994:     {
 8995:         use integer;
 8996:         $e=($a+$b);
 8997:         $f=($c+$d);
 8998:         if ($_64bit) {
 8999:             $e=(($e<<32)>>32);
 9000:             $f=(($f<<32)>>32);
 9001:         }
 9002:     }
 9003:     if (wantarray) {
 9004: 	return ($e,$f);
 9005:     } else {
 9006: 	my $g;
 9007: 	{
 9008: 	    use integer;
 9009: 	    $g=($e+$f);
 9010: 	    if ($_64bit) {
 9011: 		$g=(($g<<32)>>32);
 9012: 	    }
 9013: 	}
 9014: 	return $g;
 9015:     }
 9016: }
 9017: 
 9018: sub latest_rnd_algorithm_id {
 9019:     return '64bit5';
 9020: }
 9021: 
 9022: sub get_rand_alg {
 9023:     my ($courseid)=@_;
 9024:     if (!$courseid) { $courseid=(&whichuser())[1]; }
 9025:     if ($courseid) {
 9026: 	return $env{"course.$courseid.rndseed"};
 9027:     }
 9028:     return &latest_rnd_algorithm_id();
 9029: }
 9030: 
 9031: sub validCODE {
 9032:     my ($CODE)=@_;
 9033:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 9034:     return 0;
 9035: }
 9036: 
 9037: sub getCODE {
 9038:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 9039:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 9040: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 9041: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 9042: 	return $Apache::lonhomework::history{'resource.CODE'};
 9043:     }
 9044:     return undef;
 9045: }
 9046: 
 9047: sub rndseed {
 9048:     my ($symb,$courseid,$domain,$username)=@_;
 9049:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
 9050:     if (!defined($symb)) {
 9051: 	unless ($symb=$wsymb) { return time; }
 9052:     }
 9053:     if (!$courseid) { $courseid=$wcourseid; }
 9054:     if (!$domain) { $domain=$wdomain; }
 9055:     if (!$username) { $username=$wusername }
 9056:     my $which=&get_rand_alg();
 9057: 
 9058:     if (defined(&getCODE())) {
 9059: 	if ($which eq '64bit5') {
 9060: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 9061: 	} elsif ($which eq '64bit4') {
 9062: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 9063: 	} else {
 9064: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 9065: 	}
 9066:     } elsif ($which eq '64bit5') {
 9067: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 9068:     } elsif ($which eq '64bit4') {
 9069: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 9070:     } elsif ($which eq '64bit3') {
 9071: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 9072:     } elsif ($which eq '64bit2') {
 9073: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 9074:     } elsif ($which eq '64bit') {
 9075: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 9076:     }
 9077:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 9078: }
 9079: 
 9080: sub rndseed_32bit {
 9081:     my ($symb,$courseid,$domain,$username)=@_;
 9082:     {
 9083: 	use integer;
 9084: 	my $symbchck=unpack("%32C*",$symb) << 27;
 9085: 	my $symbseed=numval($symb) << 22;
 9086: 	my $namechck=unpack("%32C*",$username) << 17;
 9087: 	my $nameseed=numval($username) << 12;
 9088: 	my $domainseed=unpack("%32C*",$domain) << 7;
 9089: 	my $courseseed=unpack("%32C*",$courseid);
 9090: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 9091: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 9092: 	#&logthis("rndseed :$num:$symb");
 9093: 	if ($_64bit) { $num=(($num<<32)>>32); }
 9094: 	return $num;
 9095:     }
 9096: }
 9097: 
 9098: sub rndseed_64bit {
 9099:     my ($symb,$courseid,$domain,$username)=@_;
 9100:     {
 9101: 	use integer;
 9102: 	my $symbchck=unpack("%32S*",$symb) << 21;
 9103: 	my $symbseed=numval($symb) << 10;
 9104: 	my $namechck=unpack("%32S*",$username);
 9105: 	
 9106: 	my $nameseed=numval($username) << 21;
 9107: 	my $domainseed=unpack("%32S*",$domain) << 10;
 9108: 	my $courseseed=unpack("%32S*",$courseid);
 9109: 	
 9110: 	my $num1=$symbchck+$symbseed+$namechck;
 9111: 	my $num2=$nameseed+$domainseed+$courseseed;
 9112: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 9113: 	#&logthis("rndseed :$num:$symb");
 9114: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 9115: 	return "$num1,$num2";
 9116:     }
 9117: }
 9118: 
 9119: sub rndseed_64bit2 {
 9120:     my ($symb,$courseid,$domain,$username)=@_;
 9121:     {
 9122: 	use integer;
 9123: 	# strings need to be an even # of cahracters long, it it is odd the
 9124:         # last characters gets thrown away
 9125: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 9126: 	my $symbseed=numval($symb) << 10;
 9127: 	my $namechck=unpack("%32S*",$username.' ');
 9128: 	
 9129: 	my $nameseed=numval($username) << 21;
 9130: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 9131: 	my $courseseed=unpack("%32S*",$courseid.' ');
 9132: 	
 9133: 	my $num1=$symbchck+$symbseed+$namechck;
 9134: 	my $num2=$nameseed+$domainseed+$courseseed;
 9135: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 9136: 	#&logthis("rndseed :$num:$symb");
 9137: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 9138: 	return "$num1,$num2";
 9139:     }
 9140: }
 9141: 
 9142: sub rndseed_64bit3 {
 9143:     my ($symb,$courseid,$domain,$username)=@_;
 9144:     {
 9145: 	use integer;
 9146: 	# strings need to be an even # of cahracters long, it it is odd the
 9147:         # last characters gets thrown away
 9148: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 9149: 	my $symbseed=numval2($symb) << 10;
 9150: 	my $namechck=unpack("%32S*",$username.' ');
 9151: 	
 9152: 	my $nameseed=numval2($username) << 21;
 9153: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 9154: 	my $courseseed=unpack("%32S*",$courseid.' ');
 9155: 	
 9156: 	my $num1=$symbchck+$symbseed+$namechck;
 9157: 	my $num2=$nameseed+$domainseed+$courseseed;
 9158: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 9159: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 9160: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 9161: 	
 9162: 	return "$num1:$num2";
 9163:     }
 9164: }
 9165: 
 9166: sub rndseed_64bit4 {
 9167:     my ($symb,$courseid,$domain,$username)=@_;
 9168:     {
 9169: 	use integer;
 9170: 	# strings need to be an even # of cahracters long, it it is odd the
 9171:         # last characters gets thrown away
 9172: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 9173: 	my $symbseed=numval3($symb) << 10;
 9174: 	my $namechck=unpack("%32S*",$username.' ');
 9175: 	
 9176: 	my $nameseed=numval3($username) << 21;
 9177: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 9178: 	my $courseseed=unpack("%32S*",$courseid.' ');
 9179: 	
 9180: 	my $num1=$symbchck+$symbseed+$namechck;
 9181: 	my $num2=$nameseed+$domainseed+$courseseed;
 9182: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 9183: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 9184: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 9185: 	
 9186: 	return "$num1:$num2";
 9187:     }
 9188: }
 9189: 
 9190: sub rndseed_64bit5 {
 9191:     my ($symb,$courseid,$domain,$username)=@_;
 9192:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 9193:     return "$num1:$num2";
 9194: }
 9195: 
 9196: sub rndseed_CODE_64bit {
 9197:     my ($symb,$courseid,$domain,$username)=@_;
 9198:     {
 9199: 	use integer;
 9200: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 9201: 	my $symbseed=numval2($symb);
 9202: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 9203: 	my $CODEseed=numval(&getCODE());
 9204: 	my $courseseed=unpack("%32S*",$courseid.' ');
 9205: 	my $num1=$symbseed+$CODEchck;
 9206: 	my $num2=$CODEseed+$courseseed+$symbchck;
 9207: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 9208: 	#&logthis("rndseed :$num1:$num2:$symb");
 9209: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 9210: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 9211: 	return "$num1:$num2";
 9212:     }
 9213: }
 9214: 
 9215: sub rndseed_CODE_64bit4 {
 9216:     my ($symb,$courseid,$domain,$username)=@_;
 9217:     {
 9218: 	use integer;
 9219: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 9220: 	my $symbseed=numval3($symb);
 9221: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 9222: 	my $CODEseed=numval3(&getCODE());
 9223: 	my $courseseed=unpack("%32S*",$courseid.' ');
 9224: 	my $num1=$symbseed+$CODEchck;
 9225: 	my $num2=$CODEseed+$courseseed+$symbchck;
 9226: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 9227: 	#&logthis("rndseed :$num1:$num2:$symb");
 9228: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 9229: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 9230: 	return "$num1:$num2";
 9231:     }
 9232: }
 9233: 
 9234: sub rndseed_CODE_64bit5 {
 9235:     my ($symb,$courseid,$domain,$username)=@_;
 9236:     my $code = &getCODE();
 9237:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 9238:     return "$num1:$num2";
 9239: }
 9240: 
 9241: sub setup_random_from_rndseed {
 9242:     my ($rndseed)=@_;
 9243:     if ($rndseed =~/([,:])/) {
 9244: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 9245: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 9246:     } else {
 9247: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 9248:     }
 9249: }
 9250: 
 9251: sub latest_receipt_algorithm_id {
 9252:     return 'receipt3';
 9253: }
 9254: 
 9255: sub recunique {
 9256:     my $fucourseid=shift;
 9257:     my $unique;
 9258:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 9259: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 9260: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 9261:     } else {
 9262: 	$unique=$perlvar{'lonReceipt'};
 9263:     }
 9264:     return unpack("%32C*",$unique);
 9265: }
 9266: 
 9267: sub recprefix {
 9268:     my $fucourseid=shift;
 9269:     my $prefix;
 9270:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
 9271: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 9272: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 9273:     } else {
 9274: 	$prefix=$perlvar{'lonHostID'};
 9275:     }
 9276:     return unpack("%32C*",$prefix);
 9277: }
 9278: 
 9279: sub ireceipt {
 9280:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 9281: 
 9282:     my $return =&recprefix($fucourseid).'-';
 9283: 
 9284:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
 9285: 	$env{'request.state'} eq 'construct') {
 9286: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
 9287: 	return $return;
 9288:     }
 9289: 
 9290:     my $cuname=unpack("%32C*",$funame);
 9291:     my $cudom=unpack("%32C*",$fudom);
 9292:     my $cucourseid=unpack("%32C*",$fucourseid);
 9293:     my $cusymb=unpack("%32C*",$fusymb);
 9294:     my $cunique=&recunique($fucourseid);
 9295:     my $cpart=unpack("%32S*",$part);
 9296:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 9297: 
 9298: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
 9299: 			       
 9300: 	$return.= ($cunique%$cuname+
 9301: 		   $cunique%$cudom+
 9302: 		   $cusymb%$cuname+
 9303: 		   $cusymb%$cudom+
 9304: 		   $cucourseid%$cuname+
 9305: 		   $cucourseid%$cudom+
 9306: 		   $cpart%$cuname+
 9307: 		   $cpart%$cudom);
 9308:     } else {
 9309: 	$return.= ($cunique%$cuname+
 9310: 		   $cunique%$cudom+
 9311: 		   $cusymb%$cuname+
 9312: 		   $cusymb%$cudom+
 9313: 		   $cucourseid%$cuname+
 9314: 		   $cucourseid%$cudom);
 9315:     }
 9316:     return $return;
 9317: }
 9318: 
 9319: sub receipt {
 9320:     my ($part)=@_;
 9321:     my ($symb,$courseid,$domain,$name) = &whichuser();
 9322:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 9323: }
 9324: 
 9325: sub whichuser {
 9326:     my ($passedsymb)=@_;
 9327:     my ($symb,$courseid,$domain,$name,$publicuser);
 9328:     if (defined($env{'form.grade_symb'})) {
 9329: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
 9330: 	my $allowed=&allowed('vgr',$tmp_courseid);
 9331: 	if (!$allowed &&
 9332: 	    exists($env{'request.course.sec'}) &&
 9333: 	    $env{'request.course.sec'} !~ /^\s*$/) {
 9334: 	    $allowed=&allowed('vgr',$tmp_courseid.
 9335: 			      '/'.$env{'request.course.sec'});
 9336: 	}
 9337: 	if ($allowed) {
 9338: 	    ($symb)=&get_env_multiple('form.grade_symb');
 9339: 	    $courseid=$tmp_courseid;
 9340: 	    ($domain)=&get_env_multiple('form.grade_domain');
 9341: 	    ($name)=&get_env_multiple('form.grade_username');
 9342: 	    return ($symb,$courseid,$domain,$name,$publicuser);
 9343: 	}
 9344:     }
 9345:     if (!$passedsymb) {
 9346: 	$symb=&symbread();
 9347:     } else {
 9348: 	$symb=$passedsymb;
 9349:     }
 9350:     $courseid=$env{'request.course.id'};
 9351:     $domain=$env{'user.domain'};
 9352:     $name=$env{'user.name'};
 9353:     if ($name eq 'public' && $domain eq 'public') {
 9354: 	if (!defined($env{'form.username'})) {
 9355: 	    $env{'form.username'}.=time.rand(10000000);
 9356: 	}
 9357: 	$name.=$env{'form.username'};
 9358:     }
 9359:     return ($symb,$courseid,$domain,$name,$publicuser);
 9360: 
 9361: }
 9362: 
 9363: # ------------------------------------------------------------ Serves up a file
 9364: # returns either the contents of the file or 
 9365: # -1 if the file doesn't exist
 9366: #
 9367: # if the target is a file that was uploaded via DOCS, 
 9368: # a check will be made to see if a current copy exists on the local server,
 9369: # if it does this will be served, otherwise a copy will be retrieved from
 9370: # the home server for the course and stored in /home/httpd/html/userfiles on
 9371: # the local server.   
 9372: 
 9373: sub getfile {
 9374:     my ($file) = @_;
 9375:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 9376:     &repcopy($file);
 9377:     return &readfile($file);
 9378: }
 9379: 
 9380: sub repcopy_userfile {
 9381:     my ($file)=@_;
 9382:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 9383:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 9384:     my ($cdom,$cnum,$filename) = 
 9385: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
 9386:     my $uri="/uploaded/$cdom/$cnum/$filename";
 9387:     if (-e "$file") {
 9388: # we already have a local copy, check it out
 9389: 	my @fileinfo = stat($file);
 9390: 	my $rtncode;
 9391: 	my $info;
 9392: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 9393: 	if ($lwpresp ne 'ok') {
 9394: # there is no such file anymore, even though we had a local copy
 9395: 	    if ($rtncode eq '404') {
 9396: 		unlink($file);
 9397: 	    }
 9398: 	    return -1;
 9399: 	}
 9400: 	if ($info < $fileinfo[9]) {
 9401: # nice, the file we have is up-to-date, just say okay
 9402: 	    return 'ok';
 9403: 	} else {
 9404: # the file is outdated, get rid of it
 9405: 	    unlink($file);
 9406: 	}
 9407:     }
 9408: # one way or the other, at this point, we don't have the file
 9409: # construct the correct path for the file
 9410:     my @parts = ($cdom,$cnum); 
 9411:     if ($filename =~ m|^(.+)/[^/]+$|) {
 9412: 	push @parts, split(/\//,$1);
 9413:     }
 9414:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 9415:     foreach my $part (@parts) {
 9416: 	$path .= '/'.$part;
 9417: 	if (!-e $path) {
 9418: 	    mkdir($path,0770);
 9419: 	}
 9420:     }
 9421: # now the path exists for sure
 9422: # get a user agent
 9423:     my $ua=new LWP::UserAgent;
 9424:     my $transferfile=$file.'.in.transfer';
 9425: # FIXME: this should flock
 9426:     if (-e $transferfile) { return 'ok'; }
 9427:     my $request;
 9428:     $uri=~s/^\///;
 9429:     my $homeserver = &homeserver($cnum,$cdom);
 9430:     my $protocol = $protocol{$homeserver};
 9431:     $protocol = 'http' if ($protocol ne 'https');
 9432:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
 9433:     my $response=$ua->request($request,$transferfile);
 9434: # did it work?
 9435:     if ($response->is_error()) {
 9436: 	unlink($transferfile);
 9437: 	&logthis("Userfile repcopy failed for $uri");
 9438: 	return -1;
 9439:     }
 9440: # worked, rename the transfer file
 9441:     rename($transferfile,$file);
 9442:     return 'ok';
 9443: }
 9444: 
 9445: sub tokenwrapper {
 9446:     my $uri=shift;
 9447:     $uri=~s|^https?\://([^/]+)||;
 9448:     $uri=~s|^/||;
 9449:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
 9450:     my $token=$1;
 9451:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 9452:     if ($udom && $uname && $file) {
 9453: 	$file=~s|(\?\.*)*$||;
 9454:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
 9455:         my $homeserver = &homeserver($uname,$udom);
 9456:         my $protocol = $protocol{$homeserver};
 9457:         $protocol = 'http' if ($protocol ne 'https');
 9458:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
 9459:                (($uri=~/\?/)?'&':'?').'token='.$token.
 9460:                                '&tokenissued='.$perlvar{'lonHostID'};
 9461:     } else {
 9462:         return '/adm/notfound.html';
 9463:     }
 9464: }
 9465: 
 9466: # call with reqtype HEAD: get last modification time
 9467: # call with reqtype GET: get the file contents
 9468: # Do not call this with reqtype GET for large files! It loads everything into memory
 9469: #
 9470: sub getuploaded {
 9471:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 9472:     $uri=~s/^\///;
 9473:     my $homeserver = &homeserver($cnum,$cdom);
 9474:     my $protocol = $protocol{$homeserver};
 9475:     $protocol = 'http' if ($protocol ne 'https');
 9476:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
 9477:     my $ua=new LWP::UserAgent;
 9478:     my $request=new HTTP::Request($reqtype,$uri);
 9479:     my $response=$ua->request($request);
 9480:     $$rtncode = $response->code;
 9481:     if (! $response->is_success()) {
 9482: 	return 'failed';
 9483:     }      
 9484:     if ($reqtype eq 'HEAD') {
 9485: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 9486:     } elsif ($reqtype eq 'GET') {
 9487: 	$$info = $response->content;
 9488:     }
 9489:     return 'ok';
 9490: }
 9491: 
 9492: sub readfile {
 9493:     my $file = shift;
 9494:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 9495:     my $fh;
 9496:     open($fh,"<$file");
 9497:     my $a='';
 9498:     while (my $line = <$fh>) { $a .= $line; }
 9499:     return $a;
 9500: }
 9501: 
 9502: sub filelocation {
 9503:     my ($dir,$file) = @_;
 9504:     my $location;
 9505:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 9506: 
 9507:     if ($file =~ m-^/adm/-) {
 9508: 	$file=~s-^/adm/wrapper/-/-;
 9509: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 9510:     }
 9511: 
 9512:     if ($file=~m:^/~:) { # is a contruction space reference
 9513:         $location = $file;
 9514:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 9515:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
 9516: 	# is a correct contruction space reference
 9517:         $location = $file;
 9518:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
 9519:         $location = $file;
 9520:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
 9521:         my ($udom,$uname,$filename)=
 9522:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
 9523:         my $home=&homeserver($uname,$udom);
 9524:         my $is_me=0;
 9525:         my @ids=&current_machine_ids();
 9526:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 9527:         if ($is_me) {
 9528:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
 9529:         } else {
 9530:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 9531:   	      $udom.'/'.$uname.'/'.$filename;
 9532:         }
 9533:     } elsif ($file =~ m-^/adm/-) {
 9534: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
 9535:     } else {
 9536:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 9537:         $file=~s:^/res/:/:;
 9538:         if ( !( $file =~ m:^/:) ) {
 9539:             $location = $dir. '/'.$file;
 9540:         } else {
 9541:             $location = '/home/httpd/html/res'.$file;
 9542:         }
 9543:     }
 9544:     $location=~s://+:/:g; # remove duplicate /
 9545:     while ($location=~m{/\.\./}) {
 9546: 	if ($location =~ m{/[^/]+/\.\./}) {
 9547: 	    $location=~ s{/[^/]+/\.\./}{/}g;
 9548: 	} else {
 9549: 	    $location=~ s{/\.\./}{/}g;
 9550: 	}
 9551:     } #remove dir/..
 9552:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 9553:     return $location;
 9554: }
 9555: 
 9556: sub hreflocation {
 9557:     my ($dir,$file)=@_;
 9558:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
 9559: 	$file=filelocation($dir,$file);
 9560:     } elsif ($file=~m-^/adm/-) {
 9561: 	$file=~s-^/adm/wrapper/-/-;
 9562: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 9563:     }
 9564:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
 9565: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
 9566:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
 9567: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
 9568:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
 9569: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
 9570: 	    -/uploaded/$1/$2/-x;
 9571:     }
 9572:     if ($file=~ m{^/userfiles/}) {
 9573: 	$file =~ s{^/userfiles/}{/uploaded/};
 9574:     }
 9575:     return $file;
 9576: }
 9577: 
 9578: sub current_machine_domains {
 9579:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
 9580: }
 9581: 
 9582: sub machine_domains {
 9583:     my ($hostname) = @_;
 9584:     my @domains;
 9585:     my %hostname = &all_hostnames();
 9586:     while( my($id, $name) = each(%hostname)) {
 9587: #	&logthis("-$id-$name-$hostname-");
 9588: 	if ($hostname eq $name) {
 9589: 	    push(@domains,&host_domain($id));
 9590: 	}
 9591:     }
 9592:     return @domains;
 9593: }
 9594: 
 9595: sub current_machine_ids {
 9596:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
 9597: }
 9598: 
 9599: sub machine_ids {
 9600:     my ($hostname) = @_;
 9601:     $hostname ||= &hostname($perlvar{'lonHostID'});
 9602:     my @ids;
 9603:     my %name_to_host = &all_names();
 9604:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
 9605: 	return @{ $name_to_host{$hostname} };
 9606:     }
 9607:     return;
 9608: }
 9609: 
 9610: sub additional_machine_domains {
 9611:     my @domains;
 9612:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
 9613:     while( my $line = <$fh>) {
 9614:         $line =~ s/\s//g;
 9615:         push(@domains,$line);
 9616:     }
 9617:     return @domains;
 9618: }
 9619: 
 9620: sub default_login_domain {
 9621:     my $domain = $perlvar{'lonDefDomain'};
 9622:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
 9623:     foreach my $posdom (&current_machine_domains(),
 9624:                         &additional_machine_domains()) {
 9625:         if (lc($posdom) eq lc($testdomain)) {
 9626:             $domain=$posdom;
 9627:             last;
 9628:         }
 9629:     }
 9630:     return $domain;
 9631: }
 9632: 
 9633: # ------------------------------------------------------------- Declutters URLs
 9634: 
 9635: sub declutter {
 9636:     my $thisfn=shift;
 9637:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 9638:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 9639:     $thisfn=~s/^\///;
 9640:     $thisfn=~s|^adm/wrapper/||;
 9641:     $thisfn=~s|^adm/coursedocs/showdoc/||;
 9642:     $thisfn=~s/^res\///;
 9643:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
 9644:         $thisfn=~s/\?.+$//;
 9645:     }
 9646:     return $thisfn;
 9647: }
 9648: 
 9649: # ------------------------------------------------------------- Clutter up URLs
 9650: 
 9651: sub clutter {
 9652:     my $thisfn='/'.&declutter(shift);
 9653:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
 9654: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
 9655:        $thisfn='/res'.$thisfn; 
 9656:     }
 9657:     if ($thisfn !~m|^/adm|) {
 9658: 	if ($thisfn =~ m|^/ext/|) {
 9659: 	    $thisfn='/adm/wrapper'.$thisfn;
 9660: 	} else {
 9661: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
 9662: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
 9663: 	    if ($embstyle eq 'ssi'
 9664: 		|| ($embstyle eq 'hdn')
 9665: 		|| ($embstyle eq 'rat')
 9666: 		|| ($embstyle eq 'prv')
 9667: 		|| ($embstyle eq 'ign')) {
 9668: 		#do nothing with these
 9669: 	    } elsif (($embstyle eq 'img') 
 9670: 		|| ($embstyle eq 'emb')
 9671: 		|| ($embstyle eq 'wrp')) {
 9672: 		$thisfn='/adm/wrapper'.$thisfn;
 9673: 	    } elsif ($embstyle eq 'unk'
 9674: 		     && $thisfn!~/\.(sequence|page)$/) {
 9675: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
 9676: 	    } else {
 9677: #		&logthis("Got a blank emb style");
 9678: 	    }
 9679: 	}
 9680:     }
 9681:     return $thisfn;
 9682: }
 9683: 
 9684: sub clutter_with_no_wrapper {
 9685:     my $uri = &clutter(shift);
 9686:     if ($uri =~ m-^/adm/-) {
 9687: 	$uri =~ s-^/adm/wrapper/-/-;
 9688: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
 9689:     }
 9690:     return $uri;
 9691: }
 9692: 
 9693: sub freeze_escape {
 9694:     my ($value)=@_;
 9695:     if (ref($value)) {
 9696: 	$value=&nfreeze($value);
 9697: 	return '__FROZEN__'.&escape($value);
 9698:     }
 9699:     return &escape($value);
 9700: }
 9701: 
 9702: 
 9703: sub thaw_unescape {
 9704:     my ($value)=@_;
 9705:     if ($value =~ /^__FROZEN__/) {
 9706: 	substr($value,0,10,undef);
 9707: 	$value=&unescape($value);
 9708: 	return &thaw($value);
 9709:     }
 9710:     return &unescape($value);
 9711: }
 9712: 
 9713: sub correct_line_ends {
 9714:     my ($result)=@_;
 9715:     $$result =~s/\r\n/\n/mg;
 9716:     $$result =~s/\r/\n/mg;
 9717: }
 9718: # ================================================================ Main Program
 9719: 
 9720: sub goodbye {
 9721:    &logthis("Starting Shut down");
 9722: #not converted to using infrastruture and probably shouldn't be
 9723:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
 9724: #converted
 9725: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 9726:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
 9727: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
 9728: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
 9729: #1.1 only
 9730: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
 9731: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
 9732: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
 9733: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
 9734:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
 9735:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
 9736:    &logthis(sprintf("%-20s is %s",'hits',$hits));
 9737:    &flushcourselogs();
 9738:    &logthis("Shutting down");
 9739: }
 9740: 
 9741: sub get_dns {
 9742:     my ($url,$func,$ignore_cache) = @_;
 9743:     if (!$ignore_cache) {
 9744: 	my ($content,$cached)=
 9745: 	    &Apache::lonnet::is_cached_new('dns',$url);
 9746: 	if ($cached) {
 9747: 	    &$func($content);
 9748: 	    return;
 9749: 	}
 9750:     }
 9751: 
 9752:     my %alldns;
 9753:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 9754:     foreach my $dns (<$config>) {
 9755: 	next if ($dns !~ /^\^(\S*)/x);
 9756:         my $line = $1;
 9757:         my ($host,$protocol) = split(/:/,$line);
 9758:         if ($protocol ne 'https') {
 9759:             $protocol = 'http';
 9760:         }
 9761: 	$alldns{$host} = $protocol;
 9762:     }
 9763:     while (%alldns) {
 9764: 	my ($dns) = keys(%alldns);
 9765: 	my $ua=new LWP::UserAgent;
 9766: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
 9767: 	my $response=$ua->request($request);
 9768:         delete($alldns{$dns});
 9769: 	next if ($response->is_error());
 9770: 	my @content = split("\n",$response->content);
 9771: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
 9772: 	&$func(\@content);
 9773: 	return;
 9774:     }
 9775:     close($config);
 9776:     my $which = (split('/',$url))[3];
 9777:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
 9778:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
 9779:     my @content = <$config>;
 9780:     &$func(\@content);
 9781:     return;
 9782: }
 9783: # ------------------------------------------------------------ Read domain file
 9784: {
 9785:     my $loaded;
 9786:     my %domain;
 9787: 
 9788:     sub parse_domain_tab {
 9789: 	my ($lines) = @_;
 9790: 	foreach my $line (@$lines) {
 9791: 	    next if ($line =~ /^(\#|\s*$ )/x);
 9792: 
 9793: 	    chomp($line);
 9794: 	    my ($name,@elements) = split(/:/,$line,9);
 9795: 	    my %this_domain;
 9796: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
 9797: 			       'lang_def', 'city', 'longi', 'lati',
 9798: 			       'primary') {
 9799: 		$this_domain{$field} = shift(@elements);
 9800: 	    }
 9801: 	    $domain{$name} = \%this_domain;
 9802: 	}
 9803:     }
 9804: 
 9805:     sub reset_domain_info {
 9806: 	undef($loaded);
 9807: 	undef(%domain);
 9808:     }
 9809: 
 9810:     sub load_domain_tab {
 9811: 	my ($ignore_cache) = @_;
 9812: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
 9813: 	my $fh;
 9814: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
 9815: 	    my @lines = <$fh>;
 9816: 	    &parse_domain_tab(\@lines);
 9817: 	}
 9818: 	close($fh);
 9819: 	$loaded = 1;
 9820:     }
 9821: 
 9822:     sub domain {
 9823: 	&load_domain_tab() if (!$loaded);
 9824: 
 9825: 	my ($name,$what) = @_;
 9826: 	return if ( !exists($domain{$name}) );
 9827: 
 9828: 	if (!$what) {
 9829: 	    return $domain{$name}{'description'};
 9830: 	}
 9831: 	return $domain{$name}{$what};
 9832:     }
 9833: 
 9834:     sub domain_info {
 9835:         &load_domain_tab() if (!$loaded);
 9836:         return %domain;
 9837:     }
 9838: 
 9839: }
 9840: 
 9841: 
 9842: # ------------------------------------------------------------- Read hosts file
 9843: {
 9844:     my %hostname;
 9845:     my %hostdom;
 9846:     my %libserv;
 9847:     my $loaded;
 9848:     my %name_to_host;
 9849:     my %internetdom;
 9850: 
 9851:     sub parse_hosts_tab {
 9852: 	my ($file) = @_;
 9853: 	foreach my $configline (@$file) {
 9854: 	    next if ($configline =~ /^(\#|\s*$ )/x);
 9855: 	    next if ($configline =~ /^\^/);
 9856: 	    chomp($configline);
 9857: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
 9858: 	    $name=~s/\s//g;
 9859: 	    if ($id && $domain && $role && $name) {
 9860: 		$hostname{$id}=$name;
 9861: 		push(@{$name_to_host{$name}}, $id);
 9862: 		$hostdom{$id}=$domain;
 9863: 		if ($role eq 'library') { $libserv{$id}=$name; }
 9864:                 if (defined($protocol)) {
 9865:                     if ($protocol eq 'https') {
 9866:                         $protocol{$id} = $protocol;
 9867:                     } else {
 9868:                         $protocol{$id} = 'http'; 
 9869:                     }
 9870:                 } else {
 9871:                     $protocol{$id} = 'http';
 9872:                 }
 9873:                 if (defined($intdom)) {
 9874:                     $internetdom{$id} = $intdom;
 9875:                 }
 9876: 	    }
 9877: 	}
 9878:     }
 9879:     
 9880:     sub reset_hosts_info {
 9881: 	&purge_remembered();
 9882: 	&reset_domain_info();
 9883: 	&reset_hosts_ip_info();
 9884: 	undef(%name_to_host);
 9885: 	undef(%hostname);
 9886: 	undef(%hostdom);
 9887: 	undef(%libserv);
 9888: 	undef($loaded);
 9889:     }
 9890: 
 9891:     sub load_hosts_tab {
 9892: 	my ($ignore_cache) = @_;
 9893: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
 9894: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 9895: 	my @config = <$config>;
 9896: 	&parse_hosts_tab(\@config);
 9897: 	close($config);
 9898: 	$loaded=1;
 9899:     }
 9900: 
 9901:     sub hostname {
 9902: 	&load_hosts_tab() if (!$loaded);
 9903: 
 9904: 	my ($lonid) = @_;
 9905: 	return $hostname{$lonid};
 9906:     }
 9907: 
 9908:     sub all_hostnames {
 9909: 	&load_hosts_tab() if (!$loaded);
 9910: 
 9911: 	return %hostname;
 9912:     }
 9913: 
 9914:     sub all_names {
 9915: 	&load_hosts_tab() if (!$loaded);
 9916: 
 9917: 	return %name_to_host;
 9918:     }
 9919: 
 9920:     sub all_host_domain {
 9921:         &load_hosts_tab() if (!$loaded);
 9922:         return %hostdom;
 9923:     }
 9924: 
 9925:     sub is_library {
 9926: 	&load_hosts_tab() if (!$loaded);
 9927: 
 9928: 	return exists($libserv{$_[0]});
 9929:     }
 9930: 
 9931:     sub all_library {
 9932: 	&load_hosts_tab() if (!$loaded);
 9933: 
 9934: 	return %libserv;
 9935:     }
 9936: 
 9937:     sub unique_library {
 9938: 	#2x reverse removes all hostnames that appear more than once
 9939:         my %unique = reverse &all_library();
 9940:         return reverse %unique;
 9941:     }
 9942: 
 9943:     sub get_servers {
 9944: 	&load_hosts_tab() if (!$loaded);
 9945: 
 9946: 	my ($domain,$type) = @_;
 9947: 	my %possible_hosts = ($type eq 'library') ? %libserv
 9948: 	                                          : %hostname;
 9949: 	my %result;
 9950: 	if (ref($domain) eq 'ARRAY') {
 9951: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 9952: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
 9953: 		    $result{$host} = $hostname;
 9954: 		}
 9955: 	    }
 9956: 	} else {
 9957: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 9958: 		if ($hostdom{$host} eq $domain) {
 9959: 		    $result{$host} = $hostname;
 9960: 		}
 9961: 	    }
 9962: 	}
 9963: 	return %result;
 9964:     }
 9965: 
 9966:     sub get_unique_servers {
 9967:         my %unique = reverse &get_servers(@_);
 9968: 	return reverse %unique;
 9969:     }
 9970: 
 9971:     sub host_domain {
 9972: 	&load_hosts_tab() if (!$loaded);
 9973: 
 9974: 	my ($lonid) = @_;
 9975: 	return $hostdom{$lonid};
 9976:     }
 9977: 
 9978:     sub all_domains {
 9979: 	&load_hosts_tab() if (!$loaded);
 9980: 
 9981: 	my %seen;
 9982: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
 9983: 	return @uniq;
 9984:     }
 9985: 
 9986:     sub internet_dom {
 9987:         &load_hosts_tab() if (!$loaded);
 9988: 
 9989:         my ($lonid) = @_;
 9990:         return $internetdom{$lonid};
 9991:     }
 9992: }
 9993: 
 9994: { 
 9995:     my %iphost;
 9996:     my %name_to_ip;
 9997:     my %lonid_to_ip;
 9998: 
 9999:     sub get_hosts_from_ip {
10000: 	my ($ip) = @_;
10001: 	my %iphosts = &get_iphost();
10002: 	if (ref($iphosts{$ip})) {
10003: 	    return @{$iphosts{$ip}};
10004: 	}
10005: 	return;
10006:     }
10007:     
10008:     sub reset_hosts_ip_info {
10009: 	undef(%iphost);
10010: 	undef(%name_to_ip);
10011: 	undef(%lonid_to_ip);
10012:     }
10013: 
10014:     sub get_host_ip {
10015: 	my ($lonid) = @_;
10016: 	if (exists($lonid_to_ip{$lonid})) {
10017: 	    return $lonid_to_ip{$lonid};
10018: 	}
10019: 	my $name=&hostname($lonid);
10020:    	my $ip = gethostbyname($name);
10021: 	return if (!$ip || length($ip) ne 4);
10022: 	$ip=inet_ntoa($ip);
10023: 	$name_to_ip{$name}   = $ip;
10024: 	$lonid_to_ip{$lonid} = $ip;
10025: 	return $ip;
10026:     }
10027:     
10028:     sub get_iphost {
10029: 	my ($ignore_cache) = @_;
10030: 
10031: 	if (!$ignore_cache) {
10032: 	    if (%iphost) {
10033: 		return %iphost;
10034: 	    }
10035: 	    my ($ip_info,$cached)=
10036: 		&Apache::lonnet::is_cached_new('iphost','iphost');
10037: 	    if ($cached) {
10038: 		%iphost      = %{$ip_info->[0]};
10039: 		%name_to_ip  = %{$ip_info->[1]};
10040: 		%lonid_to_ip = %{$ip_info->[2]};
10041: 		return %iphost;
10042: 	    }
10043: 	}
10044: 
10045: 	# get yesterday's info for fallback
10046: 	my %old_name_to_ip;
10047: 	my ($ip_info,$cached)=
10048: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
10049: 	if ($cached) {
10050: 	    %old_name_to_ip = %{$ip_info->[1]};
10051: 	}
10052: 
10053: 	my %name_to_host = &all_names();
10054: 	foreach my $name (keys(%name_to_host)) {
10055: 	    my $ip;
10056: 	    if (!exists($name_to_ip{$name})) {
10057: 		$ip = gethostbyname($name);
10058: 		if (!$ip || length($ip) ne 4) {
10059: 		    if (defined($old_name_to_ip{$name})) {
10060: 			$ip = $old_name_to_ip{$name};
10061: 			&logthis("Can't find $name defaulting to old $ip");
10062: 		    } else {
10063: 			&logthis("Name $name no IP found");
10064: 			next;
10065: 		    }
10066: 		} else {
10067: 		    $ip=inet_ntoa($ip);
10068: 		}
10069: 		$name_to_ip{$name} = $ip;
10070: 	    } else {
10071: 		$ip = $name_to_ip{$name};
10072: 	    }
10073: 	    foreach my $id (@{ $name_to_host{$name} }) {
10074: 		$lonid_to_ip{$id} = $ip;
10075: 	    }
10076: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
10077: 	}
10078: 	&Apache::lonnet::do_cache_new('iphost','iphost',
10079: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
10080: 				      48*60*60);
10081: 
10082: 	return %iphost;
10083:     }
10084: 
10085:     #
10086:     #  Given a DNS returns the loncapa host name for that DNS 
10087:     # 
10088:     sub host_from_dns {
10089:         my ($dns) = @_;
10090:         my @hosts;
10091:         my $ip;
10092: 
10093:         if (exists($name_to_ip{$dns})) {
10094:             $ip = $name_to_ip{$dns};
10095:         }
10096:         if (!$ip) {
10097:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
10098:             if (length($ip) == 4) { 
10099: 	        $ip   = &IO::Socket::inet_ntoa($ip);
10100:             }
10101:         }
10102:         if ($ip) {
10103: 	    @hosts = get_hosts_from_ip($ip);
10104: 	    return $hosts[0];
10105:         }
10106:         return undef;
10107:     }
10108: 
10109:     sub get_internet_names {
10110:         my ($lonid) = @_;
10111:         return if ($lonid eq '');
10112:         my ($idnref,$cached)=
10113:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
10114:         if ($cached) {
10115:             return $idnref;
10116:         }
10117:         my $ip = &get_host_ip($lonid);
10118:         my @hosts = &get_hosts_from_ip($ip);
10119:         my %iphost = &get_iphost();
10120:         my (@idns,%seen);
10121:         foreach my $id (@hosts) {
10122:             my $dom = &host_domain($id);
10123:             my $prim_id = &domain($dom,'primary');
10124:             my $prim_ip = &get_host_ip($prim_id);
10125:             next if ($seen{$prim_ip});
10126:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
10127:                 foreach my $id (@{$iphost{$prim_ip}}) {
10128:                     my $intdom = &internet_dom($id);
10129:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
10130:                         push(@idns,$intdom);
10131:                     }
10132:                 }
10133:             }
10134:             $seen{$prim_ip} = 1;
10135:         }
10136:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
10137:     }
10138: 
10139: }
10140: 
10141: BEGIN {
10142: 
10143: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
10144:     unless ($readit) {
10145: {
10146:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
10147:     %perlvar = (%perlvar,%{$configvars});
10148: }
10149: 
10150: 
10151: # ------------------------------------------------------ Read spare server file
10152: {
10153:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
10154: 
10155:     while (my $configline=<$config>) {
10156:        chomp($configline);
10157:        if ($configline) {
10158: 	   my ($host,$type) = split(':',$configline,2);
10159: 	   if (!defined($type) || $type eq '') { $type = 'default' };
10160: 	   push(@{ $spareid{$type} }, $host);
10161:        }
10162:     }
10163:     close($config);
10164: }
10165: # ------------------------------------------------------------ Read permissions
10166: {
10167:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
10168: 
10169:     while (my $configline=<$config>) {
10170: 	chomp($configline);
10171: 	if ($configline) {
10172: 	    my ($role,$perm)=split(/ /,$configline);
10173: 	    if ($perm ne '') { $pr{$role}=$perm; }
10174: 	}
10175:     }
10176:     close($config);
10177: }
10178: 
10179: # -------------------------------------------- Read plain texts for permissions
10180: {
10181:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
10182: 
10183:     while (my $configline=<$config>) {
10184: 	chomp($configline);
10185: 	if ($configline) {
10186: 	    my ($short,@plain)=split(/:/,$configline);
10187:             %{$prp{$short}} = ();
10188: 	    if (@plain > 0) {
10189:                 $prp{$short}{'std'} = $plain[0];
10190:                 for (my $i=1; $i<@plain; $i++) {
10191:                     $prp{$short}{'alt'.$i} = $plain[$i];  
10192:                 }
10193:             }
10194: 	}
10195:     }
10196:     close($config);
10197: }
10198: 
10199: # ---------------------------------------------------------- Read package table
10200: {
10201:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
10202: 
10203:     while (my $configline=<$config>) {
10204: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
10205: 	chomp($configline);
10206: 	my ($short,$plain)=split(/:/,$configline);
10207: 	my ($pack,$name)=split(/\&/,$short);
10208: 	if ($plain ne '') {
10209: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
10210: 	    $packagetab{$short}=$plain; 
10211: 	}
10212:     }
10213:     close($config);
10214: }
10215: 
10216: # ---------------------------------------------------------- Read loncaparev table
10217: {
10218:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
10219:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
10220:             while (my $configline=<$config>) {
10221:                 chomp($configline);
10222:                 my ($hostid,$loncaparev)=split(/:/,$configline);
10223:                 $loncaparevs{$hostid}=$loncaparev;
10224:             }
10225:             close($config);
10226:         }
10227:     }
10228: }
10229: 
10230: # ---------------------------------------------------------- Read serverhostID table
10231: {
10232:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
10233:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
10234:             while (my $configline=<$config>) {
10235:                 chomp($configline);
10236:                 my ($name,$id)=split(/:/,$configline);
10237:                 $serverhomeIDs{$name}=$id;
10238:             }
10239:             close($config);
10240:         }
10241:     }
10242: }
10243: 
10244: sub all_loncaparevs {
10245:     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);
10246: }
10247: 
10248: # ------------- set up temporary directory
10249: {
10250:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
10251: 
10252: }
10253: 
10254: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
10255: 				'compress_threshold'=> 20_000,
10256:  			        });
10257: 
10258: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
10259: $dumpcount=0;
10260: $locknum=0;
10261: 
10262: &logtouch();
10263: &logthis('<font color="yellow">INFO: Read configuration</font>');
10264: $readit=1;
10265:     {
10266: 	use integer;
10267: 	my $test=(2**32)+1;
10268: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
10269: 	&logthis(" Detected 64bit platform ($_64bit)");
10270:     }
10271: }
10272: }
10273: 
10274: 1;
10275: __END__
10276: 
10277: =pod
10278: 
10279: =head1 NAME
10280: 
10281: Apache::lonnet - Subroutines to ask questions about things in the network.
10282: 
10283: =head1 SYNOPSIS
10284: 
10285: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
10286: 
10287:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
10288: 
10289: Common parameters:
10290: 
10291: =over 4
10292: 
10293: =item *
10294: 
10295: $uname : an internal username (if $cname expecting a course Id specifically)
10296: 
10297: =item *
10298: 
10299: $udom : a domain (if $cdom expecting a course's domain specifically)
10300: 
10301: =item *
10302: 
10303: $symb : a resource instance identifier
10304: 
10305: =item *
10306: 
10307: $namespace : the name of a .db file that contains the data needed or
10308: being set.
10309: 
10310: =back
10311: 
10312: =head1 OVERVIEW
10313: 
10314: lonnet provides subroutines which interact with the
10315: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
10316: about classes, users, and resources.
10317: 
10318: For many of these objects you can also use this to store data about
10319: them or modify them in various ways.
10320: 
10321: =head2 Symbs
10322: 
10323: To identify a specific instance of a resource, LON-CAPA uses symbols
10324: or "symbs"X<symb>. These identifiers are built from the URL of the
10325: map, the resource number of the resource in the map, and the URL of
10326: the resource itself. The latter is somewhat redundant, but might help
10327: if maps change.
10328: 
10329: An example is
10330: 
10331:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
10332: 
10333: The respective map entry is
10334: 
10335:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
10336:   title="Problem 2">
10337:  </resource>
10338: 
10339: Symbs are used by the random number generator, as well as to store and
10340: restore data specific to a certain instance of for example a problem.
10341: 
10342: =head2 Storing And Retrieving Data
10343: 
10344: X<store()>X<cstore()>X<restore()>Three of the most important functions
10345: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
10346: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
10347: is is the non-critical message twin of cstore. These functions are for
10348: handlers to store a perl hash to a user's permanent data space in an
10349: easy manner, and to retrieve it again on another call. It is expected
10350: that a handler would use this once at the beginning to retrieve data,
10351: and then again once at the end to send only the new data back.
10352: 
10353: The data is stored in the user's data directory on the user's
10354: homeserver under the ID of the course.
10355: 
10356: The hash that is returned by restore will have all of the previous
10357: value for all of the elements of the hash.
10358: 
10359: Example:
10360: 
10361:  #creating a hash
10362:  my %hash;
10363:  $hash{'foo'}='bar';
10364: 
10365:  #storing it
10366:  &Apache::lonnet::cstore(\%hash);
10367: 
10368:  #changing a value
10369:  $hash{'foo'}='notbar';
10370: 
10371:  #adding a new value
10372:  $hash{'bar'}='foo';
10373:  &Apache::lonnet::cstore(\%hash);
10374: 
10375:  #retrieving the hash
10376:  my %history=&Apache::lonnet::restore();
10377: 
10378:  #print the hash
10379:  foreach my $key (sort(keys(%history))) {
10380:    print("\%history{$key} = $history{$key}");
10381:  }
10382: 
10383: Will print out:
10384: 
10385:  %history{1:foo} = bar
10386:  %history{1:keys} = foo:timestamp
10387:  %history{1:timestamp} = 990455579
10388:  %history{2:bar} = foo
10389:  %history{2:foo} = notbar
10390:  %history{2:keys} = foo:bar:timestamp
10391:  %history{2:timestamp} = 990455580
10392:  %history{bar} = foo
10393:  %history{foo} = notbar
10394:  %history{timestamp} = 990455580
10395:  %history{version} = 2
10396: 
10397: Note that the special hash entries C<keys>, C<version> and
10398: C<timestamp> were added to the hash. C<version> will be equal to the
10399: total number of versions of the data that have been stored. The
10400: C<timestamp> attribute will be the UNIX time the hash was
10401: stored. C<keys> is available in every historical section to list which
10402: keys were added or changed at a specific historical revision of a
10403: hash.
10404: 
10405: B<Warning>: do not store the hash that restore returns directly. This
10406: will cause a mess since it will restore the historical keys as if the
10407: were new keys. I.E. 1:foo will become 1:1:foo etc.
10408: 
10409: Calling convention:
10410: 
10411:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
10412:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
10413: 
10414: For more detailed information, see lonnet specific documentation.
10415: 
10416: =head1 RETURN MESSAGES
10417: 
10418: =over 4
10419: 
10420: =item * B<con_lost>: unable to contact remote host
10421: 
10422: =item * B<con_delayed>: unable to contact remote host, message will be delivered
10423: when the connection is brought back up
10424: 
10425: =item * B<con_failed>: unable to contact remote host and unable to save message
10426: for later delivery
10427: 
10428: =item * B<error:>: an error a occurred, a description of the error follows the :
10429: 
10430: =item * B<no_such_host>: unable to fund a host associated with the user/domain
10431: that was requested
10432: 
10433: =back
10434: 
10435: =head1 PUBLIC SUBROUTINES
10436: 
10437: =head2 Session Environment Functions
10438: 
10439: =over 4
10440: 
10441: =item * 
10442: X<appenv()>
10443: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
10444: the user envirnoment file, and will be restored for each access this
10445: user makes during this session, also modifies the %env for the current
10446: process. Optional rolesarrayref - if defined contains a reference to an array
10447: of roles which are exempt from the restriction on modifying user.role entries 
10448: in the user's environment.db and in %env.    
10449: 
10450: =item *
10451: X<delenv()>
10452: B<delenv($delthis,$regexp)>: removes all items from the session
10453: environment file that begin with $delthis. If the 
10454: optional second arg - $regexp - is true, $delthis is treated as a 
10455: regular expression, otherwise \Q$delthis\E is used. 
10456: The values are also deleted from the current processes %env.
10457: 
10458: =item * get_env_multiple($name) 
10459: 
10460: gets $name from the %env hash, it seemlessly handles the cases where multiple
10461: values may be defined and end up as an array ref.
10462: 
10463: returns an array of values
10464: 
10465: =back
10466: 
10467: =head2 User Information
10468: 
10469: =over 4
10470: 
10471: =item *
10472: X<queryauthenticate()>
10473: B<queryauthenticate($uname,$udom)>: try to determine user's current 
10474: authentication scheme
10475: 
10476: =item *
10477: X<authenticate()>
10478: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
10479: authenticate user from domain's lib servers (first use the current
10480: one). C<$upass> should be the users password.
10481: $checkdefauth is optional (value is 1 if a check should be made to
10482:    authenticate user using default authentication method, and allow
10483:    account creation if username does not have account in the domain).
10484: $clientcancheckhost is optional (value is 1 if checking whether the
10485:    server can host will occur on the client side in lonauth.pm).   
10486: 
10487: =item *
10488: X<homeserver()>
10489: B<homeserver($uname,$udom)>: find the server which has
10490: the user's directory and files (there must be only one), this caches
10491: the answer, and also caches if there is a borken connection.
10492: 
10493: =item *
10494: X<idget()>
10495: B<idget($udom,@ids)>: find the usernames behind a list of IDs
10496: (IDs are a unique resource in a domain, there must be only 1 ID per
10497: username, and only 1 username per ID in a specific domain) (returns
10498: hash: id=>name,id=>name)
10499: 
10500: =item *
10501: X<idrget()>
10502: B<idrget($udom,@unames)>: find the IDs behind a list of
10503: usernames (returns hash: name=>id,name=>id)
10504: 
10505: =item *
10506: X<idput()>
10507: B<idput($udom,%ids)>: store away a list of names and associated IDs
10508: 
10509: =item *
10510: X<rolesinit()>
10511: B<rolesinit($udom,$username,$authhost)>: get user privileges
10512: 
10513: =item *
10514: X<getsection()>
10515: B<getsection($udom,$uname,$cname)>: finds the section of student in the
10516: course $cname, return section name/number or '' for "not in course"
10517: and '-1' for "no section"
10518: 
10519: =item *
10520: X<userenvironment()>
10521: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
10522: passed in @what from the requested user's environment, returns a hash
10523: 
10524: =item * 
10525: X<userlog_query()>
10526: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
10527: activity.log file. %filters defines filters applied when parsing the
10528: log file. These can be start or end timestamps, or the type of action
10529: - log to look for Login or Logout events, check for Checkin or
10530: Checkout, role for role selection. The response is in the form
10531: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
10532: escaped strings of the action recorded in the activity.log file.
10533: 
10534: =back
10535: 
10536: =head2 User Roles
10537: 
10538: =over 4
10539: 
10540: =item *
10541: 
10542: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
10543:  F: full access
10544:  U,I,K: authentication modes (cxx only)
10545:  '': forbidden
10546:  1: user needs to choose course
10547:  2: browse allowed
10548:  A: passphrase authentication needed
10549: 
10550: =item *
10551: 
10552: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
10553: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
10554: and course level
10555: 
10556: =item *
10557: 
10558: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
10559: (rolesplain.tab); plain text explanation of a user role term.
10560: $type is Course (default) or Community.
10561: If $forcedefault evaluates to true, text returned will be default 
10562: text for $type. Otherwise, if this is a course, the text returned 
10563: will be a custom name for the role (if defined in the course's 
10564: environment).  If no custom name is defined the default is returned.
10565:    
10566: =item *
10567: 
10568: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
10569: All arguments are optional. Returns a hash of a roles, either for
10570: co-author/assistant author roles for a user's Construction Space
10571: (default), or if $context is 'userroles', roles for the user himself,
10572: In the hash, keys are set to colon-separated $uname,$udom,$role, and
10573: (optionally) if $withsec is true, a fourth colon-separated item - $section.
10574: For each key, value is set to colon-separated start and end times for
10575: the role.  If no username and domain are specified, will default to
10576: current user/domain. Types, roles, and roledoms are references to arrays
10577: of role statuses (active, future or previous), roles 
10578: (e.g., cc,in, st etc.) and domains of the roles which can be used
10579: to restrict the list of roles reported. If no array ref is 
10580: provided for types, will default to return only active roles.
10581: 
10582: =back
10583: 
10584: =head2 User Modification
10585: 
10586: =over 4
10587: 
10588: =item *
10589: 
10590: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
10591: user for the level given by URL.  Optional start and end dates (leave empty
10592: string or zero for "no date")
10593: 
10594: =item *
10595: 
10596: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
10597: change a users, password, possible return values are: ok,
10598: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
10599: refused
10600: 
10601: =item *
10602: 
10603: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
10604: 
10605: =item *
10606: 
10607: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
10608:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
10609: 
10610: will update user information (firstname,middlename,lastname,generation,
10611: permanentemail), and if forceid is true, student/employee ID also.
10612: A user's institutional affiliation(s) can also be updated.
10613: User information fields will not be overwritten with empty entries 
10614: unless the field is included in the $candelete array reference.
10615: This array is included when a single user is modified via "Manage Users",
10616: or when Autoupdate.pl is run by cron in a domain.
10617: 
10618: =item *
10619: 
10620: modifystudent
10621: 
10622: modify a student's enrollment and identification information.
10623: The course id is resolved based on the current users environment.  
10624: This means the envoking user must be a course coordinator or otherwise
10625: associated with a course.
10626: 
10627: This call is essentially a wrapper for lonnet::modifyuser and
10628: lonnet::modify_student_enrollment
10629: 
10630: Inputs: 
10631: 
10632: =over 4
10633: 
10634: =item B<$udom> Student's loncapa domain
10635: 
10636: =item B<$uname> Student's loncapa login name
10637: 
10638: =item B<$uid> Student/Employee ID
10639: 
10640: =item B<$umode> Student's authentication mode
10641: 
10642: =item B<$upass> Student's password
10643: 
10644: =item B<$first> Student's first name
10645: 
10646: =item B<$middle> Student's middle name
10647: 
10648: =item B<$last> Student's last name
10649: 
10650: =item B<$gene> Student's generation
10651: 
10652: =item B<$usec> Student's section in course
10653: 
10654: =item B<$end> Unix time of the roles expiration
10655: 
10656: =item B<$start> Unix time of the roles start date
10657: 
10658: =item B<$forceid> If defined, allow $uid to be changed
10659: 
10660: =item B<$desiredhome> server to use as home server for student
10661: 
10662: =item B<$email> Student's permanent e-mail address
10663: 
10664: =item B<$type> Type of enrollment (auto or manual)
10665: 
10666: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
10667: 
10668: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
10669: 
10670: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
10671: 
10672: =item B<$context> role change context (shown in User Management Logs display in a course)
10673: 
10674: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
10675: 
10676: =back
10677: 
10678: =item *
10679: 
10680: modify_student_enrollment
10681: 
10682: Change a students enrollment status in a class.  The environment variable
10683: 'role.request.course' must be defined for this function to proceed.
10684: 
10685: Inputs:
10686: 
10687: =over 4
10688: 
10689: =item $udom, students domain
10690: 
10691: =item $uname, students name
10692: 
10693: =item $uid, students user id
10694: 
10695: =item $first, students first name
10696: 
10697: =item $middle
10698: 
10699: =item $last
10700: 
10701: =item $gene
10702: 
10703: =item $usec
10704: 
10705: =item $end
10706: 
10707: =item $start
10708: 
10709: =item $type
10710: 
10711: =item $locktype
10712: 
10713: =item $cid
10714: 
10715: =item $selfenroll
10716: 
10717: =item $context
10718: 
10719: =back
10720: 
10721: 
10722: =item *
10723: 
10724: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
10725: custom role; give a custom role to a user for the level given by URL.  Specify
10726: name and domain of role author, and role name
10727: 
10728: =item *
10729: 
10730: revokerole($udom,$uname,$url,$role) : revoke a role for url
10731: 
10732: =item *
10733: 
10734: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
10735: 
10736: =back
10737: 
10738: =head2 Course Infomation
10739: 
10740: =over 4
10741: 
10742: =item *
10743: 
10744: coursedescription($courseid) : returns a hash of information about the
10745: specified course id, including all environment settings for the
10746: course, the description of the course will be in the hash under the
10747: key 'description'
10748: 
10749: =item *
10750: 
10751: resdata($name,$domain,$type,@which) : request for current parameter
10752: setting for a specific $type, where $type is either 'course' or 'user',
10753: @what should be a list of parameters to ask about. This routine caches
10754: answers for 5 minutes.
10755: 
10756: =item *
10757: 
10758: get_courseresdata($courseid, $domain) : dump the entire course resource
10759: data base, returning a hash that is keyed by the resource name and has
10760: values that are the resource value.  I believe that the timestamps and
10761: versions are also returned.
10762: 
10763: 
10764: =back
10765: 
10766: =head2 Course Modification
10767: 
10768: =over 4
10769: 
10770: =item *
10771: 
10772: writecoursepref($courseid,%prefs) : write preferences (environment
10773: database) for a course
10774: 
10775: =item *
10776: 
10777: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
10778: 
10779: =item *
10780: 
10781: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
10782: 
10783: =back
10784: 
10785: =head2 Resource Subroutines
10786: 
10787: =over 4
10788: 
10789: =item *
10790: 
10791: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
10792: 
10793: =item *
10794: 
10795: repcopy($filename) : subscribes to the requested file, and attempts to
10796: replicate from the owning library server, Might return
10797: 'unavailable', 'not_found', 'forbidden', 'ok', or
10798: 'bad_request', also attempts to grab the metadata for the
10799: resource. Expects the local filesystem pathname
10800: (/home/httpd/html/res/....)
10801: 
10802: =back
10803: 
10804: =head2 Resource Information
10805: 
10806: =over 4
10807: 
10808: =item *
10809: 
10810: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
10811: a vairety of different possible values, $varname should be a request
10812: string, and the other parameters can be used to specify who and what
10813: one is asking about.
10814: 
10815: Possible values for $varname are environment.lastname (or other item
10816: from the envirnment hash), user.name (or someother aspect about the
10817: user), resource.0.maxtries (or some other part and parameter of a
10818: resource)
10819: 
10820: =item *
10821: 
10822: directcondval($number) : get current value of a condition; reads from a state
10823: string
10824: 
10825: =item *
10826: 
10827: condval($condidx) : value of condition index based on state
10828: 
10829: =item *
10830: 
10831: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
10832: resource's metadata, $what should be either a specific key, or either
10833: 'keys' (to get a list of possible keys) or 'packages' to get a list of
10834: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
10835: 
10836: this function automatically caches all requests
10837: 
10838: =item *
10839: 
10840: metadata_query($query,$custom,$customshow) : make a metadata query against the
10841: network of library servers; returns file handle of where SQL and regex results
10842: will be stored for query
10843: 
10844: =item *
10845: 
10846: symbread($filename) : return symbolic list entry (filename argument optional);
10847: returns the data handle
10848: 
10849: =item *
10850: 
10851: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
10852: a possible symb for the URL in $thisfn, and if is an encryypted
10853: resource that the user accessed using /enc/ returns a 1 on success, 0
10854: on failure, user must be in a course, as it assumes the existance of
10855: the course initial hash, and uses $env('request.course.id'}
10856: 
10857: 
10858: =item *
10859: 
10860: symbclean($symb) : removes versions numbers from a symb, returns the
10861: cleaned symb
10862: 
10863: =item *
10864: 
10865: is_on_map($uri) : checks if the $uri is somewhere on the current
10866: course map, user must be in a course for it to work.
10867: 
10868: =item *
10869: 
10870: numval($salt) : return random seed value (addend for rndseed)
10871: 
10872: =item *
10873: 
10874: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
10875: a random seed, all arguments are optional, if they aren't sent it uses the
10876: environment to derive them. Note: if symb isn't sent and it can't get one
10877: from &symbread it will use the current time as its return value
10878: 
10879: =item *
10880: 
10881: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
10882: unfakeable, receipt
10883: 
10884: =item *
10885: 
10886: receipt() : API to ireceipt working off of env values; given out to users
10887: 
10888: =item *
10889: 
10890: countacc($url) : count the number of accesses to a given URL
10891: 
10892: =item *
10893: 
10894: 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
10895: 
10896: =item *
10897: 
10898: 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)
10899: 
10900: =item *
10901: 
10902: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
10903: 
10904: =item *
10905: 
10906: devalidate($symb) : devalidate temporary spreadsheet calculations,
10907: forcing spreadsheet to reevaluate the resource scores next time.
10908: 
10909: =back
10910: 
10911: =head2 Storing/Retreiving Data
10912: 
10913: =over 4
10914: 
10915: =item *
10916: 
10917: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
10918: for this url; hashref needs to be given and should be a \%hashname; the
10919: remaining args aren't required and if they aren't passed or are '' they will
10920: be derived from the env
10921: 
10922: =item *
10923: 
10924: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
10925: uses critical subroutine
10926: 
10927: =item *
10928: 
10929: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
10930: all args are optional
10931: 
10932: =item *
10933: 
10934: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
10935: dumps the complete (or key matching regexp) namespace into a hash
10936: ($udom, $uname, $regexp, $range are optional) for a namespace that is
10937: normally &store()ed into
10938: 
10939: $range should be either an integer '100' (give me the first 100
10940:                                            matching records)
10941:               or be  two integers sperated by a - with no spaces
10942:                  '30-50' (give me the 30th through the 50th matching
10943:                           records)
10944: 
10945: 
10946: =item *
10947: 
10948: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
10949: replaces a &store() version of data with a replacement set of data
10950: for a particular resource in a namespace passed in the $storehash hash 
10951: reference
10952: 
10953: =item *
10954: 
10955: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
10956: works very similar to store/cstore, but all data is stored in a
10957: temporary location and can be reset using tmpreset, $storehash should
10958: be a hash reference, returns nothing on success
10959: 
10960: =item *
10961: 
10962: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
10963: similar to restore, but all data is stored in a temporary location and
10964: can be reset using tmpreset. Returns a hash of values on success,
10965: error string otherwise.
10966: 
10967: =item *
10968: 
10969: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
10970: deltes all keys for $symb form the temporary storage hash.
10971: 
10972: =item *
10973: 
10974: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
10975: reference filled in from namesp ($udom and $uname are optional)
10976: 
10977: =item *
10978: 
10979: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
10980: namesp ($udom and $uname are optional)
10981: 
10982: =item *
10983: 
10984: dump($namespace,$udom,$uname,$regexp,$range) : 
10985: dumps the complete (or key matching regexp) namespace into a hash
10986: ($udom, $uname, $regexp, $range are optional)
10987: 
10988: $range should be either an integer '100' (give me the first 100
10989:                                            matching records)
10990:               or be  two integers sperated by a - with no spaces
10991:                  '30-50' (give me the 30th through the 50th matching
10992:                           records)
10993: =item *
10994: 
10995: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
10996: $store can be a scalar, an array reference, or if the amount to be 
10997: incremented is > 1, a hash reference.
10998: 
10999: ($udom and $uname are optional)
11000: 
11001: =item *
11002: 
11003: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
11004: ($udom and $uname are optional)
11005: 
11006: =item *
11007: 
11008: cput($namespace,$storehash,$udom,$uname) : critical put
11009: ($udom and $uname are optional)
11010: 
11011: =item *
11012: 
11013: newput($namespace,$storehash,$udom,$uname) :
11014: 
11015: Attempts to store the items in the $storehash, but only if they don't
11016: currently exist, if this succeeds you can be certain that you have 
11017: successfully created a new key value pair in the $namespace db.
11018: 
11019: 
11020: Args:
11021:  $namespace: name of database to store values to
11022:  $storehash: hashref to store to the db
11023:  $udom: (optional) domain of user containing the db
11024:  $uname: (optional) name of user caontaining the db
11025: 
11026: Returns:
11027:  'ok' -> succeeded in storing all keys of $storehash
11028:  'key_exists: <key>' -> failed to anything out of $storehash, as at
11029:                         least <key> already existed in the db (other
11030:                         requested keys may also already exist)
11031:  'error: <msg>' -> unable to tie the DB or other error occurred
11032:  'con_lost' -> unable to contact request server
11033:  'refused' -> action was not allowed by remote machine
11034: 
11035: 
11036: =item *
11037: 
11038: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11039: reference filled in from namesp (encrypts the return communication)
11040: ($udom and $uname are optional)
11041: 
11042: =item *
11043: 
11044: log($udom,$name,$home,$message) : write to permanent log for user; use
11045: critical subroutine
11046: 
11047: =item *
11048: 
11049: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
11050: array reference filled in from namespace found in domain level on either
11051: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
11052: 
11053: =item *
11054: 
11055: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
11056: domain level either on specified domain server ($uhome) or primary domain 
11057: server ($udom and $uhome are optional)
11058: 
11059: =item * 
11060: 
11061: get_domain_defaults($target_domain) : returns hash with defaults for
11062: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
11063: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
11064: or localauth), initial password or a kerberos realm, language (e.g., en-us).
11065: Values are retrieved from cache (if current), or from domain's configuration.db
11066: (if available), or lastly from values in lonTabs/dns_domain,tab, 
11067: or lonTabs/domain.tab. 
11068: 
11069: %domdefaults = &get_auth_defaults($target_domain);
11070: 
11071: =back
11072: 
11073: =head2 Network Status Functions
11074: 
11075: =over 4
11076: 
11077: =item *
11078: 
11079: dirlist($uri) : return directory list based on URI
11080: 
11081: =item *
11082: 
11083: spareserver() : find server with least workload from spare.tab
11084: 
11085: 
11086: =item *
11087: 
11088: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
11089: if there is no corresponding loncapa host.
11090: 
11091: =back
11092: 
11093: 
11094: =head2 Apache Request
11095: 
11096: =over 4
11097: 
11098: =item *
11099: 
11100: ssi($url,%hash) : server side include, does a complete request cycle on url to
11101: localhost, posts hash
11102: 
11103: =back
11104: 
11105: =head2 Data to String to Data
11106: 
11107: =over 4
11108: 
11109: =item *
11110: 
11111: hash2str(%hash) : convert a hash into a string complete with escaping and '='
11112: and '&' separators, supports elements that are arrayrefs and hashrefs
11113: 
11114: =item *
11115: 
11116: hashref2str($hashref) : convert a hashref into a string complete with
11117: escaping and '=' and '&' separators, supports elements that are
11118: arrayrefs and hashrefs
11119: 
11120: =item *
11121: 
11122: arrayref2str($arrayref) : convert an arrayref into a string complete
11123: with escaping and '&' separators, supports elements that are arrayrefs
11124: and hashrefs
11125: 
11126: =item *
11127: 
11128: str2hash($string) : convert string to hash using unescaping and
11129: splitting on '=' and '&', supports elements that are arrayrefs and
11130: hashrefs
11131: 
11132: =item *
11133: 
11134: str2array($string) : convert string to hash using unescaping and
11135: splitting on '&', supports elements that are arrayrefs and hashrefs
11136: 
11137: =back
11138: 
11139: =head2 Logging Routines
11140: 
11141: =over 4
11142: 
11143: These routines allow one to make log messages in the lonnet.log and
11144: lonnet.perm logfiles.
11145: 
11146: =item *
11147: 
11148: logtouch() : make sure the logfile, lonnet.log, exists
11149: 
11150: =item *
11151: 
11152: logthis() : append message to the normal lonnet.log file, it gets
11153: preiodically rolled over and deleted.
11154: 
11155: =item *
11156: 
11157: logperm() : append a permanent message to lonnet.perm.log, this log
11158: file never gets deleted by any automated portion of the system, only
11159: messages of critical importance should go in here.
11160: 
11161: =back
11162: 
11163: =head2 General File Helper Routines
11164: 
11165: =over 4
11166: 
11167: =item *
11168: 
11169: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
11170: (a) files in /uploaded
11171:   (i) If a local copy of the file exists - 
11172:       compares modification date of local copy with last-modified date for 
11173:       definitive version stored on home server for course. If local copy is 
11174:       stale, requests a new version from the home server and stores it. 
11175:       If the original has been removed from the home server, then local copy 
11176:       is unlinked.
11177:   (ii) If local copy does not exist -
11178:       requests the file from the home server and stores it. 
11179:   
11180:   If $caller is 'uploadrep':  
11181:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
11182:     for request for files originally uploaded via DOCS. 
11183:      - returns 'ok' if fresh local copy now available, -1 otherwise.
11184:   
11185:   Otherwise:
11186:      This indicates a call from the content generation phase of the request.
11187:      -  returns the entire contents of the file or -1.
11188:      
11189: (b) files in /res
11190:    - returns the entire contents of a file or -1; 
11191:    it properly subscribes to and replicates the file if neccessary.
11192: 
11193: 
11194: =item *
11195: 
11196: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
11197:                   reference
11198: 
11199: returns either a stat() list of data about the file or an empty list
11200: if the file doesn't exist or couldn't find out about it (connection
11201: problems or user unknown)
11202: 
11203: =item *
11204: 
11205: filelocation($dir,$file) : returns file system location of a file
11206: based on URI; meant to be "fairly clean" absolute reference, $dir is a
11207: directory that relative $file lookups are to looked in ($dir of /a/dir
11208: and a file of ../bob will become /a/bob)
11209: 
11210: =item *
11211: 
11212: hreflocation($dir,$file) : returns file system location or a URL; same as
11213: filelocation except for hrefs
11214: 
11215: =item *
11216: 
11217: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
11218: 
11219: =back
11220: 
11221: =head2 Usererfile file routines (/uploaded*)
11222: 
11223: =over 4
11224: 
11225: =item *
11226: 
11227: userfileupload(): main rotine for putting a file in a user or course's
11228:                   filespace, arguments are,
11229: 
11230:  formname - required - this is the name of the element in $env where the
11231:            filename, and the contents of the file to create/modifed exist
11232:            the filename is in $env{'form.'.$formname.'.filename'} and the
11233:            contents of the file is located in $env{'form.'.$formname}
11234:  coursedoc - if true, store the file in the course of the active role
11235:              of the current user
11236:  subdir - required - subdirectory to put the file in under ../userfiles/
11237:          if undefined, it will be placed in "unknown"
11238: 
11239:  (This routine calls clean_filename() to remove any dangerous
11240:  characters from the filename, and then calls finuserfileupload() to
11241:  complete the transaction)
11242: 
11243:  returns either the url of the uploaded file (/uploaded/....) if successful
11244:  and /adm/notfound.html if unsuccessful
11245: 
11246: =item *
11247: 
11248: clean_filename(): routine for cleaing a filename up for storage in
11249:                  userfile space, argument is:
11250: 
11251:  filename - proposed filename
11252: 
11253: returns: the new clean filename
11254: 
11255: =item *
11256: 
11257: finishuserfileupload(): routine that creaes and sends the file to
11258: userspace, probably shouldn't be called directly
11259: 
11260:   docuname: username or courseid of destination for the file
11261:   docudom: domain of user/course of destination for the file
11262:   formname: same as for userfileupload()
11263:   fname: filename (inculding subdirectories) for the file
11264: 
11265:  returns either the url of the uploaded file (/uploaded/....) if successful
11266:  and /adm/notfound.html if unsuccessful
11267: 
11268: =item *
11269: 
11270: renameuserfile(): renames an existing userfile to a new name
11271: 
11272:   Args:
11273:    docuname: username or courseid of destination for the file
11274:    docudom: domain of user/course of destination for the file
11275:    old: current file name (including any subdirs under userfiles)
11276:    new: desired file name (including any subdirs under userfiles)
11277: 
11278: =item *
11279: 
11280: mkdiruserfile(): creates a directory is a userfiles dir
11281: 
11282:   Args:
11283:    docuname: username or courseid of destination for the file
11284:    docudom: domain of user/course of destination for the file
11285:    dir: dir to create (including any subdirs under userfiles)
11286: 
11287: =item *
11288: 
11289: removeuserfile(): removes a file that exists in userfiles
11290: 
11291:   Args:
11292:    docuname: username or courseid of destination for the file
11293:    docudom: domain of user/course of destination for the file
11294:    fname: filname to delete (including any subdirs under userfiles)
11295: 
11296: =item *
11297: 
11298: removeuploadedurl(): convience function for removeuserfile()
11299: 
11300:   Args:
11301:    url:  a full /uploaded/... url to delete
11302: 
11303: =item * 
11304: 
11305: get_portfile_permissions():
11306:   Args:
11307:     domain: domain of user or course contain the portfolio files
11308:     user: name of user or num of course contain the portfolio files
11309:   Returns:
11310:     hashref of a dump of the proper file_permissions.db
11311:    
11312: 
11313: =item * 
11314: 
11315: get_access_controls():
11316: 
11317: Args:
11318:   current_permissions: the hash ref returned from get_portfile_permissions()
11319:   group: (optional) the group you want the files associated with
11320:   file: (optional) the file you want access info on
11321: 
11322: Returns:
11323:     a hash (keys are file names) of hashes containing
11324:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
11325:         values are XML containing access control settings (see below) 
11326: 
11327: Internal notes:
11328: 
11329:  access controls are stored in file_permissions.db as key=value pairs.
11330:     key -> path to file/file_name\0uniqueID:scope_end_start
11331:         where scope -> public,guest,course,group,domains or users.
11332:               end -> UNIX time for end of access (0 -> no end date)
11333:               start -> UNIX time for start of access
11334: 
11335:     value -> XML description of access control
11336:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
11337:             <start></start>
11338:             <end></end>
11339: 
11340:             <password></password>  for scope type = guest
11341: 
11342:             <domain></domain>     for scope type = course or group
11343:             <number></number>
11344:             <roles id="">
11345:              <role></role>
11346:              <access></access>
11347:              <section></section>
11348:              <group></group>
11349:             </roles>
11350: 
11351:             <dom></dom>         for scope type = domains
11352: 
11353:             <users>             for scope type = users
11354:              <user>
11355:               <uname></uname>
11356:               <udom></udom>
11357:              </user>
11358:             </users>
11359:            </scope> 
11360:               
11361:  Access data is also aggregated for each file in an additional key=value pair:
11362:  key -> path to file/file_name\0accesscontrol 
11363:  value -> reference to hash
11364:           hash contains key = value pairs
11365:           where key = uniqueID:scope_end_start
11366:                 value = UNIX time record was last updated
11367: 
11368:           Used to improve speed of look-ups of access controls for each file.  
11369:  
11370:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
11371: 
11372: modify_access_controls():
11373: 
11374: Modifies access controls for a portfolio file
11375: Args
11376: 1. file name
11377: 2. reference to hash of required changes,
11378: 3. domain
11379: 4. username
11380:   where domain,username are the domain of the portfolio owner 
11381:   (either a user or a course) 
11382: 
11383: Returns:
11384: 1. result of additions or updates ('ok' or 'error', with error message). 
11385: 2. result of deletions ('ok' or 'error', with error message).
11386: 3. reference to hash of any new or updated access controls.
11387: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
11388:    key = integer (inbound ID)
11389:    value = uniqueID  
11390: 
11391: =back
11392: 
11393: =head2 HTTP Helper Routines
11394: 
11395: =over 4
11396: 
11397: =item *
11398: 
11399: escape() : unpack non-word characters into CGI-compatible hex codes
11400: 
11401: =item *
11402: 
11403: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
11404: 
11405: =back
11406: 
11407: =head1 PRIVATE SUBROUTINES
11408: 
11409: =head2 Underlying communication routines (Shouldn't call)
11410: 
11411: =over 4
11412: 
11413: =item *
11414: 
11415: subreply() : tries to pass a message to lonc, returns con_lost if incapable
11416: 
11417: =item *
11418: 
11419: reply() : uses subreply to send a message to remote machine, logs all failures
11420: 
11421: =item *
11422: 
11423: critical() : passes a critical message to another server; if cannot
11424: get through then place message in connection buffer directory and
11425: returns con_delayed, if incapable of saving message, returns
11426: con_failed
11427: 
11428: =item *
11429: 
11430: reconlonc() : tries to reconnect lonc client processes.
11431: 
11432: =back
11433: 
11434: =head2 Resource Access Logging
11435: 
11436: =over 4
11437: 
11438: =item *
11439: 
11440: flushcourselogs() : flush (save) buffer logs and access logs
11441: 
11442: =item *
11443: 
11444: courselog($what) : save message for course in hash
11445: 
11446: =item *
11447: 
11448: courseacclog($what) : save message for course using &courselog().  Perform
11449: special processing for specific resource types (problems, exams, quizzes, etc).
11450: 
11451: =item *
11452: 
11453: goodbye() : flush course logs and log shutting down; it is called in srm.conf
11454: as a PerlChildExitHandler
11455: 
11456: =back
11457: 
11458: =head2 Other
11459: 
11460: =over 4
11461: 
11462: =item *
11463: 
11464: symblist($mapname,%newhash) : update symbolic storage links
11465: 
11466: =back
11467: 
11468: =cut
11469: 

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