File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.1078: download - view: text, annotated - select for diffs
Mon Jul 26 21:52:19 2010 UTC (13 years, 11 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- For Course/Community roles requiring a specific minimum LON-CAPA version,
  where server hosting session is not running a recent enough version:
  (a) If server hosting session is running 2.10 or later, switch server
      link shown for role on roles/courses screen.
      - switch is to a server in user's domain (if any have required version)
        or to a server in course's domain (if any have required version).
  (b) For servers hosting sessions running 2.9 or earlier, lond on the
      user's home machine will only supply information for roles which
      can be run on the version on the server hosting the session.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.1078 2010/07/26 21:52:19 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 $extra = &freeze_escape({'clientcheckrole' => 1});
 3947:     my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
 3948:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
 3949:         ($rolesdump =~ /^error:/)) {
 3950:         return \%userroles;
 3951:     }
 3952:     my %allroles=();
 3953:     my %allgroups=();   
 3954:     my $group_privs;
 3955: 
 3956:     if ($rolesdump ne '') {
 3957:         foreach my $entry (split(/&/,$rolesdump)) {
 3958: 	  if ($entry!~/^rolesdef_/) {
 3959:             my ($area,$role)=split(/=/,$entry);
 3960: 	    $area=~s/\_\w\w$//;
 3961:             my ($trole,$tend,$tstart,$group_privs);
 3962: 	    if ($role=~/^cr/) { 
 3963: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 3964: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
 3965: 		    ($tend,$tstart)=split('_',$trest);
 3966: 		} else {
 3967: 		    $trole=$role;
 3968: 		}
 3969:             } elsif ($role =~ m|^gr/|) {
 3970:                 ($trole,$tend,$tstart) = split(/_/,$role);
 3971:                 ($trole,$group_privs) = split(/\//,$trole);
 3972:                 $group_privs = &unescape($group_privs);
 3973: 	    } else {
 3974: 		($trole,$tend,$tstart)=split(/_/,$role);
 3975: 	    }
 3976: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 3977: 					 $username);
 3978: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 3979:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 3980:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 3981:             if (($area ne '') && ($trole ne '')) {
 3982: 		my $spec=$trole.'.'.$area;
 3983: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 3984: 		if ($trole =~ /^cr\//) {
 3985:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 3986:                 } elsif ($trole eq 'gr') {
 3987:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 3988: 		} else {
 3989:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 3990: 		}
 3991:             }
 3992:           }
 3993:         }
 3994:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 3995:         $userroles{'user.adv'}    = $adv;
 3996: 	$userroles{'user.author'} = $author;
 3997:         $env{'user.adv'}=$adv;
 3998:     }
 3999:     return \%userroles;  
 4000: }
 4001: 
 4002: sub set_arearole {
 4003:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 4004: # log the associated role with the area
 4005:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 4006:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 4007: }
 4008: 
 4009: sub custom_roleprivs {
 4010:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 4011:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 4012:     my $homsvr=homeserver($rauthor,$rdomain);
 4013:     if (&hostname($homsvr) ne '') {
 4014:         my ($rdummy,$roledef)=
 4015:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 4016:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 4017:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 4018:             if (defined($syspriv)) {
 4019:                 if ($trest =~ /^$match_community$/) {
 4020:                     $syspriv =~ s/bre\&S//; 
 4021:                 }
 4022:                 $$allroles{'cm./'}.=':'.$syspriv;
 4023:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 4024:             }
 4025:             if ($tdomain ne '') {
 4026:                 if (defined($dompriv)) {
 4027:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 4028:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 4029:                 }
 4030:                 if (($trest ne '') && (defined($coursepriv))) {
 4031:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 4032:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 4033:                 }
 4034:             }
 4035:         }
 4036:     }
 4037: }
 4038: 
 4039: sub group_roleprivs {
 4040:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 4041:     my $access = 1;
 4042:     my $now = time;
 4043:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 4044:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 4045:     if ($access) {
 4046:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 4047:         $$allgroups{$course}{$group} .=':'.$group_privs;
 4048:     }
 4049: }
 4050: 
 4051: sub standard_roleprivs {
 4052:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 4053:     if (defined($pr{$trole.':s'})) {
 4054:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 4055:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 4056:     }
 4057:     if ($tdomain ne '') {
 4058:         if (defined($pr{$trole.':d'})) {
 4059:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 4060:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 4061:         }
 4062:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 4063:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 4064:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 4065:         }
 4066:     }
 4067: }
 4068: 
 4069: sub set_userprivs {
 4070:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
 4071:     my $author=0;
 4072:     my $adv=0;
 4073:     my %grouproles = ();
 4074:     if (keys(%{$allgroups}) > 0) {
 4075:         my @groupkeys; 
 4076:         foreach my $role (keys(%{$allroles})) {
 4077:             push(@groupkeys,$role);
 4078:         }
 4079:         if (ref($groups_roles) eq 'HASH') {
 4080:             foreach my $key (keys(%{$groups_roles})) {
 4081:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
 4082:                     push(@groupkeys,$key);
 4083:                 }
 4084:             }
 4085:         }
 4086:         if (@groupkeys > 0) {
 4087:             foreach my $role (@groupkeys) {
 4088:                 my ($trole,$area,$sec,$extendedarea);
 4089:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 4090:                     $trole = $1;
 4091:                     $area = $2;
 4092:                     $sec = $3;
 4093:                     $extendedarea = $area.$sec;
 4094:                     if (exists($$allgroups{$area})) {
 4095:                         foreach my $group (keys(%{$$allgroups{$area}})) {
 4096:                             my $spec = $trole.'.'.$extendedarea;
 4097:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
 4098:                                                 $$allgroups{$area}{$group};
 4099:                         }
 4100:                     }
 4101:                 }
 4102:             }
 4103:         }
 4104:     }
 4105:     foreach my $group (keys(%grouproles)) {
 4106:         $$allroles{$group} = $grouproles{$group};
 4107:     }
 4108:     foreach my $role (keys(%{$allroles})) {
 4109:         my %thesepriv;
 4110:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 4111:         foreach my $item (split(/:/,$$allroles{$role})) {
 4112:             if ($item ne '') {
 4113:                 my ($privilege,$restrictions)=split(/&/,$item);
 4114:                 if ($restrictions eq '') {
 4115:                     $thesepriv{$privilege}='F';
 4116:                 } elsif ($thesepriv{$privilege} ne 'F') {
 4117:                     $thesepriv{$privilege}.=$restrictions;
 4118:                 }
 4119:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 4120:             }
 4121:         }
 4122:         my $thesestr='';
 4123:         foreach my $priv (keys(%thesepriv)) {
 4124: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 4125: 	}
 4126:         $userroles->{'user.priv.'.$role} = $thesestr;
 4127:     }
 4128:     return ($author,$adv);
 4129: }
 4130: 
 4131: sub role_status {
 4132:     my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
 4133:     my @pwhere = ();
 4134:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
 4135:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
 4136:         unless (!defined($$role) || $$role eq '') {
 4137:             $$where=join('.',@pwhere);
 4138:             $$trolecode=$$role.'.'.$$where;
 4139:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
 4140:             $$tstatus='is';
 4141:             if ($$tstart && $$tstart>$then) {
 4142:                 $$tstatus='future';
 4143:                 if ($$tstart<$now) {
 4144:                     if ($$tstart && $$tstart>$refresh) {
 4145:                         if (($$where ne '') && ($$role ne '')) {
 4146:                             my (%allroles,%allgroups,$group_privs,
 4147:                                 %groups_roles,@rolecodes);
 4148:                             my %userroles = (
 4149:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
 4150:                             );
 4151:                             @rolecodes = ('cm'); 
 4152:                             my $spec=$$role.'.'.$$where;
 4153:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
 4154:                             if ($$role =~ /^cr\//) {
 4155:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
 4156:                                 push(@rolecodes,'cr');
 4157:                             } elsif ($$role eq 'gr') {
 4158:                                 push(@rolecodes,$$role);
 4159:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
 4160:                                                     $env{'user.name'});
 4161:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
 4162:                                 (undef,my $group_privs) = split(/\//,$trole);
 4163:                                 $group_privs = &unescape($group_privs);
 4164:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
 4165:                                 my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
 4166:                                 if (keys(%course_roles) > 0) {
 4167:                                     my ($tnum) = ($trest =~ /^($match_courseid)/);
 4168:                                     if ($tdomain ne '' && $tnum ne '') { 
 4169:                                         foreach my $key (keys(%course_roles)) {
 4170:                                             if ($key =~ /^\Q$tnum\E:\Q$tdomain\E:([^:]+):?([^:]*)/) {
 4171:                                                 my $crsrole = $1;
 4172:                                                 my $crssec = $2;
 4173:                                                 if ($crsrole =~ /^cr/) {
 4174:                                                     unless (grep(/^cr$/,@rolecodes)) {
 4175:                                                         push(@rolecodes,'cr');
 4176:                                                     }
 4177:                                                 } else {
 4178:                                                     unless(grep(/^\Q$crsrole\E$/,@rolecodes)) {
 4179:                                                         push(@rolecodes,$crsrole);
 4180:                                                     }
 4181:                                                 }
 4182:                                                 my $rolekey = $crsrole.'./'.$tdomain.'/'.$tnum;
 4183:                                                 if ($crssec ne '') {
 4184:                                                     $rolekey .= '/'.$crssec;
 4185:                                                 }
 4186:                                                 $rolekey .= './';
 4187:                                                 $groups_roles{$rolekey} = \@rolecodes;
 4188:                                             }
 4189:                                         }
 4190:                                     }
 4191:                                 }
 4192:                             } else {
 4193:                                 push(@rolecodes,$$role);
 4194:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
 4195:                             }
 4196:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
 4197:                             &appenv(\%userroles,\@rolecodes);
 4198:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 4199:                         }
 4200:                     }
 4201:                     $$tstatus = 'is';
 4202:                 }
 4203:             }
 4204:             if ($$tend) {
 4205:                 if ($$tend<$then) {
 4206:                     $$tstatus='expired';
 4207:                 } elsif ($$tend<$now) {
 4208:                     $$tstatus='will_not';
 4209:                 }
 4210:             }
 4211:         }
 4212:     }
 4213: }
 4214: 
 4215: sub check_adhoc_privs {
 4216:     my ($cdom,$cnum,$then,$refresh,$now,$checkrole) = @_;
 4217:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
 4218:     if ($env{$cckey}) {
 4219:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
 4220:         &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
 4221:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
 4222:             &set_adhoc_privileges($cdom,$cnum,$checkrole);
 4223:         }
 4224:     } else {
 4225:         &set_adhoc_privileges($cdom,$cnum,$checkrole);
 4226:     }
 4227: }
 4228: 
 4229: sub set_adhoc_privileges {
 4230: # role can be cc or ca
 4231:     my ($dcdom,$pickedcourse,$role) = @_;
 4232:     my $area = '/'.$dcdom.'/'.$pickedcourse;
 4233:     my $spec = $role.'.'.$area;
 4234:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
 4235:                                   $env{'user.name'});
 4236:     my %ccrole = ();
 4237:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
 4238:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
 4239:     &appenv(\%userroles,[$role,'cm']);
 4240:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
 4241:     &appenv( {'request.role'        => $spec,
 4242:               'request.role.domain' => $dcdom,
 4243:               'request.course.sec'  => ''
 4244:              }
 4245:            );
 4246:     my $tadv=0;
 4247:     if (&allowed('adv') eq 'F') { $tadv=1; }
 4248:     &appenv({'request.role.adv'    => $tadv});
 4249: }
 4250: 
 4251: # --------------------------------------------------------------- get interface
 4252: 
 4253: sub get {
 4254:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4255:    my $items='';
 4256:    foreach my $item (@$storearr) {
 4257:        $items.=&escape($item).'&';
 4258:    }
 4259:    $items=~s/\&$//;
 4260:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4261:    if (!$uname) { $uname=$env{'user.name'}; }
 4262:    my $uhome=&homeserver($uname,$udomain);
 4263: 
 4264:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 4265:    my @pairs=split(/\&/,$rep);
 4266:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 4267:      return @pairs;
 4268:    }
 4269:    my %returnhash=();
 4270:    my $i=0;
 4271:    foreach my $item (@$storearr) {
 4272:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 4273:       $i++;
 4274:    }
 4275:    return %returnhash;
 4276: }
 4277: 
 4278: # --------------------------------------------------------------- del interface
 4279: 
 4280: sub del {
 4281:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4282:    my $items='';
 4283:    foreach my $item (@$storearr) {
 4284:        $items.=&escape($item).'&';
 4285:    }
 4286: 
 4287:    $items=~s/\&$//;
 4288:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4289:    if (!$uname) { $uname=$env{'user.name'}; }
 4290:    my $uhome=&homeserver($uname,$udomain);
 4291:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 4292: }
 4293: 
 4294: # -------------------------------------------------------------- dump interface
 4295: 
 4296: sub dump {
 4297:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 4298:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4299:     if (!$uname) { $uname=$env{'user.name'}; }
 4300:     my $uhome=&homeserver($uname,$udomain);
 4301:     if ($regexp) {
 4302: 	$regexp=&escape($regexp);
 4303:     } else {
 4304: 	$regexp='.';
 4305:     }
 4306:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 4307:     my @pairs=split(/\&/,$rep);
 4308:     my %returnhash=();
 4309:     foreach my $item (@pairs) {
 4310: 	my ($key,$value)=split(/=/,$item,2);
 4311: 	$key = &unescape($key);
 4312: 	next if ($key =~ /^error: 2 /);
 4313: 	$returnhash{$key}=&thaw_unescape($value);
 4314:     }
 4315:     return %returnhash;
 4316: }
 4317: 
 4318: # --------------------------------------------------------- dumpstore interface
 4319: 
 4320: sub dumpstore {
 4321:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 4322:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4323:    if (!$uname) { $uname=$env{'user.name'}; }
 4324:    my $uhome=&homeserver($uname,$udomain);
 4325:    if ($regexp) {
 4326:        $regexp=&escape($regexp);
 4327:    } else {
 4328:        $regexp='.';
 4329:    }
 4330:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 4331:    my @pairs=split(/\&/,$rep);
 4332:    my %returnhash=();
 4333:    foreach my $item (@pairs) {
 4334:        my ($key,$value)=split(/=/,$item,2);
 4335:        next if ($key =~ /^error: 2 /);
 4336:        $returnhash{$key}=&thaw_unescape($value);
 4337:    }
 4338:    return %returnhash;
 4339: }
 4340: 
 4341: # -------------------------------------------------------------- keys interface
 4342: 
 4343: sub getkeys {
 4344:    my ($namespace,$udomain,$uname)=@_;
 4345:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4346:    if (!$uname) { $uname=$env{'user.name'}; }
 4347:    my $uhome=&homeserver($uname,$udomain);
 4348:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 4349:    my @keyarray=();
 4350:    foreach my $key (split(/\&/,$rep)) {
 4351:       next if ($key =~ /^error: 2 /);
 4352:       push(@keyarray,&unescape($key));
 4353:    }
 4354:    return @keyarray;
 4355: }
 4356: 
 4357: # --------------------------------------------------------------- currentdump
 4358: sub currentdump {
 4359:    my ($courseid,$sdom,$sname)=@_;
 4360:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 4361:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 4362:    $sname    = $env{'user.name'}         if (! defined($sname));
 4363:    my $uhome = &homeserver($sname,$sdom);
 4364:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 4365:    return if ($rep =~ /^(error:|no_such_host)/);
 4366:    #
 4367:    my %returnhash=();
 4368:    #
 4369:    if ($rep eq "unknown_cmd") { 
 4370:        # an old lond will not know currentdump
 4371:        # Do a dump and make it look like a currentdump
 4372:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 4373:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 4374:        my %hash = @tmp;
 4375:        @tmp=();
 4376:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 4377:    } else {
 4378:        my @pairs=split(/\&/,$rep);
 4379:        foreach my $pair (@pairs) {
 4380:            my ($key,$value)=split(/=/,$pair,2);
 4381:            my ($symb,$param) = split(/:/,$key);
 4382:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 4383:                                                         &thaw_unescape($value);
 4384:        }
 4385:    }
 4386:    return %returnhash;
 4387: }
 4388: 
 4389: sub convert_dump_to_currentdump{
 4390:     my %hash = %{shift()};
 4391:     my %returnhash;
 4392:     # Code ripped from lond, essentially.  The only difference
 4393:     # here is the unescaping done by lonnet::dump().  Conceivably
 4394:     # we might run in to problems with parameter names =~ /^v\./
 4395:     while (my ($key,$value) = each(%hash)) {
 4396:         my ($v,$symb,$param) = split(/:/,$key);
 4397: 	$symb  = &unescape($symb);
 4398: 	$param = &unescape($param);
 4399:         next if ($v eq 'version' || $symb eq 'keys');
 4400:         next if (exists($returnhash{$symb}) &&
 4401:                  exists($returnhash{$symb}->{$param}) &&
 4402:                  $returnhash{$symb}->{'v.'.$param} > $v);
 4403:         $returnhash{$symb}->{$param}=$value;
 4404:         $returnhash{$symb}->{'v.'.$param}=$v;
 4405:     }
 4406:     #
 4407:     # Remove all of the keys in the hashes which keep track of
 4408:     # the version of the parameter.
 4409:     while (my ($symb,$param_hash) = each(%returnhash)) {
 4410:         # use a foreach because we are going to delete from the hash.
 4411:         foreach my $key (keys(%$param_hash)) {
 4412:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 4413:         }
 4414:     }
 4415:     return \%returnhash;
 4416: }
 4417: 
 4418: # ------------------------------------------------------ critical inc interface
 4419: 
 4420: sub cinc {
 4421:     return &inc(@_,'critical');
 4422: }
 4423: 
 4424: # --------------------------------------------------------------- inc interface
 4425: 
 4426: sub inc {
 4427:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 4428:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4429:     if (!$uname) { $uname=$env{'user.name'}; }
 4430:     my $uhome=&homeserver($uname,$udomain);
 4431:     my $items='';
 4432:     if (! ref($store)) {
 4433:         # got a single value, so use that instead
 4434:         $items = &escape($store).'=&';
 4435:     } elsif (ref($store) eq 'SCALAR') {
 4436:         $items = &escape($$store).'=&';        
 4437:     } elsif (ref($store) eq 'ARRAY') {
 4438:         $items = join('=&',map {&escape($_);} @{$store});
 4439:     } elsif (ref($store) eq 'HASH') {
 4440:         while (my($key,$value) = each(%{$store})) {
 4441:             $items.= &escape($key).'='.&escape($value).'&';
 4442:         }
 4443:     }
 4444:     $items=~s/\&$//;
 4445:     if ($critical) {
 4446: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 4447:     } else {
 4448: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 4449:     }
 4450: }
 4451: 
 4452: # --------------------------------------------------------------- put interface
 4453: 
 4454: sub put {
 4455:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4456:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4457:    if (!$uname) { $uname=$env{'user.name'}; }
 4458:    my $uhome=&homeserver($uname,$udomain);
 4459:    my $items='';
 4460:    foreach my $item (keys(%$storehash)) {
 4461:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4462:    }
 4463:    $items=~s/\&$//;
 4464:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 4465: }
 4466: 
 4467: # ------------------------------------------------------------ newput interface
 4468: 
 4469: sub newput {
 4470:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4471:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4472:    if (!$uname) { $uname=$env{'user.name'}; }
 4473:    my $uhome=&homeserver($uname,$udomain);
 4474:    my $items='';
 4475:    foreach my $key (keys(%$storehash)) {
 4476:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4477:    }
 4478:    $items=~s/\&$//;
 4479:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 4480: }
 4481: 
 4482: # ---------------------------------------------------------  putstore interface
 4483: 
 4484: sub putstore {
 4485:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 4486:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4487:    if (!$uname) { $uname=$env{'user.name'}; }
 4488:    my $uhome=&homeserver($uname,$udomain);
 4489:    my $items='';
 4490:    foreach my $key (keys(%$storehash)) {
 4491:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 4492:    }
 4493:    $items=~s/\&$//;
 4494:    my $esc_symb=&escape($symb);
 4495:    my $esc_v=&escape($version);
 4496:    my $reply =
 4497:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 4498: 	      $uhome);
 4499:    if ($reply eq 'unknown_cmd') {
 4500:        # gfall back to way things use to be done
 4501:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 4502: 			    $uname);
 4503:    }
 4504:    return $reply;
 4505: }
 4506: 
 4507: sub old_putstore {
 4508:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 4509:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4510:     if (!$uname) { $uname=$env{'user.name'}; }
 4511:     my $uhome=&homeserver($uname,$udomain);
 4512:     my %newstorehash;
 4513:     foreach my $item (keys(%$storehash)) {
 4514: 	my $key = $version.':'.&escape($symb).':'.$item;
 4515: 	$newstorehash{$key} = $storehash->{$item};
 4516:     }
 4517:     my $items='';
 4518:     my %allitems = ();
 4519:     foreach my $item (keys(%newstorehash)) {
 4520: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 4521: 	    my $key = $1.':keys:'.$2;
 4522: 	    $allitems{$key} .= $3.':';
 4523: 	}
 4524: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 4525:     }
 4526:     foreach my $item (keys(%allitems)) {
 4527: 	$allitems{$item} =~ s/\:$//;
 4528: 	$items.= $item.'='.$allitems{$item}.'&';
 4529:     }
 4530:     $items=~s/\&$//;
 4531:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 4532: }
 4533: 
 4534: # ------------------------------------------------------ critical put interface
 4535: 
 4536: sub cput {
 4537:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4538:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4539:    if (!$uname) { $uname=$env{'user.name'}; }
 4540:    my $uhome=&homeserver($uname,$udomain);
 4541:    my $items='';
 4542:    foreach my $item (keys(%$storehash)) {
 4543:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4544:    }
 4545:    $items=~s/\&$//;
 4546:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 4547: }
 4548: 
 4549: # -------------------------------------------------------------- eget interface
 4550: 
 4551: sub eget {
 4552:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4553:    my $items='';
 4554:    foreach my $item (@$storearr) {
 4555:        $items.=&escape($item).'&';
 4556:    }
 4557:    $items=~s/\&$//;
 4558:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4559:    if (!$uname) { $uname=$env{'user.name'}; }
 4560:    my $uhome=&homeserver($uname,$udomain);
 4561:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 4562:    my @pairs=split(/\&/,$rep);
 4563:    my %returnhash=();
 4564:    my $i=0;
 4565:    foreach my $item (@$storearr) {
 4566:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 4567:       $i++;
 4568:    }
 4569:    return %returnhash;
 4570: }
 4571: 
 4572: # ------------------------------------------------------------ tmpput interface
 4573: sub tmpput {
 4574:     my ($storehash,$server,$context)=@_;
 4575:     my $items='';
 4576:     foreach my $item (keys(%$storehash)) {
 4577: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4578:     }
 4579:     $items=~s/\&$//;
 4580:     if (defined($context)) {
 4581:         $items .= ':'.&escape($context);
 4582:     }
 4583:     return &reply("tmpput:$items",$server);
 4584: }
 4585: 
 4586: # ------------------------------------------------------------ tmpget interface
 4587: sub tmpget {
 4588:     my ($token,$server)=@_;
 4589:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 4590:     my $rep=&reply("tmpget:$token",$server);
 4591:     my %returnhash;
 4592:     foreach my $item (split(/\&/,$rep)) {
 4593: 	my ($key,$value)=split(/=/,$item);
 4594:         next if ($key =~ /^error: 2 /);
 4595: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 4596:     }
 4597:     return %returnhash;
 4598: }
 4599: 
 4600: # ------------------------------------------------------------ tmpget interface
 4601: sub tmpdel {
 4602:     my ($token,$server)=@_;
 4603:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 4604:     return &reply("tmpdel:$token",$server);
 4605: }
 4606: 
 4607: # -------------------------------------------------- portfolio access checking
 4608: 
 4609: sub portfolio_access {
 4610:     my ($requrl) = @_;
 4611:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 4612:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 4613:     if ($result) {
 4614:         my %setters;
 4615:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4616:             my ($startblock,$endblock) =
 4617:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 4618:             if ($startblock && $endblock) {
 4619:                 return 'B';
 4620:             }
 4621:         } else {
 4622:             my ($startblock,$endblock) =
 4623:                 &Apache::loncommon::blockcheck(\%setters,'port');
 4624:             if ($startblock && $endblock) {
 4625:                 return 'B';
 4626:             }
 4627:         }
 4628:     }
 4629:     if ($result eq 'ok') {
 4630:        return 'F';
 4631:     } elsif ($result =~ /^[^:]+:guest_/) {
 4632:        return 'A';
 4633:     }
 4634:     return '';
 4635: }
 4636: 
 4637: sub get_portfolio_access {
 4638:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 4639: 
 4640:     if (!ref($access_hash)) {
 4641: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 4642: 	my %access_controls = &get_access_controls($current_perms,$group,
 4643: 						   $file_name);
 4644: 	$access_hash = $access_controls{$file_name};
 4645:     }
 4646: 
 4647:     my ($public,$guest,@domains,@users,@courses,@groups);
 4648:     my $now = time;
 4649:     if (ref($access_hash) eq 'HASH') {
 4650:         foreach my $key (keys(%{$access_hash})) {
 4651:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 4652:             if ($start > $now) {
 4653:                 next;
 4654:             }
 4655:             if ($end && $end<$now) {
 4656:                 next;
 4657:             }
 4658:             if ($scope eq 'public') {
 4659:                 $public = $key;
 4660:                 last;
 4661:             } elsif ($scope eq 'guest') {
 4662:                 $guest = $key;
 4663:             } elsif ($scope eq 'domains') {
 4664:                 push(@domains,$key);
 4665:             } elsif ($scope eq 'users') {
 4666:                 push(@users,$key);
 4667:             } elsif ($scope eq 'course') {
 4668:                 push(@courses,$key);
 4669:             } elsif ($scope eq 'group') {
 4670:                 push(@groups,$key);
 4671:             }
 4672:         }
 4673:         if ($public) {
 4674:             return 'ok';
 4675:         }
 4676:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4677:             if ($guest) {
 4678:                 return $guest;
 4679:             }
 4680:         } else {
 4681:             if (@domains > 0) {
 4682:                 foreach my $domkey (@domains) {
 4683:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 4684:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 4685:                             return 'ok';
 4686:                         }
 4687:                     }
 4688:                 }
 4689:             }
 4690:             if (@users > 0) {
 4691:                 foreach my $userkey (@users) {
 4692:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 4693:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 4694:                             if (ref($item) eq 'HASH') {
 4695:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 4696:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 4697:                                     return 'ok';
 4698:                                 }
 4699:                             }
 4700:                         }
 4701:                     } 
 4702:                 }
 4703:             }
 4704:             my %roleshash;
 4705:             my @courses_and_groups = @courses;
 4706:             push(@courses_and_groups,@groups); 
 4707:             if (@courses_and_groups > 0) {
 4708:                 my (%allgroups,%allroles); 
 4709:                 my ($start,$end,$role,$sec,$group);
 4710:                 foreach my $envkey (%env) {
 4711:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4712:                         my $cid = $2.'_'.$3; 
 4713:                         if ($1 eq 'gr') {
 4714:                             $group = $4;
 4715:                             $allgroups{$cid}{$group} = $env{$envkey};
 4716:                         } else {
 4717:                             if ($4 eq '') {
 4718:                                 $sec = 'none';
 4719:                             } else {
 4720:                                 $sec = $4;
 4721:                             }
 4722:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4723:                         }
 4724:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4725:                         my $cid = $2.'_'.$3;
 4726:                         if ($4 eq '') {
 4727:                             $sec = 'none';
 4728:                         } else {
 4729:                             $sec = $4;
 4730:                         }
 4731:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4732:                     }
 4733:                 }
 4734:                 if (keys(%allroles) == 0) {
 4735:                     return;
 4736:                 }
 4737:                 foreach my $key (@courses_and_groups) {
 4738:                     my %content = %{$$access_hash{$key}};
 4739:                     my $cnum = $content{'number'};
 4740:                     my $cdom = $content{'domain'};
 4741:                     my $cid = $cdom.'_'.$cnum;
 4742:                     if (!exists($allroles{$cid})) {
 4743:                         next;
 4744:                     }    
 4745:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 4746:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 4747:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 4748:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 4749:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 4750:                         foreach my $role (keys(%{$allroles{$cid}})) {
 4751:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 4752:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 4753:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 4754:                                         if (grep/^all$/,@sections) {
 4755:                                             return 'ok';
 4756:                                         } else {
 4757:                                             if (grep/^$sec$/,@sections) {
 4758:                                                 return 'ok';
 4759:                                             }
 4760:                                         }
 4761:                                     }
 4762:                                 }
 4763:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 4764:                                     if (grep/^none$/,@groups) {
 4765:                                         return 'ok';
 4766:                                     }
 4767:                                 } else {
 4768:                                     if (grep/^all$/,@groups) {
 4769:                                         return 'ok';
 4770:                                     } 
 4771:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 4772:                                         if (grep/^$group$/,@groups) {
 4773:                                             return 'ok';
 4774:                                         }
 4775:                                     }
 4776:                                 } 
 4777:                             }
 4778:                         }
 4779:                     }
 4780:                 }
 4781:             }
 4782:             if ($guest) {
 4783:                 return $guest;
 4784:             }
 4785:         }
 4786:     }
 4787:     return;
 4788: }
 4789: 
 4790: sub course_group_datechecker {
 4791:     my ($dates,$now,$status) = @_;
 4792:     my ($start,$end) = split(/\./,$dates);
 4793:     if (!$start && !$end) {
 4794:         return 'ok';
 4795:     }
 4796:     if (grep/^active$/,@{$status}) {
 4797:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 4798:             return 'ok';
 4799:         }
 4800:     }
 4801:     if (grep/^previous$/,@{$status}) {
 4802:         if ($end > $now ) {
 4803:             return 'ok';
 4804:         }
 4805:     }
 4806:     if (grep/^future$/,@{$status}) {
 4807:         if ($start > $now) {
 4808:             return 'ok';
 4809:         }
 4810:     }
 4811:     return; 
 4812: }
 4813: 
 4814: sub parse_portfolio_url {
 4815:     my ($url) = @_;
 4816: 
 4817:     my ($type,$udom,$unum,$group,$file_name);
 4818:     
 4819:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 4820: 	$type = 1;
 4821:         $udom = $1;
 4822:         $unum = $2;
 4823:         $file_name = $3;
 4824:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 4825: 	$type = 2;
 4826:         $udom = $1;
 4827:         $unum = $2;
 4828:         $group = $3;
 4829:         $file_name = $3.'/'.$4;
 4830:     }
 4831:     if (wantarray) {
 4832: 	return ($type,$udom,$unum,$file_name,$group);
 4833:     }
 4834:     return $type;
 4835: }
 4836: 
 4837: sub is_portfolio_url {
 4838:     my ($url) = @_;
 4839:     return scalar(&parse_portfolio_url($url));
 4840: }
 4841: 
 4842: sub is_portfolio_file {
 4843:     my ($file) = @_;
 4844:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 4845:         return 1;
 4846:     }
 4847:     return;
 4848: }
 4849: 
 4850: sub usertools_access {
 4851:     my ($uname,$udom,$tool,$action,$context) = @_;
 4852:     my ($access,%tools);
 4853:     if ($context eq '') {
 4854:         $context = 'tools';
 4855:     }
 4856:     if ($context eq 'requestcourses') {
 4857:         %tools = (
 4858:                       official   => 1,
 4859:                       unofficial => 1,
 4860:                       community  => 1,
 4861:                  );
 4862:     } else {
 4863:         %tools = (
 4864:                       aboutme   => 1,
 4865:                       blog      => 1,
 4866:                       portfolio => 1,
 4867:                  );
 4868:     }
 4869:     return if (!defined($tools{$tool}));
 4870: 
 4871:     if ((!defined($udom)) || (!defined($uname))) {
 4872:         $udom = $env{'user.domain'};
 4873:         $uname = $env{'user.name'};
 4874:     }
 4875: 
 4876:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 4877:         if ($action ne 'reload') {
 4878:             if ($context eq 'requestcourses') {
 4879:                 return $env{'environment.canrequest.'.$tool};
 4880:             } else {
 4881:                 return $env{'environment.availabletools.'.$tool};
 4882:             }
 4883:         }
 4884:     }
 4885: 
 4886:     my ($toolstatus,$inststatus);
 4887: 
 4888:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
 4889:          ($action ne 'reload')) {
 4890:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
 4891:         $inststatus = $env{'environment.inststatus'};
 4892:     } else {
 4893:         my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
 4894:         $toolstatus = $userenv{$context.'.'.$tool};
 4895:         $inststatus = $userenv{'inststatus'};
 4896:     }
 4897: 
 4898:     if ($toolstatus ne '') {
 4899:         if ($toolstatus) {
 4900:             $access = 1;
 4901:         } else {
 4902:             $access = 0;
 4903:         }
 4904:         return $access;
 4905:     }
 4906: 
 4907:     my $is_adv = &is_advanced_user($udom,$uname);
 4908:     my %domdef = &get_domain_defaults($udom);
 4909:     if (ref($domdef{$tool}) eq 'HASH') {
 4910:         if ($is_adv) {
 4911:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 4912:                 if ($domdef{$tool}{'_LC_adv'}) { 
 4913:                     $access = 1;
 4914:                 } else {
 4915:                     $access = 0;
 4916:                 }
 4917:                 return $access;
 4918:             }
 4919:         }
 4920:         if ($inststatus ne '') {
 4921:             my ($hasaccess,$hasnoaccess);
 4922:             foreach my $affiliation (split(/:/,$inststatus)) {
 4923:                 if ($domdef{$tool}{$affiliation} ne '') { 
 4924:                     if ($domdef{$tool}{$affiliation}) {
 4925:                         $hasaccess = 1;
 4926:                     } else {
 4927:                         $hasnoaccess = 1;
 4928:                     }
 4929:                 }
 4930:             }
 4931:             if ($hasaccess || $hasnoaccess) {
 4932:                 if ($hasaccess) {
 4933:                     $access = 1;
 4934:                 } elsif ($hasnoaccess) {
 4935:                     $access = 0; 
 4936:                 }
 4937:                 return $access;
 4938:             }
 4939:         } else {
 4940:             if ($domdef{$tool}{'default'} ne '') {
 4941:                 if ($domdef{$tool}{'default'}) {
 4942:                     $access = 1;
 4943:                 } elsif ($domdef{$tool}{'default'} == 0) {
 4944:                     $access = 0;
 4945:                 }
 4946:                 return $access;
 4947:             }
 4948:         }
 4949:     } else {
 4950:         if ($context eq 'tools') {
 4951:             $access = 1;
 4952:         } else {
 4953:             $access = 0;
 4954:         }
 4955:         return $access;
 4956:     }
 4957: }
 4958: 
 4959: sub is_course_owner {
 4960:     my ($cdom,$cnum,$udom,$uname) = @_;
 4961:     if (($udom eq '') || ($uname eq '')) {
 4962:         $udom = $env{'user.domain'};
 4963:         $uname = $env{'user.name'};
 4964:     }
 4965:     unless (($udom eq '') || ($uname eq '')) {
 4966:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
 4967:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
 4968:                 return 1;
 4969:             } else {
 4970:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
 4971:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
 4972:                     return 1;
 4973:                 }
 4974:             }
 4975:         }
 4976:     }
 4977:     return;
 4978: }
 4979: 
 4980: sub is_advanced_user {
 4981:     my ($udom,$uname) = @_;
 4982:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 4983:     my %allroles;
 4984:     my $is_adv;
 4985:     foreach my $role (keys(%roleshash)) {
 4986:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 4987:         my $area = '/'.$tdomain.'/'.$trest;
 4988:         if ($sec ne '') {
 4989:             $area .= '/'.$sec;
 4990:         }
 4991:         if (($area ne '') && ($trole ne '')) {
 4992:             my $spec=$trole.'.'.$area;
 4993:             if ($trole =~ /^cr\//) {
 4994:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 4995:             } elsif ($trole ne 'gr') {
 4996:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 4997:             }
 4998:         }
 4999:     }
 5000:     foreach my $role (keys(%allroles)) {
 5001:         last if ($is_adv);
 5002:         foreach my $item (split(/:/,$allroles{$role})) {
 5003:             if ($item ne '') {
 5004:                 my ($privilege,$restrictions)=split(/&/,$item);
 5005:                 if ($privilege eq 'adv') {
 5006:                     $is_adv = 1;
 5007:                     last;
 5008:                 }
 5009:             }
 5010:         }
 5011:     }
 5012:     return $is_adv;
 5013: }
 5014: 
 5015: sub check_can_request {
 5016:     my ($dom,$can_request,$request_domains) = @_;
 5017:     my $canreq = 0;
 5018:     my ($types,$typename) = &Apache::loncommon::course_types();
 5019:     my @options = ('approval','validate','autolimit');
 5020:     my $optregex = join('|',@options);
 5021:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
 5022:         foreach my $type (@{$types}) {
 5023:             if (&usertools_access($env{'user.name'},
 5024:                                   $env{'user.domain'},
 5025:                                   $type,undef,'requestcourses')) {
 5026:                 $canreq ++;
 5027:                 if (ref($request_domains) eq 'HASH') {
 5028:                     push(@{$request_domains->{$type}},$env{'user.domain'});
 5029:                 }
 5030:                 if ($dom eq $env{'user.domain'}) {
 5031:                     $can_request->{$type} = 1;
 5032:                 }
 5033:             }
 5034:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
 5035:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
 5036:                 if (@curr > 0) {
 5037:                     foreach my $item (@curr) {
 5038:                         if (ref($request_domains) eq 'HASH') {
 5039:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
 5040:                             if ($otherdom ne '') {
 5041:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
 5042:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
 5043:                                         push(@{$request_domains->{$type}},$otherdom);
 5044:                                     }
 5045:                                 } else {
 5046:                                     push(@{$request_domains->{$type}},$otherdom);
 5047:                                 }
 5048:                             }
 5049:                         }
 5050:                     }
 5051:                     unless($dom eq $env{'user.domain'}) {
 5052:                         $canreq ++;
 5053:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
 5054:                             $can_request->{$type} = 1;
 5055:                         }
 5056:                     }
 5057:                 }
 5058:             }
 5059:         }
 5060:     }
 5061:     return $canreq;
 5062: }
 5063: 
 5064: # ---------------------------------------------- Custom access rule evaluation
 5065: 
 5066: sub customaccess {
 5067:     my ($priv,$uri)=@_;
 5068:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 5069:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 5070:     $udom = &LONCAPA::clean_domain($udom);
 5071:     $ucrs = &LONCAPA::clean_username($ucrs);
 5072:     my $access=0;
 5073:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 5074: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 5075: 	if ($type eq 'user') {
 5076: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 5077: 		my ($tdom,$tuname)=split(m{/},$scope);
 5078: 		if ($tdom) {
 5079: 		    if ($tdom ne $env{'user.domain'}) { next; }
 5080: 		}
 5081: 		if ($tuname) {
 5082: 		    if ($tuname ne $env{'user.name'}) { next; }
 5083: 		}
 5084: 		$access=($effect eq 'allow');
 5085: 		last;
 5086: 	    }
 5087: 	} else {
 5088: 	    if ($role) {
 5089: 		if ($role ne $urole) { next; }
 5090: 	    }
 5091: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 5092: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 5093: 		if ($tdom) {
 5094: 		    if ($tdom ne $udom) { next; }
 5095: 		}
 5096: 		if ($tcrs) {
 5097: 		    if ($tcrs ne $ucrs) { next; }
 5098: 		}
 5099: 		if ($tsec) {
 5100: 		    if ($tsec ne $usec) { next; }
 5101: 		}
 5102: 		$access=($effect eq 'allow');
 5103: 		last;
 5104: 	    }
 5105: 	    if ($realm eq '' && $role eq '') {
 5106: 		$access=($effect eq 'allow');
 5107: 	    }
 5108: 	}
 5109:     }
 5110:     return $access;
 5111: }
 5112: 
 5113: # ------------------------------------------------- Check for a user privilege
 5114: 
 5115: sub allowed {
 5116:     my ($priv,$uri,$symb,$role)=@_;
 5117:     my $ver_orguri=$uri;
 5118:     $uri=&deversion($uri);
 5119:     my $orguri=$uri;
 5120:     $uri=&declutter($uri);
 5121: 
 5122:     if ($priv eq 'evb') {
 5123: # Evade communication block restrictions for specified role in a course
 5124:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 5125:             return $1;
 5126:         } else {
 5127:             return;
 5128:         }
 5129:     }
 5130: 
 5131:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 5132: # Free bre access to adm and meta resources
 5133:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 5134: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 5135: 	&& ($priv eq 'bre')) {
 5136: 	return 'F';
 5137:     }
 5138: 
 5139: # Free bre access to user's own portfolio contents
 5140:     my ($space,$domain,$name,@dir)=split('/',$uri);
 5141:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 5142: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 5143:         my %setters;
 5144:         my ($startblock,$endblock) = 
 5145:             &Apache::loncommon::blockcheck(\%setters,'port');
 5146:         if ($startblock && $endblock) {
 5147:             return 'B';
 5148:         } else {
 5149:             return 'F';
 5150:         }
 5151:     }
 5152: 
 5153: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 5154:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 5155:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 5156:         if (exists($env{'request.course.id'})) {
 5157:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 5158:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 5159:             if (($domain eq $cdom) && ($name eq $cnum)) {
 5160:                 my $courseprivid=$env{'request.course.id'};
 5161:                 $courseprivid=~s/\_/\//;
 5162:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 5163:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 5164:                     return $1; 
 5165:                 } else {
 5166:                     if ($env{'request.course.sec'}) {
 5167:                         $courseprivid.='/'.$env{'request.course.sec'};
 5168:                     }
 5169:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 5170:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 5171:                         return $2;
 5172:                     }
 5173:                 }
 5174:             }
 5175:         }
 5176:     }
 5177: 
 5178: # Free bre to public access
 5179: 
 5180:     if ($priv eq 'bre') {
 5181:         my $copyright=&metadata($uri,'copyright');
 5182: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 5183:            return 'F'; 
 5184:         }
 5185:         if ($copyright eq 'priv') {
 5186:             $uri=~/([^\/]+)\/([^\/]+)\//;
 5187: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 5188: 		return '';
 5189:             }
 5190:         }
 5191:         if ($copyright eq 'domain') {
 5192:             $uri=~/([^\/]+)\/([^\/]+)\//;
 5193: 	    unless (($env{'user.domain'} eq $1) ||
 5194:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 5195: 		return '';
 5196:             }
 5197:         }
 5198:         if ($env{'request.role'}=~ /li\.\//) {
 5199:             # Library role, so allow browsing of resources in this domain.
 5200:             return 'F';
 5201:         }
 5202:         if ($copyright eq 'custom') {
 5203: 	    unless (&customaccess($priv,$uri)) { return ''; }
 5204:         }
 5205:     }
 5206:     # Domain coordinator is trying to create a course
 5207:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 5208:         # uri is the requested domain in this case.
 5209:         # comparison to 'request.role.domain' shows if the user has selected
 5210:         # a role of dc for the domain in question.
 5211:         return 'F' if ($uri eq $env{'request.role.domain'});
 5212:     }
 5213: 
 5214:     my $thisallowed='';
 5215:     my $statecond=0;
 5216:     my $courseprivid='';
 5217: 
 5218:     my $ownaccess;
 5219:     # Community Coordinator or Assistant Co-author browsing resource space.
 5220:     if (($priv eq 'bro') && ($env{'user.author'})) {
 5221:         if ($uri eq '') {
 5222:             $ownaccess = 1;
 5223:         } else {
 5224:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
 5225:                 my $udom = $env{'user.domain'};
 5226:                 my $uname = $env{'user.name'};
 5227:                 if ($uri =~ m{^\Q$udom\E/?$}) {
 5228:                     $ownaccess = 1;
 5229:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
 5230:                     unless ($uri =~ m{\.\./}) {
 5231:                         $ownaccess = 1;
 5232:                     }
 5233:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
 5234:                     my $now = time;
 5235:                     if ($uri =~ m{^([^/]+)/?$}) {
 5236:                         my $adom = $1;
 5237:                         foreach my $key (keys(%env)) {
 5238:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
 5239:                                 my ($start,$end) = split('.',$env{$key});
 5240:                                 if (($now >= $start) && (!$end || $end < $now)) {
 5241:                                     $ownaccess = 1;
 5242:                                     last;
 5243:                                 }
 5244:                             }
 5245:                         }
 5246:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
 5247:                         my $adom = $1;
 5248:                         my $aname = $2;
 5249:                         foreach my $role ('ca','aa') { 
 5250:                             if ($env{"user.role.$role./$adom/$aname"}) {
 5251:                                 my ($start,$end) =
 5252:                                     split('.',$env{"user.role.$role./$adom/$aname"});
 5253:                                 if (($now >= $start) && (!$end || $end < $now)) {
 5254:                                     $ownaccess = 1;
 5255:                                     last;
 5256:                                 }
 5257:                             }
 5258:                         }
 5259:                     }
 5260:                 }
 5261:             }
 5262:         }
 5263:     }
 5264: 
 5265: # Course
 5266: 
 5267:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 5268:         unless (($priv eq 'bro') && (!$ownaccess)) {
 5269:             $thisallowed.=$1;
 5270:         }
 5271:     }
 5272: 
 5273: # Domain
 5274: 
 5275:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 5276:        =~/\Q$priv\E\&([^\:]*)/) {
 5277:         unless (($priv eq 'bro') && (!$ownaccess)) {
 5278:             $thisallowed.=$1;
 5279:         }
 5280:     }
 5281: 
 5282: # Course: uri itself is a course
 5283:     my $courseuri=$uri;
 5284:     $courseuri=~s/\_(\d)/\/$1/;
 5285:     $courseuri=~s/^([^\/])/\/$1/;
 5286: 
 5287:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 5288:        =~/\Q$priv\E\&([^\:]*)/) {
 5289:         unless (($priv eq 'bro') && (!$ownaccess)) {
 5290:             $thisallowed.=$1;
 5291:         }
 5292:     }
 5293: 
 5294: # URI is an uploaded document for this course, default permissions don't matter
 5295: # not allowing 'edit' access (editupload) to uploaded course docs
 5296:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 5297: 	$thisallowed='';
 5298:         my ($match)=&is_on_map($uri);
 5299:         if ($match) {
 5300:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 5301:                   =~/\Q$priv\E\&([^\:]*)/) {
 5302:                 $thisallowed.=$1;
 5303:             }
 5304:         } else {
 5305:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 5306:             if ($refuri) {
 5307:                 if ($refuri =~ m|^/adm/|) {
 5308:                     $thisallowed='F';
 5309:                 } else {
 5310:                     $refuri=&declutter($refuri);
 5311:                     my ($match) = &is_on_map($refuri);
 5312:                     if ($match) {
 5313:                         $thisallowed='F';
 5314:                     }
 5315:                 }
 5316:             }
 5317:         }
 5318:     }
 5319: 
 5320:     if ($priv eq 'bre'
 5321: 	&& $thisallowed ne 'F' 
 5322: 	&& $thisallowed ne '2'
 5323: 	&& &is_portfolio_url($uri)) {
 5324: 	$thisallowed = &portfolio_access($uri);
 5325:     }
 5326:     
 5327: # Full access at system, domain or course-wide level? Exit.
 5328:     if ($thisallowed=~/F/) {
 5329: 	return 'F';
 5330:     }
 5331: 
 5332: # If this is generating or modifying users, exit with special codes
 5333: 
 5334:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 5335: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 5336: 	    my ($audom,$auname)=split('/',$uri);
 5337: # no author name given, so this just checks on the general right to make a co-author in this domain
 5338: 	    unless ($auname) { return $thisallowed; }
 5339: # an author name is given, so we are about to actually make a co-author for a certain account
 5340: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 5341: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 5342: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 5343: 	}
 5344: 	return $thisallowed;
 5345:     }
 5346: #
 5347: # Gathered so far: system, domain and course wide privileges
 5348: #
 5349: # Course: See if uri or referer is an individual resource that is part of 
 5350: # the course
 5351: 
 5352:     if ($env{'request.course.id'}) {
 5353: 
 5354:        $courseprivid=$env{'request.course.id'};
 5355:        if ($env{'request.course.sec'}) {
 5356:           $courseprivid.='/'.$env{'request.course.sec'};
 5357:        }
 5358:        $courseprivid=~s/\_/\//;
 5359:        my $checkreferer=1;
 5360:        my ($match,$cond)=&is_on_map($uri);
 5361:        if ($match) {
 5362:            $statecond=$cond;
 5363:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 5364:                =~/\Q$priv\E\&([^\:]*)/) {
 5365:                $thisallowed.=$1;
 5366:                $checkreferer=0;
 5367:            }
 5368:        }
 5369:        
 5370:        if ($checkreferer) {
 5371: 	  my $refuri=$env{'httpref.'.$orguri};
 5372:             unless ($refuri) {
 5373:                 foreach my $key (keys(%env)) {
 5374: 		    if ($key=~/^httpref\..*\*/) {
 5375: 			my $pattern=$key;
 5376:                         $pattern=~s/^httpref\.\/res\///;
 5377:                         $pattern=~s/\*/\[\^\/\]\+/g;
 5378:                         $pattern=~s/\//\\\//g;
 5379:                         if ($orguri=~/$pattern/) {
 5380: 			    $refuri=$env{$key};
 5381:                         }
 5382:                     }
 5383:                 }
 5384:             }
 5385: 
 5386:          if ($refuri) { 
 5387: 	  $refuri=&declutter($refuri);
 5388:           my ($match,$cond)=&is_on_map($refuri);
 5389:             if ($match) {
 5390:               my $refstatecond=$cond;
 5391:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 5392:                   =~/\Q$priv\E\&([^\:]*)/) {
 5393:                   $thisallowed.=$1;
 5394:                   $uri=$refuri;
 5395:                   $statecond=$refstatecond;
 5396:               }
 5397:           }
 5398:         }
 5399:        }
 5400:    }
 5401: 
 5402: #
 5403: # Gathered now: all privileges that could apply, and condition number
 5404: # 
 5405: #
 5406: # Full or no access?
 5407: #
 5408: 
 5409:     if ($thisallowed=~/F/) {
 5410: 	return 'F';
 5411:     }
 5412: 
 5413:     unless ($thisallowed) {
 5414:         return '';
 5415:     }
 5416: 
 5417: # Restrictions exist, deal with them
 5418: #
 5419: #   C:according to course preferences
 5420: #   R:according to resource settings
 5421: #   L:unless locked
 5422: #   X:according to user session state
 5423: #
 5424: 
 5425: # Possibly locked functionality, check all courses
 5426: # Locks might take effect only after 10 minutes cache expiration for other
 5427: # courses, and 2 minutes for current course
 5428: 
 5429:     my $envkey;
 5430:     if ($thisallowed=~/L/) {
 5431:         foreach $envkey (keys(%env)) {
 5432:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 5433:                my $courseid=$2;
 5434:                my $roleid=$1.'.'.$2;
 5435:                $courseid=~s/^\///;
 5436:                my $expiretime=600;
 5437:                if ($env{'request.role'} eq $roleid) {
 5438: 		  $expiretime=120;
 5439:                }
 5440: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 5441:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 5442:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 5443: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 5444:                }
 5445:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 5446:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 5447: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 5448:                        &log($env{'user.domain'},$env{'user.name'},
 5449:                             $env{'user.home'},
 5450:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 5451:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 5452:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 5453: 		       return '';
 5454:                    }
 5455:                }
 5456:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 5457:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 5458: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 5459:                        &log($env{'user.domain'},$env{'user.name'},
 5460:                             $env{'user.home'},
 5461:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 5462:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 5463:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 5464: 		       return '';
 5465:                    }
 5466:                }
 5467: 	   }
 5468:        }
 5469:     }
 5470:    
 5471: #
 5472: # Rest of the restrictions depend on selected course
 5473: #
 5474: 
 5475:     unless ($env{'request.course.id'}) {
 5476: 	if ($thisallowed eq 'A') {
 5477: 	    return 'A';
 5478:         } elsif ($thisallowed eq 'B') {
 5479:             return 'B';
 5480: 	} else {
 5481: 	    return '1';
 5482: 	}
 5483:     }
 5484: 
 5485: #
 5486: # Now user is definitely in a course
 5487: #
 5488: 
 5489: 
 5490: # Course preferences
 5491: 
 5492:    if ($thisallowed=~/C/) {
 5493:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 5494:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 5495:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 5496: 	   =~/\Q$rolecode\E/) {
 5497: 	   if ($priv ne 'pch') { 
 5498: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 5499: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 5500: 			$env{'request.course.id'});
 5501: 	   }
 5502:            return '';
 5503:        }
 5504: 
 5505:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 5506: 	   =~/\Q$unamedom\E/) {
 5507: 	   if ($priv ne 'pch') { 
 5508: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 5509: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 5510: 			$env{'request.course.id'});
 5511: 	   }
 5512:            return '';
 5513:        }
 5514:    }
 5515: 
 5516: # Resource preferences
 5517: 
 5518:    if ($thisallowed=~/R/) {
 5519:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 5520:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 5521: 	   if ($priv ne 'pch') { 
 5522: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 5523: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 5524: 	   }
 5525: 	   return '';
 5526:        }
 5527:    }
 5528: 
 5529: # Restricted by state or randomout?
 5530: 
 5531:    if ($thisallowed=~/X/) {
 5532:       if ($env{'acc.randomout'}) {
 5533: 	 if (!$symb) { $symb=&symbread($uri,1); }
 5534:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 5535:             return ''; 
 5536:          }
 5537:       }
 5538:       if (&condval($statecond)) {
 5539: 	 return '2';
 5540:       } else {
 5541:          return '';
 5542:       }
 5543:    }
 5544: 
 5545:     if ($thisallowed eq 'A') {
 5546: 	return 'A';
 5547:     } elsif ($thisallowed eq 'B') {
 5548:         return 'B';
 5549:     }
 5550:    return 'F';
 5551: }
 5552: 
 5553: sub split_uri_for_cond {
 5554:     my $uri=&deversion(&declutter(shift));
 5555:     my @uriparts=split(/\//,$uri);
 5556:     my $filename=pop(@uriparts);
 5557:     my $pathname=join('/',@uriparts);
 5558:     return ($pathname,$filename);
 5559: }
 5560: # --------------------------------------------------- Is a resource on the map?
 5561: 
 5562: sub is_on_map {
 5563:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 5564:     #Trying to find the conditional for the file
 5565:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 5566: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 5567:     if ($match) {
 5568: 	return (1,$1);
 5569:     } else {
 5570: 	return (0,0);
 5571:     }
 5572: }
 5573: 
 5574: # --------------------------------------------------------- Get symb from alias
 5575: 
 5576: sub get_symb_from_alias {
 5577:     my $symb=shift;
 5578:     my ($map,$resid,$url)=&decode_symb($symb);
 5579: # Already is a symb
 5580:     if ($url) { return $symb; }
 5581: # Must be an alias
 5582:     my $aliassymb='';
 5583:     my %bighash;
 5584:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 5585:                             &GDBM_READER(),0640)) {
 5586:         my $rid=$bighash{'mapalias_'.$symb};
 5587: 	if ($rid) {
 5588: 	    my ($mapid,$resid)=split(/\./,$rid);
 5589: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 5590: 				    $resid,$bighash{'src_'.$rid});
 5591: 	}
 5592:         untie %bighash;
 5593:     }
 5594:     return $aliassymb;
 5595: }
 5596: 
 5597: # ----------------------------------------------------------------- Define Role
 5598: 
 5599: sub definerole {
 5600:   if (allowed('mcr','/')) {
 5601:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 5602:     foreach my $role (split(':',$sysrole)) {
 5603: 	my ($crole,$cqual)=split(/\&/,$role);
 5604:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 5605:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 5606: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 5607:                return "refused:s:$crole&$cqual"; 
 5608:             }
 5609:         }
 5610:     }
 5611:     foreach my $role (split(':',$domrole)) {
 5612: 	my ($crole,$cqual)=split(/\&/,$role);
 5613:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 5614:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 5615: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 5616:                return "refused:d:$crole&$cqual"; 
 5617:             }
 5618:         }
 5619:     }
 5620:     foreach my $role (split(':',$courole)) {
 5621: 	my ($crole,$cqual)=split(/\&/,$role);
 5622:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 5623:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 5624: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 5625:                return "refused:c:$crole&$cqual"; 
 5626:             }
 5627:         }
 5628:     }
 5629:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 5630:                 "$env{'user.domain'}:$env{'user.name'}:".
 5631: 	        "rolesdef_$rolename=".
 5632:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 5633:     return reply($command,$env{'user.home'});
 5634:   } else {
 5635:     return 'refused';
 5636:   }
 5637: }
 5638: 
 5639: # ---------------- Make a metadata query against the network of library servers
 5640: 
 5641: sub metadata_query {
 5642:     my ($query,$custom,$customshow,$server_array)=@_;
 5643:     my %rhash;
 5644:     my %libserv = &all_library();
 5645:     my @server_list = (defined($server_array) ? @$server_array
 5646:                                               : keys(%libserv) );
 5647:     for my $server (@server_list) {
 5648: 	unless ($custom or $customshow) {
 5649: 	    my $reply=&reply("querysend:".&escape($query),$server);
 5650: 	    $rhash{$server}=$reply;
 5651: 	}
 5652: 	else {
 5653: 	    my $reply=&reply("querysend:".&escape($query).':'.
 5654: 			     &escape($custom).':'.&escape($customshow),
 5655: 			     $server);
 5656: 	    $rhash{$server}=$reply;
 5657: 	}
 5658:     }
 5659:     return \%rhash;
 5660: }
 5661: 
 5662: # ----------------------------------------- Send log queries and wait for reply
 5663: 
 5664: sub log_query {
 5665:     my ($uname,$udom,$query,%filters)=@_;
 5666:     my $uhome=&homeserver($uname,$udom);
 5667:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 5668:     my $uhost=&hostname($uhome);
 5669:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 5670:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 5671:                        $uhome);
 5672:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 5673:     return get_query_reply($queryid);
 5674: }
 5675: 
 5676: # -------------------------- Update MySQL table for portfolio file
 5677: 
 5678: sub update_portfolio_table {
 5679:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 5680:     if ($group ne '') {
 5681:         $file_name =~s /^\Q$group\E//;
 5682:     }
 5683:     my $homeserver = &homeserver($uname,$udom);
 5684:     my $queryid=
 5685:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 5686:                ':'.&escape($file_name).':'.$action,$homeserver);
 5687:     my $reply = &get_query_reply($queryid);
 5688:     return $reply;
 5689: }
 5690: 
 5691: # -------------------------- Update MySQL allusers table
 5692: 
 5693: sub update_allusers_table {
 5694:     my ($uname,$udom,$names) = @_;
 5695:     my $homeserver = &homeserver($uname,$udom);
 5696:     my $queryid=
 5697:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 5698:                'lastname='.&escape($names->{'lastname'}).'%%'.
 5699:                'firstname='.&escape($names->{'firstname'}).'%%'.
 5700:                'middlename='.&escape($names->{'middlename'}).'%%'.
 5701:                'generation='.&escape($names->{'generation'}).'%%'.
 5702:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 5703:                'id='.&escape($names->{'id'}),$homeserver);
 5704:     return;
 5705: }
 5706: 
 5707: # ------- Request retrieval of institutional classlists for course(s)
 5708: 
 5709: sub fetch_enrollment_query {
 5710:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 5711:     my $homeserver;
 5712:     my $maxtries = 1;
 5713:     if ($context eq 'automated') {
 5714:         $homeserver = $perlvar{'lonHostID'};
 5715:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 5716:     } else {
 5717:         $homeserver = &homeserver($cnum,$dom);
 5718:     }
 5719:     my $host=&hostname($homeserver);
 5720:     my $cmd = '';
 5721:     foreach my $affiliate (keys(%{$affiliatesref})) {
 5722:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5723:     }
 5724:     $cmd =~ s/%%$//;
 5725:     $cmd = &escape($cmd);
 5726:     my $query = 'fetchenrollment';
 5727:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 5728:     unless ($queryid=~/^\Q$host\E\_/) { 
 5729:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 5730:         return 'error: '.$queryid;
 5731:     }
 5732:     my $reply = &get_query_reply($queryid);
 5733:     my $tries = 1;
 5734:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5735:         $reply = &get_query_reply($queryid);
 5736:         $tries ++;
 5737:     }
 5738:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5739:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5740:     } else {
 5741:         my @responses = split(/:/,$reply);
 5742:         if ($homeserver eq $perlvar{'lonHostID'}) {
 5743:             foreach my $line (@responses) {
 5744:                 my ($key,$value) = split(/=/,$line,2);
 5745:                 $$replyref{$key} = $value;
 5746:             }
 5747:         } else {
 5748:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 5749:             foreach my $line (@responses) {
 5750:                 my ($key,$value) = split(/=/,$line);
 5751:                 $$replyref{$key} = $value;
 5752:                 if ($value > 0) {
 5753:                     foreach my $item (@{$$affiliatesref{$key}}) {
 5754:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 5755:                         my $destname = $pathname.'/'.$filename;
 5756:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 5757:                         if ($xml_classlist =~ /^error/) {
 5758:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 5759:                         } else {
 5760:                             if ( open(FILE,">$destname") ) {
 5761:                                 print FILE &unescape($xml_classlist);
 5762:                                 close(FILE);
 5763:                             } else {
 5764:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 5765:                             }
 5766:                         }
 5767:                     }
 5768:                 }
 5769:             }
 5770:         }
 5771:         return 'ok';
 5772:     }
 5773:     return 'error';
 5774: }
 5775: 
 5776: sub get_query_reply {
 5777:     my $queryid=shift;
 5778:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 5779:     my $reply='';
 5780:     for (1..100) {
 5781: 	sleep 2;
 5782:         if (-e $replyfile.'.end') {
 5783: 	    if (open(my $fh,$replyfile)) {
 5784: 		$reply = join('',<$fh>);
 5785: 		close($fh);
 5786: 	   } else { return 'error: reply_file_error'; }
 5787:            return &unescape($reply);
 5788: 	}
 5789:     }
 5790:     return 'timeout:'.$queryid;
 5791: }
 5792: 
 5793: sub courselog_query {
 5794: #
 5795: # possible filters:
 5796: # url: url or symb
 5797: # username
 5798: # domain
 5799: # action: view, submit, grade
 5800: # start: timestamp
 5801: # end: timestamp
 5802: #
 5803:     my (%filters)=@_;
 5804:     unless ($env{'request.course.id'}) { return 'no_course'; }
 5805:     if ($filters{'url'}) {
 5806: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 5807:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 5808:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 5809:     }
 5810:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5811:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5812:     return &log_query($cname,$cdom,'courselog',%filters);
 5813: }
 5814: 
 5815: sub userlog_query {
 5816: #
 5817: # possible filters:
 5818: # action: log check role
 5819: # start: timestamp
 5820: # end: timestamp
 5821: #
 5822:     my ($uname,$udom,%filters)=@_;
 5823:     return &log_query($uname,$udom,'userlog',%filters);
 5824: }
 5825: 
 5826: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 5827: 
 5828: sub auto_run {
 5829:     my ($cnum,$cdom) = @_;
 5830:     my $response = 0;
 5831:     my $settings;
 5832:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 5833:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 5834:         $settings = $domconfig{'autoenroll'};
 5835:         if ($settings->{'run'} eq '1') {
 5836:             $response = 1;
 5837:         }
 5838:     } else {
 5839:         my $homeserver;
 5840:         if (&is_course($cdom,$cnum)) {
 5841:             $homeserver = &homeserver($cnum,$cdom);
 5842:         } else {
 5843:             $homeserver = &domain($cdom,'primary');
 5844:         }
 5845:         if ($homeserver ne 'no_host') {
 5846:             $response = &reply('autorun:'.$cdom,$homeserver);
 5847:         }
 5848:     }
 5849:     return $response;
 5850: }
 5851: 
 5852: sub auto_get_sections {
 5853:     my ($cnum,$cdom,$inst_coursecode) = @_;
 5854:     my $homeserver;
 5855:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
 5856:         $homeserver = &homeserver($cnum,$cdom);
 5857:     }
 5858:     if (!defined($homeserver)) { 
 5859:         if ($cdom =~ /^$match_domain$/) {
 5860:             $homeserver = &domain($cdom,'primary');
 5861:         }
 5862:     }
 5863:     my @secs;
 5864:     if (defined($homeserver)) {
 5865:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 5866:         unless ($response eq 'refused') {
 5867:             @secs = split(/:/,$response);
 5868:         }
 5869:     }
 5870:     return @secs;
 5871: }
 5872: 
 5873: sub auto_new_course {
 5874:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 5875:     my $homeserver = &homeserver($cnum,$cdom);
 5876:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 5877:     return $response;
 5878: }
 5879: 
 5880: sub auto_validate_courseID {
 5881:     my ($cnum,$cdom,$inst_course_id) = @_;
 5882:     my $homeserver = &homeserver($cnum,$cdom);
 5883:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 5884:     return $response;
 5885: }
 5886: 
 5887: sub auto_validate_instcode {
 5888:     my ($cnum,$cdom,$instcode,$owner) = @_;
 5889:     my ($homeserver,$response);
 5890:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 5891:         $homeserver = &homeserver($cnum,$cdom);
 5892:     }
 5893:     if (!defined($homeserver)) {
 5894:         if ($cdom =~ /^$match_domain$/) {
 5895:             $homeserver = &domain($cdom,'primary');
 5896:         }
 5897:     }
 5898:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
 5899:                         &escape($instcode).':'.&escape($owner),$homeserver));
 5900:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
 5901:     return ($outcome,$description);
 5902: }
 5903: 
 5904: sub auto_create_password {
 5905:     my ($cnum,$cdom,$authparam,$udom) = @_;
 5906:     my ($homeserver,$response);
 5907:     my $create_passwd = 0;
 5908:     my $authchk = '';
 5909:     if ($udom =~ /^$match_domain$/) {
 5910:         $homeserver = &domain($udom,'primary');
 5911:     }
 5912:     if ($homeserver eq '') {
 5913:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 5914:             $homeserver = &homeserver($cnum,$cdom);
 5915:         }
 5916:     }
 5917:     if ($homeserver eq '') {
 5918:         $authchk = 'nodomain';
 5919:     } else {
 5920:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 5921:         if ($response eq 'refused') {
 5922:             $authchk = 'refused';
 5923:         } else {
 5924:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 5925:         }
 5926:     }
 5927:     return ($authparam,$create_passwd,$authchk);
 5928: }
 5929: 
 5930: sub auto_photo_permission {
 5931:     my ($cnum,$cdom,$students) = @_;
 5932:     my $homeserver = &homeserver($cnum,$cdom);
 5933:     my ($outcome,$perm_reqd,$conditions) = 
 5934: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 5935:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5936: 	return (undef,undef);
 5937:     }
 5938:     return ($outcome,$perm_reqd,$conditions);
 5939: }
 5940: 
 5941: sub auto_checkphotos {
 5942:     my ($uname,$udom,$pid) = @_;
 5943:     my $homeserver = &homeserver($uname,$udom);
 5944:     my ($result,$resulttype);
 5945:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 5946: 				   &escape($uname).':'.&escape($pid),
 5947: 				   $homeserver));
 5948:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5949: 	return (undef,undef);
 5950:     }
 5951:     if ($outcome) {
 5952:         ($result,$resulttype) = split(/:/,$outcome);
 5953:     } 
 5954:     return ($result,$resulttype);
 5955: }
 5956: 
 5957: sub auto_photochoice {
 5958:     my ($cnum,$cdom) = @_;
 5959:     my $homeserver = &homeserver($cnum,$cdom);
 5960:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 5961: 						       &escape($cdom),
 5962: 						       $homeserver)));
 5963:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5964: 	return (undef,undef);
 5965:     }
 5966:     return ($update,$comment);
 5967: }
 5968: 
 5969: sub auto_photoupdate {
 5970:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 5971:     my $homeserver = &homeserver($cnum,$dom);
 5972:     my $host=&hostname($homeserver);
 5973:     my $cmd = '';
 5974:     my $maxtries = 1;
 5975:     foreach my $affiliate (keys(%{$affiliatesref})) {
 5976:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5977:     }
 5978:     $cmd =~ s/%%$//;
 5979:     $cmd = &escape($cmd);
 5980:     my $query = 'institutionalphotos';
 5981:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 5982:     unless ($queryid=~/^\Q$host\E\_/) {
 5983:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 5984:         return 'error: '.$queryid;
 5985:     }
 5986:     my $reply = &get_query_reply($queryid);
 5987:     my $tries = 1;
 5988:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5989:         $reply = &get_query_reply($queryid);
 5990:         $tries ++;
 5991:     }
 5992:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5993:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5994:     } else {
 5995:         my @responses = split(/:/,$reply);
 5996:         my $outcome = shift(@responses); 
 5997:         foreach my $item (@responses) {
 5998:             my ($key,$value) = split(/=/,$item);
 5999:             $$photo{$key} = $value;
 6000:         }
 6001:         return $outcome;
 6002:     }
 6003:     return 'error';
 6004: }
 6005: 
 6006: sub auto_instcode_format {
 6007:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 6008: 	$cat_order) = @_;
 6009:     my $courses = '';
 6010:     my @homeservers;
 6011:     if ($caller eq 'global') {
 6012: 	my %servers = &get_servers($codedom,'library');
 6013: 	foreach my $tryserver (keys(%servers)) {
 6014: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 6015: 		push(@homeservers,$tryserver);
 6016: 	    }
 6017:         }
 6018:     } elsif ($caller eq 'requests') {
 6019:         if ($codedom =~ /^$match_domain$/) {
 6020:             my $chome = &domain($codedom,'primary');
 6021:             unless ($chome eq 'no_host') {
 6022:                 push(@homeservers,$chome);
 6023:             }
 6024:         }
 6025:     } else {
 6026:         push(@homeservers,&homeserver($caller,$codedom));
 6027:     }
 6028:     foreach my $code (keys(%{$instcodes})) {
 6029:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 6030:     }
 6031:     chop($courses);
 6032:     my $ok_response = 0;
 6033:     my $response;
 6034:     while (@homeservers > 0 && $ok_response == 0) {
 6035:         my $server = shift(@homeservers); 
 6036:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 6037:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 6038:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 6039: 		split(/:/,$response);
 6040:             %{$codes} = (%{$codes},&str2hash($codes_str));
 6041:             push(@{$codetitles},&str2array($codetitles_str));
 6042:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 6043:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 6044:             $ok_response = 1;
 6045:         }
 6046:     }
 6047:     if ($ok_response) {
 6048:         return 'ok';
 6049:     } else {
 6050:         return $response;
 6051:     }
 6052: }
 6053: 
 6054: sub auto_instcode_defaults {
 6055:     my ($domain,$returnhash,$code_order) = @_;
 6056:     my @homeservers;
 6057: 
 6058:     my %servers = &get_servers($domain,'library');
 6059:     foreach my $tryserver (keys(%servers)) {
 6060: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 6061: 	    push(@homeservers,$tryserver);
 6062: 	}
 6063:     }
 6064: 
 6065:     my $response;
 6066:     foreach my $server (@homeservers) {
 6067:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 6068:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 6069: 	
 6070: 	foreach my $pair (split(/\&/,$response)) {
 6071: 	    my ($name,$value)=split(/\=/,$pair);
 6072: 	    if ($name eq 'code_order') {
 6073: 		@{$code_order} = split(/\&/,&unescape($value));
 6074: 	    } else {
 6075: 		$returnhash->{&unescape($name)}=&unescape($value);
 6076: 	    }
 6077: 	}
 6078: 	return 'ok';
 6079:     }
 6080: 
 6081:     return $response;
 6082: }
 6083: 
 6084: sub auto_possible_instcodes {
 6085:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
 6086:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
 6087:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
 6088:         return;
 6089:     }
 6090:     my (@homeservers,$uhome);
 6091:     if (defined(&domain($domain,'primary'))) {
 6092:         $uhome=&domain($domain,'primary');
 6093:         push(@homeservers,&domain($domain,'primary'));
 6094:     } else {
 6095:         my %servers = &get_servers($domain,'library');
 6096:         foreach my $tryserver (keys(%servers)) {
 6097:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 6098:                 push(@homeservers,$tryserver);
 6099:             }
 6100:         }
 6101:     }
 6102:     my $response;
 6103:     foreach my $server (@homeservers) {
 6104:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
 6105:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 6106:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
 6107:             split(':',$response);
 6108:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
 6109:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
 6110:         foreach my $item (split('&',$cat_title)) {   
 6111:             my ($name,$value)=split('=',$item);
 6112:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
 6113:         }
 6114:         foreach my $item (split('&',$cat_order)) {
 6115:             my ($name,$value)=split('=',$item);
 6116:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
 6117:         }
 6118:         return 'ok';
 6119:     }
 6120:     return $response;
 6121: }
 6122: 
 6123: sub auto_courserequest_checks {
 6124:     my ($dom) = @_;
 6125:     my ($homeserver,%validations);
 6126:     if ($dom =~ /^$match_domain$/) {
 6127:         $homeserver = &domain($dom,'primary');
 6128:     }
 6129:     unless ($homeserver eq 'no_host') {
 6130:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
 6131:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
 6132:             my @items = split(/&/,$response);
 6133:             foreach my $item (@items) {
 6134:                 my ($key,$value) = split('=',$item);
 6135:                 $validations{&unescape($key)} = &thaw_unescape($value);
 6136:             }
 6137:         }
 6138:     }
 6139:     return %validations; 
 6140: }
 6141: 
 6142: sub auto_courserequest_validation {
 6143:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
 6144:     my ($homeserver,$response);
 6145:     if ($dom =~ /^$match_domain$/) {
 6146:         $homeserver = &domain($dom,'primary');
 6147:     }
 6148:     unless ($homeserver eq 'no_host') {  
 6149:           
 6150:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
 6151:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
 6152:                                     ':'.&escape($instcode).':'.&escape($instseclist),
 6153:                                     $homeserver));
 6154:     }
 6155:     return $response;
 6156: }
 6157: 
 6158: sub auto_validate_class_sec {
 6159:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 6160:     my $homeserver = &homeserver($cnum,$cdom);
 6161:     my $ownerlist;
 6162:     if (ref($owners) eq 'ARRAY') {
 6163:         $ownerlist = join(',',@{$owners});
 6164:     } else {
 6165:         $ownerlist = $owners;
 6166:     }
 6167:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 6168:                         &escape($ownerlist).':'.$cdom,$homeserver);
 6169:     return $response;
 6170: }
 6171: 
 6172: # ------------------------------------------------------- Course Group routines
 6173: 
 6174: sub get_coursegroups {
 6175:     my ($cdom,$cnum,$group,$namespace) = @_;
 6176:     return(&dump($namespace,$cdom,$cnum,$group));
 6177: }
 6178: 
 6179: sub modify_coursegroup {
 6180:     my ($cdom,$cnum,$groupsettings) = @_;
 6181:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 6182: }
 6183: 
 6184: sub toggle_coursegroup_status {
 6185:     my ($cdom,$cnum,$group,$action) = @_;
 6186:     my ($from_namespace,$to_namespace);
 6187:     if ($action eq 'delete') {
 6188:         $from_namespace = 'coursegroups';
 6189:         $to_namespace = 'deleted_groups';
 6190:     } else {
 6191:         $from_namespace = 'deleted_groups';
 6192:         $to_namespace = 'coursegroups';
 6193:     }
 6194:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 6195:     if (my $tmp = &error(%curr_group)) {
 6196:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 6197:         return ('read error',$tmp);
 6198:     } else {
 6199:         my %savedsettings = %curr_group; 
 6200:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 6201:         my $deloutcome;
 6202:         if ($result eq 'ok') {
 6203:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 6204:         } else {
 6205:             return ('write error',$result);
 6206:         }
 6207:         if ($deloutcome eq 'ok') {
 6208:             return 'ok';
 6209:         } else {
 6210:             return ('delete error',$deloutcome);
 6211:         }
 6212:     }
 6213: }
 6214: 
 6215: sub modify_group_roles {
 6216:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 6217:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 6218:     my $role = 'gr/'.&escape($userprivs);
 6219:     my ($uname,$udom) = split(/:/,$user);
 6220:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 6221:     if ($result eq 'ok') {
 6222:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 6223:     }
 6224:     return $result;
 6225: }
 6226: 
 6227: sub modify_coursegroup_membership {
 6228:     my ($cdom,$cnum,$membership) = @_;
 6229:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 6230:     return $result;
 6231: }
 6232: 
 6233: sub get_active_groups {
 6234:     my ($udom,$uname,$cdom,$cnum) = @_;
 6235:     my $now = time;
 6236:     my %groups = ();
 6237:     foreach my $key (keys(%env)) {
 6238:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 6239:             my ($start,$end) = split(/\./,$env{$key});
 6240:             if (($end!=0) && ($end<$now)) { next; }
 6241:             if (($start!=0) && ($start>$now)) { next; }
 6242:             if ($1 eq $cdom && $2 eq $cnum) {
 6243:                 $groups{$3} = $env{$key} ;
 6244:             }
 6245:         }
 6246:     }
 6247:     return %groups;
 6248: }
 6249: 
 6250: sub get_group_membership {
 6251:     my ($cdom,$cnum,$group) = @_;
 6252:     return(&dump('groupmembership',$cdom,$cnum,$group));
 6253: }
 6254: 
 6255: sub get_users_groups {
 6256:     my ($udom,$uname,$courseid) = @_;
 6257:     my @usersgroups;
 6258:     my $cachetime=1800;
 6259: 
 6260:     my $hashid="$udom:$uname:$courseid";
 6261:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 6262:     if (defined($cached)) {
 6263:         @usersgroups = split(/:/,$grouplist);
 6264:     } else {  
 6265:         $grouplist = '';
 6266:         my $courseurl = &courseid_to_courseurl($courseid);
 6267:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 6268:         my $access_end = $env{'course.'.$courseid.
 6269:                               '.default_enrollment_end_date'};
 6270:         my $now = time;
 6271:         foreach my $key (keys(%roleshash)) {
 6272:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 6273:                 my $group = $1;
 6274:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 6275:                     my $start = $2;
 6276:                     my $end = $1;
 6277:                     if ($start == -1) { next; } # deleted from group
 6278:                     if (($start!=0) && ($start>$now)) { next; }
 6279:                     if (($end!=0) && ($end<$now)) {
 6280:                         if ($access_end && $access_end < $now) {
 6281:                             if ($access_end - $end < 86400) {
 6282:                                 push(@usersgroups,$group);
 6283:                             }
 6284:                         }
 6285:                         next;
 6286:                     }
 6287:                     push(@usersgroups,$group);
 6288:                 }
 6289:             }
 6290:         }
 6291:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 6292:         $grouplist = join(':',@usersgroups);
 6293:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 6294:     }
 6295:     return @usersgroups;
 6296: }
 6297: 
 6298: sub devalidate_getgroups_cache {
 6299:     my ($udom,$uname,$cdom,$cnum)=@_;
 6300:     my $courseid = $cdom.'_'.$cnum;
 6301: 
 6302:     my $hashid="$udom:$uname:$courseid";
 6303:     &devalidate_cache_new('getgroups',$hashid);
 6304: }
 6305: 
 6306: # ------------------------------------------------------------------ Plain Text
 6307: 
 6308: sub plaintext {
 6309:     my ($short,$type,$cid,$forcedefault) = @_;
 6310:     if ($short =~ m{^cr/}) {
 6311: 	return (split('/',$short))[-1];
 6312:     }
 6313:     if (!defined($cid)) {
 6314:         $cid = $env{'request.course.id'};
 6315:     }
 6316:     my %rolenames = (
 6317:                       Course    => 'std',
 6318:                       Community => 'alt1',
 6319:                     );
 6320:     if ($cid ne '') {
 6321:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
 6322:             unless ($forcedefault) {
 6323:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
 6324:                 &Apache::lonlocal::mt_escape(\$roletext);
 6325:                 return &Apache::lonlocal::mt($roletext);
 6326:             }
 6327:         }
 6328:     }
 6329:     if ((defined($type)) && (defined($rolenames{$type})) &&
 6330:         (defined($rolenames{$type})) && 
 6331:         (defined($prp{$short}{$rolenames{$type}}))) {
 6332:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 6333:     } elsif ($cid ne '') {
 6334:         my $crstype = $env{'course.'.$cid.'.type'};
 6335:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
 6336:             (defined($prp{$short}{$rolenames{$crstype}}))) {
 6337:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
 6338:         }
 6339:     }
 6340:     return &Apache::lonlocal::mt($prp{$short}{'std'});
 6341: }
 6342: 
 6343: # ----------------------------------------------------------------- Assign Role
 6344: 
 6345: sub assignrole {
 6346:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 6347:         $context)=@_;
 6348:     my $mrole;
 6349:     if ($role =~ /^cr\//) {
 6350:         my $cwosec=$url;
 6351:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 6352: 	unless (&allowed('ccr',$cwosec)) {
 6353:            my $refused = 1;
 6354:            if ($context eq 'requestcourses') {
 6355:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
 6356:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
 6357:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
 6358:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 6359:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 6360:                            if ($crsenv{'internal.courseowner'} eq
 6361:                                $env{'user.name'}.':'.$env{'user.domain'}) {
 6362:                                $refused = '';
 6363:                            }
 6364:                        }
 6365:                    }
 6366:                }
 6367:            }
 6368:            if ($refused) {
 6369:                &logthis('Refused custom assignrole: '.
 6370:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
 6371:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
 6372:                return 'refused';
 6373:            }
 6374:         }
 6375:         $mrole='cr';
 6376:     } elsif ($role =~ /^gr\//) {
 6377:         my $cwogrp=$url;
 6378:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 6379:         unless (&allowed('mdg',$cwogrp)) {
 6380:             &logthis('Refused group assignrole: '.
 6381:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 6382:                     $env{'user.name'}.' at '.$env{'user.domain'});
 6383:             return 'refused';
 6384:         }
 6385:         $mrole='gr';
 6386:     } else {
 6387:         my $cwosec=$url;
 6388:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 6389:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 6390:             my $refused;
 6391:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 6392:                 if (!(&allowed('c'.$role,$url))) {
 6393:                     $refused = 1;
 6394:                 }
 6395:             } else {
 6396:                 $refused = 1;
 6397:             }
 6398:             if ($refused) {
 6399:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
 6400:                 if (!$selfenroll && $context eq 'course') {
 6401:                     my %crsenv;
 6402:                     if ($role eq 'cc' || $role eq 'co') {
 6403:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 6404:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
 6405:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
 6406:                                 if ($crsenv{'internal.courseowner'} eq 
 6407:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 6408:                                     $refused = '';
 6409:                                 }
 6410:                             }
 6411:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
 6412:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
 6413:                                 if ($crsenv{'internal.courseowner'} eq 
 6414:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
 6415:                                     $refused = '';
 6416:                                 }
 6417:                             }
 6418:                         }
 6419:                     }
 6420:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 6421:                     $refused = '';
 6422:                 } elsif ($context eq 'requestcourses') {
 6423:                     my @possroles = ('st','ta','ep','in','cc','co');
 6424:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
 6425:                         my $wrongcc;
 6426:                         if ($cnum =~ /^$match_community$/) {
 6427:                             $wrongcc = 1 if ($role eq 'cc');
 6428:                         } else {
 6429:                             $wrongcc = 1 if ($role eq 'co');
 6430:                         }
 6431:                         unless ($wrongcc) {
 6432:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
 6433:                             if ($crsenv{'internal.courseowner'} eq 
 6434:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
 6435:                                 $refused = '';
 6436:                             }
 6437:                         }
 6438:                     }
 6439:                 }
 6440:                 if ($refused) {
 6441:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 6442:                              ' '.$role.' '.$end.' '.$start.' by '.
 6443: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 6444:                     return 'refused';
 6445:                 }
 6446:             }
 6447:         }
 6448:         $mrole=$role;
 6449:     }
 6450:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 6451:                 "$udom:$uname:$url".'_'."$mrole=$role";
 6452:     if ($end) { $command.='_'.$end; }
 6453:     if ($start) {
 6454: 	if ($end) { 
 6455:            $command.='_'.$start; 
 6456:         } else {
 6457:            $command.='_0_'.$start;
 6458:         }
 6459:     }
 6460:     my $origstart = $start;
 6461:     my $origend = $end;
 6462:     my $delflag;
 6463: # actually delete
 6464:     if ($deleteflag) {
 6465: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 6466: # modify command to delete the role
 6467:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 6468:                 "$udom:$uname:$url".'_'."$mrole";
 6469: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 6470: # set start and finish to negative values for userrolelog
 6471:            $start=-1;
 6472:            $end=-1;
 6473:            $delflag = 1;
 6474:         }
 6475:     }
 6476: # send command
 6477:     my $answer=&reply($command,&homeserver($uname,$udom));
 6478: # log new user role if status is ok
 6479:     if ($answer eq 'ok') {
 6480: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 6481: # for course roles, perform group memberships changes triggered by role change.
 6482:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
 6483:         unless ($role =~ /^gr/) {
 6484:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 6485:                                              $origstart,$selfenroll,$context);
 6486:         }
 6487:         if ($role eq 'cc') {
 6488:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
 6489:         }
 6490:     }
 6491:     return $answer;
 6492: }
 6493: 
 6494: sub autoupdate_coowners {
 6495:     my ($url,$end,$start,$uname,$udom) = @_;
 6496:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
 6497:     if (($cdom ne '') && ($cnum ne '')) {
 6498:         my $now = time;
 6499:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
 6500:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
 6501:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
 6502:             my $instcode = $coursehash{'internal.coursecode'};
 6503:             if ($instcode ne '') {
 6504:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
 6505:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
 6506:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
 6507:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
 6508:                         if ($result eq 'valid') {
 6509:                             if ($coursehash{'internal.co-owners'}) {
 6510:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 6511:                                     push(@newcoowners,$coowner);
 6512:                                 }
 6513:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
 6514:                                     push(@newcoowners,$uname.':'.$udom);
 6515:                                 }
 6516:                                 @newcoowners = sort(@newcoowners);
 6517:                             } else {
 6518:                                 push(@newcoowners,$uname.':'.$udom);
 6519:                             }
 6520:                         } else {
 6521:                             if ($coursehash{'internal.co-owners'}) {
 6522:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
 6523:                                     unless ($coowner eq $uname.':'.$udom) {
 6524:                                         push(@newcoowners,$coowner);
 6525:                                     }
 6526:                                 }
 6527:                                 unless (@newcoowners > 0) {
 6528:                                     $delcoowners = 1;
 6529:                                     $coowners = '';
 6530:                                 }
 6531:                             }
 6532:                         }
 6533:                         if (@newcoowners || $delcoowners) {
 6534:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
 6535:                                             $delcoowners,@newcoowners);
 6536:                         }
 6537:                     }
 6538:                 }
 6539:             }
 6540:         }
 6541:     }
 6542: }
 6543: 
 6544: sub store_coowners {
 6545:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
 6546:     my $cid = $cdom.'_'.$cnum;
 6547:     my ($coowners,$delresult,$putresult);
 6548:     if (@newcoowners) {
 6549:         $coowners = join(',',@newcoowners);
 6550:         my %coownershash = (
 6551:                             'internal.co-owners' => $coowners,
 6552:                            );
 6553:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
 6554:         if ($putresult eq 'ok') {
 6555:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
 6556:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
 6557:             }
 6558:         }
 6559:     }
 6560:     if ($delcoowners) {
 6561:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
 6562:         if ($delresult eq 'ok') {
 6563:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
 6564:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
 6565:             }
 6566:         }
 6567:     }
 6568:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
 6569:         my %crsinfo =
 6570:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
 6571:         if (ref($crsinfo{$cid}) eq 'HASH') {
 6572:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
 6573:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
 6574:         }
 6575:     }
 6576: }
 6577: 
 6578: # -------------------------------------------------- Modify user authentication
 6579: # Overrides without validation
 6580: 
 6581: sub modifyuserauth {
 6582:     my ($udom,$uname,$umode,$upass)=@_;
 6583:     my $uhome=&homeserver($uname,$udom);
 6584:     unless (&allowed('mau',$udom)) { return 'refused'; }
 6585:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 6586:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 6587:              ' in domain '.$env{'request.role.domain'});  
 6588:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 6589: 		     &escape($upass),$uhome);
 6590:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 6591:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 6592:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 6593:     &log($udom,,$uname,$uhome,
 6594:         'Authentication changed by '.$env{'user.domain'}.', '.
 6595:                                      $env{'user.name'}.', '.$umode.
 6596:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 6597:     unless ($reply eq 'ok') {
 6598:         &logthis('Authentication mode error: '.$reply);
 6599: 	return 'error: '.$reply;
 6600:     }   
 6601:     return 'ok';
 6602: }
 6603: 
 6604: # --------------------------------------------------------------- Modify a user
 6605: 
 6606: sub modifyuser {
 6607:     my ($udom,    $uname, $uid,
 6608:         $umode,   $upass, $first,
 6609:         $middle,  $last,  $gene,
 6610:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
 6611:     $udom= &LONCAPA::clean_domain($udom);
 6612:     $uname=&LONCAPA::clean_username($uname);
 6613:     my $showcandelete = 'none';
 6614:     if (ref($candelete) eq 'ARRAY') {
 6615:         if (@{$candelete} > 0) {
 6616:             $showcandelete = join(', ',@{$candelete});
 6617:         }
 6618:     }
 6619:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 6620:              $umode.', '.$first.', '.$middle.', '.
 6621: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
 6622:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 6623:                                      ' desiredhome not specified'). 
 6624:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 6625:              ' in domain '.$env{'request.role.domain'});
 6626:     my $uhome=&homeserver($uname,$udom,'true');
 6627:     my $newuser;
 6628:     if ($uhome eq 'no_host') {
 6629:         $newuser = 1;
 6630:     }
 6631: # ----------------------------------------------------------------- Create User
 6632:     if (($uhome eq 'no_host') && 
 6633: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 6634:         my $unhome='';
 6635:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 6636:             $unhome = $desiredhome;
 6637: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 6638: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 6639:         } else { # load balancing routine for determining $unhome
 6640:             my $loadm=10000000;
 6641: 	    my %servers = &get_servers($udom,'library');
 6642: 	    foreach my $tryserver (keys(%servers)) {
 6643: 		my $answer=reply('load',$tryserver);
 6644: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 6645: 		    $loadm=$answer;
 6646: 		    $unhome=$tryserver;
 6647: 		}
 6648: 	    }
 6649:         }
 6650:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 6651: 	    return 'error: unable to find a home server for '.$uname.
 6652:                    ' in domain '.$udom;
 6653:         }
 6654:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 6655:                          &escape($upass),$unhome);
 6656: 	unless ($reply eq 'ok') {
 6657:             return 'error: '.$reply;
 6658:         }   
 6659:         $uhome=&homeserver($uname,$udom,'true');
 6660:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 6661: 	    return 'error: unable verify users home machine.';
 6662:         }
 6663:     }   # End of creation of new user
 6664: # ---------------------------------------------------------------------- Add ID
 6665:     if ($uid) {
 6666:        $uid=~tr/A-Z/a-z/;
 6667:        my %uidhash=&idrget($udom,$uname);
 6668:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 6669:          && (!$forceid)) {
 6670: 	  unless ($uid eq $uidhash{$uname}) {
 6671: 	      return 'error: user id "'.$uid.'" does not match '.
 6672:                   'current user id "'.$uidhash{$uname}.'".';
 6673:           }
 6674:        } else {
 6675: 	  &idput($udom,($uname => $uid));
 6676:        }
 6677:     }
 6678: # -------------------------------------------------------------- Add names, etc
 6679:     my @tmp=&get('environment',
 6680: 		   ['firstname','middlename','lastname','generation','id',
 6681:                     'permanentemail','inststatus'],
 6682: 		   $udom,$uname);
 6683:     my (%names,%oldnames);
 6684:     if ($tmp[0] =~ m/^error:.*/) { 
 6685:         %names=(); 
 6686:     } else {
 6687:         %names = @tmp;
 6688:         %oldnames = %names;
 6689:     }
 6690: #
 6691: # If name, email and/or uid are blank (e.g., because an uploaded file
 6692: # of users did not contain them), do not overwrite existing values
 6693: # unless field is in $candelete array ref.  
 6694: #
 6695: 
 6696:     my @fields = ('firstname','middlename','lastname','generation',
 6697:                   'permanentemail','id');
 6698:     my %newvalues;
 6699:     if (ref($candelete) eq 'ARRAY') {
 6700:         foreach my $field (@fields) {
 6701:             if (grep(/^\Q$field\E$/,@{$candelete})) {
 6702:                 if ($field eq 'firstname') {
 6703:                     $names{$field} = $first;
 6704:                 } elsif ($field eq 'middlename') {
 6705:                     $names{$field} = $middle;
 6706:                 } elsif ($field eq 'lastname') {
 6707:                     $names{$field} = $last;
 6708:                 } elsif ($field eq 'generation') { 
 6709:                     $names{$field} = $gene;
 6710:                 } elsif ($field eq 'permanentemail') {
 6711:                     $names{$field} = $email;
 6712:                 } elsif ($field eq 'id') {
 6713:                     $names{$field}  = $uid;
 6714:                 }
 6715:             }
 6716:         }
 6717:     }
 6718:     if ($first)  { $names{'firstname'}  = $first; }
 6719:     if (defined($middle)) { $names{'middlename'} = $middle; }
 6720:     if ($last)   { $names{'lastname'}   = $last; }
 6721:     if (defined($gene))   { $names{'generation'} = $gene; }
 6722:     if ($email) {
 6723:        $email=~s/[^\w\@\.\-\,]//gs;
 6724:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 6725:     }
 6726:     if ($uid) { $names{'id'}  = $uid; }
 6727:     if (defined($inststatus)) {
 6728:         $names{'inststatus'} = '';
 6729:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
 6730:         if (ref($usertypes) eq 'HASH') {
 6731:             my @okstatuses; 
 6732:             foreach my $item (split(/:/,$inststatus)) {
 6733:                 if (defined($usertypes->{$item})) {
 6734:                     push(@okstatuses,$item);  
 6735:                 }
 6736:             }
 6737:             if (@okstatuses) {
 6738:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
 6739:             }
 6740:         }
 6741:     }
 6742:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
 6743:                  $umode.', '.$first.', '.$middle.', '.
 6744:                  $last.', '.$gene.', '.$email.', '.$inststatus;
 6745:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 6746:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 6747:     } else {
 6748:         $logmsg .= ' during self creation';
 6749:     }
 6750:     my $changed;
 6751:     if ($newuser) {
 6752:         $changed = 1;
 6753:     } else {
 6754:         foreach my $field (@fields) {
 6755:             if ($names{$field} ne $oldnames{$field}) {
 6756:                 $changed = 1;
 6757:                 last;
 6758:             }
 6759:         }
 6760:     }
 6761:     unless ($changed) {
 6762:         $logmsg = 'No changes in user information needed for: '.$logmsg;
 6763:         &logthis($logmsg);
 6764:         return 'ok';
 6765:     }
 6766:     my $reply = &put('environment', \%names, $udom,$uname);
 6767:     if ($reply ne 'ok') { 
 6768:         return 'error: '.$reply;
 6769:     }
 6770:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 6771:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 6772:     $logmsg = 'Success modifying user '.$logmsg;
 6773:     &logthis($logmsg);
 6774:     return 'ok';
 6775: }
 6776: 
 6777: # -------------------------------------------------------------- Modify student
 6778: 
 6779: sub modifystudent {
 6780:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 6781:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 6782:         $selfenroll,$context,$inststatus)=@_;
 6783:     if (!$cid) {
 6784: 	unless ($cid=$env{'request.course.id'}) {
 6785: 	    return 'not_in_class';
 6786: 	}
 6787:     }
 6788: # --------------------------------------------------------------- Make the user
 6789:     my $reply=&modifyuser
 6790: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 6791:          $desiredhome,$email,$inststatus);
 6792:     unless ($reply eq 'ok') { return $reply; }
 6793:     # This will cause &modify_student_enrollment to get the uid from the
 6794:     # students environment
 6795:     $uid = undef if (!$forceid);
 6796:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 6797: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
 6798:     return $reply;
 6799: }
 6800: 
 6801: sub modify_student_enrollment {
 6802:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
 6803:     my ($cdom,$cnum,$chome);
 6804:     if (!$cid) {
 6805: 	unless ($cid=$env{'request.course.id'}) {
 6806: 	    return 'not_in_class';
 6807: 	}
 6808: 	$cdom=$env{'course.'.$cid.'.domain'};
 6809: 	$cnum=$env{'course.'.$cid.'.num'};
 6810:     } else {
 6811: 	($cdom,$cnum)=split(/_/,$cid);
 6812:     }
 6813:     $chome=$env{'course.'.$cid.'.home'};
 6814:     if (!$chome) {
 6815: 	$chome=&homeserver($cnum,$cdom);
 6816:     }
 6817:     if (!$chome) { return 'unknown_course'; }
 6818:     # Make sure the user exists
 6819:     my $uhome=&homeserver($uname,$udom);
 6820:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 6821: 	return 'error: no such user';
 6822:     }
 6823:     # Get student data if we were not given enough information
 6824:     if (!defined($first)  || $first  eq '' || 
 6825:         !defined($last)   || $last   eq '' || 
 6826:         !defined($uid)    || $uid    eq '' || 
 6827:         !defined($middle) || $middle eq '' || 
 6828:         !defined($gene)   || $gene   eq '') {
 6829:         # They did not supply us with enough data to enroll the student, so
 6830:         # we need to pick up more information.
 6831:         my %tmp = &get('environment',
 6832:                        ['firstname','middlename','lastname', 'generation','id']
 6833:                        ,$udom,$uname);
 6834: 
 6835:         #foreach my $key (keys(%tmp)) {
 6836:         #    &logthis("key $key = ".$tmp{$key});
 6837:         #}
 6838:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 6839:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 6840:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 6841:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 6842:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 6843:     }
 6844:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 6845:     my $reply=cput('classlist',
 6846: 		   {"$uname:$udom" => 
 6847: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 6848: 		   $cdom,$cnum);
 6849:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 6850: 	return 'error: '.$reply;
 6851:     } else {
 6852: 	&devalidate_getsection_cache($udom,$uname,$cid);
 6853:     }
 6854:     # Add student role to user
 6855:     my $uurl='/'.$cid;
 6856:     $uurl=~s/\_/\//g;
 6857:     if ($usec) {
 6858: 	$uurl.='/'.$usec;
 6859:     }
 6860:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
 6861: }
 6862: 
 6863: sub format_name {
 6864:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 6865:     my $name;
 6866:     if ($first ne 'lastname') {
 6867: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 6868:     } else {
 6869: 	if ($lastname=~/\S/) {
 6870: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 6871: 	    $name=~s/\s+,/,/;
 6872: 	} else {
 6873: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 6874: 	}
 6875:     }
 6876:     $name=~s/^\s+//;
 6877:     $name=~s/\s+$//;
 6878:     $name=~s/\s+/ /g;
 6879:     return $name;
 6880: }
 6881: 
 6882: # ------------------------------------------------- Write to course preferences
 6883: 
 6884: sub writecoursepref {
 6885:     my ($courseid,%prefs)=@_;
 6886:     $courseid=~s/^\///;
 6887:     $courseid=~s/\_/\//g;
 6888:     my ($cdomain,$cnum)=split(/\//,$courseid);
 6889:     my $chome=homeserver($cnum,$cdomain);
 6890:     if (($chome eq '') || ($chome eq 'no_host')) { 
 6891: 	return 'error: no such course';
 6892:     }
 6893:     my $cstring='';
 6894:     foreach my $pref (keys(%prefs)) {
 6895: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 6896:     }
 6897:     $cstring=~s/\&$//;
 6898:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 6899: }
 6900: 
 6901: # ---------------------------------------------------------- Make/modify course
 6902: 
 6903: sub createcourse {
 6904:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 6905:         $course_owner,$crstype,$cnum,$context,$category)=@_;
 6906:     $url=&declutter($url);
 6907:     my $cid='';
 6908:     if ($context eq 'requestcourses') {
 6909:         my $can_create = 0;
 6910:         my ($ownername,$ownerdom) = split(':',$course_owner);
 6911:         if ($udom eq $ownerdom) {
 6912:             if (&usertools_access($ownername,$ownerdom,$category,undef,
 6913:                                   $context)) {
 6914:                 $can_create = 1;
 6915:             }
 6916:         } else {
 6917:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
 6918:                                            $category);
 6919:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
 6920:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
 6921:                 if (@curr > 0) {
 6922:                     my @options = qw(approval validate autolimit);
 6923:                     my $optregex = join('|',@options);
 6924:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
 6925:                         $can_create = 1;
 6926:                     }
 6927:                 }
 6928:             }
 6929:         }
 6930:         if ($can_create) {
 6931:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
 6932:                 unless (&allowed('ccc',$udom)) {
 6933:                     return 'refused'; 
 6934:                 }
 6935:             }
 6936:         } else {
 6937:             return 'refused';
 6938:         }
 6939:     } elsif (!&allowed('ccc',$udom)) {
 6940:         return 'refused';
 6941:     }
 6942: # --------------------------------------------------------------- Get Unique ID
 6943:     my $uname;
 6944:     if ($cnum =~ /^$match_courseid$/) {
 6945:         my $chome=&homeserver($cnum,$udom,'true');
 6946:         if (($chome eq '') || ($chome eq 'no_host')) {
 6947:             $uname = $cnum;
 6948:         } else {
 6949:             $uname = &generate_coursenum($udom,$crstype);
 6950:         }
 6951:     } else {
 6952:         $uname = &generate_coursenum($udom,$crstype);
 6953:     }
 6954:     return $uname if ($uname =~ /^error/);
 6955: # -------------------------------------------------- Check supplied server name
 6956:     if (!defined($course_server)) {
 6957:         if (defined(&domain($udom,'primary'))) {
 6958:             $course_server = &domain($udom,'primary');
 6959:         } else {
 6960:             $course_server = $env{'user.home'}; 
 6961:         }
 6962:     }
 6963:     my %host_servers =
 6964:         &Apache::lonnet::get_servers($udom,'library');
 6965:     unless ($host_servers{$course_server}) {
 6966:         return 'error: invalid home server for course: '.$course_server;
 6967:     }
 6968: # ------------------------------------------------------------- Make the course
 6969:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 6970:                       $course_server);
 6971:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 6972:     my $uhome=&homeserver($uname,$udom,'true');
 6973:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 6974: 	return 'error: no such course';
 6975:     }
 6976: # ----------------------------------------------------------------- Course made
 6977: # log existence
 6978:     my $now = time;
 6979:     my $newcourse = {
 6980:                     $udom.'_'.$uname => {
 6981:                                      description => $description,
 6982:                                      inst_code   => $inst_code,
 6983:                                      owner       => $course_owner,
 6984:                                      type        => $crstype,
 6985:                                      creator     => $env{'user.name'}.':'.
 6986:                                                     $env{'user.domain'},
 6987:                                      created     => $now,
 6988:                                      context     => $context,
 6989:                                                 },
 6990:                     };
 6991:     &courseidput($udom,$newcourse,$uhome,'notime');
 6992: # set toplevel url
 6993:     my $topurl=$url;
 6994:     unless ($nonstandard) {
 6995: # ------------------------------------------ For standard courses, make top url
 6996:         my $mapurl=&clutter($url);
 6997:         if ($mapurl eq '/res/') { $mapurl=''; }
 6998:         $env{'form.initmap'}=(<<ENDINITMAP);
 6999: <map>
 7000: <resource id="1" type="start"></resource>
 7001: <resource id="2" src="$mapurl"></resource>
 7002: <resource id="3" type="finish"></resource>
 7003: <link index="1" from="1" to="2"></link>
 7004: <link index="2" from="2" to="3"></link>
 7005: </map>
 7006: ENDINITMAP
 7007:         $topurl=&declutter(
 7008:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 7009:                           );
 7010:     }
 7011: # ----------------------------------------------------------- Write preferences
 7012:     &writecoursepref($udom.'_'.$uname,
 7013:                      ('description'              => $description,
 7014:                       'url'                      => $topurl,
 7015:                       'internal.creator'         => $env{'user.name'}.':'.
 7016:                                                     $env{'user.domain'},
 7017:                       'internal.created'         => $now,
 7018:                       'internal.creationcontext' => $context)
 7019:                     );
 7020:     return '/'.$udom.'/'.$uname;
 7021: }
 7022: 
 7023: # ------------------------------------------------------------------- Create ID
 7024: sub generate_coursenum {
 7025:     my ($udom,$crstype) = @_;
 7026:     my $domdesc = &domain($udom);
 7027:     return 'error: invalid domain' if ($domdesc eq '');
 7028:     my $first;
 7029:     if ($crstype eq 'Community') {
 7030:         $first = '0';
 7031:     } else {
 7032:         $first = int(1+rand(9)); 
 7033:     } 
 7034:     my $uname=$first.
 7035:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 7036:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
 7037:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 7038: # ----------------------------------------------- Make sure that does not exist
 7039:     my $uhome=&homeserver($uname,$udom,'true');
 7040:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
 7041:         if ($crstype eq 'Community') {
 7042:             $first = '0';
 7043:         } else {
 7044:             $first = int(1+rand(9));
 7045:         }
 7046:         $uname=$first.
 7047:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 7048:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
 7049:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 7050:         $uhome=&homeserver($uname,$udom,'true');
 7051:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
 7052:             return 'error: unable to generate unique course-ID';
 7053:         }
 7054:     }
 7055:     return $uname;
 7056: }
 7057: 
 7058: sub is_course {
 7059:     my ($cdom,$cnum) = @_;
 7060:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
 7061: 				undef,'.');
 7062:     if (exists($courses{$cdom.'_'.$cnum})) {
 7063:         return 1;
 7064:     }
 7065:     return 0;
 7066: }
 7067: 
 7068: sub store_userdata {
 7069:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
 7070:     my $result;
 7071:     if ($datakey ne '') {
 7072:         if (ref($storehash) eq 'HASH') {
 7073:             if ($udom eq '' || $uname eq '') {
 7074:                 $udom = $env{'user.domain'};
 7075:                 $uname = $env{'user.name'};
 7076:             }
 7077:             my $uhome=&homeserver($uname,$udom);
 7078:             if (($uhome eq '') || ($uhome eq 'no_host')) {
 7079:                 $result = 'error: no_host';
 7080:             } else {
 7081:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
 7082:                 $storehash->{'host'} = $perlvar{'lonHostID'};
 7083: 
 7084:                 my $namevalue='';
 7085:                 foreach my $key (keys(%{$storehash})) {
 7086:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 7087:                 }
 7088:                 $namevalue=~s/\&$//;
 7089:                 $result =  &reply("store:$env{'user.domain'}:$env{'user.name'}:".
 7090:                                   "$namespace:$datakey:$namevalue",$uhome);
 7091:             }
 7092:         } else {
 7093:             $result = 'error: data to store was not a hash reference'; 
 7094:         }
 7095:     } else {
 7096:         $result= 'error: invalid requestkey'; 
 7097:     }
 7098:     return $result;
 7099: }
 7100: 
 7101: # ---------------------------------------------------------- Assign Custom Role
 7102: 
 7103: sub assigncustomrole {
 7104:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 7105:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 7106:                        $end,$start,$deleteflag,$selfenroll,$context);
 7107: }
 7108: 
 7109: # ----------------------------------------------------------------- Revoke Role
 7110: 
 7111: sub revokerole {
 7112:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 7113:     my $now=time;
 7114:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 7115: }
 7116: 
 7117: # ---------------------------------------------------------- Revoke Custom Role
 7118: 
 7119: sub revokecustomrole {
 7120:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 7121:     my $now=time;
 7122:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 7123:            $deleteflag,$selfenroll,$context);
 7124: }
 7125: 
 7126: # ------------------------------------------------------------ Disk usage
 7127: sub diskusage {
 7128:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 7129:     $directorypath =~ s/\/$//;
 7130:     my $listing=&reply('du2:'.&escape($directorypath).':'
 7131:                        .&escape($getpropath).':'.&escape($uname).':'
 7132:                        .&escape($udom),homeserver($uname,$udom));
 7133:     if ($listing eq 'unknown_cmd') {
 7134:         if ($getpropath) {
 7135:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 7136:         }
 7137:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 7138:     }
 7139:     return $listing;
 7140: }
 7141: 
 7142: sub is_locked {
 7143:     my ($file_name, $domain, $user) = @_;
 7144:     my @check;
 7145:     my $is_locked;
 7146:     push @check, $file_name;
 7147:     my %locked = &get('file_permissions',\@check,
 7148: 		      $env{'user.domain'},$env{'user.name'});
 7149:     my ($tmp)=keys(%locked);
 7150:     if ($tmp=~/^error:/) { undef(%locked); }
 7151:     
 7152:     if (ref($locked{$file_name}) eq 'ARRAY') {
 7153:         $is_locked = 'false';
 7154:         foreach my $entry (@{$locked{$file_name}}) {
 7155:            if (ref($entry) eq 'ARRAY') { 
 7156:                $is_locked = 'true';
 7157:                last;
 7158:            }
 7159:        }
 7160:     } else {
 7161:         $is_locked = 'false';
 7162:     }
 7163: }
 7164: 
 7165: sub declutter_portfile {
 7166:     my ($file) = @_;
 7167:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 7168:     return $file;
 7169: }
 7170: 
 7171: # ------------------------------------------------------------- Mark as Read Only
 7172: 
 7173: sub mark_as_readonly {
 7174:     my ($domain,$user,$files,$what) = @_;
 7175:     my %current_permissions = &dump('file_permissions',$domain,$user);
 7176:     my ($tmp)=keys(%current_permissions);
 7177:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 7178:     foreach my $file (@{$files}) {
 7179: 	$file = &declutter_portfile($file);
 7180:         push(@{$current_permissions{$file}},$what);
 7181:     }
 7182:     &put('file_permissions',\%current_permissions,$domain,$user);
 7183:     return;
 7184: }
 7185: 
 7186: # ------------------------------------------------------------Save Selected Files
 7187: 
 7188: sub save_selected_files {
 7189:     my ($user, $path, @files) = @_;
 7190:     my $filename = $user."savedfiles";
 7191:     my @other_files = &files_not_in_path($user, $path);
 7192:     open (OUT, '>'.$tmpdir.$filename);
 7193:     foreach my $file (@files) {
 7194:         print (OUT $env{'form.currentpath'}.$file."\n");
 7195:     }
 7196:     foreach my $file (@other_files) {
 7197:         print (OUT $file."\n");
 7198:     }
 7199:     close (OUT);
 7200:     return 'ok';
 7201: }
 7202: 
 7203: sub clear_selected_files {
 7204:     my ($user) = @_;
 7205:     my $filename = $user."savedfiles";
 7206:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 7207:     print (OUT undef);
 7208:     close (OUT);
 7209:     return ("ok");    
 7210: }
 7211: 
 7212: sub files_in_path {
 7213:     my ($user, $path) = @_;
 7214:     my $filename = $user."savedfiles";
 7215:     my %return_files;
 7216:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 7217:     while (my $line_in = <IN>) {
 7218:         chomp ($line_in);
 7219:         my @paths_and_file = split (m!/!, $line_in);
 7220:         my $file_part = pop (@paths_and_file);
 7221:         my $path_part = join ('/', @paths_and_file);
 7222:         $path_part.='/';
 7223:         my $path_and_file = $path_part.$file_part;
 7224:         if ($path_part eq $path) {
 7225:             $return_files{$file_part}= 'selected';
 7226:         }
 7227:     }
 7228:     close (IN);
 7229:     return (\%return_files);
 7230: }
 7231: 
 7232: # called in portfolio select mode, to show files selected NOT in current directory
 7233: sub files_not_in_path {
 7234:     my ($user, $path) = @_;
 7235:     my $filename = $user."savedfiles";
 7236:     my @return_files;
 7237:     my $path_part;
 7238:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 7239:     while (my $line = <IN>) {
 7240:         #ok, I know it's clunky, but I want it to work
 7241:         my @paths_and_file = split(m|/|, $line);
 7242:         my $file_part = pop(@paths_and_file);
 7243:         chomp($file_part);
 7244:         my $path_part = join('/', @paths_and_file);
 7245:         $path_part .= '/';
 7246:         my $path_and_file = $path_part.$file_part;
 7247:         if ($path_part ne $path) {
 7248:             push(@return_files, ($path_and_file));
 7249:         }
 7250:     }
 7251:     close(OUT);
 7252:     return (@return_files);
 7253: }
 7254: 
 7255: #----------------------------------------------Get portfolio file permissions
 7256: 
 7257: sub get_portfile_permissions {
 7258:     my ($domain,$user) = @_;
 7259:     my %current_permissions = &dump('file_permissions',$domain,$user);
 7260:     my ($tmp)=keys(%current_permissions);
 7261:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 7262:     return \%current_permissions;
 7263: }
 7264: 
 7265: #---------------------------------------------Get portfolio file access controls
 7266: 
 7267: sub get_access_controls {
 7268:     my ($current_permissions,$group,$file) = @_;
 7269:     my %access;
 7270:     my $real_file = $file;
 7271:     $file =~ s/\.meta$//;
 7272:     if (defined($file)) {
 7273:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 7274:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 7275:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 7276:             }
 7277:         }
 7278:     } else {
 7279:         foreach my $key (keys(%{$current_permissions})) {
 7280:             if ($key =~ /\0accesscontrol$/) {
 7281:                 if (defined($group)) {
 7282:                     if ($key !~ m-^\Q$group\E/-) {
 7283:                         next;
 7284:                     }
 7285:                 }
 7286:                 my ($fullpath) = split(/\0/,$key);
 7287:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 7288:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 7289:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 7290:                     }
 7291:                 }
 7292:             }
 7293:         }
 7294:     }
 7295:     return %access;
 7296: }
 7297: 
 7298: sub modify_access_controls {
 7299:     my ($file_name,$changes,$domain,$user)=@_;
 7300:     my ($outcome,$deloutcome);
 7301:     my %store_permissions;
 7302:     my %new_values;
 7303:     my %new_control;
 7304:     my %translation;
 7305:     my @deletions = ();
 7306:     my $now = time;
 7307:     if (exists($$changes{'activate'})) {
 7308:         if (ref($$changes{'activate'}) eq 'HASH') {
 7309:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 7310:             my $numnew = scalar(@newitems);
 7311:             for (my $i=0; $i<$numnew; $i++) {
 7312:                 my $newkey = $newitems[$i];
 7313:                 my $newid = &Apache::loncommon::get_cgi_id();
 7314:                 if ($newkey =~ /^\d+:/) { 
 7315:                     $newkey =~ s/^(\d+)/$newid/;
 7316:                     $translation{$1} = $newid;
 7317:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 7318:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 7319:                     $translation{$1} = $newid;
 7320:                 }
 7321:                 $new_values{$file_name."\0".$newkey} = 
 7322:                                           $$changes{'activate'}{$newitems[$i]};
 7323:                 $new_control{$newkey} = $now;
 7324:             }
 7325:         }
 7326:     }
 7327:     my %todelete;
 7328:     my %changed_items;
 7329:     foreach my $action ('delete','update') {
 7330:         if (exists($$changes{$action})) {
 7331:             if (ref($$changes{$action}) eq 'HASH') {
 7332:                 foreach my $key (keys(%{$$changes{$action}})) {
 7333:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 7334:                     if ($action eq 'delete') { 
 7335:                         $todelete{$itemnum} = 1;
 7336:                     } else {
 7337:                         $changed_items{$itemnum} = $key;
 7338:                     }
 7339:                 }
 7340:             }
 7341:         }
 7342:     }
 7343:     # get lock on access controls for file.
 7344:     my $lockhash = {
 7345:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 7346:                                                        ':'.$env{'user.domain'},
 7347:                    }; 
 7348:     my $tries = 0;
 7349:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 7350:    
 7351:     while (($gotlock ne 'ok') && $tries <3) {
 7352:         $tries ++;
 7353:         sleep 1;
 7354:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 7355:     }
 7356:     if ($gotlock eq 'ok') {
 7357:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 7358:         my ($tmp)=keys(%curr_permissions);
 7359:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 7360:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 7361:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 7362:             if (ref($curr_controls) eq 'HASH') {
 7363:                 foreach my $control_item (keys(%{$curr_controls})) {
 7364:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 7365:                     if (defined($todelete{$itemnum})) {
 7366:                         push(@deletions,$file_name."\0".$control_item);
 7367:                     } else {
 7368:                         if (defined($changed_items{$itemnum})) {
 7369:                             $new_control{$changed_items{$itemnum}} = $now;
 7370:                             push(@deletions,$file_name."\0".$control_item);
 7371:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 7372:                         } else {
 7373:                             $new_control{$control_item} = $$curr_controls{$control_item};
 7374:                         }
 7375:                     }
 7376:                 }
 7377:             }
 7378:         }
 7379:         my ($group);
 7380:         if (&is_course($domain,$user)) {
 7381:             ($group,my $file) = split(/\//,$file_name,2);
 7382:         }
 7383:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 7384:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 7385:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 7386:         #  remove lock
 7387:         my @del_lock = ($file_name."\0".'locked_access_records');
 7388:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 7389:         my $sqlresult =
 7390:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 7391:                                     $group);
 7392:     } else {
 7393:         $outcome = "error: could not obtain lockfile\n";  
 7394:     }
 7395:     return ($outcome,$deloutcome,\%new_values,\%translation);
 7396: }
 7397: 
 7398: sub make_public_indefinitely {
 7399:     my ($requrl) = @_;
 7400:     my $now = time;
 7401:     my $action = 'activate';
 7402:     my $aclnum = 0;
 7403:     if (&is_portfolio_url($requrl)) {
 7404:         my (undef,$udom,$unum,$file_name,$group) =
 7405:             &parse_portfolio_url($requrl);
 7406:         my $current_perms = &get_portfile_permissions($udom,$unum);
 7407:         my %access_controls = &get_access_controls($current_perms,
 7408:                                                    $group,$file_name);
 7409:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 7410:             my ($num,$scope,$end,$start) = 
 7411:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 7412:             if ($scope eq 'public') {
 7413:                 if ($start <= $now && $end == 0) {
 7414:                     $action = 'none';
 7415:                 } else {
 7416:                     $action = 'update';
 7417:                     $aclnum = $num;
 7418:                 }
 7419:                 last;
 7420:             }
 7421:         }
 7422:         if ($action eq 'none') {
 7423:              return 'ok';
 7424:         } else {
 7425:             my %changes;
 7426:             my $newend = 0;
 7427:             my $newstart = $now;
 7428:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 7429:             $changes{$action}{$newkey} = {
 7430:                 type => 'public',
 7431:                 time => {
 7432:                     start => $newstart,
 7433:                     end   => $newend,
 7434:                 },
 7435:             };
 7436:             my ($outcome,$deloutcome,$new_values,$translation) =
 7437:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 7438:             return $outcome;
 7439:         }
 7440:     } else {
 7441:         return 'invalid';
 7442:     }
 7443: }
 7444: 
 7445: #------------------------------------------------------Get Marked as Read Only
 7446: 
 7447: sub get_marked_as_readonly {
 7448:     my ($domain,$user,$what,$group) = @_;
 7449:     my $current_permissions = &get_portfile_permissions($domain,$user);
 7450:     my @readonly_files;
 7451:     my $cmp1=$what;
 7452:     if (ref($what)) { $cmp1=join('',@{$what}) };
 7453:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 7454:         if (defined($group)) {
 7455:             if ($file_name !~ m-^\Q$group\E/-) {
 7456:                 next;
 7457:             }
 7458:         }
 7459:         if (ref($value) eq "ARRAY"){
 7460:             foreach my $stored_what (@{$value}) {
 7461:                 my $cmp2=$stored_what;
 7462:                 if (ref($stored_what) eq 'ARRAY') {
 7463:                     $cmp2=join('',@{$stored_what});
 7464:                 }
 7465:                 if ($cmp1 eq $cmp2) {
 7466:                     push(@readonly_files, $file_name);
 7467:                     last;
 7468:                 } elsif (!defined($what)) {
 7469:                     push(@readonly_files, $file_name);
 7470:                     last;
 7471:                 }
 7472:             }
 7473:         }
 7474:     }
 7475:     return @readonly_files;
 7476: }
 7477: #-----------------------------------------------------------Get Marked as Read Only Hash
 7478: 
 7479: sub get_marked_as_readonly_hash {
 7480:     my ($current_permissions,$group,$what) = @_;
 7481:     my %readonly_files;
 7482:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 7483:         if (defined($group)) {
 7484:             if ($file_name !~ m-^\Q$group\E/-) {
 7485:                 next;
 7486:             }
 7487:         }
 7488:         if (ref($value) eq "ARRAY"){
 7489:             foreach my $stored_what (@{$value}) {
 7490:                 if (ref($stored_what) eq 'ARRAY') {
 7491:                     foreach my $lock_descriptor(@{$stored_what}) {
 7492:                         if ($lock_descriptor eq 'graded') {
 7493:                             $readonly_files{$file_name} = 'graded';
 7494:                         } elsif ($lock_descriptor eq 'handback') {
 7495:                             $readonly_files{$file_name} = 'handback';
 7496:                         } else {
 7497:                             if (!exists($readonly_files{$file_name})) {
 7498:                                 $readonly_files{$file_name} = 'locked';
 7499:                             }
 7500:                         }
 7501:                     }
 7502:                 } 
 7503:             }
 7504:         } 
 7505:     }
 7506:     return %readonly_files;
 7507: }
 7508: # ------------------------------------------------------------ Unmark as Read Only
 7509: 
 7510: sub unmark_as_readonly {
 7511:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 7512:     # for portfolio submissions, $what contains [$symb,$crsid] 
 7513:     my ($domain,$user,$what,$file_name,$group) = @_;
 7514:     $file_name = &declutter_portfile($file_name);
 7515:     my $symb_crs = $what;
 7516:     if (ref($what)) { $symb_crs=join('',@$what); }
 7517:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 7518:     my ($tmp)=keys(%current_permissions);
 7519:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 7520:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 7521:     foreach my $file (@readonly_files) {
 7522: 	my $clean_file = &declutter_portfile($file);
 7523: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 7524: 	my $current_locks = $current_permissions{$file};
 7525:         my @new_locks;
 7526:         my @del_keys;
 7527:         if (ref($current_locks) eq "ARRAY"){
 7528:             foreach my $locker (@{$current_locks}) {
 7529:                 my $compare=$locker;
 7530:                 if (ref($locker) eq 'ARRAY') {
 7531:                     $compare=join('',@{$locker});
 7532:                     if ($compare ne $symb_crs) {
 7533:                         push(@new_locks, $locker);
 7534:                     }
 7535:                 }
 7536:             }
 7537:             if (scalar(@new_locks) > 0) {
 7538:                 $current_permissions{$file} = \@new_locks;
 7539:             } else {
 7540:                 push(@del_keys, $file);
 7541:                 &del('file_permissions',\@del_keys, $domain, $user);
 7542:                 delete($current_permissions{$file});
 7543:             }
 7544:         }
 7545:     }
 7546:     &put('file_permissions',\%current_permissions,$domain,$user);
 7547:     return;
 7548: }
 7549: 
 7550: # ------------------------------------------------------------ Directory lister
 7551: 
 7552: sub dirlist {
 7553:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 7554:     $uri=~s/^\///;
 7555:     $uri=~s/\/$//;
 7556:     my ($udom, $uname);
 7557:     if ($getuserdir) {
 7558:         $udom = $userdomain;
 7559:         $uname = $username;
 7560:     } else {
 7561:         (undef,$udom,$uname)=split(/\//,$uri);
 7562:         if(defined($userdomain)) {
 7563:             $udom = $userdomain;
 7564:         }
 7565:         if(defined($username)) {
 7566:             $uname = $username;
 7567:         }
 7568:     }
 7569:     my ($dirRoot,$listing,@listing_results);
 7570: 
 7571:     $dirRoot = $perlvar{'lonDocRoot'};
 7572:     if (defined($getpropath)) {
 7573:         $dirRoot = &propath($udom,$uname);
 7574:         $dirRoot =~ s/\/$//;
 7575:     } elsif (defined($getuserdir)) {
 7576:         my $subdir=$uname.'__';
 7577:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 7578:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 7579:                    ."/$udom/$subdir/$uname";
 7580:     } elsif (defined($alternateRoot)) {
 7581:         $dirRoot = $alternateRoot;
 7582:     }
 7583: 
 7584:     if($udom) {
 7585:         if($uname) {
 7586:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 7587:                               .$getuserdir.':'.&escape($dirRoot)
 7588:                               .':'.&escape($uname).':'.&escape($udom),
 7589:                               &homeserver($uname,$udom));
 7590:             if ($listing eq 'unknown_cmd') {
 7591:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
 7592:                                   &homeserver($uname,$udom));
 7593:             } else {
 7594:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 7595:             }
 7596:             if ($listing eq 'unknown_cmd') {
 7597:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
 7598: 				  &homeserver($uname,$udom));
 7599:                 @listing_results = split(/:/,$listing);
 7600:             } else {
 7601:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 7602:             }
 7603:             return @listing_results;
 7604:         } elsif(!$alternateRoot) {
 7605:             my %allusers;
 7606: 	    my %servers = &get_servers($udom,'library');
 7607:  	    foreach my $tryserver (keys(%servers)) {
 7608:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 7609:                                   &escape($udom),$tryserver);
 7610:                 if ($listing eq 'unknown_cmd') {
 7611: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 7612: 				      $udom, $tryserver);
 7613:                 } else {
 7614:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 7615:                 }
 7616: 		if ($listing eq 'unknown_cmd') {
 7617: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 7618: 				      $udom, $tryserver);
 7619: 		    @listing_results = split(/:/,$listing);
 7620: 		} else {
 7621: 		    @listing_results =
 7622: 			map { &unescape($_); } split(/:/,$listing);
 7623: 		}
 7624: 		if ($listing_results[0] ne 'no_such_dir' && 
 7625: 		    $listing_results[0] ne 'empty'       &&
 7626: 		    $listing_results[0] ne 'con_lost') {
 7627: 		    foreach my $line (@listing_results) {
 7628: 			my ($entry) = split(/&/,$line,2);
 7629: 			$allusers{$entry} = 1;
 7630: 		    }
 7631: 		}
 7632:             }
 7633:             my $alluserstr='';
 7634:             foreach my $user (sort(keys(%allusers))) {
 7635:                 $alluserstr.=$user.'&user:';
 7636:             }
 7637:             $alluserstr=~s/:$//;
 7638:             return split(/:/,$alluserstr);
 7639:         } else {
 7640:             return ('missing user name');
 7641:         }
 7642:     } elsif(!defined($getpropath)) {
 7643:         my @all_domains = sort(&all_domains());
 7644:         foreach my $domain (@all_domains) {
 7645:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
 7646:         }
 7647:         return @all_domains;
 7648:     } else {
 7649:         return ('missing domain');
 7650:     }
 7651: }
 7652: 
 7653: # --------------------------------------------- GetFileTimestamp
 7654: # This function utilizes dirlist and returns the date stamp for
 7655: # when it was last modified.  It will also return an error of -1
 7656: # if an error occurs
 7657: 
 7658: sub GetFileTimestamp {
 7659:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 7660:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 7661:     $studentName   = &LONCAPA::clean_username($studentName);
 7662:     my ($fileStat) = 
 7663:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
 7664:                                  undef,$getuserdir);
 7665:     my @stats = split('&', $fileStat);
 7666:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 7667:         # @stats contains first the filename, then the stat output
 7668:         return $stats[10]; # so this is 10 instead of 9.
 7669:     } else {
 7670:         return -1;
 7671:     }
 7672: }
 7673: 
 7674: sub stat_file {
 7675:     my ($uri) = @_;
 7676:     $uri = &clutter_with_no_wrapper($uri);
 7677: 
 7678:     my ($udom,$uname,$file);
 7679:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 7680: 	($udom,$uname,$file) =
 7681: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 7682: 	$file = 'userfiles/'.$file;
 7683:     }
 7684:     if ($uri =~ m-^/res/-) {
 7685: 	($udom,$uname) = 
 7686: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 7687: 	$file = $uri;
 7688:     }
 7689: 
 7690:     if (!$udom || !$uname || !$file) {
 7691: 	# unable to handle the uri
 7692: 	return ();
 7693:     }
 7694:     my $getpropath;
 7695:     if ($file =~ /^userfiles\//) {
 7696:         $getpropath = 1;
 7697:     }
 7698:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
 7699:     my @stats = split('&', $result);
 7700:     
 7701:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 7702: 	shift(@stats); #filename is first
 7703: 	return @stats;
 7704:     }
 7705:     return ();
 7706: }
 7707: 
 7708: # -------------------------------------------------------- Value of a Condition
 7709: 
 7710: # gets the value of a specific preevaluated condition
 7711: #    stored in the string  $env{user.state.<cid>}
 7712: # or looks up a condition reference in the bighash and if if hasn't
 7713: # already been evaluated recurses into docondval to get the value of
 7714: # the condition, then memoizing it to 
 7715: #   $env{user.state.<cid>.<condition>}
 7716: sub directcondval {
 7717:     my $number=shift;
 7718:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 7719: 	&Apache::lonuserstate::evalstate();
 7720:     }
 7721:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 7722: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 7723:     } elsif ($number =~ /^_/) {
 7724: 	my $sub_condition;
 7725: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7726: 		&GDBM_READER(),0640)) {
 7727: 	    $sub_condition=$bighash{'conditions'.$number};
 7728: 	    untie(%bighash);
 7729: 	}
 7730: 	my $value = &docondval($sub_condition);
 7731: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 7732: 	return $value;
 7733:     }
 7734:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 7735:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 7736:     } else {
 7737:        return 2;
 7738:     }
 7739: }
 7740: 
 7741: # get the collection of conditions for this resource
 7742: sub condval {
 7743:     my $condidx=shift;
 7744:     my $allpathcond='';
 7745:     foreach my $cond (split(/\|/,$condidx)) {
 7746: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 7747: 	    $allpathcond.=
 7748: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 7749: 	}
 7750:     }
 7751:     $allpathcond=~s/\|$//;
 7752:     return &docondval($allpathcond);
 7753: }
 7754: 
 7755: #evaluates an expression of conditions
 7756: sub docondval {
 7757:     my ($allpathcond) = @_;
 7758:     my $result=0;
 7759:     if ($env{'request.course.id'}
 7760: 	&& defined($allpathcond)) {
 7761: 	my $operand='|';
 7762: 	my @stack;
 7763: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 7764: 	    if ($chunk eq '(') {
 7765: 		push @stack,($operand,$result);
 7766: 	    } elsif ($chunk eq ')') {
 7767: 		my $before=pop @stack;
 7768: 		if (pop @stack eq '&') {
 7769: 		    $result=$result>$before?$before:$result;
 7770: 		} else {
 7771: 		    $result=$result>$before?$result:$before;
 7772: 		}
 7773: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 7774: 		$operand=$chunk;
 7775: 	    } else {
 7776: 		my $new=directcondval($chunk);
 7777: 		if ($operand eq '&') {
 7778: 		    $result=$result>$new?$new:$result;
 7779: 		} else {
 7780: 		    $result=$result>$new?$result:$new;
 7781: 		}
 7782: 	    }
 7783: 	}
 7784:     }
 7785:     return $result;
 7786: }
 7787: 
 7788: # ---------------------------------------------------- Devalidate courseresdata
 7789: 
 7790: sub devalidatecourseresdata {
 7791:     my ($coursenum,$coursedomain)=@_;
 7792:     my $hashid=$coursenum.':'.$coursedomain;
 7793:     &devalidate_cache_new('courseres',$hashid);
 7794: }
 7795: 
 7796: 
 7797: # --------------------------------------------------- Course Resourcedata Query
 7798: #
 7799: #  Parameters:
 7800: #      $coursenum    - Number of the course.
 7801: #      $coursedomain - Domain at which the course was created.
 7802: #  Returns:
 7803: #     A hash of the course parameters along (I think) with timestamps
 7804: #     and version info.
 7805: 
 7806: sub get_courseresdata {
 7807:     my ($coursenum,$coursedomain)=@_;
 7808:     my $coursehom=&homeserver($coursenum,$coursedomain);
 7809:     my $hashid=$coursenum.':'.$coursedomain;
 7810:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 7811:     my %dumpreply;
 7812:     unless (defined($cached)) {
 7813: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 7814: 	$result=\%dumpreply;
 7815: 	my ($tmp) = keys(%dumpreply);
 7816: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 7817: 	    &do_cache_new('courseres',$hashid,$result,600);
 7818: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 7819: 	    return $tmp;
 7820: 	} elsif ($tmp =~ /^(error)/) {
 7821: 	    $result=undef;
 7822: 	    &do_cache_new('courseres',$hashid,$result,600);
 7823: 	}
 7824:     }
 7825:     return $result;
 7826: }
 7827: 
 7828: sub devalidateuserresdata {
 7829:     my ($uname,$udom)=@_;
 7830:     my $hashid="$udom:$uname";
 7831:     &devalidate_cache_new('userres',$hashid);
 7832: }
 7833: 
 7834: sub get_userresdata {
 7835:     my ($uname,$udom)=@_;
 7836:     #most student don\'t have any data set, check if there is some data
 7837:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 7838: 
 7839:     my $hashid="$udom:$uname";
 7840:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 7841:     if (!defined($cached)) {
 7842: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 7843: 	$result=\%resourcedata;
 7844: 	&do_cache_new('userres',$hashid,$result,600);
 7845:     }
 7846:     my ($tmp)=keys(%$result);
 7847:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 7848: 	return $result;
 7849:     }
 7850:     #error 2 occurs when the .db doesn't exist
 7851:     if ($tmp!~/error: 2 /) {
 7852: 	&logthis("<font color=\"blue\">WARNING:".
 7853: 		 " Trying to get resource data for ".
 7854: 		 $uname." at ".$udom.": ".
 7855: 		 $tmp."</font>");
 7856:     } elsif ($tmp=~/error: 2 /) {
 7857: 	#&EXT_cache_set($udom,$uname);
 7858: 	&do_cache_new('userres',$hashid,undef,600);
 7859: 	undef($tmp); # not really an error so don't send it back
 7860:     }
 7861:     return $tmp;
 7862: }
 7863: #----------------------------------------------- resdata - return resource data
 7864: #  Purpose:
 7865: #    Return resource data for either users or for a course.
 7866: #  Parameters:
 7867: #     $name      - Course/user name.
 7868: #     $domain    - Name of the domain the user/course is registered on.
 7869: #     $type      - Type of thing $name is (must be 'course' or 'user'
 7870: #     @which     - Array of names of resources desired.
 7871: #  Returns:
 7872: #     The value of the first reasource in @which that is found in the
 7873: #     resource hash.
 7874: #  Exceptional Conditions:
 7875: #     If the $type passed in is not valid (not the string 'course' or 
 7876: #     'user', an undefined  reference is returned.
 7877: #     If none of the resources are found, an undef is returned
 7878: sub resdata {
 7879:     my ($name,$domain,$type,@which)=@_;
 7880:     my $result;
 7881:     if ($type eq 'course') {
 7882: 	$result=&get_courseresdata($name,$domain);
 7883:     } elsif ($type eq 'user') {
 7884: 	$result=&get_userresdata($name,$domain);
 7885:     }
 7886:     if (!ref($result)) { return $result; }    
 7887:     foreach my $item (@which) {
 7888: 	if (defined($result->{$item->[0]})) {
 7889: 	    return [$result->{$item->[0]},$item->[1]];
 7890: 	}
 7891:     }
 7892:     return undef;
 7893: }
 7894: 
 7895: #
 7896: # EXT resource caching routines
 7897: #
 7898: 
 7899: sub clear_EXT_cache_status {
 7900:     &delenv('cache.EXT.');
 7901: }
 7902: 
 7903: sub EXT_cache_status {
 7904:     my ($target_domain,$target_user) = @_;
 7905:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 7906:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 7907:         # We know already the user has no data
 7908:         return 1;
 7909:     } else {
 7910:         return 0;
 7911:     }
 7912: }
 7913: 
 7914: sub EXT_cache_set {
 7915:     my ($target_domain,$target_user) = @_;
 7916:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 7917:     #&appenv({$cachename => time});
 7918: }
 7919: 
 7920: # --------------------------------------------------------- Value of a Variable
 7921: sub EXT {
 7922: 
 7923:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 7924:     unless ($varname) { return ''; }
 7925:     #get real user name/domain, courseid and symb
 7926:     my $courseid;
 7927:     my $publicuser;
 7928:     if ($symbparm) {
 7929: 	$symbparm=&get_symb_from_alias($symbparm);
 7930:     }
 7931:     if (!($uname && $udom)) {
 7932:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 7933:       if (!$symbparm) {	$symbparm=$cursymb; }
 7934:     } else {
 7935: 	$courseid=$env{'request.course.id'};
 7936:     }
 7937:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 7938:     my $rest;
 7939:     if (defined($therest[0])) {
 7940:        $rest=join('.',@therest);
 7941:     } else {
 7942:        $rest='';
 7943:     }
 7944: 
 7945:     my $qualifierrest=$qualifier;
 7946:     if ($rest) { $qualifierrest.='.'.$rest; }
 7947:     my $spacequalifierrest=$space;
 7948:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 7949:     if ($realm eq 'user') {
 7950: # --------------------------------------------------------------- user.resource
 7951: 	if ($space eq 'resource') {
 7952: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 7953: 		  || defined($Apache::lonhomework::parsing_a_task))
 7954: 		 &&
 7955: 		 ($symbparm eq &symbread()) ) {	
 7956: 		# if we are in the middle of processing the resource the
 7957: 		# get the value we are planning on committing
 7958:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 7959:                     return $Apache::lonhomework::results{$qualifierrest};
 7960:                 } else {
 7961:                     return $Apache::lonhomework::history{$qualifierrest};
 7962:                 }
 7963: 	    } else {
 7964: 		my %restored;
 7965: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 7966: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 7967: 		} else {
 7968: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 7969: 		}
 7970: 		return $restored{$qualifierrest};
 7971: 	    }
 7972: # ----------------------------------------------------------------- user.access
 7973:         } elsif ($space eq 'access') {
 7974: 	    # FIXME - not supporting calls for a specific user
 7975:             return &allowed($qualifier,$rest);
 7976: # ------------------------------------------ user.preferences, user.environment
 7977:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 7978: 	    if (($uname eq $env{'user.name'}) &&
 7979: 		($udom eq $env{'user.domain'})) {
 7980: 		return $env{join('.',('environment',$qualifierrest))};
 7981: 	    } else {
 7982: 		my %returnhash;
 7983: 		if (!$publicuser) {
 7984: 		    %returnhash=&userenvironment($udom,$uname,
 7985: 						 $qualifierrest);
 7986: 		}
 7987: 		return $returnhash{$qualifierrest};
 7988: 	    }
 7989: # ----------------------------------------------------------------- user.course
 7990:         } elsif ($space eq 'course') {
 7991: 	    # FIXME - not supporting calls for a specific user
 7992:             return $env{join('.',('request.course',$qualifier))};
 7993: # ------------------------------------------------------------------- user.role
 7994:         } elsif ($space eq 'role') {
 7995: 	    # FIXME - not supporting calls for a specific user
 7996:             my ($role,$where)=split(/\./,$env{'request.role'});
 7997:             if ($qualifier eq 'value') {
 7998: 		return $role;
 7999:             } elsif ($qualifier eq 'extent') {
 8000:                 return $where;
 8001:             }
 8002: # ----------------------------------------------------------------- user.domain
 8003:         } elsif ($space eq 'domain') {
 8004:             return $udom;
 8005: # ------------------------------------------------------------------- user.name
 8006:         } elsif ($space eq 'name') {
 8007:             return $uname;
 8008: # ---------------------------------------------------- Any other user namespace
 8009:         } else {
 8010: 	    my %reply;
 8011: 	    if (!$publicuser) {
 8012: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 8013: 	    }
 8014: 	    return $reply{$qualifierrest};
 8015:         }
 8016:     } elsif ($realm eq 'query') {
 8017: # ---------------------------------------------- pull stuff out of query string
 8018:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 8019: 						[$spacequalifierrest]);
 8020: 	return $env{'form.'.$spacequalifierrest}; 
 8021:    } elsif ($realm eq 'request') {
 8022: # ------------------------------------------------------------- request.browser
 8023:         if ($space eq 'browser') {
 8024: 	    if ($qualifier eq 'textremote') {
 8025: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
 8026: 		    return 1;
 8027: 		} else {
 8028: 		    return 0;
 8029: 		}
 8030: 	    } else {
 8031: 		return $env{'browser.'.$qualifier};
 8032: 	    }
 8033: # ------------------------------------------------------------ request.filename
 8034:         } else {
 8035:             return $env{'request.'.$spacequalifierrest};
 8036:         }
 8037:     } elsif ($realm eq 'course') {
 8038: # ---------------------------------------------------------- course.description
 8039:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 8040:     } elsif ($realm eq 'resource') {
 8041: 
 8042: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 8043: 	    if (!$symbparm) { $symbparm=&symbread(); }
 8044: 	}
 8045: 
 8046: 	if ($space eq 'title') {
 8047: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 8048: 	    return &gettitle($symbparm);
 8049: 	}
 8050: 	
 8051: 	if ($space eq 'map') {
 8052: 	    my ($map) = &decode_symb($symbparm);
 8053: 	    return &symbread($map);
 8054: 	}
 8055: 	if ($space eq 'filename') {
 8056: 	    if ($symbparm) {
 8057: 		return &clutter((&decode_symb($symbparm))[2]);
 8058: 	    }
 8059: 	    return &hreflocation('',$env{'request.filename'});
 8060: 	}
 8061: 
 8062: 	my ($section, $group, @groups);
 8063: 	my ($courselevelm,$courselevel);
 8064: 	if ($symbparm && defined($courseid) && 
 8065: 	    $courseid eq $env{'request.course.id'}) {
 8066: 
 8067: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 8068: 
 8069: # ----------------------------------------------------- Cascading lookup scheme
 8070: 	    my $symbp=$symbparm;
 8071: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 8072: 
 8073: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 8074: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 8075: 
 8076: 	    if (($env{'user.name'} eq $uname) &&
 8077: 		($env{'user.domain'} eq $udom)) {
 8078: 		$section=$env{'request.course.sec'};
 8079:                 @groups = split(/:/,$env{'request.course.groups'});  
 8080:                 @groups=&sort_course_groups($courseid,@groups); 
 8081: 	    } else {
 8082: 		if (! defined($usection)) {
 8083: 		    $section=&getsection($udom,$uname,$courseid);
 8084: 		} else {
 8085: 		    $section = $usection;
 8086: 		}
 8087:                 @groups = &get_users_groups($udom,$uname,$courseid);
 8088: 	    }
 8089: 
 8090: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 8091: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 8092: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 8093: 
 8094: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 8095: 	    my $courselevelr=$courseid.'.'.$symbparm;
 8096: 	    $courselevelm=$courseid.'.'.$mapparm;
 8097: 
 8098: # ----------------------------------------------------------- first, check user
 8099: 
 8100: 	    my $userreply=&resdata($uname,$udom,'user',
 8101: 				       ([$courselevelr,'resource'],
 8102: 					[$courselevelm,'map'     ],
 8103: 					[$courselevel, 'course'  ]));
 8104: 	    if (defined($userreply)) { return &get_reply($userreply); }
 8105: 
 8106: # ------------------------------------------------ second, check some of course
 8107:             my $coursereply;
 8108:             if (@groups > 0) {
 8109:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 8110:                                        $mapparm,$spacequalifierrest);
 8111:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 8112:             }
 8113: 
 8114: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 8115: 				  $env{'course.'.$courseid.'.domain'},
 8116: 				  'course',
 8117: 				  ([$seclevelr,   'resource'],
 8118: 				   [$seclevelm,   'map'     ],
 8119: 				   [$seclevel,    'course'  ],
 8120: 				   [$courselevelr,'resource']));
 8121: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 8122: 
 8123: # ------------------------------------------------------ third, check map parms
 8124: 	    my %parmhash=();
 8125: 	    my $thisparm='';
 8126: 	    if (tie(%parmhash,'GDBM_File',
 8127: 		    $env{'request.course.fn'}.'_parms.db',
 8128: 		    &GDBM_READER(),0640)) {
 8129: 		$thisparm=$parmhash{$symbparm};
 8130: 		untie(%parmhash);
 8131: 	    }
 8132: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 8133: 	}
 8134: # ------------------------------------------ fourth, look in resource metadata
 8135: 
 8136: 	$spacequalifierrest=~s/\./\_/;
 8137: 	my $filename;
 8138: 	if (!$symbparm) { $symbparm=&symbread(); }
 8139: 	if ($symbparm) {
 8140: 	    $filename=(&decode_symb($symbparm))[2];
 8141: 	} else {
 8142: 	    $filename=$env{'request.filename'};
 8143: 	}
 8144: 	my $metadata=&metadata($filename,$spacequalifierrest);
 8145: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 8146: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 8147: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 8148: 
 8149: # ---------------------------------------------- fourth, look in rest of course
 8150: 	if ($symbparm && defined($courseid) && 
 8151: 	    $courseid eq $env{'request.course.id'}) {
 8152: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 8153: 				     $env{'course.'.$courseid.'.domain'},
 8154: 				     'course',
 8155: 				     ([$courselevelm,'map'   ],
 8156: 				      [$courselevel, 'course']));
 8157: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 8158: 	}
 8159: # ------------------------------------------------------------------ Cascade up
 8160: 	unless ($space eq '0') {
 8161: 	    my @parts=split(/_/,$space);
 8162: 	    my $id=pop(@parts);
 8163: 	    my $part=join('_',@parts);
 8164: 	    if ($part eq '') { $part='0'; }
 8165: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 8166: 				 $symbparm,$udom,$uname,$section,1);
 8167: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 8168: 	}
 8169: 	if ($recurse) { return undef; }
 8170: 	my $pack_def=&packages_tab_default($filename,$varname);
 8171: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 8172: # ---------------------------------------------------- Any other user namespace
 8173:     } elsif ($realm eq 'environment') {
 8174: # ----------------------------------------------------------------- environment
 8175: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 8176: 	    return $env{'environment.'.$spacequalifierrest};
 8177: 	} else {
 8178: 	    if ($uname eq 'anonymous' && $udom eq '') {
 8179: 		return '';
 8180: 	    }
 8181: 	    my %returnhash=&userenvironment($udom,$uname,
 8182: 					    $spacequalifierrest);
 8183: 	    return $returnhash{$spacequalifierrest};
 8184: 	}
 8185:     } elsif ($realm eq 'system') {
 8186: # ----------------------------------------------------------------- system.time
 8187: 	if ($space eq 'time') {
 8188: 	    return time;
 8189:         }
 8190:     } elsif ($realm eq 'server') {
 8191: # ----------------------------------------------------------------- system.time
 8192: 	if ($space eq 'name') {
 8193: 	    return $ENV{'SERVER_NAME'};
 8194:         }
 8195:     }
 8196:     return '';
 8197: }
 8198: 
 8199: sub get_reply {
 8200:     my ($reply_value) = @_;
 8201:     if (ref($reply_value) eq 'ARRAY') {
 8202:         if (wantarray) {
 8203: 	    return @$reply_value;
 8204:         }
 8205:         return $reply_value->[0];
 8206:     } else {
 8207:         return $reply_value;
 8208:     }
 8209: }
 8210: 
 8211: sub check_group_parms {
 8212:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 8213:     my @groupitems = ();
 8214:     my $resultitem;
 8215:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 8216:     foreach my $group (@{$groups}) {
 8217:         foreach my $level (@levels) {
 8218:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 8219:              push(@groupitems,[$item,$level->[1]]);
 8220:         }
 8221:     }
 8222:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 8223:                             $env{'course.'.$courseid.'.domain'},
 8224:                                      'course',@groupitems);
 8225:     return $coursereply;
 8226: }
 8227: 
 8228: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 8229:     my ($courseid,@groups) = @_;
 8230:     @groups = sort(@groups);
 8231:     return @groups;
 8232: }
 8233: 
 8234: sub packages_tab_default {
 8235:     my ($uri,$varname)=@_;
 8236:     my (undef,$part,$name)=split(/\./,$varname);
 8237: 
 8238:     my (@extension,@specifics,$do_default);
 8239:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 8240: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 8241: 	if ($pack_type eq 'default') {
 8242: 	    $do_default=1;
 8243: 	} elsif ($pack_type eq 'extension') {
 8244: 	    push(@extension,[$package,$pack_type,$pack_part]);
 8245: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 8246: 	    # only look at packages defaults for packages that this id is
 8247: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 8248: 	}
 8249:     }
 8250:     # first look for a package that matches the requested part id
 8251:     foreach my $package (@specifics) {
 8252: 	my (undef,$pack_type,$pack_part)=@{$package};
 8253: 	next if ($pack_part ne $part);
 8254: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 8255: 	    return $packagetab{"$pack_type&$name&default"};
 8256: 	}
 8257:     }
 8258:     # look for any possible matching non extension_ package
 8259:     foreach my $package (@specifics) {
 8260: 	my (undef,$pack_type,$pack_part)=@{$package};
 8261: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 8262: 	    return $packagetab{"$pack_type&$name&default"};
 8263: 	}
 8264: 	if ($pack_type eq 'part') { $pack_part='0'; }
 8265: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 8266: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 8267: 	}
 8268:     }
 8269:     # look for any posible extension_ match
 8270:     foreach my $package (@extension) {
 8271: 	my ($package,$pack_type)=@{$package};
 8272: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 8273: 	    return $packagetab{"$pack_type&$name&default"};
 8274: 	}
 8275: 	if (defined($packagetab{$package."&$name&default"})) {
 8276: 	    return $packagetab{$package."&$name&default"};
 8277: 	}
 8278:     }
 8279:     # look for a global default setting
 8280:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 8281: 	return $packagetab{"default&$name&default"};
 8282:     }
 8283:     return undef;
 8284: }
 8285: 
 8286: sub add_prefix_and_part {
 8287:     my ($prefix,$part)=@_;
 8288:     my $keyroot;
 8289:     if (defined($prefix) && $prefix !~ /^__/) {
 8290: 	# prefix that has a part already
 8291: 	$keyroot=$prefix;
 8292:     } elsif (defined($prefix)) {
 8293: 	# prefix that is missing a part
 8294: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 8295:     } else {
 8296: 	# no prefix at all
 8297: 	if (defined($part)) { $keyroot='_'.$part; }
 8298:     }
 8299:     return $keyroot;
 8300: }
 8301: 
 8302: # ---------------------------------------------------------------- Get metadata
 8303: 
 8304: my %metaentry;
 8305: my %importedpartids;
 8306: sub metadata {
 8307:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 8308:     $uri=&declutter($uri);
 8309:     # if it is a non metadata possible uri return quickly
 8310:     if (($uri eq '') || 
 8311: 	(($uri =~ m|^/*adm/|) && 
 8312: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 8313:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
 8314: 	return undef;
 8315:     }
 8316:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
 8317: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
 8318: 	return undef;
 8319:     }
 8320:     my $filename=$uri;
 8321:     $uri=~s/\.meta$//;
 8322: #
 8323: # Is the metadata already cached?
 8324: # Look at timestamp of caching
 8325: # Everything is cached by the main uri, libraries are never directly cached
 8326: #
 8327:     if (!defined($liburi)) {
 8328: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 8329: 	if (defined($cached)) { return $result->{':'.$what}; }
 8330:     }
 8331:     {
 8332: # Imported parts would go here
 8333:         my %importedids=();
 8334:         my @origfileimportpartids=();
 8335:         my $importedparts=0;
 8336: #
 8337: # Is this a recursive call for a library?
 8338: #
 8339: #	if (! exists($metacache{$uri})) {
 8340: #	    $metacache{$uri}={};
 8341: #	}
 8342: 	my $cachetime = 60*60;
 8343:         if ($liburi) {
 8344: 	    $liburi=&declutter($liburi);
 8345:             $filename=$liburi;
 8346:         } else {
 8347: 	    &devalidate_cache_new('meta',$uri);
 8348: 	    undef(%metaentry);
 8349: 	}
 8350:         my %metathesekeys=();
 8351:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 8352: 	my $metastring;
 8353: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
 8354: 	    my $which = &hreflocation('','/'.($liburi || $uri));
 8355: 	    $metastring = 
 8356: 		&Apache::lonnet::ssi_body($which,
 8357: 					  ('grade_target' => 'meta'));
 8358: 	    $cachetime = 1; # only want this cached in the child not long term
 8359: 	} elsif ($uri !~ m -^(editupload)/-) {
 8360: 	    my $file=&filelocation('',&clutter($filename));
 8361: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 8362: 	    $metastring=&getfile($file);
 8363: 	}
 8364:         my $parser=HTML::LCParser->new(\$metastring);
 8365:         my $token;
 8366:         undef %metathesekeys;
 8367:         while ($token=$parser->get_token) {
 8368: 	    if ($token->[0] eq 'S') {
 8369: 		if (defined($token->[2]->{'package'})) {
 8370: #
 8371: # This is a package - get package info
 8372: #
 8373: 		    my $package=$token->[2]->{'package'};
 8374: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 8375: 		    if (defined($token->[2]->{'id'})) { 
 8376: 			$keyroot.='_'.$token->[2]->{'id'}; 
 8377: 		    }
 8378: 		    if ($metaentry{':packages'}) {
 8379: 			$metaentry{':packages'}.=','.$package.$keyroot;
 8380: 		    } else {
 8381: 			$metaentry{':packages'}=$package.$keyroot;
 8382: 		    }
 8383: 		    foreach my $pack_entry (keys(%packagetab)) {
 8384: 			my $part=$keyroot;
 8385: 			$part=~s/^\_//;
 8386: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 8387: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 8388: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 8389: 			    # ignore package.tab specified default values
 8390:                             # here &package_tab_default() will fetch those
 8391: 			    if ($subp eq 'default') { next; }
 8392: 			    my $value=$packagetab{$pack_entry};
 8393: 			    my $unikey;
 8394: 			    if ($pack =~ /_0$/) {
 8395: 				$unikey='parameter_0_'.$name;
 8396: 				$part=0;
 8397: 			    } else {
 8398: 				$unikey='parameter'.$keyroot.'_'.$name;
 8399: 			    }
 8400: 			    if ($subp eq 'display') {
 8401: 				$value.=' [Part: '.$part.']';
 8402: 			    }
 8403: 			    $metaentry{':'.$unikey.'.part'}=$part;
 8404: 			    $metathesekeys{$unikey}=1;
 8405: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 8406: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 8407: 			    }
 8408: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 8409: 				$metaentry{':'.$unikey}=
 8410: 				    $metaentry{':'.$unikey.'.default'};
 8411: 			    }
 8412: 			}
 8413: 		    }
 8414: 		} else {
 8415: #
 8416: # This is not a package - some other kind of start tag
 8417: #
 8418: 		    my $entry=$token->[1];
 8419: 		    my $unikey='';
 8420: 
 8421: 		    if ($entry eq 'import') {
 8422: #
 8423: # Importing a library here
 8424: #
 8425:                         my $location=$parser->get_text('/import');
 8426:                         my $dir=$filename;
 8427:                         $dir=~s|[^/]*$||;
 8428:                         $location=&filelocation($dir,$location);
 8429:                        
 8430:                         my $importmode=$token->[2]->{'importmode'};
 8431:                         if ($importmode eq 'problem') {
 8432: # Import as problem/response
 8433:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 8434:                         } elsif ($importmode eq 'part') {
 8435: # Import as part(s)
 8436:                            $importedparts=1;
 8437: # We need to get the original file and the imported file to get the part order correct
 8438: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
 8439: # Load and inspect original file
 8440:                            if ($#origfileimportpartids<0) {
 8441:                               undef(%importedpartids);
 8442:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
 8443:                               my $origfile=&getfile($origfilelocation);
 8444:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
 8445:                            }
 8446: 
 8447: # Load and inspect imported file
 8448:                            my $impfile=&getfile($location);
 8449:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
 8450:                            if ($#impfilepartids>=0) {
 8451: # This problem had parts
 8452:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
 8453:                            } else {
 8454: # Importing by turning a single problem into a problem part
 8455: # It gets the import-tags ID as part-ID
 8456:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
 8457:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
 8458:                            }
 8459:                         } else {
 8460: # Normal import
 8461:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 8462:                            if (defined($token->[2]->{'id'})) {
 8463:                               $unikey.='_'.$token->[2]->{'id'};
 8464:                            }
 8465:                         }
 8466: 
 8467: 			if ($depthcount<20) {
 8468: 			    my $metadata = 
 8469: 				&metadata($uri,'keys', $location,$unikey,
 8470: 					  $depthcount+1);
 8471: 			    foreach my $meta (split(',',$metadata)) {
 8472: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 8473: 				$metathesekeys{$meta}=1;
 8474: 			    }
 8475: 			
 8476:                         }
 8477: 		    } else {
 8478: #
 8479: # Not importing, some other kind of non-package, non-library start tag
 8480: # 
 8481:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
 8482:                         if (defined($token->[2]->{'id'})) {
 8483:                             $unikey.='_'.$token->[2]->{'id'};
 8484:                         }
 8485: 			if (defined($token->[2]->{'name'})) { 
 8486: 			    $unikey.='_'.$token->[2]->{'name'}; 
 8487: 			}
 8488: 			$metathesekeys{$unikey}=1;
 8489: 			foreach my $param (@{$token->[3]}) {
 8490: 			    $metaentry{':'.$unikey.'.'.$param} =
 8491: 				$token->[2]->{$param};
 8492: 			}
 8493: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 8494: 			my $default=$metaentry{':'.$unikey.'.default'};
 8495: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 8496: 		 # only ws inside the tag, and not in default, so use default
 8497: 		 # as value
 8498: 			    $metaentry{':'.$unikey}=$default;
 8499: 			} elsif ( $internaltext =~ /\S/ ) {
 8500: 		  # something interesting inside the tag
 8501: 			    $metaentry{':'.$unikey}=$internaltext;
 8502: 			} else {
 8503: 		  # no interesting values, don't set a default
 8504: 			}
 8505: # end of not-a-package not-a-library import
 8506: 		    }
 8507: # end of not-a-package start tag
 8508: 		}
 8509: # the next is the end of "start tag"
 8510: 	    }
 8511: 	}
 8512: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 8513: 	$extension = lc($extension);
 8514: 	if ($extension eq 'htm') { $extension='html'; }
 8515: 
 8516: 	foreach my $key (keys(%packagetab)) {
 8517: 	    #no specific packages #how's our extension
 8518: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 8519: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 8520: 					 \%metathesekeys);
 8521: 	}
 8522: 
 8523: 	if (!exists($metaentry{':packages'})
 8524: 	    || $packagetab{"import_defaults&extension_$extension"}) {
 8525: 	    foreach my $key (keys(%packagetab)) {
 8526: 		#no specific packages well let's get default then
 8527: 		if ($key!~/^default&/) { next; }
 8528: 		&metadata_create_package_def($uri,$key,'default',
 8529: 					     \%metathesekeys);
 8530: 	    }
 8531: 	}
 8532: # are there custom rights to evaluate
 8533: 	if ($metaentry{':copyright'} eq 'custom') {
 8534: 
 8535:     #
 8536:     # Importing a rights file here
 8537:     #
 8538: 	    unless ($depthcount) {
 8539: 		my $location=$metaentry{':customdistributionfile'};
 8540: 		my $dir=$filename;
 8541: 		$dir=~s|[^/]*$||;
 8542: 		$location=&filelocation($dir,$location);
 8543: 		my $rights_metadata =
 8544: 		    &metadata($uri,'keys',$location,'_rights',
 8545: 			      $depthcount+1);
 8546: 		foreach my $rights (split(',',$rights_metadata)) {
 8547: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 8548: 		    $metathesekeys{$rights}=1;
 8549: 		}
 8550: 	    }
 8551: 	}
 8552: 	# uniqifiy package listing
 8553: 	my %seen;
 8554: 	my @uniq_packages =
 8555: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 8556: 	$metaentry{':packages'} = join(',',@uniq_packages);
 8557: 
 8558:         if ($importedparts) {
 8559: # We had imported parts and need to rebuild partorder
 8560:            $metaentry{':partorder'}='';
 8561:            $metathesekeys{'partorder'}=1;
 8562:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
 8563:                if ($origfileimportpartids[$index] eq 'part') {
 8564: # original part, part of the problem
 8565:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
 8566:                } else {
 8567: # we have imported parts at this position
 8568:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
 8569:                }
 8570:            }
 8571:            $metaentry{':partorder'}=~s/^\,//;
 8572:         }
 8573: 
 8574: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 8575: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 8576: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 8577: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
 8578: # this is the end of "was not already recently cached
 8579:     }
 8580:     return $metaentry{':'.$what};
 8581: }
 8582: 
 8583: sub metadata_create_package_def {
 8584:     my ($uri,$key,$package,$metathesekeys)=@_;
 8585:     my ($pack,$name,$subp)=split(/\&/,$key);
 8586:     if ($subp eq 'default') { next; }
 8587:     
 8588:     if (defined($metaentry{':packages'})) {
 8589: 	$metaentry{':packages'}.=','.$package;
 8590:     } else {
 8591: 	$metaentry{':packages'}=$package;
 8592:     }
 8593:     my $value=$packagetab{$key};
 8594:     my $unikey;
 8595:     $unikey='parameter_0_'.$name;
 8596:     $metaentry{':'.$unikey.'.part'}=0;
 8597:     $$metathesekeys{$unikey}=1;
 8598:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 8599: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 8600:     }
 8601:     if (defined($metaentry{':'.$unikey.'.default'})) {
 8602: 	$metaentry{':'.$unikey}=
 8603: 	    $metaentry{':'.$unikey.'.default'};
 8604:     }
 8605: }
 8606: 
 8607: sub metadata_generate_part0 {
 8608:     my ($metadata,$metacache,$uri) = @_;
 8609:     my %allnames;
 8610:     foreach my $metakey (keys(%$metadata)) {
 8611: 	if ($metakey=~/^parameter\_(.*)/) {
 8612: 	  my $part=$$metacache{':'.$metakey.'.part'};
 8613: 	  my $name=$$metacache{':'.$metakey.'.name'};
 8614: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 8615: 	    $allnames{$name}=$part;
 8616: 	  }
 8617: 	}
 8618:     }
 8619:     foreach my $name (keys(%allnames)) {
 8620:       $$metadata{"parameter_0_$name"}=1;
 8621:       my $key=":parameter_0_$name";
 8622:       $$metacache{"$key.part"}='0';
 8623:       $$metacache{"$key.name"}=$name;
 8624:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 8625: 					   $allnames{$name}.'_'.$name.
 8626: 					   '.type'};
 8627:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 8628: 			     '.display'};
 8629:       my $expr='[Part: '.$allnames{$name}.']';
 8630:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 8631:       $$metacache{"$key.display"}=$olddis;
 8632:     }
 8633: }
 8634: 
 8635: # ------------------------------------------------------ Devalidate title cache
 8636: 
 8637: sub devalidate_title_cache {
 8638:     my ($url)=@_;
 8639:     if (!$env{'request.course.id'}) { return; }
 8640:     my $symb=&symbread($url);
 8641:     if (!$symb) { return; }
 8642:     my $key=$env{'request.course.id'}."\0".$symb;
 8643:     &devalidate_cache_new('title',$key);
 8644: }
 8645: 
 8646: # ------------------------------------------------- Get the title of a course
 8647: 
 8648: sub current_course_title {
 8649:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
 8650: }
 8651: # ------------------------------------------------- Get the title of a resource
 8652: 
 8653: sub gettitle {
 8654:     my $urlsymb=shift;
 8655:     my $symb=&symbread($urlsymb);
 8656:     if ($symb) {
 8657: 	my $key=$env{'request.course.id'}."\0".$symb;
 8658: 	my ($result,$cached)=&is_cached_new('title',$key);
 8659: 	if (defined($cached)) { 
 8660: 	    return $result;
 8661: 	}
 8662: 	my ($map,$resid,$url)=&decode_symb($symb);
 8663: 	my $title='';
 8664: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
 8665: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
 8666: 	} else {
 8667: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8668: 		    &GDBM_READER(),0640)) {
 8669: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
 8670: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
 8671: 		untie(%bighash);
 8672: 	    }
 8673: 	}
 8674: 	$title=~s/\&colon\;/\:/gs;
 8675: 	if ($title) {
 8676: 	    return &do_cache_new('title',$key,$title,600);
 8677: 	}
 8678: 	$urlsymb=$url;
 8679:     }
 8680:     my $title=&metadata($urlsymb,'title');
 8681:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 8682:     return $title;
 8683: }
 8684: 
 8685: sub get_slot {
 8686:     my ($which,$cnum,$cdom)=@_;
 8687:     if (!$cnum || !$cdom) {
 8688: 	(undef,my $courseid)=&whichuser();
 8689: 	$cdom=$env{'course.'.$courseid.'.domain'};
 8690: 	$cnum=$env{'course.'.$courseid.'.num'};
 8691:     }
 8692:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 8693:     my %slotinfo;
 8694:     if (exists($remembered{$key})) {
 8695: 	$slotinfo{$which} = $remembered{$key};
 8696:     } else {
 8697: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 8698: 	&Apache::lonhomework::showhash(%slotinfo);
 8699: 	my ($tmp)=keys(%slotinfo);
 8700: 	if ($tmp=~/^error:/) { return (); }
 8701: 	$remembered{$key} = $slotinfo{$which};
 8702:     }
 8703:     if (ref($slotinfo{$which}) eq 'HASH') {
 8704: 	return %{$slotinfo{$which}};
 8705:     }
 8706:     return $slotinfo{$which};
 8707: }
 8708: # ------------------------------------------------- Update symbolic store links
 8709: 
 8710: sub symblist {
 8711:     my ($mapname,%newhash)=@_;
 8712:     $mapname=&deversion(&declutter($mapname));
 8713:     my %hash;
 8714:     if (($env{'request.course.fn'}) && (%newhash)) {
 8715:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 8716:                       &GDBM_WRCREAT(),0640)) {
 8717: 	    foreach my $url (keys(%newhash)) {
 8718: 		next if ($url eq 'last_known'
 8719: 			 && $env{'form.no_update_last_known'});
 8720: 		$hash{declutter($url)}=&encode_symb($mapname,
 8721: 						    $newhash{$url}->[1],
 8722: 						    $newhash{$url}->[0]);
 8723:             }
 8724:             if (untie(%hash)) {
 8725: 		return 'ok';
 8726:             }
 8727:         }
 8728:     }
 8729:     return 'error';
 8730: }
 8731: 
 8732: # --------------------------------------------------------------- Verify a symb
 8733: 
 8734: sub symbverify {
 8735:     my ($symb,$thisurl)=@_;
 8736:     my $thisfn=$thisurl;
 8737:     $thisfn=&declutter($thisfn);
 8738: # direct jump to resource in page or to a sequence - will construct own symbs
 8739:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 8740: # check URL part
 8741:     my ($map,$resid,$url)=&decode_symb($symb);
 8742: 
 8743:     unless ($url eq $thisfn) { return 0; }
 8744: 
 8745:     $symb=&symbclean($symb);
 8746:     $thisurl=&deversion($thisurl);
 8747:     $thisfn=&deversion($thisfn);
 8748: 
 8749:     my %bighash;
 8750:     my $okay=0;
 8751: 
 8752:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8753:                             &GDBM_READER(),0640)) {
 8754:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
 8755:             $thisurl =~ s/\?.+$//;
 8756:         }
 8757:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 8758:         unless ($ids) { 
 8759:            $ids=$bighash{'ids_/'.$thisurl};
 8760:         }
 8761:         if ($ids) {
 8762: # ------------------------------------------------------------------- Has ID(s)
 8763: 	    foreach my $id (split(/\,/,$ids)) {
 8764: 	       my ($mapid,$resid)=split(/\./,$id);
 8765:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
 8766:                    $symb =~ s/\?.+$//;
 8767:                }
 8768:                if (
 8769:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 8770:    eq $symb) { 
 8771: 		   if (($env{'request.role.adv'}) ||
 8772: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
 8773: 		       $okay=1; 
 8774: 		   }
 8775: 	       }
 8776: 	   }
 8777:         }
 8778: 	untie(%bighash);
 8779:     }
 8780:     return $okay;
 8781: }
 8782: 
 8783: # --------------------------------------------------------------- Clean-up symb
 8784: 
 8785: sub symbclean {
 8786:     my $symb=shift;
 8787:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 8788: # remove version from map
 8789:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 8790: 
 8791: # remove version from URL
 8792:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 8793: 
 8794: # remove wrapper
 8795: 
 8796:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 8797:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 8798:     return $symb;
 8799: }
 8800: 
 8801: # ---------------------------------------------- Split symb to find map and url
 8802: 
 8803: sub encode_symb {
 8804:     my ($map,$resid,$url)=@_;
 8805:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 8806: }
 8807: 
 8808: sub decode_symb {
 8809:     my $symb=shift;
 8810:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 8811:     my ($map,$resid,$url)=split(/___/,$symb);
 8812:     return (&fixversion($map),$resid,&fixversion($url));
 8813: }
 8814: 
 8815: sub fixversion {
 8816:     my $fn=shift;
 8817:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 8818:     my %bighash;
 8819:     my $uri=&clutter($fn);
 8820:     my $key=$env{'request.course.id'}.'_'.$uri;
 8821: # is this cached?
 8822:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 8823:     if (defined($cached)) { return $result; }
 8824: # unfortunately not cached, or expired
 8825:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8826: 	    &GDBM_READER(),0640)) {
 8827:  	if ($bighash{'version_'.$uri}) {
 8828:  	    my $version=$bighash{'version_'.$uri};
 8829:  	    unless (($version eq 'mostrecent') || 
 8830: 		    ($version==&getversion($uri))) {
 8831:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 8832:  	    }
 8833:  	}
 8834:  	untie %bighash;
 8835:     }
 8836:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 8837: }
 8838: 
 8839: sub deversion {
 8840:     my $url=shift;
 8841:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 8842:     return $url;
 8843: }
 8844: 
 8845: # ------------------------------------------------------ Return symb list entry
 8846: 
 8847: sub symbread {
 8848:     my ($thisfn,$donotrecurse)=@_;
 8849:     my $cache_str='request.symbread.cached.'.$thisfn;
 8850:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 8851: # no filename provided? try from environment
 8852:     unless ($thisfn) {
 8853:         if ($env{'request.symb'}) {
 8854: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 8855: 	}
 8856: 	$thisfn=$env{'request.filename'};
 8857:     }
 8858:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 8859: # is that filename actually a symb? Verify, clean, and return
 8860:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 8861: 	if (&symbverify($thisfn,$1)) {
 8862: 	    return $env{$cache_str}=&symbclean($thisfn);
 8863: 	}
 8864:     }
 8865:     $thisfn=declutter($thisfn);
 8866:     my %hash;
 8867:     my %bighash;
 8868:     my $syval='';
 8869:     if (($env{'request.course.fn'}) && ($thisfn)) {
 8870:         my $targetfn = $thisfn;
 8871:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 8872:             $targetfn = 'adm/wrapper/'.$thisfn;
 8873:         }
 8874: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 8875: 	    $targetfn=$1;
 8876: 	}
 8877:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 8878:                       &GDBM_READER(),0640)) {
 8879: 	    $syval=$hash{$targetfn};
 8880:             untie(%hash);
 8881:         }
 8882: # ---------------------------------------------------------- There was an entry
 8883:         if ($syval) {
 8884: 	    #unless ($syval=~/\_\d+$/) {
 8885: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 8886: 		    #&appenv({'request.ambiguous' => $thisfn});
 8887: 		    #return $env{$cache_str}='';
 8888: 		#}    
 8889: 		#$syval.=$1;
 8890: 	    #}
 8891:         } else {
 8892: # ------------------------------------------------------- Was not in symb table
 8893:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 8894:                             &GDBM_READER(),0640)) {
 8895: # ---------------------------------------------- Get ID(s) for current resource
 8896:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 8897:               unless ($ids) { 
 8898:                  $ids=$bighash{'ids_/'.$thisfn};
 8899:               }
 8900:               unless ($ids) {
 8901: # alias?
 8902: 		  $ids=$bighash{'mapalias_'.$thisfn};
 8903:               }
 8904:               if ($ids) {
 8905: # ------------------------------------------------------------------- Has ID(s)
 8906:                  my @possibilities=split(/\,/,$ids);
 8907:                  if ($#possibilities==0) {
 8908: # ----------------------------------------------- There is only one possibility
 8909: 		     my ($mapid,$resid)=split(/\./,$ids);
 8910: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 8911: 						    $resid,$thisfn);
 8912:                  } elsif (!$donotrecurse) {
 8913: # ------------------------------------------ There is more than one possibility
 8914:                      my $realpossible=0;
 8915:                      foreach my $id (@possibilities) {
 8916: 			 my $file=$bighash{'src_'.$id};
 8917:                          if (&allowed('bre',$file)) {
 8918:          		    my ($mapid,$resid)=split(/\./,$id);
 8919:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 8920: 				$realpossible++;
 8921:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 8922: 						    $resid,$thisfn);
 8923:                             }
 8924: 			 }
 8925:                      }
 8926: 		     if ($realpossible!=1) { $syval=''; }
 8927:                  } else {
 8928:                      $syval='';
 8929:                  }
 8930: 	      }
 8931:               untie(%bighash)
 8932:            }
 8933:         }
 8934:         if ($syval) {
 8935: 	    return $env{$cache_str}=$syval;
 8936:         }
 8937:     }
 8938:     &appenv({'request.ambiguous' => $thisfn});
 8939:     return $env{$cache_str}='';
 8940: }
 8941: 
 8942: # ---------------------------------------------------------- Return random seed
 8943: 
 8944: sub numval {
 8945:     my $txt=shift;
 8946:     $txt=~tr/A-J/0-9/;
 8947:     $txt=~tr/a-j/0-9/;
 8948:     $txt=~tr/K-T/0-9/;
 8949:     $txt=~tr/k-t/0-9/;
 8950:     $txt=~tr/U-Z/0-5/;
 8951:     $txt=~tr/u-z/0-5/;
 8952:     $txt=~s/\D//g;
 8953:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 8954:     return int($txt);
 8955: }
 8956: 
 8957: sub numval2 {
 8958:     my $txt=shift;
 8959:     $txt=~tr/A-J/0-9/;
 8960:     $txt=~tr/a-j/0-9/;
 8961:     $txt=~tr/K-T/0-9/;
 8962:     $txt=~tr/k-t/0-9/;
 8963:     $txt=~tr/U-Z/0-5/;
 8964:     $txt=~tr/u-z/0-5/;
 8965:     $txt=~s/\D//g;
 8966:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 8967:     my $total;
 8968:     foreach my $val (@txts) { $total+=$val; }
 8969:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 8970:     return int($total);
 8971: }
 8972: 
 8973: sub numval3 {
 8974:     use integer;
 8975:     my $txt=shift;
 8976:     $txt=~tr/A-J/0-9/;
 8977:     $txt=~tr/a-j/0-9/;
 8978:     $txt=~tr/K-T/0-9/;
 8979:     $txt=~tr/k-t/0-9/;
 8980:     $txt=~tr/U-Z/0-5/;
 8981:     $txt=~tr/u-z/0-5/;
 8982:     $txt=~s/\D//g;
 8983:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 8984:     my $total;
 8985:     foreach my $val (@txts) { $total+=$val; }
 8986:     if ($_64bit) { $total=(($total<<32)>>32); }
 8987:     return $total;
 8988: }
 8989: 
 8990: sub digest {
 8991:     my ($data)=@_;
 8992:     my $digest=&Digest::MD5::md5($data);
 8993:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 8994:     my ($e,$f);
 8995:     {
 8996:         use integer;
 8997:         $e=($a+$b);
 8998:         $f=($c+$d);
 8999:         if ($_64bit) {
 9000:             $e=(($e<<32)>>32);
 9001:             $f=(($f<<32)>>32);
 9002:         }
 9003:     }
 9004:     if (wantarray) {
 9005: 	return ($e,$f);
 9006:     } else {
 9007: 	my $g;
 9008: 	{
 9009: 	    use integer;
 9010: 	    $g=($e+$f);
 9011: 	    if ($_64bit) {
 9012: 		$g=(($g<<32)>>32);
 9013: 	    }
 9014: 	}
 9015: 	return $g;
 9016:     }
 9017: }
 9018: 
 9019: sub latest_rnd_algorithm_id {
 9020:     return '64bit5';
 9021: }
 9022: 
 9023: sub get_rand_alg {
 9024:     my ($courseid)=@_;
 9025:     if (!$courseid) { $courseid=(&whichuser())[1]; }
 9026:     if ($courseid) {
 9027: 	return $env{"course.$courseid.rndseed"};
 9028:     }
 9029:     return &latest_rnd_algorithm_id();
 9030: }
 9031: 
 9032: sub validCODE {
 9033:     my ($CODE)=@_;
 9034:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 9035:     return 0;
 9036: }
 9037: 
 9038: sub getCODE {
 9039:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 9040:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 9041: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 9042: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 9043: 	return $Apache::lonhomework::history{'resource.CODE'};
 9044:     }
 9045:     return undef;
 9046: }
 9047: 
 9048: sub rndseed {
 9049:     my ($symb,$courseid,$domain,$username)=@_;
 9050:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
 9051:     if (!defined($symb)) {
 9052: 	unless ($symb=$wsymb) { return time; }
 9053:     }
 9054:     if (!$courseid) { $courseid=$wcourseid; }
 9055:     if (!$domain) { $domain=$wdomain; }
 9056:     if (!$username) { $username=$wusername }
 9057:     my $which=&get_rand_alg();
 9058: 
 9059:     if (defined(&getCODE())) {
 9060: 	if ($which eq '64bit5') {
 9061: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 9062: 	} elsif ($which eq '64bit4') {
 9063: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 9064: 	} else {
 9065: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 9066: 	}
 9067:     } elsif ($which eq '64bit5') {
 9068: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 9069:     } elsif ($which eq '64bit4') {
 9070: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 9071:     } elsif ($which eq '64bit3') {
 9072: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 9073:     } elsif ($which eq '64bit2') {
 9074: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 9075:     } elsif ($which eq '64bit') {
 9076: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 9077:     }
 9078:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 9079: }
 9080: 
 9081: sub rndseed_32bit {
 9082:     my ($symb,$courseid,$domain,$username)=@_;
 9083:     {
 9084: 	use integer;
 9085: 	my $symbchck=unpack("%32C*",$symb) << 27;
 9086: 	my $symbseed=numval($symb) << 22;
 9087: 	my $namechck=unpack("%32C*",$username) << 17;
 9088: 	my $nameseed=numval($username) << 12;
 9089: 	my $domainseed=unpack("%32C*",$domain) << 7;
 9090: 	my $courseseed=unpack("%32C*",$courseid);
 9091: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 9092: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 9093: 	#&logthis("rndseed :$num:$symb");
 9094: 	if ($_64bit) { $num=(($num<<32)>>32); }
 9095: 	return $num;
 9096:     }
 9097: }
 9098: 
 9099: sub rndseed_64bit {
 9100:     my ($symb,$courseid,$domain,$username)=@_;
 9101:     {
 9102: 	use integer;
 9103: 	my $symbchck=unpack("%32S*",$symb) << 21;
 9104: 	my $symbseed=numval($symb) << 10;
 9105: 	my $namechck=unpack("%32S*",$username);
 9106: 	
 9107: 	my $nameseed=numval($username) << 21;
 9108: 	my $domainseed=unpack("%32S*",$domain) << 10;
 9109: 	my $courseseed=unpack("%32S*",$courseid);
 9110: 	
 9111: 	my $num1=$symbchck+$symbseed+$namechck;
 9112: 	my $num2=$nameseed+$domainseed+$courseseed;
 9113: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 9114: 	#&logthis("rndseed :$num:$symb");
 9115: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 9116: 	return "$num1,$num2";
 9117:     }
 9118: }
 9119: 
 9120: sub rndseed_64bit2 {
 9121:     my ($symb,$courseid,$domain,$username)=@_;
 9122:     {
 9123: 	use integer;
 9124: 	# strings need to be an even # of cahracters long, it it is odd the
 9125:         # last characters gets thrown away
 9126: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 9127: 	my $symbseed=numval($symb) << 10;
 9128: 	my $namechck=unpack("%32S*",$username.' ');
 9129: 	
 9130: 	my $nameseed=numval($username) << 21;
 9131: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 9132: 	my $courseseed=unpack("%32S*",$courseid.' ');
 9133: 	
 9134: 	my $num1=$symbchck+$symbseed+$namechck;
 9135: 	my $num2=$nameseed+$domainseed+$courseseed;
 9136: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 9137: 	#&logthis("rndseed :$num:$symb");
 9138: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 9139: 	return "$num1,$num2";
 9140:     }
 9141: }
 9142: 
 9143: sub rndseed_64bit3 {
 9144:     my ($symb,$courseid,$domain,$username)=@_;
 9145:     {
 9146: 	use integer;
 9147: 	# strings need to be an even # of cahracters long, it it is odd the
 9148:         # last characters gets thrown away
 9149: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 9150: 	my $symbseed=numval2($symb) << 10;
 9151: 	my $namechck=unpack("%32S*",$username.' ');
 9152: 	
 9153: 	my $nameseed=numval2($username) << 21;
 9154: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 9155: 	my $courseseed=unpack("%32S*",$courseid.' ');
 9156: 	
 9157: 	my $num1=$symbchck+$symbseed+$namechck;
 9158: 	my $num2=$nameseed+$domainseed+$courseseed;
 9159: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 9160: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 9161: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 9162: 	
 9163: 	return "$num1:$num2";
 9164:     }
 9165: }
 9166: 
 9167: sub rndseed_64bit4 {
 9168:     my ($symb,$courseid,$domain,$username)=@_;
 9169:     {
 9170: 	use integer;
 9171: 	# strings need to be an even # of cahracters long, it it is odd the
 9172:         # last characters gets thrown away
 9173: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 9174: 	my $symbseed=numval3($symb) << 10;
 9175: 	my $namechck=unpack("%32S*",$username.' ');
 9176: 	
 9177: 	my $nameseed=numval3($username) << 21;
 9178: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 9179: 	my $courseseed=unpack("%32S*",$courseid.' ');
 9180: 	
 9181: 	my $num1=$symbchck+$symbseed+$namechck;
 9182: 	my $num2=$nameseed+$domainseed+$courseseed;
 9183: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 9184: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 9185: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 9186: 	
 9187: 	return "$num1:$num2";
 9188:     }
 9189: }
 9190: 
 9191: sub rndseed_64bit5 {
 9192:     my ($symb,$courseid,$domain,$username)=@_;
 9193:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 9194:     return "$num1:$num2";
 9195: }
 9196: 
 9197: sub rndseed_CODE_64bit {
 9198:     my ($symb,$courseid,$domain,$username)=@_;
 9199:     {
 9200: 	use integer;
 9201: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 9202: 	my $symbseed=numval2($symb);
 9203: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 9204: 	my $CODEseed=numval(&getCODE());
 9205: 	my $courseseed=unpack("%32S*",$courseid.' ');
 9206: 	my $num1=$symbseed+$CODEchck;
 9207: 	my $num2=$CODEseed+$courseseed+$symbchck;
 9208: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 9209: 	#&logthis("rndseed :$num1:$num2:$symb");
 9210: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 9211: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 9212: 	return "$num1:$num2";
 9213:     }
 9214: }
 9215: 
 9216: sub rndseed_CODE_64bit4 {
 9217:     my ($symb,$courseid,$domain,$username)=@_;
 9218:     {
 9219: 	use integer;
 9220: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 9221: 	my $symbseed=numval3($symb);
 9222: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 9223: 	my $CODEseed=numval3(&getCODE());
 9224: 	my $courseseed=unpack("%32S*",$courseid.' ');
 9225: 	my $num1=$symbseed+$CODEchck;
 9226: 	my $num2=$CODEseed+$courseseed+$symbchck;
 9227: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 9228: 	#&logthis("rndseed :$num1:$num2:$symb");
 9229: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 9230: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 9231: 	return "$num1:$num2";
 9232:     }
 9233: }
 9234: 
 9235: sub rndseed_CODE_64bit5 {
 9236:     my ($symb,$courseid,$domain,$username)=@_;
 9237:     my $code = &getCODE();
 9238:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 9239:     return "$num1:$num2";
 9240: }
 9241: 
 9242: sub setup_random_from_rndseed {
 9243:     my ($rndseed)=@_;
 9244:     if ($rndseed =~/([,:])/) {
 9245: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 9246: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 9247:     } else {
 9248: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 9249:     }
 9250: }
 9251: 
 9252: sub latest_receipt_algorithm_id {
 9253:     return 'receipt3';
 9254: }
 9255: 
 9256: sub recunique {
 9257:     my $fucourseid=shift;
 9258:     my $unique;
 9259:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 9260: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 9261: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 9262:     } else {
 9263: 	$unique=$perlvar{'lonReceipt'};
 9264:     }
 9265:     return unpack("%32C*",$unique);
 9266: }
 9267: 
 9268: sub recprefix {
 9269:     my $fucourseid=shift;
 9270:     my $prefix;
 9271:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
 9272: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 9273: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 9274:     } else {
 9275: 	$prefix=$perlvar{'lonHostID'};
 9276:     }
 9277:     return unpack("%32C*",$prefix);
 9278: }
 9279: 
 9280: sub ireceipt {
 9281:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 9282: 
 9283:     my $return =&recprefix($fucourseid).'-';
 9284: 
 9285:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
 9286: 	$env{'request.state'} eq 'construct') {
 9287: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
 9288: 	return $return;
 9289:     }
 9290: 
 9291:     my $cuname=unpack("%32C*",$funame);
 9292:     my $cudom=unpack("%32C*",$fudom);
 9293:     my $cucourseid=unpack("%32C*",$fucourseid);
 9294:     my $cusymb=unpack("%32C*",$fusymb);
 9295:     my $cunique=&recunique($fucourseid);
 9296:     my $cpart=unpack("%32S*",$part);
 9297:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 9298: 
 9299: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
 9300: 			       
 9301: 	$return.= ($cunique%$cuname+
 9302: 		   $cunique%$cudom+
 9303: 		   $cusymb%$cuname+
 9304: 		   $cusymb%$cudom+
 9305: 		   $cucourseid%$cuname+
 9306: 		   $cucourseid%$cudom+
 9307: 		   $cpart%$cuname+
 9308: 		   $cpart%$cudom);
 9309:     } else {
 9310: 	$return.= ($cunique%$cuname+
 9311: 		   $cunique%$cudom+
 9312: 		   $cusymb%$cuname+
 9313: 		   $cusymb%$cudom+
 9314: 		   $cucourseid%$cuname+
 9315: 		   $cucourseid%$cudom);
 9316:     }
 9317:     return $return;
 9318: }
 9319: 
 9320: sub receipt {
 9321:     my ($part)=@_;
 9322:     my ($symb,$courseid,$domain,$name) = &whichuser();
 9323:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 9324: }
 9325: 
 9326: sub whichuser {
 9327:     my ($passedsymb)=@_;
 9328:     my ($symb,$courseid,$domain,$name,$publicuser);
 9329:     if (defined($env{'form.grade_symb'})) {
 9330: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
 9331: 	my $allowed=&allowed('vgr',$tmp_courseid);
 9332: 	if (!$allowed &&
 9333: 	    exists($env{'request.course.sec'}) &&
 9334: 	    $env{'request.course.sec'} !~ /^\s*$/) {
 9335: 	    $allowed=&allowed('vgr',$tmp_courseid.
 9336: 			      '/'.$env{'request.course.sec'});
 9337: 	}
 9338: 	if ($allowed) {
 9339: 	    ($symb)=&get_env_multiple('form.grade_symb');
 9340: 	    $courseid=$tmp_courseid;
 9341: 	    ($domain)=&get_env_multiple('form.grade_domain');
 9342: 	    ($name)=&get_env_multiple('form.grade_username');
 9343: 	    return ($symb,$courseid,$domain,$name,$publicuser);
 9344: 	}
 9345:     }
 9346:     if (!$passedsymb) {
 9347: 	$symb=&symbread();
 9348:     } else {
 9349: 	$symb=$passedsymb;
 9350:     }
 9351:     $courseid=$env{'request.course.id'};
 9352:     $domain=$env{'user.domain'};
 9353:     $name=$env{'user.name'};
 9354:     if ($name eq 'public' && $domain eq 'public') {
 9355: 	if (!defined($env{'form.username'})) {
 9356: 	    $env{'form.username'}.=time.rand(10000000);
 9357: 	}
 9358: 	$name.=$env{'form.username'};
 9359:     }
 9360:     return ($symb,$courseid,$domain,$name,$publicuser);
 9361: 
 9362: }
 9363: 
 9364: # ------------------------------------------------------------ Serves up a file
 9365: # returns either the contents of the file or 
 9366: # -1 if the file doesn't exist
 9367: #
 9368: # if the target is a file that was uploaded via DOCS, 
 9369: # a check will be made to see if a current copy exists on the local server,
 9370: # if it does this will be served, otherwise a copy will be retrieved from
 9371: # the home server for the course and stored in /home/httpd/html/userfiles on
 9372: # the local server.   
 9373: 
 9374: sub getfile {
 9375:     my ($file) = @_;
 9376:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 9377:     &repcopy($file);
 9378:     return &readfile($file);
 9379: }
 9380: 
 9381: sub repcopy_userfile {
 9382:     my ($file)=@_;
 9383:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 9384:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 9385:     my ($cdom,$cnum,$filename) = 
 9386: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
 9387:     my $uri="/uploaded/$cdom/$cnum/$filename";
 9388:     if (-e "$file") {
 9389: # we already have a local copy, check it out
 9390: 	my @fileinfo = stat($file);
 9391: 	my $rtncode;
 9392: 	my $info;
 9393: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 9394: 	if ($lwpresp ne 'ok') {
 9395: # there is no such file anymore, even though we had a local copy
 9396: 	    if ($rtncode eq '404') {
 9397: 		unlink($file);
 9398: 	    }
 9399: 	    return -1;
 9400: 	}
 9401: 	if ($info < $fileinfo[9]) {
 9402: # nice, the file we have is up-to-date, just say okay
 9403: 	    return 'ok';
 9404: 	} else {
 9405: # the file is outdated, get rid of it
 9406: 	    unlink($file);
 9407: 	}
 9408:     }
 9409: # one way or the other, at this point, we don't have the file
 9410: # construct the correct path for the file
 9411:     my @parts = ($cdom,$cnum); 
 9412:     if ($filename =~ m|^(.+)/[^/]+$|) {
 9413: 	push @parts, split(/\//,$1);
 9414:     }
 9415:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 9416:     foreach my $part (@parts) {
 9417: 	$path .= '/'.$part;
 9418: 	if (!-e $path) {
 9419: 	    mkdir($path,0770);
 9420: 	}
 9421:     }
 9422: # now the path exists for sure
 9423: # get a user agent
 9424:     my $ua=new LWP::UserAgent;
 9425:     my $transferfile=$file.'.in.transfer';
 9426: # FIXME: this should flock
 9427:     if (-e $transferfile) { return 'ok'; }
 9428:     my $request;
 9429:     $uri=~s/^\///;
 9430:     my $homeserver = &homeserver($cnum,$cdom);
 9431:     my $protocol = $protocol{$homeserver};
 9432:     $protocol = 'http' if ($protocol ne 'https');
 9433:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
 9434:     my $response=$ua->request($request,$transferfile);
 9435: # did it work?
 9436:     if ($response->is_error()) {
 9437: 	unlink($transferfile);
 9438: 	&logthis("Userfile repcopy failed for $uri");
 9439: 	return -1;
 9440:     }
 9441: # worked, rename the transfer file
 9442:     rename($transferfile,$file);
 9443:     return 'ok';
 9444: }
 9445: 
 9446: sub tokenwrapper {
 9447:     my $uri=shift;
 9448:     $uri=~s|^https?\://([^/]+)||;
 9449:     $uri=~s|^/||;
 9450:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
 9451:     my $token=$1;
 9452:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 9453:     if ($udom && $uname && $file) {
 9454: 	$file=~s|(\?\.*)*$||;
 9455:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
 9456:         my $homeserver = &homeserver($uname,$udom);
 9457:         my $protocol = $protocol{$homeserver};
 9458:         $protocol = 'http' if ($protocol ne 'https');
 9459:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
 9460:                (($uri=~/\?/)?'&':'?').'token='.$token.
 9461:                                '&tokenissued='.$perlvar{'lonHostID'};
 9462:     } else {
 9463:         return '/adm/notfound.html';
 9464:     }
 9465: }
 9466: 
 9467: # call with reqtype HEAD: get last modification time
 9468: # call with reqtype GET: get the file contents
 9469: # Do not call this with reqtype GET for large files! It loads everything into memory
 9470: #
 9471: sub getuploaded {
 9472:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 9473:     $uri=~s/^\///;
 9474:     my $homeserver = &homeserver($cnum,$cdom);
 9475:     my $protocol = $protocol{$homeserver};
 9476:     $protocol = 'http' if ($protocol ne 'https');
 9477:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
 9478:     my $ua=new LWP::UserAgent;
 9479:     my $request=new HTTP::Request($reqtype,$uri);
 9480:     my $response=$ua->request($request);
 9481:     $$rtncode = $response->code;
 9482:     if (! $response->is_success()) {
 9483: 	return 'failed';
 9484:     }      
 9485:     if ($reqtype eq 'HEAD') {
 9486: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 9487:     } elsif ($reqtype eq 'GET') {
 9488: 	$$info = $response->content;
 9489:     }
 9490:     return 'ok';
 9491: }
 9492: 
 9493: sub readfile {
 9494:     my $file = shift;
 9495:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 9496:     my $fh;
 9497:     open($fh,"<$file");
 9498:     my $a='';
 9499:     while (my $line = <$fh>) { $a .= $line; }
 9500:     return $a;
 9501: }
 9502: 
 9503: sub filelocation {
 9504:     my ($dir,$file) = @_;
 9505:     my $location;
 9506:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 9507: 
 9508:     if ($file =~ m-^/adm/-) {
 9509: 	$file=~s-^/adm/wrapper/-/-;
 9510: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 9511:     }
 9512: 
 9513:     if ($file=~m:^/~:) { # is a contruction space reference
 9514:         $location = $file;
 9515:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 9516:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
 9517: 	# is a correct contruction space reference
 9518:         $location = $file;
 9519:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
 9520:         $location = $file;
 9521:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
 9522:         my ($udom,$uname,$filename)=
 9523:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
 9524:         my $home=&homeserver($uname,$udom);
 9525:         my $is_me=0;
 9526:         my @ids=&current_machine_ids();
 9527:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 9528:         if ($is_me) {
 9529:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
 9530:         } else {
 9531:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 9532:   	      $udom.'/'.$uname.'/'.$filename;
 9533:         }
 9534:     } elsif ($file =~ m-^/adm/-) {
 9535: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
 9536:     } else {
 9537:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 9538:         $file=~s:^/res/:/:;
 9539:         if ( !( $file =~ m:^/:) ) {
 9540:             $location = $dir. '/'.$file;
 9541:         } else {
 9542:             $location = '/home/httpd/html/res'.$file;
 9543:         }
 9544:     }
 9545:     $location=~s://+:/:g; # remove duplicate /
 9546:     while ($location=~m{/\.\./}) {
 9547: 	if ($location =~ m{/[^/]+/\.\./}) {
 9548: 	    $location=~ s{/[^/]+/\.\./}{/}g;
 9549: 	} else {
 9550: 	    $location=~ s{/\.\./}{/}g;
 9551: 	}
 9552:     } #remove dir/..
 9553:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 9554:     return $location;
 9555: }
 9556: 
 9557: sub hreflocation {
 9558:     my ($dir,$file)=@_;
 9559:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
 9560: 	$file=filelocation($dir,$file);
 9561:     } elsif ($file=~m-^/adm/-) {
 9562: 	$file=~s-^/adm/wrapper/-/-;
 9563: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 9564:     }
 9565:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
 9566: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
 9567:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
 9568: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
 9569:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
 9570: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
 9571: 	    -/uploaded/$1/$2/-x;
 9572:     }
 9573:     if ($file=~ m{^/userfiles/}) {
 9574: 	$file =~ s{^/userfiles/}{/uploaded/};
 9575:     }
 9576:     return $file;
 9577: }
 9578: 
 9579: sub current_machine_domains {
 9580:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
 9581: }
 9582: 
 9583: sub machine_domains {
 9584:     my ($hostname) = @_;
 9585:     my @domains;
 9586:     my %hostname = &all_hostnames();
 9587:     while( my($id, $name) = each(%hostname)) {
 9588: #	&logthis("-$id-$name-$hostname-");
 9589: 	if ($hostname eq $name) {
 9590: 	    push(@domains,&host_domain($id));
 9591: 	}
 9592:     }
 9593:     return @domains;
 9594: }
 9595: 
 9596: sub current_machine_ids {
 9597:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
 9598: }
 9599: 
 9600: sub machine_ids {
 9601:     my ($hostname) = @_;
 9602:     $hostname ||= &hostname($perlvar{'lonHostID'});
 9603:     my @ids;
 9604:     my %name_to_host = &all_names();
 9605:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
 9606: 	return @{ $name_to_host{$hostname} };
 9607:     }
 9608:     return;
 9609: }
 9610: 
 9611: sub additional_machine_domains {
 9612:     my @domains;
 9613:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
 9614:     while( my $line = <$fh>) {
 9615:         $line =~ s/\s//g;
 9616:         push(@domains,$line);
 9617:     }
 9618:     return @domains;
 9619: }
 9620: 
 9621: sub default_login_domain {
 9622:     my $domain = $perlvar{'lonDefDomain'};
 9623:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
 9624:     foreach my $posdom (&current_machine_domains(),
 9625:                         &additional_machine_domains()) {
 9626:         if (lc($posdom) eq lc($testdomain)) {
 9627:             $domain=$posdom;
 9628:             last;
 9629:         }
 9630:     }
 9631:     return $domain;
 9632: }
 9633: 
 9634: # ------------------------------------------------------------- Declutters URLs
 9635: 
 9636: sub declutter {
 9637:     my $thisfn=shift;
 9638:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 9639:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 9640:     $thisfn=~s/^\///;
 9641:     $thisfn=~s|^adm/wrapper/||;
 9642:     $thisfn=~s|^adm/coursedocs/showdoc/||;
 9643:     $thisfn=~s/^res\///;
 9644:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
 9645:         $thisfn=~s/\?.+$//;
 9646:     }
 9647:     return $thisfn;
 9648: }
 9649: 
 9650: # ------------------------------------------------------------- Clutter up URLs
 9651: 
 9652: sub clutter {
 9653:     my $thisfn='/'.&declutter(shift);
 9654:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
 9655: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
 9656:        $thisfn='/res'.$thisfn; 
 9657:     }
 9658:     if ($thisfn !~m|^/adm|) {
 9659: 	if ($thisfn =~ m|^/ext/|) {
 9660: 	    $thisfn='/adm/wrapper'.$thisfn;
 9661: 	} else {
 9662: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
 9663: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
 9664: 	    if ($embstyle eq 'ssi'
 9665: 		|| ($embstyle eq 'hdn')
 9666: 		|| ($embstyle eq 'rat')
 9667: 		|| ($embstyle eq 'prv')
 9668: 		|| ($embstyle eq 'ign')) {
 9669: 		#do nothing with these
 9670: 	    } elsif (($embstyle eq 'img') 
 9671: 		|| ($embstyle eq 'emb')
 9672: 		|| ($embstyle eq 'wrp')) {
 9673: 		$thisfn='/adm/wrapper'.$thisfn;
 9674: 	    } elsif ($embstyle eq 'unk'
 9675: 		     && $thisfn!~/\.(sequence|page)$/) {
 9676: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
 9677: 	    } else {
 9678: #		&logthis("Got a blank emb style");
 9679: 	    }
 9680: 	}
 9681:     }
 9682:     return $thisfn;
 9683: }
 9684: 
 9685: sub clutter_with_no_wrapper {
 9686:     my $uri = &clutter(shift);
 9687:     if ($uri =~ m-^/adm/-) {
 9688: 	$uri =~ s-^/adm/wrapper/-/-;
 9689: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
 9690:     }
 9691:     return $uri;
 9692: }
 9693: 
 9694: sub freeze_escape {
 9695:     my ($value)=@_;
 9696:     if (ref($value)) {
 9697: 	$value=&nfreeze($value);
 9698: 	return '__FROZEN__'.&escape($value);
 9699:     }
 9700:     return &escape($value);
 9701: }
 9702: 
 9703: 
 9704: sub thaw_unescape {
 9705:     my ($value)=@_;
 9706:     if ($value =~ /^__FROZEN__/) {
 9707: 	substr($value,0,10,undef);
 9708: 	$value=&unescape($value);
 9709: 	return &thaw($value);
 9710:     }
 9711:     return &unescape($value);
 9712: }
 9713: 
 9714: sub correct_line_ends {
 9715:     my ($result)=@_;
 9716:     $$result =~s/\r\n/\n/mg;
 9717:     $$result =~s/\r/\n/mg;
 9718: }
 9719: # ================================================================ Main Program
 9720: 
 9721: sub goodbye {
 9722:    &logthis("Starting Shut down");
 9723: #not converted to using infrastruture and probably shouldn't be
 9724:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
 9725: #converted
 9726: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 9727:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
 9728: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
 9729: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
 9730: #1.1 only
 9731: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
 9732: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
 9733: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
 9734: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
 9735:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
 9736:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
 9737:    &logthis(sprintf("%-20s is %s",'hits',$hits));
 9738:    &flushcourselogs();
 9739:    &logthis("Shutting down");
 9740: }
 9741: 
 9742: sub get_dns {
 9743:     my ($url,$func,$ignore_cache) = @_;
 9744:     if (!$ignore_cache) {
 9745: 	my ($content,$cached)=
 9746: 	    &Apache::lonnet::is_cached_new('dns',$url);
 9747: 	if ($cached) {
 9748: 	    &$func($content);
 9749: 	    return;
 9750: 	}
 9751:     }
 9752: 
 9753:     my %alldns;
 9754:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 9755:     foreach my $dns (<$config>) {
 9756: 	next if ($dns !~ /^\^(\S*)/x);
 9757:         my $line = $1;
 9758:         my ($host,$protocol) = split(/:/,$line);
 9759:         if ($protocol ne 'https') {
 9760:             $protocol = 'http';
 9761:         }
 9762: 	$alldns{$host} = $protocol;
 9763:     }
 9764:     while (%alldns) {
 9765: 	my ($dns) = keys(%alldns);
 9766: 	my $ua=new LWP::UserAgent;
 9767: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
 9768: 	my $response=$ua->request($request);
 9769:         delete($alldns{$dns});
 9770: 	next if ($response->is_error());
 9771: 	my @content = split("\n",$response->content);
 9772: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
 9773: 	&$func(\@content);
 9774: 	return;
 9775:     }
 9776:     close($config);
 9777:     my $which = (split('/',$url))[3];
 9778:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
 9779:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
 9780:     my @content = <$config>;
 9781:     &$func(\@content);
 9782:     return;
 9783: }
 9784: # ------------------------------------------------------------ Read domain file
 9785: {
 9786:     my $loaded;
 9787:     my %domain;
 9788: 
 9789:     sub parse_domain_tab {
 9790: 	my ($lines) = @_;
 9791: 	foreach my $line (@$lines) {
 9792: 	    next if ($line =~ /^(\#|\s*$ )/x);
 9793: 
 9794: 	    chomp($line);
 9795: 	    my ($name,@elements) = split(/:/,$line,9);
 9796: 	    my %this_domain;
 9797: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
 9798: 			       'lang_def', 'city', 'longi', 'lati',
 9799: 			       'primary') {
 9800: 		$this_domain{$field} = shift(@elements);
 9801: 	    }
 9802: 	    $domain{$name} = \%this_domain;
 9803: 	}
 9804:     }
 9805: 
 9806:     sub reset_domain_info {
 9807: 	undef($loaded);
 9808: 	undef(%domain);
 9809:     }
 9810: 
 9811:     sub load_domain_tab {
 9812: 	my ($ignore_cache) = @_;
 9813: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
 9814: 	my $fh;
 9815: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
 9816: 	    my @lines = <$fh>;
 9817: 	    &parse_domain_tab(\@lines);
 9818: 	}
 9819: 	close($fh);
 9820: 	$loaded = 1;
 9821:     }
 9822: 
 9823:     sub domain {
 9824: 	&load_domain_tab() if (!$loaded);
 9825: 
 9826: 	my ($name,$what) = @_;
 9827: 	return if ( !exists($domain{$name}) );
 9828: 
 9829: 	if (!$what) {
 9830: 	    return $domain{$name}{'description'};
 9831: 	}
 9832: 	return $domain{$name}{$what};
 9833:     }
 9834: 
 9835:     sub domain_info {
 9836:         &load_domain_tab() if (!$loaded);
 9837:         return %domain;
 9838:     }
 9839: 
 9840: }
 9841: 
 9842: 
 9843: # ------------------------------------------------------------- Read hosts file
 9844: {
 9845:     my %hostname;
 9846:     my %hostdom;
 9847:     my %libserv;
 9848:     my $loaded;
 9849:     my %name_to_host;
 9850:     my %internetdom;
 9851: 
 9852:     sub parse_hosts_tab {
 9853: 	my ($file) = @_;
 9854: 	foreach my $configline (@$file) {
 9855: 	    next if ($configline =~ /^(\#|\s*$ )/x);
 9856: 	    next if ($configline =~ /^\^/);
 9857: 	    chomp($configline);
 9858: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
 9859: 	    $name=~s/\s//g;
 9860: 	    if ($id && $domain && $role && $name) {
 9861: 		$hostname{$id}=$name;
 9862: 		push(@{$name_to_host{$name}}, $id);
 9863: 		$hostdom{$id}=$domain;
 9864: 		if ($role eq 'library') { $libserv{$id}=$name; }
 9865:                 if (defined($protocol)) {
 9866:                     if ($protocol eq 'https') {
 9867:                         $protocol{$id} = $protocol;
 9868:                     } else {
 9869:                         $protocol{$id} = 'http'; 
 9870:                     }
 9871:                 } else {
 9872:                     $protocol{$id} = 'http';
 9873:                 }
 9874:                 if (defined($intdom)) {
 9875:                     $internetdom{$id} = $intdom;
 9876:                 }
 9877: 	    }
 9878: 	}
 9879:     }
 9880:     
 9881:     sub reset_hosts_info {
 9882: 	&purge_remembered();
 9883: 	&reset_domain_info();
 9884: 	&reset_hosts_ip_info();
 9885: 	undef(%name_to_host);
 9886: 	undef(%hostname);
 9887: 	undef(%hostdom);
 9888: 	undef(%libserv);
 9889: 	undef($loaded);
 9890:     }
 9891: 
 9892:     sub load_hosts_tab {
 9893: 	my ($ignore_cache) = @_;
 9894: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
 9895: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 9896: 	my @config = <$config>;
 9897: 	&parse_hosts_tab(\@config);
 9898: 	close($config);
 9899: 	$loaded=1;
 9900:     }
 9901: 
 9902:     sub hostname {
 9903: 	&load_hosts_tab() if (!$loaded);
 9904: 
 9905: 	my ($lonid) = @_;
 9906: 	return $hostname{$lonid};
 9907:     }
 9908: 
 9909:     sub all_hostnames {
 9910: 	&load_hosts_tab() if (!$loaded);
 9911: 
 9912: 	return %hostname;
 9913:     }
 9914: 
 9915:     sub all_names {
 9916: 	&load_hosts_tab() if (!$loaded);
 9917: 
 9918: 	return %name_to_host;
 9919:     }
 9920: 
 9921:     sub all_host_domain {
 9922:         &load_hosts_tab() if (!$loaded);
 9923:         return %hostdom;
 9924:     }
 9925: 
 9926:     sub is_library {
 9927: 	&load_hosts_tab() if (!$loaded);
 9928: 
 9929: 	return exists($libserv{$_[0]});
 9930:     }
 9931: 
 9932:     sub all_library {
 9933: 	&load_hosts_tab() if (!$loaded);
 9934: 
 9935: 	return %libserv;
 9936:     }
 9937: 
 9938:     sub unique_library {
 9939: 	#2x reverse removes all hostnames that appear more than once
 9940:         my %unique = reverse &all_library();
 9941:         return reverse %unique;
 9942:     }
 9943: 
 9944:     sub get_servers {
 9945: 	&load_hosts_tab() if (!$loaded);
 9946: 
 9947: 	my ($domain,$type) = @_;
 9948: 	my %possible_hosts = ($type eq 'library') ? %libserv
 9949: 	                                          : %hostname;
 9950: 	my %result;
 9951: 	if (ref($domain) eq 'ARRAY') {
 9952: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 9953: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
 9954: 		    $result{$host} = $hostname;
 9955: 		}
 9956: 	    }
 9957: 	} else {
 9958: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 9959: 		if ($hostdom{$host} eq $domain) {
 9960: 		    $result{$host} = $hostname;
 9961: 		}
 9962: 	    }
 9963: 	}
 9964: 	return %result;
 9965:     }
 9966: 
 9967:     sub get_unique_servers {
 9968:         my %unique = reverse &get_servers(@_);
 9969: 	return reverse %unique;
 9970:     }
 9971: 
 9972:     sub host_domain {
 9973: 	&load_hosts_tab() if (!$loaded);
 9974: 
 9975: 	my ($lonid) = @_;
 9976: 	return $hostdom{$lonid};
 9977:     }
 9978: 
 9979:     sub all_domains {
 9980: 	&load_hosts_tab() if (!$loaded);
 9981: 
 9982: 	my %seen;
 9983: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
 9984: 	return @uniq;
 9985:     }
 9986: 
 9987:     sub internet_dom {
 9988:         &load_hosts_tab() if (!$loaded);
 9989: 
 9990:         my ($lonid) = @_;
 9991:         return $internetdom{$lonid};
 9992:     }
 9993: }
 9994: 
 9995: { 
 9996:     my %iphost;
 9997:     my %name_to_ip;
 9998:     my %lonid_to_ip;
 9999: 
10000:     sub get_hosts_from_ip {
10001: 	my ($ip) = @_;
10002: 	my %iphosts = &get_iphost();
10003: 	if (ref($iphosts{$ip})) {
10004: 	    return @{$iphosts{$ip}};
10005: 	}
10006: 	return;
10007:     }
10008:     
10009:     sub reset_hosts_ip_info {
10010: 	undef(%iphost);
10011: 	undef(%name_to_ip);
10012: 	undef(%lonid_to_ip);
10013:     }
10014: 
10015:     sub get_host_ip {
10016: 	my ($lonid) = @_;
10017: 	if (exists($lonid_to_ip{$lonid})) {
10018: 	    return $lonid_to_ip{$lonid};
10019: 	}
10020: 	my $name=&hostname($lonid);
10021:    	my $ip = gethostbyname($name);
10022: 	return if (!$ip || length($ip) ne 4);
10023: 	$ip=inet_ntoa($ip);
10024: 	$name_to_ip{$name}   = $ip;
10025: 	$lonid_to_ip{$lonid} = $ip;
10026: 	return $ip;
10027:     }
10028:     
10029:     sub get_iphost {
10030: 	my ($ignore_cache) = @_;
10031: 
10032: 	if (!$ignore_cache) {
10033: 	    if (%iphost) {
10034: 		return %iphost;
10035: 	    }
10036: 	    my ($ip_info,$cached)=
10037: 		&Apache::lonnet::is_cached_new('iphost','iphost');
10038: 	    if ($cached) {
10039: 		%iphost      = %{$ip_info->[0]};
10040: 		%name_to_ip  = %{$ip_info->[1]};
10041: 		%lonid_to_ip = %{$ip_info->[2]};
10042: 		return %iphost;
10043: 	    }
10044: 	}
10045: 
10046: 	# get yesterday's info for fallback
10047: 	my %old_name_to_ip;
10048: 	my ($ip_info,$cached)=
10049: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
10050: 	if ($cached) {
10051: 	    %old_name_to_ip = %{$ip_info->[1]};
10052: 	}
10053: 
10054: 	my %name_to_host = &all_names();
10055: 	foreach my $name (keys(%name_to_host)) {
10056: 	    my $ip;
10057: 	    if (!exists($name_to_ip{$name})) {
10058: 		$ip = gethostbyname($name);
10059: 		if (!$ip || length($ip) ne 4) {
10060: 		    if (defined($old_name_to_ip{$name})) {
10061: 			$ip = $old_name_to_ip{$name};
10062: 			&logthis("Can't find $name defaulting to old $ip");
10063: 		    } else {
10064: 			&logthis("Name $name no IP found");
10065: 			next;
10066: 		    }
10067: 		} else {
10068: 		    $ip=inet_ntoa($ip);
10069: 		}
10070: 		$name_to_ip{$name} = $ip;
10071: 	    } else {
10072: 		$ip = $name_to_ip{$name};
10073: 	    }
10074: 	    foreach my $id (@{ $name_to_host{$name} }) {
10075: 		$lonid_to_ip{$id} = $ip;
10076: 	    }
10077: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
10078: 	}
10079: 	&Apache::lonnet::do_cache_new('iphost','iphost',
10080: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
10081: 				      48*60*60);
10082: 
10083: 	return %iphost;
10084:     }
10085: 
10086:     #
10087:     #  Given a DNS returns the loncapa host name for that DNS 
10088:     # 
10089:     sub host_from_dns {
10090:         my ($dns) = @_;
10091:         my @hosts;
10092:         my $ip;
10093: 
10094:         if (exists($name_to_ip{$dns})) {
10095:             $ip = $name_to_ip{$dns};
10096:         }
10097:         if (!$ip) {
10098:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
10099:             if (length($ip) == 4) { 
10100: 	        $ip   = &IO::Socket::inet_ntoa($ip);
10101:             }
10102:         }
10103:         if ($ip) {
10104: 	    @hosts = get_hosts_from_ip($ip);
10105: 	    return $hosts[0];
10106:         }
10107:         return undef;
10108:     }
10109: 
10110:     sub get_internet_names {
10111:         my ($lonid) = @_;
10112:         return if ($lonid eq '');
10113:         my ($idnref,$cached)=
10114:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
10115:         if ($cached) {
10116:             return $idnref;
10117:         }
10118:         my $ip = &get_host_ip($lonid);
10119:         my @hosts = &get_hosts_from_ip($ip);
10120:         my %iphost = &get_iphost();
10121:         my (@idns,%seen);
10122:         foreach my $id (@hosts) {
10123:             my $dom = &host_domain($id);
10124:             my $prim_id = &domain($dom,'primary');
10125:             my $prim_ip = &get_host_ip($prim_id);
10126:             next if ($seen{$prim_ip});
10127:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
10128:                 foreach my $id (@{$iphost{$prim_ip}}) {
10129:                     my $intdom = &internet_dom($id);
10130:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
10131:                         push(@idns,$intdom);
10132:                     }
10133:                 }
10134:             }
10135:             $seen{$prim_ip} = 1;
10136:         }
10137:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
10138:     }
10139: 
10140: }
10141: 
10142: BEGIN {
10143: 
10144: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
10145:     unless ($readit) {
10146: {
10147:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
10148:     %perlvar = (%perlvar,%{$configvars});
10149: }
10150: 
10151: 
10152: # ------------------------------------------------------ Read spare server file
10153: {
10154:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
10155: 
10156:     while (my $configline=<$config>) {
10157:        chomp($configline);
10158:        if ($configline) {
10159: 	   my ($host,$type) = split(':',$configline,2);
10160: 	   if (!defined($type) || $type eq '') { $type = 'default' };
10161: 	   push(@{ $spareid{$type} }, $host);
10162:        }
10163:     }
10164:     close($config);
10165: }
10166: # ------------------------------------------------------------ Read permissions
10167: {
10168:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
10169: 
10170:     while (my $configline=<$config>) {
10171: 	chomp($configline);
10172: 	if ($configline) {
10173: 	    my ($role,$perm)=split(/ /,$configline);
10174: 	    if ($perm ne '') { $pr{$role}=$perm; }
10175: 	}
10176:     }
10177:     close($config);
10178: }
10179: 
10180: # -------------------------------------------- Read plain texts for permissions
10181: {
10182:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
10183: 
10184:     while (my $configline=<$config>) {
10185: 	chomp($configline);
10186: 	if ($configline) {
10187: 	    my ($short,@plain)=split(/:/,$configline);
10188:             %{$prp{$short}} = ();
10189: 	    if (@plain > 0) {
10190:                 $prp{$short}{'std'} = $plain[0];
10191:                 for (my $i=1; $i<@plain; $i++) {
10192:                     $prp{$short}{'alt'.$i} = $plain[$i];  
10193:                 }
10194:             }
10195: 	}
10196:     }
10197:     close($config);
10198: }
10199: 
10200: # ---------------------------------------------------------- Read package table
10201: {
10202:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
10203: 
10204:     while (my $configline=<$config>) {
10205: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
10206: 	chomp($configline);
10207: 	my ($short,$plain)=split(/:/,$configline);
10208: 	my ($pack,$name)=split(/\&/,$short);
10209: 	if ($plain ne '') {
10210: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
10211: 	    $packagetab{$short}=$plain; 
10212: 	}
10213:     }
10214:     close($config);
10215: }
10216: 
10217: # ---------------------------------------------------------- Read loncaparev table
10218: {
10219:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
10220:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
10221:             while (my $configline=<$config>) {
10222:                 chomp($configline);
10223:                 my ($hostid,$loncaparev)=split(/:/,$configline);
10224:                 $loncaparevs{$hostid}=$loncaparev;
10225:             }
10226:             close($config);
10227:         }
10228:     }
10229: }
10230: 
10231: # ---------------------------------------------------------- Read serverhostID table
10232: {
10233:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
10234:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
10235:             while (my $configline=<$config>) {
10236:                 chomp($configline);
10237:                 my ($name,$id)=split(/:/,$configline);
10238:                 $serverhomeIDs{$name}=$id;
10239:             }
10240:             close($config);
10241:         }
10242:     }
10243: }
10244: 
10245: sub all_loncaparevs {
10246:     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);
10247: }
10248: 
10249: # ------------- set up temporary directory
10250: {
10251:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
10252: 
10253: }
10254: 
10255: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
10256: 				'compress_threshold'=> 20_000,
10257:  			        });
10258: 
10259: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
10260: $dumpcount=0;
10261: $locknum=0;
10262: 
10263: &logtouch();
10264: &logthis('<font color="yellow">INFO: Read configuration</font>');
10265: $readit=1;
10266:     {
10267: 	use integer;
10268: 	my $test=(2**32)+1;
10269: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
10270: 	&logthis(" Detected 64bit platform ($_64bit)");
10271:     }
10272: }
10273: }
10274: 
10275: 1;
10276: __END__
10277: 
10278: =pod
10279: 
10280: =head1 NAME
10281: 
10282: Apache::lonnet - Subroutines to ask questions about things in the network.
10283: 
10284: =head1 SYNOPSIS
10285: 
10286: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
10287: 
10288:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
10289: 
10290: Common parameters:
10291: 
10292: =over 4
10293: 
10294: =item *
10295: 
10296: $uname : an internal username (if $cname expecting a course Id specifically)
10297: 
10298: =item *
10299: 
10300: $udom : a domain (if $cdom expecting a course's domain specifically)
10301: 
10302: =item *
10303: 
10304: $symb : a resource instance identifier
10305: 
10306: =item *
10307: 
10308: $namespace : the name of a .db file that contains the data needed or
10309: being set.
10310: 
10311: =back
10312: 
10313: =head1 OVERVIEW
10314: 
10315: lonnet provides subroutines which interact with the
10316: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
10317: about classes, users, and resources.
10318: 
10319: For many of these objects you can also use this to store data about
10320: them or modify them in various ways.
10321: 
10322: =head2 Symbs
10323: 
10324: To identify a specific instance of a resource, LON-CAPA uses symbols
10325: or "symbs"X<symb>. These identifiers are built from the URL of the
10326: map, the resource number of the resource in the map, and the URL of
10327: the resource itself. The latter is somewhat redundant, but might help
10328: if maps change.
10329: 
10330: An example is
10331: 
10332:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
10333: 
10334: The respective map entry is
10335: 
10336:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
10337:   title="Problem 2">
10338:  </resource>
10339: 
10340: Symbs are used by the random number generator, as well as to store and
10341: restore data specific to a certain instance of for example a problem.
10342: 
10343: =head2 Storing And Retrieving Data
10344: 
10345: X<store()>X<cstore()>X<restore()>Three of the most important functions
10346: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
10347: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
10348: is is the non-critical message twin of cstore. These functions are for
10349: handlers to store a perl hash to a user's permanent data space in an
10350: easy manner, and to retrieve it again on another call. It is expected
10351: that a handler would use this once at the beginning to retrieve data,
10352: and then again once at the end to send only the new data back.
10353: 
10354: The data is stored in the user's data directory on the user's
10355: homeserver under the ID of the course.
10356: 
10357: The hash that is returned by restore will have all of the previous
10358: value for all of the elements of the hash.
10359: 
10360: Example:
10361: 
10362:  #creating a hash
10363:  my %hash;
10364:  $hash{'foo'}='bar';
10365: 
10366:  #storing it
10367:  &Apache::lonnet::cstore(\%hash);
10368: 
10369:  #changing a value
10370:  $hash{'foo'}='notbar';
10371: 
10372:  #adding a new value
10373:  $hash{'bar'}='foo';
10374:  &Apache::lonnet::cstore(\%hash);
10375: 
10376:  #retrieving the hash
10377:  my %history=&Apache::lonnet::restore();
10378: 
10379:  #print the hash
10380:  foreach my $key (sort(keys(%history))) {
10381:    print("\%history{$key} = $history{$key}");
10382:  }
10383: 
10384: Will print out:
10385: 
10386:  %history{1:foo} = bar
10387:  %history{1:keys} = foo:timestamp
10388:  %history{1:timestamp} = 990455579
10389:  %history{2:bar} = foo
10390:  %history{2:foo} = notbar
10391:  %history{2:keys} = foo:bar:timestamp
10392:  %history{2:timestamp} = 990455580
10393:  %history{bar} = foo
10394:  %history{foo} = notbar
10395:  %history{timestamp} = 990455580
10396:  %history{version} = 2
10397: 
10398: Note that the special hash entries C<keys>, C<version> and
10399: C<timestamp> were added to the hash. C<version> will be equal to the
10400: total number of versions of the data that have been stored. The
10401: C<timestamp> attribute will be the UNIX time the hash was
10402: stored. C<keys> is available in every historical section to list which
10403: keys were added or changed at a specific historical revision of a
10404: hash.
10405: 
10406: B<Warning>: do not store the hash that restore returns directly. This
10407: will cause a mess since it will restore the historical keys as if the
10408: were new keys. I.E. 1:foo will become 1:1:foo etc.
10409: 
10410: Calling convention:
10411: 
10412:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
10413:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
10414: 
10415: For more detailed information, see lonnet specific documentation.
10416: 
10417: =head1 RETURN MESSAGES
10418: 
10419: =over 4
10420: 
10421: =item * B<con_lost>: unable to contact remote host
10422: 
10423: =item * B<con_delayed>: unable to contact remote host, message will be delivered
10424: when the connection is brought back up
10425: 
10426: =item * B<con_failed>: unable to contact remote host and unable to save message
10427: for later delivery
10428: 
10429: =item * B<error:>: an error a occurred, a description of the error follows the :
10430: 
10431: =item * B<no_such_host>: unable to fund a host associated with the user/domain
10432: that was requested
10433: 
10434: =back
10435: 
10436: =head1 PUBLIC SUBROUTINES
10437: 
10438: =head2 Session Environment Functions
10439: 
10440: =over 4
10441: 
10442: =item * 
10443: X<appenv()>
10444: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
10445: the user envirnoment file, and will be restored for each access this
10446: user makes during this session, also modifies the %env for the current
10447: process. Optional rolesarrayref - if defined contains a reference to an array
10448: of roles which are exempt from the restriction on modifying user.role entries 
10449: in the user's environment.db and in %env.    
10450: 
10451: =item *
10452: X<delenv()>
10453: B<delenv($delthis,$regexp)>: removes all items from the session
10454: environment file that begin with $delthis. If the 
10455: optional second arg - $regexp - is true, $delthis is treated as a 
10456: regular expression, otherwise \Q$delthis\E is used. 
10457: The values are also deleted from the current processes %env.
10458: 
10459: =item * get_env_multiple($name) 
10460: 
10461: gets $name from the %env hash, it seemlessly handles the cases where multiple
10462: values may be defined and end up as an array ref.
10463: 
10464: returns an array of values
10465: 
10466: =back
10467: 
10468: =head2 User Information
10469: 
10470: =over 4
10471: 
10472: =item *
10473: X<queryauthenticate()>
10474: B<queryauthenticate($uname,$udom)>: try to determine user's current 
10475: authentication scheme
10476: 
10477: =item *
10478: X<authenticate()>
10479: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
10480: authenticate user from domain's lib servers (first use the current
10481: one). C<$upass> should be the users password.
10482: $checkdefauth is optional (value is 1 if a check should be made to
10483:    authenticate user using default authentication method, and allow
10484:    account creation if username does not have account in the domain).
10485: $clientcancheckhost is optional (value is 1 if checking whether the
10486:    server can host will occur on the client side in lonauth.pm).   
10487: 
10488: =item *
10489: X<homeserver()>
10490: B<homeserver($uname,$udom)>: find the server which has
10491: the user's directory and files (there must be only one), this caches
10492: the answer, and also caches if there is a borken connection.
10493: 
10494: =item *
10495: X<idget()>
10496: B<idget($udom,@ids)>: find the usernames behind a list of IDs
10497: (IDs are a unique resource in a domain, there must be only 1 ID per
10498: username, and only 1 username per ID in a specific domain) (returns
10499: hash: id=>name,id=>name)
10500: 
10501: =item *
10502: X<idrget()>
10503: B<idrget($udom,@unames)>: find the IDs behind a list of
10504: usernames (returns hash: name=>id,name=>id)
10505: 
10506: =item *
10507: X<idput()>
10508: B<idput($udom,%ids)>: store away a list of names and associated IDs
10509: 
10510: =item *
10511: X<rolesinit()>
10512: B<rolesinit($udom,$username,$authhost)>: get user privileges
10513: 
10514: =item *
10515: X<getsection()>
10516: B<getsection($udom,$uname,$cname)>: finds the section of student in the
10517: course $cname, return section name/number or '' for "not in course"
10518: and '-1' for "no section"
10519: 
10520: =item *
10521: X<userenvironment()>
10522: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
10523: passed in @what from the requested user's environment, returns a hash
10524: 
10525: =item * 
10526: X<userlog_query()>
10527: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
10528: activity.log file. %filters defines filters applied when parsing the
10529: log file. These can be start or end timestamps, or the type of action
10530: - log to look for Login or Logout events, check for Checkin or
10531: Checkout, role for role selection. The response is in the form
10532: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
10533: escaped strings of the action recorded in the activity.log file.
10534: 
10535: =back
10536: 
10537: =head2 User Roles
10538: 
10539: =over 4
10540: 
10541: =item *
10542: 
10543: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
10544:  F: full access
10545:  U,I,K: authentication modes (cxx only)
10546:  '': forbidden
10547:  1: user needs to choose course
10548:  2: browse allowed
10549:  A: passphrase authentication needed
10550: 
10551: =item *
10552: 
10553: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
10554: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
10555: and course level
10556: 
10557: =item *
10558: 
10559: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
10560: (rolesplain.tab); plain text explanation of a user role term.
10561: $type is Course (default) or Community.
10562: If $forcedefault evaluates to true, text returned will be default 
10563: text for $type. Otherwise, if this is a course, the text returned 
10564: will be a custom name for the role (if defined in the course's 
10565: environment).  If no custom name is defined the default is returned.
10566:    
10567: =item *
10568: 
10569: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
10570: All arguments are optional. Returns a hash of a roles, either for
10571: co-author/assistant author roles for a user's Construction Space
10572: (default), or if $context is 'userroles', roles for the user himself,
10573: In the hash, keys are set to colon-separated $uname,$udom,$role, and
10574: (optionally) if $withsec is true, a fourth colon-separated item - $section.
10575: For each key, value is set to colon-separated start and end times for
10576: the role.  If no username and domain are specified, will default to
10577: current user/domain. Types, roles, and roledoms are references to arrays
10578: of role statuses (active, future or previous), roles 
10579: (e.g., cc,in, st etc.) and domains of the roles which can be used
10580: to restrict the list of roles reported. If no array ref is 
10581: provided for types, will default to return only active roles.
10582: 
10583: =back
10584: 
10585: =head2 User Modification
10586: 
10587: =over 4
10588: 
10589: =item *
10590: 
10591: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
10592: user for the level given by URL.  Optional start and end dates (leave empty
10593: string or zero for "no date")
10594: 
10595: =item *
10596: 
10597: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
10598: change a users, password, possible return values are: ok,
10599: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
10600: refused
10601: 
10602: =item *
10603: 
10604: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
10605: 
10606: =item *
10607: 
10608: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
10609:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
10610: 
10611: will update user information (firstname,middlename,lastname,generation,
10612: permanentemail), and if forceid is true, student/employee ID also.
10613: A user's institutional affiliation(s) can also be updated.
10614: User information fields will not be overwritten with empty entries 
10615: unless the field is included in the $candelete array reference.
10616: This array is included when a single user is modified via "Manage Users",
10617: or when Autoupdate.pl is run by cron in a domain.
10618: 
10619: =item *
10620: 
10621: modifystudent
10622: 
10623: modify a student's enrollment and identification information.
10624: The course id is resolved based on the current users environment.  
10625: This means the envoking user must be a course coordinator or otherwise
10626: associated with a course.
10627: 
10628: This call is essentially a wrapper for lonnet::modifyuser and
10629: lonnet::modify_student_enrollment
10630: 
10631: Inputs: 
10632: 
10633: =over 4
10634: 
10635: =item B<$udom> Student's loncapa domain
10636: 
10637: =item B<$uname> Student's loncapa login name
10638: 
10639: =item B<$uid> Student/Employee ID
10640: 
10641: =item B<$umode> Student's authentication mode
10642: 
10643: =item B<$upass> Student's password
10644: 
10645: =item B<$first> Student's first name
10646: 
10647: =item B<$middle> Student's middle name
10648: 
10649: =item B<$last> Student's last name
10650: 
10651: =item B<$gene> Student's generation
10652: 
10653: =item B<$usec> Student's section in course
10654: 
10655: =item B<$end> Unix time of the roles expiration
10656: 
10657: =item B<$start> Unix time of the roles start date
10658: 
10659: =item B<$forceid> If defined, allow $uid to be changed
10660: 
10661: =item B<$desiredhome> server to use as home server for student
10662: 
10663: =item B<$email> Student's permanent e-mail address
10664: 
10665: =item B<$type> Type of enrollment (auto or manual)
10666: 
10667: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
10668: 
10669: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
10670: 
10671: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
10672: 
10673: =item B<$context> role change context (shown in User Management Logs display in a course)
10674: 
10675: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
10676: 
10677: =back
10678: 
10679: =item *
10680: 
10681: modify_student_enrollment
10682: 
10683: Change a students enrollment status in a class.  The environment variable
10684: 'role.request.course' must be defined for this function to proceed.
10685: 
10686: Inputs:
10687: 
10688: =over 4
10689: 
10690: =item $udom, students domain
10691: 
10692: =item $uname, students name
10693: 
10694: =item $uid, students user id
10695: 
10696: =item $first, students first name
10697: 
10698: =item $middle
10699: 
10700: =item $last
10701: 
10702: =item $gene
10703: 
10704: =item $usec
10705: 
10706: =item $end
10707: 
10708: =item $start
10709: 
10710: =item $type
10711: 
10712: =item $locktype
10713: 
10714: =item $cid
10715: 
10716: =item $selfenroll
10717: 
10718: =item $context
10719: 
10720: =back
10721: 
10722: 
10723: =item *
10724: 
10725: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
10726: custom role; give a custom role to a user for the level given by URL.  Specify
10727: name and domain of role author, and role name
10728: 
10729: =item *
10730: 
10731: revokerole($udom,$uname,$url,$role) : revoke a role for url
10732: 
10733: =item *
10734: 
10735: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
10736: 
10737: =back
10738: 
10739: =head2 Course Infomation
10740: 
10741: =over 4
10742: 
10743: =item *
10744: 
10745: coursedescription($courseid) : returns a hash of information about the
10746: specified course id, including all environment settings for the
10747: course, the description of the course will be in the hash under the
10748: key 'description'
10749: 
10750: =item *
10751: 
10752: resdata($name,$domain,$type,@which) : request for current parameter
10753: setting for a specific $type, where $type is either 'course' or 'user',
10754: @what should be a list of parameters to ask about. This routine caches
10755: answers for 5 minutes.
10756: 
10757: =item *
10758: 
10759: get_courseresdata($courseid, $domain) : dump the entire course resource
10760: data base, returning a hash that is keyed by the resource name and has
10761: values that are the resource value.  I believe that the timestamps and
10762: versions are also returned.
10763: 
10764: 
10765: =back
10766: 
10767: =head2 Course Modification
10768: 
10769: =over 4
10770: 
10771: =item *
10772: 
10773: writecoursepref($courseid,%prefs) : write preferences (environment
10774: database) for a course
10775: 
10776: =item *
10777: 
10778: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
10779: 
10780: =item *
10781: 
10782: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
10783: 
10784: =back
10785: 
10786: =head2 Resource Subroutines
10787: 
10788: =over 4
10789: 
10790: =item *
10791: 
10792: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
10793: 
10794: =item *
10795: 
10796: repcopy($filename) : subscribes to the requested file, and attempts to
10797: replicate from the owning library server, Might return
10798: 'unavailable', 'not_found', 'forbidden', 'ok', or
10799: 'bad_request', also attempts to grab the metadata for the
10800: resource. Expects the local filesystem pathname
10801: (/home/httpd/html/res/....)
10802: 
10803: =back
10804: 
10805: =head2 Resource Information
10806: 
10807: =over 4
10808: 
10809: =item *
10810: 
10811: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
10812: a vairety of different possible values, $varname should be a request
10813: string, and the other parameters can be used to specify who and what
10814: one is asking about.
10815: 
10816: Possible values for $varname are environment.lastname (or other item
10817: from the envirnment hash), user.name (or someother aspect about the
10818: user), resource.0.maxtries (or some other part and parameter of a
10819: resource)
10820: 
10821: =item *
10822: 
10823: directcondval($number) : get current value of a condition; reads from a state
10824: string
10825: 
10826: =item *
10827: 
10828: condval($condidx) : value of condition index based on state
10829: 
10830: =item *
10831: 
10832: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
10833: resource's metadata, $what should be either a specific key, or either
10834: 'keys' (to get a list of possible keys) or 'packages' to get a list of
10835: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
10836: 
10837: this function automatically caches all requests
10838: 
10839: =item *
10840: 
10841: metadata_query($query,$custom,$customshow) : make a metadata query against the
10842: network of library servers; returns file handle of where SQL and regex results
10843: will be stored for query
10844: 
10845: =item *
10846: 
10847: symbread($filename) : return symbolic list entry (filename argument optional);
10848: returns the data handle
10849: 
10850: =item *
10851: 
10852: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
10853: a possible symb for the URL in $thisfn, and if is an encryypted
10854: resource that the user accessed using /enc/ returns a 1 on success, 0
10855: on failure, user must be in a course, as it assumes the existance of
10856: the course initial hash, and uses $env('request.course.id'}
10857: 
10858: 
10859: =item *
10860: 
10861: symbclean($symb) : removes versions numbers from a symb, returns the
10862: cleaned symb
10863: 
10864: =item *
10865: 
10866: is_on_map($uri) : checks if the $uri is somewhere on the current
10867: course map, user must be in a course for it to work.
10868: 
10869: =item *
10870: 
10871: numval($salt) : return random seed value (addend for rndseed)
10872: 
10873: =item *
10874: 
10875: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
10876: a random seed, all arguments are optional, if they aren't sent it uses the
10877: environment to derive them. Note: if symb isn't sent and it can't get one
10878: from &symbread it will use the current time as its return value
10879: 
10880: =item *
10881: 
10882: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
10883: unfakeable, receipt
10884: 
10885: =item *
10886: 
10887: receipt() : API to ireceipt working off of env values; given out to users
10888: 
10889: =item *
10890: 
10891: countacc($url) : count the number of accesses to a given URL
10892: 
10893: =item *
10894: 
10895: 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
10896: 
10897: =item *
10898: 
10899: 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)
10900: 
10901: =item *
10902: 
10903: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
10904: 
10905: =item *
10906: 
10907: devalidate($symb) : devalidate temporary spreadsheet calculations,
10908: forcing spreadsheet to reevaluate the resource scores next time.
10909: 
10910: =back
10911: 
10912: =head2 Storing/Retreiving Data
10913: 
10914: =over 4
10915: 
10916: =item *
10917: 
10918: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
10919: for this url; hashref needs to be given and should be a \%hashname; the
10920: remaining args aren't required and if they aren't passed or are '' they will
10921: be derived from the env
10922: 
10923: =item *
10924: 
10925: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
10926: uses critical subroutine
10927: 
10928: =item *
10929: 
10930: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
10931: all args are optional
10932: 
10933: =item *
10934: 
10935: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
10936: dumps the complete (or key matching regexp) namespace into a hash
10937: ($udom, $uname, $regexp, $range are optional) for a namespace that is
10938: normally &store()ed into
10939: 
10940: $range should be either an integer '100' (give me the first 100
10941:                                            matching records)
10942:               or be  two integers sperated by a - with no spaces
10943:                  '30-50' (give me the 30th through the 50th matching
10944:                           records)
10945: 
10946: 
10947: =item *
10948: 
10949: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
10950: replaces a &store() version of data with a replacement set of data
10951: for a particular resource in a namespace passed in the $storehash hash 
10952: reference
10953: 
10954: =item *
10955: 
10956: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
10957: works very similar to store/cstore, but all data is stored in a
10958: temporary location and can be reset using tmpreset, $storehash should
10959: be a hash reference, returns nothing on success
10960: 
10961: =item *
10962: 
10963: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
10964: similar to restore, but all data is stored in a temporary location and
10965: can be reset using tmpreset. Returns a hash of values on success,
10966: error string otherwise.
10967: 
10968: =item *
10969: 
10970: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
10971: deltes all keys for $symb form the temporary storage hash.
10972: 
10973: =item *
10974: 
10975: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
10976: reference filled in from namesp ($udom and $uname are optional)
10977: 
10978: =item *
10979: 
10980: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
10981: namesp ($udom and $uname are optional)
10982: 
10983: =item *
10984: 
10985: dump($namespace,$udom,$uname,$regexp,$range) : 
10986: dumps the complete (or key matching regexp) namespace into a hash
10987: ($udom, $uname, $regexp, $range are optional)
10988: 
10989: $range should be either an integer '100' (give me the first 100
10990:                                            matching records)
10991:               or be  two integers sperated by a - with no spaces
10992:                  '30-50' (give me the 30th through the 50th matching
10993:                           records)
10994: =item *
10995: 
10996: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
10997: $store can be a scalar, an array reference, or if the amount to be 
10998: incremented is > 1, a hash reference.
10999: 
11000: ($udom and $uname are optional)
11001: 
11002: =item *
11003: 
11004: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
11005: ($udom and $uname are optional)
11006: 
11007: =item *
11008: 
11009: cput($namespace,$storehash,$udom,$uname) : critical put
11010: ($udom and $uname are optional)
11011: 
11012: =item *
11013: 
11014: newput($namespace,$storehash,$udom,$uname) :
11015: 
11016: Attempts to store the items in the $storehash, but only if they don't
11017: currently exist, if this succeeds you can be certain that you have 
11018: successfully created a new key value pair in the $namespace db.
11019: 
11020: 
11021: Args:
11022:  $namespace: name of database to store values to
11023:  $storehash: hashref to store to the db
11024:  $udom: (optional) domain of user containing the db
11025:  $uname: (optional) name of user caontaining the db
11026: 
11027: Returns:
11028:  'ok' -> succeeded in storing all keys of $storehash
11029:  'key_exists: <key>' -> failed to anything out of $storehash, as at
11030:                         least <key> already existed in the db (other
11031:                         requested keys may also already exist)
11032:  'error: <msg>' -> unable to tie the DB or other error occurred
11033:  'con_lost' -> unable to contact request server
11034:  'refused' -> action was not allowed by remote machine
11035: 
11036: 
11037: =item *
11038: 
11039: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11040: reference filled in from namesp (encrypts the return communication)
11041: ($udom and $uname are optional)
11042: 
11043: =item *
11044: 
11045: log($udom,$name,$home,$message) : write to permanent log for user; use
11046: critical subroutine
11047: 
11048: =item *
11049: 
11050: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
11051: array reference filled in from namespace found in domain level on either
11052: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
11053: 
11054: =item *
11055: 
11056: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
11057: domain level either on specified domain server ($uhome) or primary domain 
11058: server ($udom and $uhome are optional)
11059: 
11060: =item * 
11061: 
11062: get_domain_defaults($target_domain) : returns hash with defaults for
11063: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
11064: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
11065: or localauth), initial password or a kerberos realm, language (e.g., en-us).
11066: Values are retrieved from cache (if current), or from domain's configuration.db
11067: (if available), or lastly from values in lonTabs/dns_domain,tab, 
11068: or lonTabs/domain.tab. 
11069: 
11070: %domdefaults = &get_auth_defaults($target_domain);
11071: 
11072: =back
11073: 
11074: =head2 Network Status Functions
11075: 
11076: =over 4
11077: 
11078: =item *
11079: 
11080: dirlist($uri) : return directory list based on URI
11081: 
11082: =item *
11083: 
11084: spareserver() : find server with least workload from spare.tab
11085: 
11086: 
11087: =item *
11088: 
11089: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
11090: if there is no corresponding loncapa host.
11091: 
11092: =back
11093: 
11094: 
11095: =head2 Apache Request
11096: 
11097: =over 4
11098: 
11099: =item *
11100: 
11101: ssi($url,%hash) : server side include, does a complete request cycle on url to
11102: localhost, posts hash
11103: 
11104: =back
11105: 
11106: =head2 Data to String to Data
11107: 
11108: =over 4
11109: 
11110: =item *
11111: 
11112: hash2str(%hash) : convert a hash into a string complete with escaping and '='
11113: and '&' separators, supports elements that are arrayrefs and hashrefs
11114: 
11115: =item *
11116: 
11117: hashref2str($hashref) : convert a hashref into a string complete with
11118: escaping and '=' and '&' separators, supports elements that are
11119: arrayrefs and hashrefs
11120: 
11121: =item *
11122: 
11123: arrayref2str($arrayref) : convert an arrayref into a string complete
11124: with escaping and '&' separators, supports elements that are arrayrefs
11125: and hashrefs
11126: 
11127: =item *
11128: 
11129: str2hash($string) : convert string to hash using unescaping and
11130: splitting on '=' and '&', supports elements that are arrayrefs and
11131: hashrefs
11132: 
11133: =item *
11134: 
11135: str2array($string) : convert string to hash using unescaping and
11136: splitting on '&', supports elements that are arrayrefs and hashrefs
11137: 
11138: =back
11139: 
11140: =head2 Logging Routines
11141: 
11142: =over 4
11143: 
11144: These routines allow one to make log messages in the lonnet.log and
11145: lonnet.perm logfiles.
11146: 
11147: =item *
11148: 
11149: logtouch() : make sure the logfile, lonnet.log, exists
11150: 
11151: =item *
11152: 
11153: logthis() : append message to the normal lonnet.log file, it gets
11154: preiodically rolled over and deleted.
11155: 
11156: =item *
11157: 
11158: logperm() : append a permanent message to lonnet.perm.log, this log
11159: file never gets deleted by any automated portion of the system, only
11160: messages of critical importance should go in here.
11161: 
11162: =back
11163: 
11164: =head2 General File Helper Routines
11165: 
11166: =over 4
11167: 
11168: =item *
11169: 
11170: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
11171: (a) files in /uploaded
11172:   (i) If a local copy of the file exists - 
11173:       compares modification date of local copy with last-modified date for 
11174:       definitive version stored on home server for course. If local copy is 
11175:       stale, requests a new version from the home server and stores it. 
11176:       If the original has been removed from the home server, then local copy 
11177:       is unlinked.
11178:   (ii) If local copy does not exist -
11179:       requests the file from the home server and stores it. 
11180:   
11181:   If $caller is 'uploadrep':  
11182:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
11183:     for request for files originally uploaded via DOCS. 
11184:      - returns 'ok' if fresh local copy now available, -1 otherwise.
11185:   
11186:   Otherwise:
11187:      This indicates a call from the content generation phase of the request.
11188:      -  returns the entire contents of the file or -1.
11189:      
11190: (b) files in /res
11191:    - returns the entire contents of a file or -1; 
11192:    it properly subscribes to and replicates the file if neccessary.
11193: 
11194: 
11195: =item *
11196: 
11197: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
11198:                   reference
11199: 
11200: returns either a stat() list of data about the file or an empty list
11201: if the file doesn't exist or couldn't find out about it (connection
11202: problems or user unknown)
11203: 
11204: =item *
11205: 
11206: filelocation($dir,$file) : returns file system location of a file
11207: based on URI; meant to be "fairly clean" absolute reference, $dir is a
11208: directory that relative $file lookups are to looked in ($dir of /a/dir
11209: and a file of ../bob will become /a/bob)
11210: 
11211: =item *
11212: 
11213: hreflocation($dir,$file) : returns file system location or a URL; same as
11214: filelocation except for hrefs
11215: 
11216: =item *
11217: 
11218: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
11219: 
11220: =back
11221: 
11222: =head2 Usererfile file routines (/uploaded*)
11223: 
11224: =over 4
11225: 
11226: =item *
11227: 
11228: userfileupload(): main rotine for putting a file in a user or course's
11229:                   filespace, arguments are,
11230: 
11231:  formname - required - this is the name of the element in $env where the
11232:            filename, and the contents of the file to create/modifed exist
11233:            the filename is in $env{'form.'.$formname.'.filename'} and the
11234:            contents of the file is located in $env{'form.'.$formname}
11235:  coursedoc - if true, store the file in the course of the active role
11236:              of the current user
11237:  subdir - required - subdirectory to put the file in under ../userfiles/
11238:          if undefined, it will be placed in "unknown"
11239: 
11240:  (This routine calls clean_filename() to remove any dangerous
11241:  characters from the filename, and then calls finuserfileupload() to
11242:  complete the transaction)
11243: 
11244:  returns either the url of the uploaded file (/uploaded/....) if successful
11245:  and /adm/notfound.html if unsuccessful
11246: 
11247: =item *
11248: 
11249: clean_filename(): routine for cleaing a filename up for storage in
11250:                  userfile space, argument is:
11251: 
11252:  filename - proposed filename
11253: 
11254: returns: the new clean filename
11255: 
11256: =item *
11257: 
11258: finishuserfileupload(): routine that creaes and sends the file to
11259: userspace, probably shouldn't be called directly
11260: 
11261:   docuname: username or courseid of destination for the file
11262:   docudom: domain of user/course of destination for the file
11263:   formname: same as for userfileupload()
11264:   fname: filename (inculding subdirectories) for the file
11265: 
11266:  returns either the url of the uploaded file (/uploaded/....) if successful
11267:  and /adm/notfound.html if unsuccessful
11268: 
11269: =item *
11270: 
11271: renameuserfile(): renames an existing userfile to a new name
11272: 
11273:   Args:
11274:    docuname: username or courseid of destination for the file
11275:    docudom: domain of user/course of destination for the file
11276:    old: current file name (including any subdirs under userfiles)
11277:    new: desired file name (including any subdirs under userfiles)
11278: 
11279: =item *
11280: 
11281: mkdiruserfile(): creates a directory is a userfiles dir
11282: 
11283:   Args:
11284:    docuname: username or courseid of destination for the file
11285:    docudom: domain of user/course of destination for the file
11286:    dir: dir to create (including any subdirs under userfiles)
11287: 
11288: =item *
11289: 
11290: removeuserfile(): removes a file that exists in userfiles
11291: 
11292:   Args:
11293:    docuname: username or courseid of destination for the file
11294:    docudom: domain of user/course of destination for the file
11295:    fname: filname to delete (including any subdirs under userfiles)
11296: 
11297: =item *
11298: 
11299: removeuploadedurl(): convience function for removeuserfile()
11300: 
11301:   Args:
11302:    url:  a full /uploaded/... url to delete
11303: 
11304: =item * 
11305: 
11306: get_portfile_permissions():
11307:   Args:
11308:     domain: domain of user or course contain the portfolio files
11309:     user: name of user or num of course contain the portfolio files
11310:   Returns:
11311:     hashref of a dump of the proper file_permissions.db
11312:    
11313: 
11314: =item * 
11315: 
11316: get_access_controls():
11317: 
11318: Args:
11319:   current_permissions: the hash ref returned from get_portfile_permissions()
11320:   group: (optional) the group you want the files associated with
11321:   file: (optional) the file you want access info on
11322: 
11323: Returns:
11324:     a hash (keys are file names) of hashes containing
11325:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
11326:         values are XML containing access control settings (see below) 
11327: 
11328: Internal notes:
11329: 
11330:  access controls are stored in file_permissions.db as key=value pairs.
11331:     key -> path to file/file_name\0uniqueID:scope_end_start
11332:         where scope -> public,guest,course,group,domains or users.
11333:               end -> UNIX time for end of access (0 -> no end date)
11334:               start -> UNIX time for start of access
11335: 
11336:     value -> XML description of access control
11337:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
11338:             <start></start>
11339:             <end></end>
11340: 
11341:             <password></password>  for scope type = guest
11342: 
11343:             <domain></domain>     for scope type = course or group
11344:             <number></number>
11345:             <roles id="">
11346:              <role></role>
11347:              <access></access>
11348:              <section></section>
11349:              <group></group>
11350:             </roles>
11351: 
11352:             <dom></dom>         for scope type = domains
11353: 
11354:             <users>             for scope type = users
11355:              <user>
11356:               <uname></uname>
11357:               <udom></udom>
11358:              </user>
11359:             </users>
11360:            </scope> 
11361:               
11362:  Access data is also aggregated for each file in an additional key=value pair:
11363:  key -> path to file/file_name\0accesscontrol 
11364:  value -> reference to hash
11365:           hash contains key = value pairs
11366:           where key = uniqueID:scope_end_start
11367:                 value = UNIX time record was last updated
11368: 
11369:           Used to improve speed of look-ups of access controls for each file.  
11370:  
11371:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
11372: 
11373: modify_access_controls():
11374: 
11375: Modifies access controls for a portfolio file
11376: Args
11377: 1. file name
11378: 2. reference to hash of required changes,
11379: 3. domain
11380: 4. username
11381:   where domain,username are the domain of the portfolio owner 
11382:   (either a user or a course) 
11383: 
11384: Returns:
11385: 1. result of additions or updates ('ok' or 'error', with error message). 
11386: 2. result of deletions ('ok' or 'error', with error message).
11387: 3. reference to hash of any new or updated access controls.
11388: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
11389:    key = integer (inbound ID)
11390:    value = uniqueID  
11391: 
11392: =back
11393: 
11394: =head2 HTTP Helper Routines
11395: 
11396: =over 4
11397: 
11398: =item *
11399: 
11400: escape() : unpack non-word characters into CGI-compatible hex codes
11401: 
11402: =item *
11403: 
11404: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
11405: 
11406: =back
11407: 
11408: =head1 PRIVATE SUBROUTINES
11409: 
11410: =head2 Underlying communication routines (Shouldn't call)
11411: 
11412: =over 4
11413: 
11414: =item *
11415: 
11416: subreply() : tries to pass a message to lonc, returns con_lost if incapable
11417: 
11418: =item *
11419: 
11420: reply() : uses subreply to send a message to remote machine, logs all failures
11421: 
11422: =item *
11423: 
11424: critical() : passes a critical message to another server; if cannot
11425: get through then place message in connection buffer directory and
11426: returns con_delayed, if incapable of saving message, returns
11427: con_failed
11428: 
11429: =item *
11430: 
11431: reconlonc() : tries to reconnect lonc client processes.
11432: 
11433: =back
11434: 
11435: =head2 Resource Access Logging
11436: 
11437: =over 4
11438: 
11439: =item *
11440: 
11441: flushcourselogs() : flush (save) buffer logs and access logs
11442: 
11443: =item *
11444: 
11445: courselog($what) : save message for course in hash
11446: 
11447: =item *
11448: 
11449: courseacclog($what) : save message for course using &courselog().  Perform
11450: special processing for specific resource types (problems, exams, quizzes, etc).
11451: 
11452: =item *
11453: 
11454: goodbye() : flush course logs and log shutting down; it is called in srm.conf
11455: as a PerlChildExitHandler
11456: 
11457: =back
11458: 
11459: =head2 Other
11460: 
11461: =over 4
11462: 
11463: =item *
11464: 
11465: symblist($mapname,%newhash) : update symbolic storage links
11466: 
11467: =back
11468: 
11469: =cut
11470: 

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