File:  [LON-CAPA] / loncom / lonnet / perl / lonnet.pm
Revision 1.976.2.7: download - view: text, annotated - select for diffs
Fri Mar 20 21:18:26 2009 UTC (15 years, 4 months ago) by raeburn
Branches: version_2_8_X
Diff to branchpoint 1.976: preferred, unified
- Backport 1.987.

    1: # The LearningOnline Network
    2: # TCP networking package
    3: #
    4: # $Id: lonnet.pm,v 1.976.2.7 2009/03/20 21:18:26 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 Date::Parse;
   77: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
   78:             $_64bit %env %protocol);
   79: 
   80: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
   81:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
   82:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
   83:     %courseownerbuf, %coursetypebuf,$locknum);
   84: 
   85: use IO::Socket;
   86: use GDBM_File;
   87: use HTML::LCParser;
   88: use Fcntl qw(:flock);
   89: use Storable qw(thaw nfreeze);
   90: use Time::HiRes qw( gettimeofday tv_interval );
   91: use Cache::Memcached;
   92: use Digest::MD5;
   93: use Math::Random;
   94: use LONCAPA qw(:DEFAULT :match);
   95: use LONCAPA::Configuration;
   96: 
   97: my $readit;
   98: my $max_connection_retries = 10;     # Or some such value.
   99: 
  100: require Exporter;
  101: 
  102: our @ISA = qw (Exporter);
  103: our @EXPORT = qw(%env);
  104: 
  105: 
  106: # --------------------------------------------------------------------- Logging
  107: {
  108:     my $logid;
  109:     sub instructor_log {
  110: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
  111:         if (($cnum eq '') || ($cdom eq '')) {
  112:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  113:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  114:         }
  115: 	$logid++;
  116:         my $now = time();
  117: 	my $id=$now.'00000'.$$.'00000'.$logid;
  118: 	return &Apache::lonnet::put('nohist_'.$hash_name,
  119: 				    { $id => {
  120: 					'exe_uname' => $env{'user.name'},
  121: 					'exe_udom'  => $env{'user.domain'},
  122: 					'exe_time'  => $now,
  123: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
  124: 					'delflag'   => $delflag,
  125: 					'logentry'  => $storehash,
  126: 					'uname'     => $uname,
  127: 					'udom'      => $udom,
  128: 				    }
  129: 				  },$cdom,$cnum);
  130:     }
  131: }
  132: 
  133: sub logtouch {
  134:     my $execdir=$perlvar{'lonDaemons'};
  135:     unless (-e "$execdir/logs/lonnet.log") {	
  136: 	open(my $fh,">>$execdir/logs/lonnet.log");
  137: 	close $fh;
  138:     }
  139:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
  140:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
  141: }
  142: 
  143: sub logthis {
  144:     my $message=shift;
  145:     my $execdir=$perlvar{'lonDaemons'};
  146:     my $now=time;
  147:     my $local=localtime($now);
  148:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
  149: 	print $fh "$local ($$): $message\n";
  150: 	close($fh);
  151:     }
  152:     return 1;
  153: }
  154: 
  155: sub logperm {
  156:     my $message=shift;
  157:     my $execdir=$perlvar{'lonDaemons'};
  158:     my $now=time;
  159:     my $local=localtime($now);
  160:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
  161: 	print $fh "$now:$message:$local\n";
  162: 	close($fh);
  163:     }
  164:     return 1;
  165: }
  166: 
  167: sub create_connection {
  168:     my ($hostname,$lonid) = @_;
  169:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
  170: 				     Type    => SOCK_STREAM,
  171: 				     Timeout => 10);
  172:     return 0 if (!$client);
  173:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
  174:     my $result = <$client>;
  175:     chomp($result);
  176:     return 1 if ($result eq 'done');
  177:     return 0;
  178: }
  179: 
  180: sub get_server_timezone {
  181:     my ($cnum,$cdom) = @_;
  182:     my $home=&homeserver($cnum,$cdom);
  183:     if ($home ne 'no_host') {
  184:         my $cachetime = 24*3600;
  185:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
  186:         if (defined($cached)) {
  187:             return $timezone;
  188:         } else {
  189:             my $timezone = &reply('servertimezone',$home);
  190:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
  191:         }
  192:     }
  193: }
  194: 
  195: # -------------------------------------------------- Non-critical communication
  196: sub subreply {
  197:     my ($cmd,$server)=@_;
  198:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
  199:     #
  200:     #  With loncnew process trimming, there's a timing hole between lonc server
  201:     #  process exit and the master server picking up the listen on the AF_UNIX
  202:     #  socket.  In that time interval, a lock file will exist:
  203: 
  204:     my $lockfile=$peerfile.".lock";
  205:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
  206: 	sleep(1);
  207:     }
  208:     # At this point, either a loncnew parent is listening or an old lonc
  209:     # or loncnew child is listening so we can connect or everything's dead.
  210:     #
  211:     #   We'll give the connection a few tries before abandoning it.  If
  212:     #   connection is not possible, we'll con_lost back to the client.
  213:     #   
  214:     my $client;
  215:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
  216: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
  217: 				      Type    => SOCK_STREAM,
  218: 				      Timeout => 10);
  219: 	if ($client) {
  220: 	    last;		# Connected!
  221: 	} else {
  222: 	    &create_connection(&hostname($server),$server);
  223: 	}
  224:         sleep(1);		# Try again later if failed connection.
  225:     }
  226:     my $answer;
  227:     if ($client) {
  228: 	print $client "sethost:$server:$cmd\n";
  229: 	$answer=<$client>;
  230: 	if (!$answer) { $answer="con_lost"; }
  231: 	chomp($answer);
  232:     } else {
  233: 	$answer = 'con_lost';	# Failed connection.
  234:     }
  235:     return $answer;
  236: }
  237: 
  238: sub reply {
  239:     my ($cmd,$server)=@_;
  240:     unless (defined(&hostname($server))) { return 'no_such_host'; }
  241:     my $answer=subreply($cmd,$server);
  242:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
  243:        &logthis("<font color=\"blue\">WARNING:".
  244:                 " $cmd to $server returned $answer</font>");
  245:     }
  246:     return $answer;
  247: }
  248: 
  249: # ----------------------------------------------------------- Send USR1 to lonc
  250: 
  251: sub reconlonc {
  252:     my ($lonid) = @_;
  253:     my $hostname = &hostname($lonid);
  254:     if ($lonid) {
  255: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
  256: 	if ($hostname && -e $peerfile) {
  257: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
  258: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
  259: 					     Type    => SOCK_STREAM,
  260: 					     Timeout => 10);
  261: 	    if ($client) {
  262: 		print $client ("reset_retries\n");
  263: 		my $answer=<$client>;
  264: 		#reset just this one.
  265: 	    }
  266: 	}
  267: 	return;
  268:     }
  269: 
  270:     &logthis("Trying to reconnect lonc");
  271:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
  272:     if (open(my $fh,"<$loncfile")) {
  273: 	my $loncpid=<$fh>;
  274:         chomp($loncpid);
  275:         if (kill 0 => $loncpid) {
  276: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
  277:             kill USR1 => $loncpid;
  278:             sleep 1;
  279:          } else {
  280: 	    &logthis(
  281:                "<font color=\"blue\">WARNING:".
  282:                " lonc at pid $loncpid not responding, giving up</font>");
  283:         }
  284:     } else {
  285: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
  286:     }
  287: }
  288: 
  289: # ------------------------------------------------------ Critical communication
  290: 
  291: sub critical {
  292:     my ($cmd,$server)=@_;
  293:     unless (&hostname($server)) {
  294:         &logthis("<font color=\"blue\">WARNING:".
  295:                " Critical message to unknown server ($server)</font>");
  296:         return 'no_such_host';
  297:     }
  298:     my $answer=reply($cmd,$server);
  299:     if ($answer eq 'con_lost') {
  300: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
  301: 	my $answer=reply($cmd,$server);
  302:         if ($answer eq 'con_lost') {
  303:             my $now=time;
  304:             my $middlename=$cmd;
  305:             $middlename=substr($middlename,0,16);
  306:             $middlename=~s/\W//g;
  307:             my $dfilename=
  308:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
  309:             $dumpcount++;
  310:             {
  311: 		my $dfh;
  312: 		if (open($dfh,">$dfilename")) {
  313: 		    print $dfh "$cmd\n"; 
  314: 		    close($dfh);
  315: 		}
  316:             }
  317:             sleep 2;
  318:             my $wcmd='';
  319:             {
  320: 		my $dfh;
  321: 		if (open($dfh,"<$dfilename")) {
  322: 		    $wcmd=<$dfh>; 
  323: 		    close($dfh);
  324: 		}
  325:             }
  326:             chomp($wcmd);
  327:             if ($wcmd eq $cmd) {
  328: 		&logthis("<font color=\"blue\">WARNING: ".
  329:                          "Connection buffer $dfilename: $cmd</font>");
  330:                 &logperm("D:$server:$cmd");
  331: 	        return 'con_delayed';
  332:             } else {
  333:                 &logthis("<font color=\"red\">CRITICAL:"
  334:                         ." Critical connection failed: $server $cmd</font>");
  335:                 &logperm("F:$server:$cmd");
  336:                 return 'con_failed';
  337:             }
  338:         }
  339:     }
  340:     return $answer;
  341: }
  342: 
  343: # ------------------------------------------- check if return value is an error
  344: 
  345: sub error {
  346:     my ($result) = @_;
  347:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
  348: 	if ($2 == 2) { return undef; }
  349: 	return $1;
  350:     }
  351:     return undef;
  352: }
  353: 
  354: sub convert_and_load_session_env {
  355:     my ($lonidsdir,$handle)=@_;
  356:     my @profile;
  357:     {
  358: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  359: 	if (!$opened) {
  360: 	    return 0;
  361: 	}
  362: 	flock($idf,LOCK_SH);
  363: 	@profile=<$idf>;
  364: 	close($idf);
  365:     }
  366:     my %temp_env;
  367:     foreach my $line (@profile) {
  368: 	if ($line !~ m/=/) {
  369: 	    return 0;
  370: 	}
  371: 	chomp($line);
  372: 	my ($envname,$envvalue)=split(/=/,$line,2);
  373: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
  374:     }
  375:     unlink("$lonidsdir/$handle.id");
  376:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
  377: 	    0640)) {
  378: 	%disk_env = %temp_env;
  379: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
  380: 	untie(%disk_env);
  381:     }
  382:     return 1;
  383: }
  384: 
  385: # ------------------------------------------- Transfer profile into environment
  386: my $env_loaded;
  387: sub transfer_profile_to_env {
  388:     my ($lonidsdir,$handle,$force_transfer) = @_;
  389:     if (!$force_transfer && $env_loaded) { return; } 
  390: 
  391:     if (!defined($lonidsdir)) {
  392: 	$lonidsdir = $perlvar{'lonIDsDir'};
  393:     }
  394:     if (!defined($handle)) {
  395:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
  396:     }
  397: 
  398:     my $convert;
  399:     {
  400:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  401: 	if (!$opened) {
  402: 	    return;
  403: 	}
  404: 	flock($idf,LOCK_SH);
  405: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  406: 		&GDBM_READER(),0640)) {
  407: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
  408: 	    untie(%disk_env);
  409: 	} else {
  410: 	    $convert = 1;
  411: 	}
  412:     }
  413:     if ($convert) {
  414: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
  415: 	    &logthis("Failed to load session, or convert session.");
  416: 	}
  417:     }
  418: 
  419:     my %remove;
  420:     while ( my $envname = each(%env) ) {
  421:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
  422:             if ($time < time-300) {
  423:                 $remove{$key}++;
  424:             }
  425:         }
  426:     }
  427: 
  428:     $env{'user.environment'} = "$lonidsdir/$handle.id";
  429:     $env_loaded=1;
  430:     foreach my $expired_key (keys(%remove)) {
  431:         &delenv($expired_key);
  432:     }
  433: }
  434: 
  435: # ---------------------------------------------------- Check for valid session 
  436: sub check_for_valid_session {
  437:     my ($r) = @_;
  438:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
  439:     my $lonid=$cookies{'lonID'};
  440:     return undef if (!$lonid);
  441: 
  442:     my $handle=&LONCAPA::clean_handle($lonid->value);
  443:     my $lonidsdir=$r->dir_config('lonIDsDir');
  444:     return undef if (!-e "$lonidsdir/$handle.id");
  445: 
  446:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
  447:     return undef if (!$opened);
  448: 
  449:     flock($idf,LOCK_SH);
  450:     my %disk_env;
  451:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
  452: 	    &GDBM_READER(),0640)) {
  453: 	return undef;	
  454:     }
  455: 
  456:     if (!defined($disk_env{'user.name'})
  457: 	|| !defined($disk_env{'user.domain'})) {
  458: 	return undef;
  459:     }
  460:     return $handle;
  461: }
  462: 
  463: sub timed_flock {
  464:     my ($file,$lock_type) = @_;
  465:     my $failed=0;
  466:     eval {
  467: 	local $SIG{__DIE__}='DEFAULT';
  468: 	local $SIG{ALRM}=sub {
  469: 	    $failed=1;
  470: 	    die("failed lock");
  471: 	};
  472: 	alarm(13);
  473: 	flock($file,$lock_type);
  474: 	alarm(0);
  475:     };
  476:     if ($failed) {
  477: 	return undef;
  478:     } else {
  479: 	return 1;
  480:     }
  481: }
  482: 
  483: # ---------------------------------------------------------- Append Environment
  484: 
  485: sub appenv {
  486:     my ($newenv,$roles) = @_;
  487:     if (ref($newenv) eq 'HASH') {
  488:         foreach my $key (keys(%{$newenv})) {
  489:             my $refused = 0;
  490: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
  491:                 $refused = 1;
  492:                 if (ref($roles) eq 'ARRAY') {
  493:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
  494:                     if (grep(/^\Q$role\E$/,@{$roles})) {
  495:                         $refused = 0;
  496:                     }
  497:                 }
  498:             }
  499:             if ($refused) {
  500:                 &logthis("<font color=\"blue\">WARNING: ".
  501:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
  502:                          .'</font>');
  503: 	        delete($newenv->{$key});
  504:             } else {
  505:                 $env{$key}=$newenv->{$key};
  506:             }
  507:         }
  508:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
  509:         if ($opened
  510: 	    && &timed_flock($env_file,LOCK_EX)
  511: 	    &&
  512: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  513: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  514: 	    while (my ($key,$value) = each(%{$newenv})) {
  515: 	        $disk_env{$key} = $value;
  516: 	    }
  517: 	    untie(%disk_env);
  518:         }
  519:     }
  520:     return 'ok';
  521: }
  522: # ----------------------------------------------------- Delete from Environment
  523: 
  524: sub delenv {
  525:     my ($delthis,$regexp) = @_;
  526:     if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
  527:         &logthis("<font color=\"blue\">WARNING: ".
  528:                 "Attempt to delete from environment ".$delthis);
  529:         return 'error';
  530:     }
  531:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
  532:     if ($opened
  533: 	&& &timed_flock($env_file,LOCK_EX)
  534: 	&&
  535: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
  536: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
  537: 	foreach my $key (keys(%disk_env)) {
  538:             if ($regexp) {
  539:                 if ($key=~/^$delthis/) {
  540:                     delete($env{$key});
  541:                     delete($disk_env{$key});
  542:                 }
  543:             } else {
  544:                 if ($key=~/^\Q$delthis\E/) {
  545:                     delete($env{$key});
  546:                     delete($disk_env{$key});
  547:                 }
  548:             }
  549: 	}
  550: 	untie(%disk_env);
  551:     }
  552:     return 'ok';
  553: }
  554: 
  555: sub get_env_multiple {
  556:     my ($name) = @_;
  557:     my @values;
  558:     if (defined($env{$name})) {
  559:         # exists is it an array
  560:         if (ref($env{$name})) {
  561:             @values=@{ $env{$name} };
  562:         } else {
  563:             $values[0]=$env{$name};
  564:         }
  565:     }
  566:     return(@values);
  567: }
  568: 
  569: # ------------------------------------------------------------------- Locking
  570: 
  571: sub set_lock {
  572:     my ($text)=@_;
  573:     $locknum++;
  574:     my $id=$$.'-'.$locknum;
  575:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
  576:              'session.lock.'.$id => $text});
  577:     return $id;
  578: }
  579: 
  580: sub get_locks {
  581:     my $num=0;
  582:     my %texts=();
  583:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  584:        if ($lock=~/\w/) {
  585:           $num++;
  586:           $texts{$lock}=$env{'session.lock.'.$lock};
  587:        }
  588:    }
  589:    return ($num,%texts);
  590: }
  591: 
  592: sub remove_lock {
  593:     my ($id)=@_;
  594:     my $newlocks='';
  595:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  596:        if (($lock=~/\w/) && ($lock ne $id)) {
  597:           $newlocks.=','.$lock;
  598:        }
  599:     }
  600:     &appenv({'session.locks' => $newlocks});
  601:     &delenv('session.lock.'.$id);
  602: }
  603: 
  604: sub remove_all_locks {
  605:     my $activelocks=$env{'session.locks'};
  606:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
  607:        if ($lock=~/\w/) {
  608:           &remove_lock($lock);
  609:        }
  610:     }
  611: }
  612: 
  613: 
  614: # ------------------------------------------ Find out current server userload
  615: sub userload {
  616:     my $numusers=0;
  617:     {
  618: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
  619: 	my $filename;
  620: 	my $curtime=time;
  621: 	while ($filename=readdir(LONIDS)) {
  622: 	    next if ($filename eq '.' || $filename eq '..');
  623: 	    next if ($filename =~ /publicuser_\d+\.id/);
  624: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
  625: 	    if ($curtime-$mtime < 1800) { $numusers++; }
  626: 	}
  627: 	closedir(LONIDS);
  628:     }
  629:     my $userloadpercent=0;
  630:     my $maxuserload=$perlvar{'lonUserLoadLim'};
  631:     if ($maxuserload) {
  632: 	$userloadpercent=100*$numusers/$maxuserload;
  633:     }
  634:     $userloadpercent=sprintf("%.2f",$userloadpercent);
  635:     return $userloadpercent;
  636: }
  637: 
  638: # ------------------------------------------ Fight off request when overloaded
  639: 
  640: sub overloaderror {
  641:     my ($r,$checkserver)=@_;
  642:     unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
  643:     my $loadavg;
  644:     if ($checkserver eq $perlvar{'lonHostID'}) {
  645:        open(my $loadfile,'/proc/loadavg');
  646:        $loadavg=<$loadfile>;
  647:        $loadavg =~ s/\s.*//g;
  648:        $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
  649:        close($loadfile);
  650:     } else {
  651:        $loadavg=&reply('load',$checkserver);
  652:     }
  653:     my $overload=$loadavg-100;
  654:     if ($overload>0) {
  655: 	$r->err_headers_out->{'Retry-After'}=$overload;
  656:         $r->log_error('Overload of '.$overload.' on '.$checkserver);
  657:         return 413;
  658:     }    
  659:     return '';
  660: }
  661: 
  662: # ------------------------------ Find server with least workload from spare.tab
  663: 
  664: sub spareserver {
  665:     my ($loadpercent,$userloadpercent,$want_server_name) = @_;
  666:     my $spare_server;
  667:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
  668:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
  669:                                                      :  $userloadpercent;
  670:     
  671:     foreach my $try_server (@{ $spareid{'primary'} }) {
  672: 	($spare_server, $lowest_load) =
  673: 	    &compare_server_load($try_server, $spare_server, $lowest_load);
  674:     }
  675: 
  676:     my $found_server = ($spare_server ne '' && $lowest_load < 100);
  677: 
  678:     if (!$found_server) {
  679: 	foreach my $try_server (@{ $spareid{'default'} }) {
  680: 	    ($spare_server, $lowest_load) =
  681: 		&compare_server_load($try_server, $spare_server, $lowest_load);
  682: 	}
  683:     }
  684: 
  685:     if (!$want_server_name) {
  686:         my $protocol = 'http';
  687:         if ($protocol{$spare_server} eq 'https') {
  688:             $protocol = $protocol{$spare_server};
  689:         }
  690: 	$spare_server = $protocol.'://'.&hostname($spare_server);
  691:     }
  692:     return $spare_server;
  693: }
  694: 
  695: sub compare_server_load {
  696:     my ($try_server, $spare_server, $lowest_load) = @_;
  697: 
  698:     my $loadans     = &reply('load',    $try_server);
  699:     my $userloadans = &reply('userload',$try_server);
  700: 
  701:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
  702: 	next; #didn't get a number from the server
  703:     }
  704: 
  705:     my $load;
  706:     if ($loadans =~ /\d/) {
  707: 	if ($userloadans =~ /\d/) {
  708: 	    #both are numbers, pick the bigger one
  709: 	    $load = ($loadans > $userloadans) ? $loadans 
  710: 		                              : $userloadans;
  711: 	} else {
  712: 	    $load = $loadans;
  713: 	}
  714:     } else {
  715: 	$load = $userloadans;
  716:     }
  717: 
  718:     if (($load =~ /\d/) && ($load < $lowest_load)) {
  719: 	$spare_server = $try_server;
  720: 	$lowest_load  = $load;
  721:     }
  722:     return ($spare_server,$lowest_load);
  723: }
  724: 
  725: # --------------------------- ask offload servers if user already has a session
  726: sub find_existing_session {
  727:     my ($udom,$uname) = @_;
  728:     foreach my $try_server (@{ $spareid{'primary'} },
  729: 			    @{ $spareid{'default'} }) {
  730: 	return $try_server if (&has_user_session($try_server, $udom, $uname));
  731:     }
  732:     return;
  733: }
  734: 
  735: # -------------------------------- ask if server already has a session for user
  736: sub has_user_session {
  737:     my ($lonid,$udom,$uname) = @_;
  738:     my $result = &reply(join(':','userhassession',
  739: 			     map {&escape($_)} ($udom,$uname)),$lonid);
  740:     return 1 if ($result eq 'ok');
  741: 
  742:     return 0;
  743: }
  744: 
  745: # --------------------------------------------- Try to change a user's password
  746: 
  747: sub changepass {
  748:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
  749:     $currentpass = &escape($currentpass);
  750:     $newpass     = &escape($newpass);
  751:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
  752: 		       $server);
  753:     if (! $answer) {
  754: 	&logthis("No reply on password change request to $server ".
  755: 		 "by $uname in domain $udom.");
  756:     } elsif ($answer =~ "^ok") {
  757:         &logthis("$uname in $udom successfully changed their password ".
  758: 		 "on $server.");
  759:     } elsif ($answer =~ "^pwchange_failure") {
  760: 	&logthis("$uname in $udom was unable to change their password ".
  761: 		 "on $server.  The action was blocked by either lcpasswd ".
  762: 		 "or pwchange");
  763:     } elsif ($answer =~ "^non_authorized") {
  764:         &logthis("$uname in $udom did not get their password correct when ".
  765: 		 "attempting to change it on $server.");
  766:     } elsif ($answer =~ "^auth_mode_error") {
  767:         &logthis("$uname in $udom attempted to change their password despite ".
  768: 		 "not being locally or internally authenticated on $server.");
  769:     } elsif ($answer =~ "^unknown_user") {
  770:         &logthis("$uname in $udom attempted to change their password ".
  771: 		 "on $server but were unable to because $server is not ".
  772: 		 "their home server.");
  773:     } elsif ($answer =~ "^refused") {
  774: 	&logthis("$server refused to change $uname in $udom password because ".
  775: 		 "it was sent an unencrypted request to change the password.");
  776:     }
  777:     return $answer;
  778: }
  779: 
  780: # ----------------------- Try to determine user's current authentication scheme
  781: 
  782: sub queryauthenticate {
  783:     my ($uname,$udom)=@_;
  784:     my $uhome=&homeserver($uname,$udom);
  785:     if (!$uhome) {
  786: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
  787: 	return 'no_host';
  788:     }
  789:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
  790:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
  791: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  792:     }
  793:     return $answer;
  794: }
  795: 
  796: # --------- Try to authenticate user from domain's lib servers (first this one)
  797: 
  798: sub authenticate {
  799:     my ($uname,$upass,$udom,$checkdefauth)=@_;
  800:     $upass=&escape($upass);
  801:     $uname= &LONCAPA::clean_username($uname);
  802:     my $uhome=&homeserver($uname,$udom,1);
  803:     my $newhome;
  804:     if ((!$uhome) || ($uhome eq 'no_host')) {
  805: # Maybe the machine was offline and only re-appeared again recently?
  806:         &reconlonc();
  807: # One more
  808: 	$uhome=&homeserver($uname,$udom,1);
  809:         if (($uhome eq 'no_host') && $checkdefauth) {
  810:             if (defined(&domain($udom,'primary'))) {
  811:                 $newhome=&domain($udom,'primary');
  812:             }
  813:             if ($newhome ne '') {
  814:                 $uhome = $newhome;
  815:             }
  816:         }
  817: 	if ((!$uhome) || ($uhome eq 'no_host')) {
  818: 	    &logthis("User $uname at $udom is unknown in authenticate");
  819: 	    return 'no_host';
  820:         }
  821:     }
  822:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth",$uhome);
  823:     if ($answer eq 'authorized') {
  824:         if ($newhome) {
  825:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
  826:             return 'no_account_on_host'; 
  827:         } else {
  828:             &logthis("User $uname at $udom authorized by $uhome");
  829:             return $uhome;
  830:         }
  831:     }
  832:     if ($answer eq 'non_authorized') {
  833: 	&logthis("User $uname at $udom rejected by $uhome");
  834: 	return 'no_host'; 
  835:     }
  836:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
  837:     return 'no_host';
  838: }
  839: 
  840: # ---------------------- Find the homebase for a user from domain's lib servers
  841: 
  842: my %homecache;
  843: sub homeserver {
  844:     my ($uname,$udom,$ignoreBadCache)=@_;
  845:     my $index="$uname:$udom";
  846: 
  847:     if (exists($homecache{$index})) { return $homecache{$index}; }
  848: 
  849:     my %servers = &get_servers($udom,'library');
  850:     foreach my $tryserver (keys(%servers)) {
  851:         next if ($ignoreBadCache ne 'true' && 
  852: 		 exists($badServerCache{$tryserver}));
  853: 
  854: 	my $answer=reply("home:$udom:$uname",$tryserver);
  855: 	if ($answer eq 'found') {
  856: 	    delete($badServerCache{$tryserver}); 
  857: 	    return $homecache{$index}=$tryserver;
  858: 	} elsif ($answer eq 'no_host') {
  859: 	    $badServerCache{$tryserver}=1;
  860: 	}
  861:     }    
  862:     return 'no_host';
  863: }
  864: 
  865: # ------------------------------------- Find the usernames behind a list of IDs
  866: 
  867: sub idget {
  868:     my ($udom,@ids)=@_;
  869:     my %returnhash=();
  870:     
  871:     my %servers = &get_servers($udom,'library');
  872:     foreach my $tryserver (keys(%servers)) {
  873: 	my $idlist=join('&',@ids);
  874: 	$idlist=~tr/A-Z/a-z/; 
  875: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
  876: 	my @answer=();
  877: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
  878: 	    @answer=split(/\&/,$reply);
  879: 	}                    ;
  880: 	my $i;
  881: 	for ($i=0;$i<=$#ids;$i++) {
  882: 	    if ($answer[$i]) {
  883: 		$returnhash{$ids[$i]}=$answer[$i];
  884: 	    } 
  885: 	}
  886:     } 
  887:     return %returnhash;
  888: }
  889: 
  890: # ------------------------------------- Find the IDs behind a list of usernames
  891: 
  892: sub idrget {
  893:     my ($udom,@unames)=@_;
  894:     my %returnhash=();
  895:     foreach my $uname (@unames) {
  896:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
  897:     }
  898:     return %returnhash;
  899: }
  900: 
  901: # ------------------------------- Store away a list of names and associated IDs
  902: 
  903: sub idput {
  904:     my ($udom,%ids)=@_;
  905:     my %servers=();
  906:     foreach my $uname (keys(%ids)) {
  907: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
  908:         my $uhom=&homeserver($uname,$udom);
  909:         if ($uhom ne 'no_host') {
  910:             my $id=&escape($ids{$uname});
  911:             $id=~tr/A-Z/a-z/;
  912:             my $esc_unam=&escape($uname);
  913: 	    if ($servers{$uhom}) {
  914: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
  915:             } else {
  916:                 $servers{$uhom}=$id.'='.$esc_unam;
  917:             }
  918:         }
  919:     }
  920:     foreach my $server (keys(%servers)) {
  921:         &critical('idput:'.$udom.':'.$servers{$server},$server);
  922:     }
  923: }
  924: 
  925: # ------------------------------------------- get items from domain db files   
  926: 
  927: sub get_dom {
  928:     my ($namespace,$storearr,$udom,$uhome)=@_;
  929:     my $items='';
  930:     foreach my $item (@$storearr) {
  931:         $items.=&escape($item).'&';
  932:     }
  933:     $items=~s/\&$//;
  934:     if (!$udom) {
  935:         $udom=$env{'user.domain'};
  936:         if (defined(&domain($udom,'primary'))) {
  937:             $uhome=&domain($udom,'primary');
  938:         } else {
  939:             undef($uhome);
  940:         }
  941:     } else {
  942:         if (!$uhome) {
  943:             if (defined(&domain($udom,'primary'))) {
  944:                 $uhome=&domain($udom,'primary');
  945:             }
  946:         }
  947:     }
  948:     if ($udom && $uhome && ($uhome ne 'no_host')) {
  949:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
  950:         my %returnhash;
  951:         if ($rep eq '' || $rep =~ /^error: 2 /) {
  952:             return %returnhash;
  953:         }
  954:         my @pairs=split(/\&/,$rep);
  955:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
  956:             return @pairs;
  957:         }
  958:         my $i=0;
  959:         foreach my $item (@$storearr) {
  960:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
  961:             $i++;
  962:         }
  963:         return %returnhash;
  964:     } else {
  965:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
  966:     }
  967: }
  968: 
  969: # -------------------------------------------- put items in domain db files 
  970: 
  971: sub put_dom {
  972:     my ($namespace,$storehash,$udom,$uhome)=@_;
  973:     if (!$udom) {
  974:         $udom=$env{'user.domain'};
  975:         if (defined(&domain($udom,'primary'))) {
  976:             $uhome=&domain($udom,'primary');
  977:         } else {
  978:             undef($uhome);
  979:         }
  980:     } else {
  981:         if (!$uhome) {
  982:             if (defined(&domain($udom,'primary'))) {
  983:                 $uhome=&domain($udom,'primary');
  984:             }
  985:         }
  986:     } 
  987:     if ($udom && $uhome && ($uhome ne 'no_host')) {
  988:         my $items='';
  989:         foreach my $item (keys(%$storehash)) {
  990:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
  991:         }
  992:         $items=~s/\&$//;
  993:         return &reply("putdom:$udom:$namespace:$items",$uhome);
  994:     } else {
  995:         &logthis("put_dom failed - no homeserver and/or domain");
  996:     }
  997: }
  998: 
  999: sub retrieve_inst_usertypes {
 1000:     my ($udom) = @_;
 1001:     my (%returnhash,@order);
 1002:     if (defined(&domain($udom,'primary'))) {
 1003:         my $uhome=&domain($udom,'primary');
 1004:         my $rep=&reply("inst_usertypes:$udom",$uhome);
 1005:         if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
 1006:             &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
 1007:             return (\%returnhash,\@order);
 1008:         }
 1009:         my ($hashitems,$orderitems) = split(/:/,$rep); 
 1010:         my @pairs=split(/\&/,$hashitems);
 1011:         foreach my $item (@pairs) {
 1012:             my ($key,$value)=split(/=/,$item,2);
 1013:             $key = &unescape($key);
 1014:             next if ($key =~ /^error: 2 /);
 1015:             $returnhash{$key}=&thaw_unescape($value);
 1016:         }
 1017:         my @esc_order = split(/\&/,$orderitems);
 1018:         foreach my $item (@esc_order) {
 1019:             push(@order,&unescape($item));
 1020:         }
 1021:     } else {
 1022:         &logthis("get_dom failed - no primary domain server for $udom");
 1023:     }
 1024:     return (\%returnhash,\@order);
 1025: }
 1026: 
 1027: sub is_domainimage {
 1028:     my ($url) = @_;
 1029:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
 1030:         if (&domain($1) ne '') {
 1031:             return '1';
 1032:         }
 1033:     }
 1034:     return;
 1035: }
 1036: 
 1037: sub inst_directory_query {
 1038:     my ($srch) = @_;
 1039:     my $udom = $srch->{'srchdomain'};
 1040:     my %results;
 1041:     my $homeserver = &domain($udom,'primary');
 1042:     my $outcome;
 1043:     if ($homeserver ne '') {
 1044: 	my $queryid=&reply("querysend:instdirsearch:".
 1045: 			   &escape($srch->{'srchby'}).':'.
 1046: 			   &escape($srch->{'srchterm'}).':'.
 1047: 			   &escape($srch->{'srchtype'}),$homeserver);
 1048: 	my $host=&hostname($homeserver);
 1049: 	if ($queryid !~/^\Q$host\E\_/) {
 1050: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1051: 	    return;
 1052: 	}
 1053: 	my $response = &get_query_reply($queryid);
 1054: 	my $maxtries = 5;
 1055: 	my $tries = 1;
 1056: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1057: 	    $response = &get_query_reply($queryid);
 1058: 	    $tries ++;
 1059: 	}
 1060: 
 1061:         if (!&error($response) && $response ne 'refused') {
 1062:             if ($response eq 'unavailable') {
 1063:                 $outcome = $response;
 1064:             } else {
 1065:                 $outcome = 'ok';
 1066:                 my @matches = split(/\n/,$response);
 1067:                 foreach my $match (@matches) {
 1068:                     my ($key,$value) = split(/=/,$match);
 1069:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
 1070:                 }
 1071:             }
 1072:         }
 1073:     }
 1074:     return ($outcome,%results);
 1075: }
 1076: 
 1077: sub usersearch {
 1078:     my ($srch) = @_;
 1079:     my $dom = $srch->{'srchdomain'};
 1080:     my %results;
 1081:     my %libserv = &all_library();
 1082:     my $query = 'usersearch';
 1083:     foreach my $tryserver (keys(%libserv)) {
 1084:         if (&host_domain($tryserver) eq $dom) {
 1085:             my $host=&hostname($tryserver);
 1086:             my $queryid=
 1087:                 &reply("querysend:".&escape($query).':'.
 1088:                        &escape($srch->{'srchby'}).':'.
 1089:                        &escape($srch->{'srchtype'}).':'.
 1090:                        &escape($srch->{'srchterm'}),$tryserver);
 1091:             if ($queryid !~/^\Q$host\E\_/) {
 1092:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
 1093:                 next;
 1094:             }
 1095:             my $reply = &get_query_reply($queryid);
 1096:             my $maxtries = 1;
 1097:             my $tries = 1;
 1098:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 1099:                 $reply = &get_query_reply($queryid);
 1100:                 $tries ++;
 1101:             }
 1102:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 1103:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
 1104:             } else {
 1105:                 my @matches;
 1106:                 if ($reply =~ /\n/) {
 1107:                     @matches = split(/\n/,$reply);
 1108:                 } else {
 1109:                     @matches = split(/\&/,$reply);
 1110:                 }
 1111:                 foreach my $match (@matches) {
 1112:                     my ($uname,$udom,%userhash);
 1113:                     foreach my $entry (split(/:/,$match)) {
 1114:                         my ($key,$value) =
 1115:                             map {&unescape($_);} split(/=/,$entry);
 1116:                         $userhash{$key} = $value;
 1117:                         if ($key eq 'username') {
 1118:                             $uname = $value;
 1119:                         } elsif ($key eq 'domain') {
 1120:                             $udom = $value;
 1121:                         }
 1122:                     }
 1123:                     $results{$uname.':'.$udom} = \%userhash;
 1124:                 }
 1125:             }
 1126:         }
 1127:     }
 1128:     return %results;
 1129: }
 1130: 
 1131: sub get_instuser {
 1132:     my ($udom,$uname,$id) = @_;
 1133:     my $homeserver = &domain($udom,'primary');
 1134:     my ($outcome,%results);
 1135:     if ($homeserver ne '') {
 1136:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
 1137:                            &escape($id).':'.&escape($udom),$homeserver);
 1138:         my $host=&hostname($homeserver);
 1139:         if ($queryid !~/^\Q$host\E\_/) {
 1140:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
 1141:             return;
 1142:         }
 1143:         my $response = &get_query_reply($queryid);
 1144:         my $maxtries = 5;
 1145:         my $tries = 1;
 1146:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
 1147:             $response = &get_query_reply($queryid);
 1148:             $tries ++;
 1149:         }
 1150:         if (!&error($response) && $response ne 'refused') {
 1151:             if ($response eq 'unavailable') {
 1152:                 $outcome = $response;
 1153:             } else {
 1154:                 $outcome = 'ok';
 1155:                 my @matches = split(/\n/,$response);
 1156:                 foreach my $match (@matches) {
 1157:                     my ($key,$value) = split(/=/,$match);
 1158:                     $results{&unescape($key)} = &thaw_unescape($value);
 1159:                 }
 1160:             }
 1161:         }
 1162:     }
 1163:     my %userinfo;
 1164:     if (ref($results{$uname}) eq 'HASH') {
 1165:         %userinfo = %{$results{$uname}};
 1166:     } 
 1167:     return ($outcome,%userinfo);
 1168: }
 1169: 
 1170: sub inst_rulecheck {
 1171:     my ($udom,$uname,$id,$item,$rules) = @_;
 1172:     my %returnhash;
 1173:     if ($udom ne '') {
 1174:         if (ref($rules) eq 'ARRAY') {
 1175:             @{$rules} = map {&escape($_);} (@{$rules});
 1176:             my $rulestr = join(':',@{$rules});
 1177:             my $homeserver=&domain($udom,'primary');
 1178:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1179:                 my $response;
 1180:                 if ($item eq 'username') {                
 1181:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
 1182:                                               ':'.&escape($uname).':'.$rulestr,
 1183:                                               $homeserver));
 1184:                 } elsif ($item eq 'id') {
 1185:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
 1186:                                               ':'.&escape($id).':'.$rulestr,
 1187:                                               $homeserver));
 1188:                 } elsif ($item eq 'selfcreate') {
 1189:                     $response=&unescape(&reply('instselfcreatecheck:'.
 1190:                                                &escape($udom).':'.&escape($uname).
 1191:                                               ':'.$rulestr,$homeserver));
 1192:                 }
 1193:                 if ($response ne 'refused') {
 1194:                     my @pairs=split(/\&/,$response);
 1195:                     foreach my $item (@pairs) {
 1196:                         my ($key,$value)=split(/=/,$item,2);
 1197:                         $key = &unescape($key);
 1198:                         next if ($key =~ /^error: 2 /);
 1199:                         $returnhash{$key}=&thaw_unescape($value);
 1200:                     }
 1201:                 }
 1202:             }
 1203:         }
 1204:     }
 1205:     return %returnhash;
 1206: }
 1207: 
 1208: sub inst_userrules {
 1209:     my ($udom,$check) = @_;
 1210:     my (%ruleshash,@ruleorder);
 1211:     if ($udom ne '') {
 1212:         my $homeserver=&domain($udom,'primary');
 1213:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
 1214:             my $response;
 1215:             if ($check eq 'id') {
 1216:                 $response=&reply('instidrules:'.&escape($udom),
 1217:                                  $homeserver);
 1218:             } elsif ($check eq 'email') {
 1219:                 $response=&reply('instemailrules:'.&escape($udom),
 1220:                                  $homeserver);
 1221:             } else {
 1222:                 $response=&reply('instuserrules:'.&escape($udom),
 1223:                                  $homeserver);
 1224:             }
 1225:             if (($response ne 'refused') && ($response ne 'error') && 
 1226:                 ($response ne 'unknown_cmd') && 
 1227:                 ($response ne 'no_such_host')) {
 1228:                 my ($hashitems,$orderitems) = split(/:/,$response);
 1229:                 my @pairs=split(/\&/,$hashitems);
 1230:                 foreach my $item (@pairs) {
 1231:                     my ($key,$value)=split(/=/,$item,2);
 1232:                     $key = &unescape($key);
 1233:                     next if ($key =~ /^error: 2 /);
 1234:                     $ruleshash{$key}=&thaw_unescape($value);
 1235:                 }
 1236:                 my @esc_order = split(/\&/,$orderitems);
 1237:                 foreach my $item (@esc_order) {
 1238:                     push(@ruleorder,&unescape($item));
 1239:                 }
 1240:             }
 1241:         }
 1242:     }
 1243:     return (\%ruleshash,\@ruleorder);
 1244: }
 1245: 
 1246: # ------------- Get Authentication, Language and User Tools Defaults for Domain
 1247: 
 1248: sub get_domain_defaults {
 1249:     my ($domain) = @_;
 1250:     my $cachetime = 60*60*24;
 1251:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
 1252:     if (defined($cached)) {
 1253:         if (ref($result) eq 'HASH') {
 1254:             return %{$result};
 1255:         }
 1256:     }
 1257:     my %domdefaults;
 1258:     my %domconfig =
 1259:          &Apache::lonnet::get_dom('configuration',['defaults','quotas'],$domain);
 1260:     if (ref($domconfig{'defaults'}) eq 'HASH') {
 1261:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
 1262:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
 1263:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
 1264:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
 1265:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
 1266:     } else {
 1267:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
 1268:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
 1269:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
 1270:     }
 1271:     if (ref($domconfig{'quotas'}) eq 'HASH') {
 1272:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
 1273:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
 1274:         } else {
 1275:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
 1276:         } 
 1277:         my @usertools = ('aboutme','blog','portfolio');
 1278:         foreach my $item (@usertools) {
 1279:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
 1280:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
 1281:             }
 1282:         }
 1283:     }
 1284:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
 1285:                                   $cachetime);
 1286:     return %domdefaults;
 1287: }
 1288: 
 1289: # --------------------------------------------------- Assign a key to a student
 1290: 
 1291: sub assign_access_key {
 1292: #
 1293: # a valid key looks like uname:udom#comments
 1294: # comments are being appended
 1295: #
 1296:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
 1297:     $kdom=
 1298:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
 1299:     $knum=
 1300:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
 1301:     $cdom=
 1302:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1303:     $cnum=
 1304:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1305:     $udom=$env{'user.name'} unless (defined($udom));
 1306:     $uname=$env{'user.domain'} unless (defined($uname));
 1307:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
 1308:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
 1309:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
 1310:                                                   # assigned to this person
 1311:                                                   # - this should not happen,
 1312:                                                   # unless something went wrong
 1313:                                                   # the first time around
 1314: # ready to assign
 1315:         $logentry=$1.'; '.$logentry;
 1316:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
 1317:                                                  $kdom,$knum) eq 'ok') {
 1318: # key now belongs to user
 1319: 	    my $envkey='key.'.$cdom.'_'.$cnum;
 1320:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
 1321:                 &appenv({'environment.'.$envkey => $ckey});
 1322:                 return 'ok';
 1323:             } else {
 1324:                 return 
 1325:   'error: Count not permanently assign key, will need to be re-entered later.';
 1326: 	    }
 1327:         } else {
 1328:             return 'error: Could not assign key, try again later.';
 1329:         }
 1330:     } elsif (!$existing{$ckey}) {
 1331: # the key does not exist
 1332: 	return 'error: The key does not exist';
 1333:     } else {
 1334: # the key is somebody else's
 1335: 	return 'error: The key is already in use';
 1336:     }
 1337: }
 1338: 
 1339: # ------------------------------------------ put an additional comment on a key
 1340: 
 1341: sub comment_access_key {
 1342: #
 1343: # a valid key looks like uname:udom#comments
 1344: # comments are being appended
 1345: #
 1346:     my ($ckey,$cdom,$cnum,$logentry)=@_;
 1347:     $cdom=
 1348:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1349:     $cnum=
 1350:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1351:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1352:     if ($existing{$ckey}) {
 1353:         $existing{$ckey}.='; '.$logentry;
 1354: # ready to assign
 1355:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
 1356:                                                  $cdom,$cnum) eq 'ok') {
 1357: 	    return 'ok';
 1358:         } else {
 1359: 	    return 'error: Count not store comment.';
 1360:         }
 1361:     } else {
 1362: # the key does not exist
 1363: 	return 'error: The key does not exist';
 1364:     }
 1365: }
 1366: 
 1367: # ------------------------------------------------------ Generate a set of keys
 1368: 
 1369: sub generate_access_keys {
 1370:     my ($number,$cdom,$cnum,$logentry)=@_;
 1371:     $cdom=
 1372:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1373:     $cnum=
 1374:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1375:     unless (&allowed('mky',$cdom)) { return 0; }
 1376:     unless (($cdom) && ($cnum)) { return 0; }
 1377:     if ($number>10000) { return 0; }
 1378:     sleep(2); # make sure don't get same seed twice
 1379:     srand(time()^($$+($$<<15))); # from "Programming Perl"
 1380:     my $total=0;
 1381:     for (my $i=1;$i<=$number;$i++) {
 1382:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
 1383:                   sprintf("%lx",int(100000*rand)).'-'.
 1384:                   sprintf("%lx",int(100000*rand));
 1385:        $newkey=~s/1/g/g; # folks mix up 1 and l
 1386:        $newkey=~s/0/h/g; # and also 0 and O
 1387:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
 1388:        if ($existing{$newkey}) {
 1389:            $i--;
 1390:        } else {
 1391: 	  if (&put('accesskeys',
 1392:               { $newkey => '# generated '.localtime().
 1393:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
 1394:                            '; '.$logentry },
 1395: 		   $cdom,$cnum) eq 'ok') {
 1396:               $total++;
 1397: 	  }
 1398:        }
 1399:     }
 1400:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 1401:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
 1402:     return $total;
 1403: }
 1404: 
 1405: # ------------------------------------------------------- Validate an accesskey
 1406: 
 1407: sub validate_access_key {
 1408:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
 1409:     $cdom=
 1410:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
 1411:     $cnum=
 1412:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
 1413:     $udom=$env{'user.domain'} unless (defined($udom));
 1414:     $uname=$env{'user.name'} unless (defined($uname));
 1415:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
 1416:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
 1417: }
 1418: 
 1419: # ------------------------------------- Find the section of student in a course
 1420: sub devalidate_getsection_cache {
 1421:     my ($udom,$unam,$courseid)=@_;
 1422:     my $hashid="$udom:$unam:$courseid";
 1423:     &devalidate_cache_new('getsection',$hashid);
 1424: }
 1425: 
 1426: sub courseid_to_courseurl {
 1427:     my ($courseid) = @_;
 1428:     #already url style courseid
 1429:     return $courseid if ($courseid =~ m{^/});
 1430: 
 1431:     if (exists($env{'course.'.$courseid.'.num'})) {
 1432: 	my $cnum = $env{'course.'.$courseid.'.num'};
 1433: 	my $cdom = $env{'course.'.$courseid.'.domain'};
 1434: 	return "/$cdom/$cnum";
 1435:     }
 1436: 
 1437:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
 1438:     if (exists($courseinfo{'num'})) {
 1439: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
 1440:     }
 1441: 
 1442:     return undef;
 1443: }
 1444: 
 1445: sub getsection {
 1446:     my ($udom,$unam,$courseid)=@_;
 1447:     my $cachetime=1800;
 1448: 
 1449:     my $hashid="$udom:$unam:$courseid";
 1450:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
 1451:     if (defined($cached)) { return $result; }
 1452: 
 1453:     my %Pending; 
 1454:     my %Expired;
 1455:     #
 1456:     # Each role can either have not started yet (pending), be active, 
 1457:     #    or have expired.
 1458:     #
 1459:     # If there is an active role, we are done.
 1460:     #
 1461:     # If there is more than one role which has not started yet, 
 1462:     #     choose the one which will start sooner
 1463:     # If there is one role which has not started yet, return it.
 1464:     #
 1465:     # If there is more than one expired role, choose the one which ended last.
 1466:     # If there is a role which has expired, return it.
 1467:     #
 1468:     $courseid = &courseid_to_courseurl($courseid);
 1469:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
 1470:     foreach my $key (keys(%roleshash)) {
 1471:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
 1472:         my $section=$1;
 1473:         if ($key eq $courseid.'_st') { $section=''; }
 1474:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
 1475:         my $now=time;
 1476:         if (defined($end) && $end && ($now > $end)) {
 1477:             $Expired{$end}=$section;
 1478:             next;
 1479:         }
 1480:         if (defined($start) && $start && ($now < $start)) {
 1481:             $Pending{$start}=$section;
 1482:             next;
 1483:         }
 1484:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
 1485:     }
 1486:     #
 1487:     # Presumedly there will be few matching roles from the above
 1488:     # loop and the sorting time will be negligible.
 1489:     if (scalar(keys(%Pending))) {
 1490:         my ($time) = sort {$a <=> $b} keys(%Pending);
 1491:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
 1492:     } 
 1493:     if (scalar(keys(%Expired))) {
 1494:         my @sorted = sort {$a <=> $b} keys(%Expired);
 1495:         my $time = pop(@sorted);
 1496:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
 1497:     }
 1498:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
 1499: }
 1500: 
 1501: sub save_cache {
 1502:     &purge_remembered();
 1503:     #&Apache::loncommon::validate_page();
 1504:     undef(%env);
 1505:     undef($env_loaded);
 1506: }
 1507: 
 1508: my $to_remember=-1;
 1509: my %remembered;
 1510: my %accessed;
 1511: my $kicks=0;
 1512: my $hits=0;
 1513: sub make_key {
 1514:     my ($name,$id) = @_;
 1515:     if (length($id) > 65 
 1516: 	&& length(&escape($id)) > 200) {
 1517: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
 1518:     }
 1519:     return &escape($name.':'.$id);
 1520: }
 1521: 
 1522: sub devalidate_cache_new {
 1523:     my ($name,$id,$debug) = @_;
 1524:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
 1525:     $id=&make_key($name,$id);
 1526:     $memcache->delete($id);
 1527:     delete($remembered{$id});
 1528:     delete($accessed{$id});
 1529: }
 1530: 
 1531: sub is_cached_new {
 1532:     my ($name,$id,$debug) = @_;
 1533:     $id=&make_key($name,$id);
 1534:     if (exists($remembered{$id})) {
 1535: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
 1536: 	$accessed{$id}=[&gettimeofday()];
 1537: 	$hits++;
 1538: 	return ($remembered{$id},1);
 1539:     }
 1540:     my $value = $memcache->get($id);
 1541:     if (!(defined($value))) {
 1542: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
 1543: 	return (undef,undef);
 1544:     }
 1545:     if ($value eq '__undef__') {
 1546: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
 1547: 	$value=undef;
 1548:     }
 1549:     &make_room($id,$value,$debug);
 1550:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
 1551:     return ($value,1);
 1552: }
 1553: 
 1554: sub do_cache_new {
 1555:     my ($name,$id,$value,$time,$debug) = @_;
 1556:     $id=&make_key($name,$id);
 1557:     my $setvalue=$value;
 1558:     if (!defined($setvalue)) {
 1559: 	$setvalue='__undef__';
 1560:     }
 1561:     if (!defined($time) ) {
 1562: 	$time=600;
 1563:     }
 1564:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
 1565:     my $result = $memcache->set($id,$setvalue,$time);
 1566:     if (! $result) {
 1567: 	&logthis("caching of id -> $id  failed");
 1568: 	$memcache->disconnect_all();
 1569:     }
 1570:     # need to make a copy of $value
 1571:     &make_room($id,$value,$debug);
 1572:     return $value;
 1573: }
 1574: 
 1575: sub make_room {
 1576:     my ($id,$value,$debug)=@_;
 1577: 
 1578:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
 1579:                                     : $value;
 1580:     if ($to_remember<0) { return; }
 1581:     $accessed{$id}=[&gettimeofday()];
 1582:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
 1583:     my $to_kick;
 1584:     my $max_time=0;
 1585:     foreach my $other (keys(%accessed)) {
 1586: 	if (&tv_interval($accessed{$other}) > $max_time) {
 1587: 	    $to_kick=$other;
 1588: 	    $max_time=&tv_interval($accessed{$other});
 1589: 	}
 1590:     }
 1591:     delete($remembered{$to_kick});
 1592:     delete($accessed{$to_kick});
 1593:     $kicks++;
 1594:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
 1595:     return;
 1596: }
 1597: 
 1598: sub purge_remembered {
 1599:     #&logthis("Tossing ".scalar(keys(%remembered)));
 1600:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
 1601:     undef(%remembered);
 1602:     undef(%accessed);
 1603: }
 1604: # ------------------------------------- Read an entry from a user's environment
 1605: 
 1606: sub userenvironment {
 1607:     my ($udom,$unam,@what)=@_;
 1608:     my $items;
 1609:     foreach my $item (@what) {
 1610:         $items.=&escape($item).'&';
 1611:     }
 1612:     $items=~s/\&$//;
 1613:     my %returnhash=();
 1614:     my @answer=split(/\&/,
 1615:                 &reply('get:'.$udom.':'.$unam.':environment:'.$items,
 1616:                       &homeserver($unam,$udom)));
 1617:     my $i;
 1618:     for ($i=0;$i<=$#what;$i++) {
 1619: 	$returnhash{$what[$i]}=&unescape($answer[$i]);
 1620:     }
 1621:     return %returnhash;
 1622: }
 1623: 
 1624: # ---------------------------------------------------------- Get a studentphoto
 1625: sub studentphoto {
 1626:     my ($udom,$unam,$ext) = @_;
 1627:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1628:     if (defined($env{'request.course.id'})) {
 1629:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
 1630:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
 1631:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
 1632:             } else {
 1633:                 my ($result,$perm_reqd)=
 1634: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1635:                 if ($result eq 'ok') {
 1636:                     if (!($perm_reqd eq 'yes')) {
 1637:                         return(&retrievestudentphoto($udom,$unam,$ext));
 1638:                     }
 1639:                 }
 1640:             }
 1641:         }
 1642:     } else {
 1643:         my ($result,$perm_reqd) = 
 1644: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
 1645:         if ($result eq 'ok') {
 1646:             if (!($perm_reqd eq 'yes')) {
 1647:                 return(&retrievestudentphoto($udom,$unam,$ext));
 1648:             }
 1649:         }
 1650:     }
 1651:     return '/adm/lonKaputt/lonlogo_broken.gif';
 1652: }
 1653: 
 1654: sub retrievestudentphoto {
 1655:     my ($udom,$unam,$ext,$type) = @_;
 1656:     my $home=&Apache::lonnet::homeserver($unam,$udom);
 1657:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
 1658:     if ($ret eq 'ok') {
 1659:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
 1660:         if ($type eq 'thumbnail') {
 1661:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
 1662:         }
 1663:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
 1664:         return $tokenurl;
 1665:     } else {
 1666:         if ($type eq 'thumbnail') {
 1667:             return '/adm/lonKaputt/genericstudent_tn.gif';
 1668:         } else { 
 1669:             return '/adm/lonKaputt/lonlogo_broken.gif';
 1670:         }
 1671:     }
 1672: }
 1673: 
 1674: # -------------------------------------------------------------------- New chat
 1675: 
 1676: sub chatsend {
 1677:     my ($newentry,$anon,$group)=@_;
 1678:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
 1679:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 1680:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
 1681:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
 1682: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
 1683: 		   &escape($newentry)).':'.$group,$chome);
 1684: }
 1685: 
 1686: # ------------------------------------------ Find current version of a resource
 1687: 
 1688: sub getversion {
 1689:     my $fname=&clutter(shift);
 1690:     unless ($fname=~/^\/res\//) { return -1; }
 1691:     return &currentversion(&filelocation('',$fname));
 1692: }
 1693: 
 1694: sub currentversion {
 1695:     my $fname=shift;
 1696:     my ($result,$cached)=&is_cached_new('resversion',$fname);
 1697:     if (defined($cached)) { return $result; }
 1698:     my $author=$fname;
 1699:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1700:     my ($udom,$uname)=split(/\//,$author);
 1701:     my $home=homeserver($uname,$udom);
 1702:     if ($home eq 'no_host') { 
 1703:         return -1; 
 1704:     }
 1705:     my $answer=reply("currentversion:$fname",$home);
 1706:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1707: 	return -1;
 1708:     }
 1709:     return &do_cache_new('resversion',$fname,$answer,600);
 1710: }
 1711: 
 1712: # ----------------------------- Subscribe to a resource, return URL if possible
 1713: 
 1714: sub subscribe {
 1715:     my $fname=shift;
 1716:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
 1717:     $fname=~s/[\n\r]//g;
 1718:     my $author=$fname;
 1719:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1720:     my ($udom,$uname)=split(/\//,$author);
 1721:     my $home=homeserver($uname,$udom);
 1722:     if ($home eq 'no_host') {
 1723:         return 'not_found';
 1724:     }
 1725:     my $answer=reply("sub:$fname",$home);
 1726:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
 1727: 	$answer.=' by '.$home;
 1728:     }
 1729:     return $answer;
 1730: }
 1731:     
 1732: # -------------------------------------------------------------- Replicate file
 1733: 
 1734: sub repcopy {
 1735:     my $filename=shift;
 1736:     $filename=~s/\/+/\//g;
 1737:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
 1738:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 1739:     if ($filename=~m|^/home/httpd/html/userfiles/| or
 1740: 	$filename=~m -^/*(uploaded|editupload)/-) { 
 1741: 	return &repcopy_userfile($filename);
 1742:     }
 1743:     $filename=~s/[\n\r]//g;
 1744:     my $transname="$filename.in.transfer";
 1745: # FIXME: this should flock
 1746:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
 1747:     my $remoteurl=subscribe($filename);
 1748:     if ($remoteurl =~ /^con_lost by/) {
 1749: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1750:            return 'unavailable';
 1751:     } elsif ($remoteurl eq 'not_found') {
 1752: 	   #&logthis("Subscribe returned not_found: $filename");
 1753: 	   return 'not_found';
 1754:     } elsif ($remoteurl =~ /^rejected by/) {
 1755: 	   &logthis("Subscribe returned $remoteurl: $filename");
 1756:            return 'forbidden';
 1757:     } elsif ($remoteurl eq 'directory') {
 1758:            return 'ok';
 1759:     } else {
 1760:         my $author=$filename;
 1761:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
 1762:         my ($udom,$uname)=split(/\//,$author);
 1763:         my $home=homeserver($uname,$udom);
 1764:         unless ($home eq $perlvar{'lonHostID'}) {
 1765:            my @parts=split(/\//,$filename);
 1766:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
 1767:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
 1768:                &logthis("Malconfiguration for replication: $filename");
 1769: 	       return 'bad_request';
 1770:            }
 1771:            my $count;
 1772:            for ($count=5;$count<$#parts;$count++) {
 1773:                $path.="/$parts[$count]";
 1774:                if ((-e $path)!=1) {
 1775: 		   mkdir($path,0777);
 1776:                }
 1777:            }
 1778:            my $ua=new LWP::UserAgent;
 1779:            my $request=new HTTP::Request('GET',"$remoteurl");
 1780:            my $response=$ua->request($request,$transname);
 1781:            if ($response->is_error()) {
 1782: 	       unlink($transname);
 1783:                my $message=$response->status_line;
 1784:                &logthis("<font color=\"blue\">WARNING:"
 1785:                        ." LWP get: $message: $filename</font>");
 1786:                return 'unavailable';
 1787:            } else {
 1788: 	       if ($remoteurl!~/\.meta$/) {
 1789:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
 1790:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
 1791:                   if ($mresponse->is_error()) {
 1792: 		      unlink($filename.'.meta');
 1793:                       &logthis(
 1794:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
 1795:                   }
 1796: 	       }
 1797:                rename($transname,$filename);
 1798:                return 'ok';
 1799:            }
 1800:        }
 1801:     }
 1802: }
 1803: 
 1804: # ------------------------------------------------ Get server side include body
 1805: sub ssi_body {
 1806:     my ($filelink,%form)=@_;
 1807:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
 1808:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
 1809:     }
 1810:     my $output='';
 1811:     my $response;
 1812:     if ($filelink=~/^https?\:/) {
 1813:        ($output,$response)=&externalssi($filelink);
 1814:     } else {
 1815:        ($output,$response)=&ssi($filelink,%form);
 1816:     }
 1817:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
 1818:     $output=~s/^.*?\<body[^\>]*\>//si;
 1819:     $output=~s/\<\/body\s*\>.*?$//si;
 1820:     if (wantarray) {
 1821:         return ($output, $response);
 1822:     } else {
 1823:         return $output;
 1824:     }
 1825: }
 1826: 
 1827: # --------------------------------------------------------- Server Side Include
 1828: 
 1829: sub absolute_url {
 1830:     my ($host_name) = @_;
 1831:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
 1832:     if ($host_name eq '') {
 1833: 	$host_name = $ENV{'SERVER_NAME'};
 1834:     }
 1835:     return $protocol.$host_name;
 1836: }
 1837: 
 1838: #
 1839: #   Server side include.
 1840: # Parameters:
 1841: #  fn     Possibly encrypted resource name/id.
 1842: #  form   Hash that describes how the rendering should be done
 1843: #         and other things.
 1844: # Returns:
 1845: #   Scalar context: The content of the response.
 1846: #   Array context:  2 element list of the content and the full response object.
 1847: #     
 1848: sub ssi {
 1849: 
 1850:     my ($fn,%form)=@_;
 1851:     my $ua=new LWP::UserAgent;
 1852:     my $request;
 1853: 
 1854:     $form{'no_update_last_known'}=1;
 1855:     &Apache::lonenc::check_encrypt(\$fn);
 1856:     if (%form) {
 1857:       $request=new HTTP::Request('POST',&absolute_url().$fn);
 1858:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
 1859:     } else {
 1860:       $request=new HTTP::Request('GET',&absolute_url().$fn);
 1861:     }
 1862: 
 1863:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
 1864:     my $response=$ua->request($request);
 1865: 
 1866:     if (wantarray) {
 1867: 	return ($response->content, $response);
 1868:     } else {
 1869: 	return $response->content;
 1870:     }
 1871: }
 1872: 
 1873: sub externalssi {
 1874:     my ($url)=@_;
 1875:     my $ua=new LWP::UserAgent;
 1876:     my $request=new HTTP::Request('GET',$url);
 1877:     my $response=$ua->request($request);
 1878:     if (wantarray) {
 1879:         return ($response->content, $response);
 1880:     } else {
 1881:         return $response->content;
 1882:     }
 1883: }
 1884: 
 1885: # -------------------------------- Allow a /uploaded/ URI to be vouched for
 1886: 
 1887: sub allowuploaded {
 1888:     my ($srcurl,$url)=@_;
 1889:     $url=&clutter(&declutter($url));
 1890:     my $dir=$url;
 1891:     $dir=~s/\/[^\/]+$//;
 1892:     my %httpref=();
 1893:     my $httpurl=&hreflocation('',$url);
 1894:     $httpref{'httpref.'.$httpurl}=$srcurl;
 1895:     &Apache::lonnet::appenv(\%httpref);
 1896: }
 1897: 
 1898: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
 1899: # input: action, courseID, current domain, intended
 1900: #        path to file, source of file, instruction to parse file for objects,
 1901: #        ref to hash for embedded objects,
 1902: #        ref to hash for codebase of java objects.
 1903: #
 1904: # output: url to file (if action was uploaddoc), 
 1905: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
 1906: #
 1907: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
 1908: # course.
 1909: #
 1910: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1911: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
 1912: #          course's home server.
 1913: #
 1914: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
 1915: #          be copied from $source (current location) to 
 1916: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1917: #         and will then be copied to
 1918: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
 1919: #         course's home server.
 1920: #
 1921: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1922: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
 1923: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
 1924: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
 1925: #         in course's home server.
 1926: #
 1927: 
 1928: sub process_coursefile {
 1929:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
 1930:     my $fetchresult;
 1931:     my $home=&homeserver($docuname,$docudom);
 1932:     if ($action eq 'propagate') {
 1933:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1934: 			     $home);
 1935:     } else {
 1936:         my $fpath = '';
 1937:         my $fname = $file;
 1938:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 1939:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 1940:         my $filepath = &build_filepath($fpath);
 1941:         if ($action eq 'copy') {
 1942:             if ($source eq '') {
 1943:                 $fetchresult = 'no source file';
 1944:                 return $fetchresult;
 1945:             } else {
 1946:                 my $destination = $filepath.'/'.$fname;
 1947:                 rename($source,$destination);
 1948:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1949:                                  $home);
 1950:             }
 1951:         } elsif ($action eq 'uploaddoc') {
 1952:             open(my $fh,'>'.$filepath.'/'.$fname);
 1953:             print $fh $env{'form.'.$source};
 1954:             close($fh);
 1955:             if ($parser eq 'parse') {
 1956:                 my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
 1957:                 unless ($parse_result eq 'ok') {
 1958:                     &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
 1959:                 }
 1960:             }
 1961:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 1962:                                  $home);
 1963:             if ($fetchresult eq 'ok') {
 1964:                 return '/uploaded/'.$fpath.'/'.$fname;
 1965:             } else {
 1966:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1967:                         ' to host '.$home.': '.$fetchresult);
 1968:                 return '/adm/notfound.html';
 1969:             }
 1970:         }
 1971:     }
 1972:     unless ( $fetchresult eq 'ok') {
 1973:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 1974:              ' to host '.$home.': '.$fetchresult);
 1975:     }
 1976:     return $fetchresult;
 1977: }
 1978: 
 1979: sub build_filepath {
 1980:     my ($fpath) = @_;
 1981:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
 1982:     unless ($fpath eq '') {
 1983:         my @parts=split('/',$fpath);
 1984:         foreach my $part (@parts) {
 1985:             $filepath.= '/'.$part;
 1986:             if ((-e $filepath)!=1) {
 1987:                 mkdir($filepath,0777);
 1988:             }
 1989:         }
 1990:     }
 1991:     return $filepath;
 1992: }
 1993: 
 1994: sub store_edited_file {
 1995:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
 1996:     my $file = $primary_url;
 1997:     $file =~ s#^/uploaded/$docudom/$docuname/##;
 1998:     my $fpath = '';
 1999:     my $fname = $file;
 2000:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
 2001:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
 2002:     my $filepath = &build_filepath($fpath);
 2003:     open(my $fh,'>'.$filepath.'/'.$fname);
 2004:     print $fh $content;
 2005:     close($fh);
 2006:     my $home=&homeserver($docuname,$docudom);
 2007:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
 2008: 			  $home);
 2009:     if ($$fetchresult eq 'ok') {
 2010:         return '/uploaded/'.$fpath.'/'.$fname;
 2011:     } else {
 2012:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
 2013: 		 ' to host '.$home.': '.$$fetchresult);
 2014:         return '/adm/notfound.html';
 2015:     }
 2016: }
 2017: 
 2018: sub clean_filename {
 2019:     my ($fname,$args)=@_;
 2020: # Replace Windows backslashes by forward slashes
 2021:     $fname=~s/\\/\//g;
 2022:     if (!$args->{'keep_path'}) {
 2023:         # Get rid of everything but the actual filename
 2024: 	$fname=~s/^.*\/([^\/]+)$/$1/;
 2025:     }
 2026: # Replace spaces by underscores
 2027:     $fname=~s/\s+/\_/g;
 2028: # Replace all other weird characters by nothing
 2029:     $fname=~s{[^/\w\.\-]}{}g;
 2030: # Replace all .\d. sequences with _\d. so they no longer look like version
 2031: # numbers
 2032:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
 2033:     return $fname;
 2034: }
 2035: 
 2036: # --------------- Take an uploaded file and put it into the userfiles directory
 2037: # input: $formname - the contents of the file are in $env{"form.$formname"}
 2038: #                    the desired filenam is in $env{"form.$formname.filename"}
 2039: #        $coursedoc - if true up to the current course
 2040: #                     if false
 2041: #        $subdir - directory in userfile to store the file into
 2042: #        $parser - instruction to parse file for objects ($parser = parse)    
 2043: #        $allfiles - reference to hash for embedded objects
 2044: #        $codebase - reference to hash for codebase of java objects
 2045: #        $desuname - username for permanent storage of uploaded file
 2046: #        $dsetudom - domain for permanaent storage of uploaded file
 2047: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
 2048: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
 2049: # 
 2050: # output: url of file in userspace, or error: <message> 
 2051: #             or /adm/notfound.html if failure to upload occurse
 2052: 
 2053: 
 2054: sub userfileupload {
 2055:     my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
 2056:         $destudom,$thumbwidth,$thumbheight)=@_;
 2057:     if (!defined($subdir)) { $subdir='unknown'; }
 2058:     my $fname=$env{'form.'.$formname.'.filename'};
 2059:     $fname=&clean_filename($fname);
 2060: # See if there is anything left
 2061:     unless ($fname) { return 'error: no uploaded file'; }
 2062:     chop($env{'form.'.$formname});
 2063:     if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
 2064:         my $now = time;
 2065:         my $filepath = 'tmp/helprequests/'.$now;
 2066:         my @parts=split(/\//,$filepath);
 2067:         my $fullpath = $perlvar{'lonDaemons'};
 2068:         for (my $i=0;$i<@parts;$i++) {
 2069:             $fullpath .= '/'.$parts[$i];
 2070:             if ((-e $fullpath)!=1) {
 2071:                 mkdir($fullpath,0777);
 2072:             }
 2073:         }
 2074:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2075:         print $fh $env{'form.'.$formname};
 2076:         close($fh);
 2077:         return $fullpath.'/'.$fname;
 2078:     } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
 2079:         my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
 2080:                        '_'.$env{'user.domain'}.'/pending';
 2081:         my @parts=split(/\//,$filepath);
 2082:         my $fullpath = $perlvar{'lonDaemons'};
 2083:         for (my $i=0;$i<@parts;$i++) {
 2084:             $fullpath .= '/'.$parts[$i];
 2085:             if ((-e $fullpath)!=1) {
 2086:                 mkdir($fullpath,0777);
 2087:             }
 2088:         }
 2089:         open(my $fh,'>'.$fullpath.'/'.$fname);
 2090:         print $fh $env{'form.'.$formname};
 2091:         close($fh);
 2092:         return $fullpath.'/'.$fname;
 2093:     }
 2094:     
 2095: # Create the directory if not present
 2096:     $fname="$subdir/$fname";
 2097:     if ($coursedoc) {
 2098: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2099: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2100:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
 2101:             return &finishuserfileupload($docuname,$docudom,
 2102: 					 $formname,$fname,$parser,$allfiles,
 2103: 					 $codebase,$thumbwidth,$thumbheight);
 2104:         } else {
 2105:             $fname=$env{'form.folder'}.'/'.$fname;
 2106:             return &process_coursefile('uploaddoc',$docuname,$docudom,
 2107: 				       $fname,$formname,$parser,
 2108: 				       $allfiles,$codebase);
 2109:         }
 2110:     } elsif (defined($destuname)) {
 2111:         my $docuname=$destuname;
 2112:         my $docudom=$destudom;
 2113: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2114: 				     $parser,$allfiles,$codebase,
 2115:                                      $thumbwidth,$thumbheight);
 2116:         
 2117:     } else {
 2118:         my $docuname=$env{'user.name'};
 2119:         my $docudom=$env{'user.domain'};
 2120:         if (exists($env{'form.group'})) {
 2121:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
 2122:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 2123:         }
 2124: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
 2125: 				     $parser,$allfiles,$codebase,
 2126:                                      $thumbwidth,$thumbheight);
 2127:     }
 2128: }
 2129: 
 2130: sub finishuserfileupload {
 2131:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
 2132:         $thumbwidth,$thumbheight) = @_;
 2133:     my $path=$docudom.'/'.$docuname.'/';
 2134:     my $filepath=$perlvar{'lonDocRoot'};
 2135:     my ($fnamepath,$file,$fetchthumb);
 2136:     $file=$fname;
 2137:     if ($fname=~m|/|) {
 2138:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
 2139: 	$path.=$fnamepath.'/';
 2140:     }
 2141:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
 2142:     my $count;
 2143:     for ($count=4;$count<=$#parts;$count++) {
 2144:         $filepath.="/$parts[$count]";
 2145:         if ((-e $filepath)!=1) {
 2146: 	    mkdir($filepath,0777);
 2147:         }
 2148:     }
 2149: # Save the file
 2150:     {
 2151: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
 2152: 	    &logthis('Failed to create '.$filepath.'/'.$file);
 2153: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
 2154: 	    return '/adm/notfound.html';
 2155: 	}
 2156: 	if (!print FH ($env{'form.'.$formname})) {
 2157: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
 2158: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
 2159: 	    return '/adm/notfound.html';
 2160: 	}
 2161: 	close(FH);
 2162:     }
 2163:     if ($parser eq 'parse') {
 2164:         my $parse_result = &extract_embedded_items($filepath.'/'.$file,$allfiles,
 2165: 						   $codebase);
 2166:         unless ($parse_result eq 'ok') {
 2167:             &logthis('Failed to parse '.$filepath.$file.
 2168: 		     ' for embedded media: '.$parse_result); 
 2169:         }
 2170:     }
 2171:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
 2172:         my $input = $filepath.'/'.$file;
 2173:         my $output = $filepath.'/'.'tn-'.$file;
 2174:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
 2175:         system("convert -sample $thumbsize $input $output");
 2176:         if (-e $filepath.'/'.'tn-'.$file) {
 2177:             $fetchthumb  = 1; 
 2178:         }
 2179:     }
 2180:  
 2181: # Notify homeserver to grep it
 2182: #
 2183:     my $docuhome=&homeserver($docuname,$docudom);
 2184:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
 2185:     if ($fetchresult eq 'ok') {
 2186:         if ($fetchthumb) {
 2187:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
 2188:             if ($thumbresult ne 'ok') {
 2189:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
 2190:                          $docuhome.': '.$thumbresult);
 2191:             }
 2192:         }
 2193: #
 2194: # Return the URL to it
 2195:         return '/uploaded/'.$path.$file;
 2196:     } else {
 2197:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
 2198: 		 ': '.$fetchresult);
 2199:         return '/adm/notfound.html';
 2200:     }
 2201: }
 2202: 
 2203: sub extract_embedded_items {
 2204:     my ($fullpath,$allfiles,$codebase,$content) = @_;
 2205:     my @state = ();
 2206:     my %javafiles = (
 2207:                       codebase => '',
 2208:                       code => '',
 2209:                       archive => ''
 2210:                     );
 2211:     my %mediafiles = (
 2212:                       src => '',
 2213:                       movie => '',
 2214:                      );
 2215:     my $p;
 2216:     if ($content) {
 2217:         $p = HTML::LCParser->new($content);
 2218:     } else {
 2219:         $p = HTML::LCParser->new($fullpath);
 2220:     }
 2221:     while (my $t=$p->get_token()) {
 2222: 	if ($t->[0] eq 'S') {
 2223: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
 2224: 	    push(@state, $tagname);
 2225:             if (lc($tagname) eq 'allow') {
 2226:                 &add_filetype($allfiles,$attr->{'src'},'src');
 2227:             }
 2228: 	    if (lc($tagname) eq 'img') {
 2229: 		&add_filetype($allfiles,$attr->{'src'},'src');
 2230: 	    }
 2231: 	    if (lc($tagname) eq 'a') {
 2232: 		&add_filetype($allfiles,$attr->{'href'},'href');
 2233: 	    }
 2234:             if (lc($tagname) eq 'script') {
 2235:                 if ($attr->{'archive'} =~ /\.jar$/i) {
 2236:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
 2237:                 } else {
 2238:                     &add_filetype($allfiles,$attr->{'src'},'src');
 2239:                 }
 2240:             }
 2241:             if (lc($tagname) eq 'link') {
 2242:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
 2243:                     &add_filetype($allfiles,$attr->{'href'},'href');
 2244:                 }
 2245:             }
 2246: 	    if (lc($tagname) eq 'object' ||
 2247: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
 2248: 		foreach my $item (keys(%javafiles)) {
 2249: 		    $javafiles{$item} = '';
 2250: 		}
 2251: 	    }
 2252: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
 2253: 		my $name = lc($attr->{'name'});
 2254: 		foreach my $item (keys(%javafiles)) {
 2255: 		    if ($name eq $item) {
 2256: 			$javafiles{$item} = $attr->{'value'};
 2257: 			last;
 2258: 		    }
 2259: 		}
 2260: 		foreach my $item (keys(%mediafiles)) {
 2261: 		    if ($name eq $item) {
 2262: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
 2263: 			last;
 2264: 		    }
 2265: 		}
 2266: 	    }
 2267: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
 2268: 		foreach my $item (keys(%javafiles)) {
 2269: 		    if ($attr->{$item}) {
 2270: 			$javafiles{$item} = $attr->{$item};
 2271: 			last;
 2272: 		    }
 2273: 		}
 2274: 		foreach my $item (keys(%mediafiles)) {
 2275: 		    if ($attr->{$item}) {
 2276: 			&add_filetype($allfiles,$attr->{$item},$item);
 2277: 			last;
 2278: 		    }
 2279: 		}
 2280: 	    }
 2281: 	} elsif ($t->[0] eq 'E') {
 2282: 	    my ($tagname) = ($t->[1]);
 2283: 	    if ($javafiles{'codebase'} ne '') {
 2284: 		$javafiles{'codebase'} .= '/';
 2285: 	    }  
 2286: 	    if (lc($tagname) eq 'applet' ||
 2287: 		lc($tagname) eq 'object' ||
 2288: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
 2289: 		) {
 2290: 		foreach my $item (keys(%javafiles)) {
 2291: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
 2292: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
 2293: 			&add_filetype($allfiles,$file,$item);
 2294: 		    }
 2295: 		}
 2296: 	    } 
 2297: 	    pop @state;
 2298: 	}
 2299:     }
 2300:     return 'ok';
 2301: }
 2302: 
 2303: sub add_filetype {
 2304:     my ($allfiles,$file,$type)=@_;
 2305:     if (exists($allfiles->{$file})) {
 2306: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
 2307: 	    push(@{$allfiles->{$file}}, &escape($type));
 2308: 	}
 2309:     } else {
 2310: 	@{$allfiles->{$file}} = (&escape($type));
 2311:     }
 2312: }
 2313: 
 2314: sub removeuploadedurl {
 2315:     my ($url)=@_;
 2316:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
 2317:     return &removeuserfile($uname,$udom,$fname);
 2318: }
 2319: 
 2320: sub removeuserfile {
 2321:     my ($docuname,$docudom,$fname)=@_;
 2322:     my $home=&homeserver($docuname,$docudom);
 2323:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
 2324:     if ($result eq 'ok') {
 2325:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
 2326:             my $metafile = $fname.'.meta';
 2327:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
 2328: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
 2329:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 2330:             my $sqlresult = 
 2331:                 &update_portfolio_table($docuname,$docudom,$file,
 2332:                                         'portfolio_metadata',$group,
 2333:                                         'delete');
 2334:         }
 2335:     }
 2336:     return $result;
 2337: }
 2338: 
 2339: sub mkdiruserfile {
 2340:     my ($docuname,$docudom,$dir)=@_;
 2341:     my $home=&homeserver($docuname,$docudom);
 2342:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
 2343: }
 2344: 
 2345: sub renameuserfile {
 2346:     my ($docuname,$docudom,$old,$new)=@_;
 2347:     my $home=&homeserver($docuname,$docudom);
 2348:     my $result = &reply("renameuserfile:$docudom:$docuname:".
 2349:                         &escape("$old").':'.&escape("$new"),$home);
 2350:     if ($result eq 'ok') {
 2351:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
 2352:             my $oldmeta = $old.'.meta';
 2353:             my $newmeta = $new.'.meta';
 2354:             my $metaresult = 
 2355:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
 2356: 	    my $url = "/uploaded/$docudom/$docuname/$old";
 2357:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
 2358:             my $sqlresult = 
 2359:                 &update_portfolio_table($docuname,$docudom,$file,
 2360:                                         'portfolio_metadata',$group,
 2361:                                         'delete');
 2362:         }
 2363:     }
 2364:     return $result;
 2365: }
 2366: 
 2367: # ------------------------------------------------------------------------- Log
 2368: 
 2369: sub log {
 2370:     my ($dom,$nam,$hom,$what)=@_;
 2371:     return critical("log:$dom:$nam:$what",$hom);
 2372: }
 2373: 
 2374: # ------------------------------------------------------------------ Course Log
 2375: #
 2376: # This routine flushes several buffers of non-mission-critical nature
 2377: #
 2378: 
 2379: sub flushcourselogs {
 2380:     &logthis('Flushing log buffers');
 2381: #
 2382: # course logs
 2383: # This is a log of all transactions in a course, which can be used
 2384: # for data mining purposes
 2385: #
 2386: # It also collects the courseid database, which lists last transaction
 2387: # times and course titles for all courseids
 2388: #
 2389:     my %courseidbuffer=();
 2390:     foreach my $crsid (keys(%courselogs)) {
 2391:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
 2392: 		          &escape($courselogs{$crsid}),
 2393: 		          $coursehombuf{$crsid}) eq 'ok') {
 2394: 	    delete $courselogs{$crsid};
 2395:         } else {
 2396:             &logthis('Failed to flush log buffer for '.$crsid);
 2397:             if (length($courselogs{$crsid})>40000) {
 2398:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
 2399:                         " exceeded maximum size, deleting.</font>");
 2400:                delete $courselogs{$crsid};
 2401:             }
 2402:         }
 2403:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
 2404:             'description' => $coursedescrbuf{$crsid},
 2405:             'inst_code'    => $courseinstcodebuf{$crsid},
 2406:             'type'        => $coursetypebuf{$crsid},
 2407:             'owner'       => $courseownerbuf{$crsid},
 2408:         };
 2409:     }
 2410: #
 2411: # Write course id database (reverse lookup) to homeserver of courses 
 2412: # Is used in pickcourse
 2413: #
 2414:     foreach my $crs_home (keys(%courseidbuffer)) {
 2415:         my $response = &courseidput(&host_domain($crs_home),
 2416:                                     $courseidbuffer{$crs_home},
 2417:                                     $crs_home,'timeonly');
 2418:     }
 2419: #
 2420: # File accesses
 2421: # Writes to the dynamic metadata of resources to get hit counts, etc.
 2422: #
 2423:     foreach my $entry (keys(%accesshash)) {
 2424:         if ($entry =~ /___count$/) {
 2425:             my ($dom,$name);
 2426:             ($dom,$name,undef)=
 2427: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
 2428:             if (! defined($dom) || $dom eq '' || 
 2429:                 ! defined($name) || $name eq '') {
 2430:                 my $cid = $env{'request.course.id'};
 2431:                 $dom  = $env{'request.'.$cid.'.domain'};
 2432:                 $name = $env{'request.'.$cid.'.num'};
 2433:             }
 2434:             my $value = $accesshash{$entry};
 2435:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
 2436:             my %temphash=($url => $value);
 2437:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
 2438:             if ($result eq 'ok') {
 2439:                 delete $accesshash{$entry};
 2440:             } elsif ($result eq 'unknown_cmd') {
 2441:                 # Target server has old code running on it.
 2442:                 my %temphash=($entry => $value);
 2443:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2444:                     delete $accesshash{$entry};
 2445:                 }
 2446:             }
 2447:         } else {
 2448:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
 2449:             my %temphash=($entry => $accesshash{$entry});
 2450:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
 2451:                 delete $accesshash{$entry};
 2452:             }
 2453:         }
 2454:     }
 2455: #
 2456: # Roles
 2457: # Reverse lookup of user roles for course faculty/staff and co-authorship
 2458: #
 2459:     foreach my $entry (keys(%userrolehash)) {
 2460:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
 2461: 	    split(/\:/,$entry);
 2462:         if (&Apache::lonnet::put('nohist_userroles',
 2463:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
 2464:                 $rudom,$runame) eq 'ok') {
 2465: 	    delete $userrolehash{$entry};
 2466:         }
 2467:     }
 2468: #
 2469: # Reverse lookup of domain roles (dc, ad, li, sc, au)
 2470: #
 2471:     my %domrolebuffer = ();
 2472:     foreach my $entry (keys %domainrolehash) {
 2473:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
 2474:         if ($domrolebuffer{$rudom}) {
 2475:             $domrolebuffer{$rudom}.='&'.&escape($entry).
 2476:                       '='.&escape($domainrolehash{$entry});
 2477:         } else {
 2478:             $domrolebuffer{$rudom}.=&escape($entry).
 2479:                       '='.&escape($domainrolehash{$entry});
 2480:         }
 2481:         delete $domainrolehash{$entry};
 2482:     }
 2483:     foreach my $dom (keys(%domrolebuffer)) {
 2484: 	my %servers = &get_servers($dom,'library');
 2485: 	foreach my $tryserver (keys(%servers)) {
 2486: 	    unless (&reply('domroleput:'.$dom.':'.
 2487: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
 2488: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
 2489: 	    }
 2490:         }
 2491:     }
 2492:     $dumpcount++;
 2493: }
 2494: 
 2495: sub courselog {
 2496:     my $what=shift;
 2497:     $what=time.':'.$what;
 2498:     unless ($env{'request.course.id'}) { return ''; }
 2499:     $coursedombuf{$env{'request.course.id'}}=
 2500:        $env{'course.'.$env{'request.course.id'}.'.domain'};
 2501:     $coursenumbuf{$env{'request.course.id'}}=
 2502:        $env{'course.'.$env{'request.course.id'}.'.num'};
 2503:     $coursehombuf{$env{'request.course.id'}}=
 2504:        $env{'course.'.$env{'request.course.id'}.'.home'};
 2505:     $coursedescrbuf{$env{'request.course.id'}}=
 2506:        $env{'course.'.$env{'request.course.id'}.'.description'};
 2507:     $courseinstcodebuf{$env{'request.course.id'}}=
 2508:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
 2509:     $courseownerbuf{$env{'request.course.id'}}=
 2510:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
 2511:     $coursetypebuf{$env{'request.course.id'}}=
 2512:        $env{'course.'.$env{'request.course.id'}.'.type'};
 2513:     if (defined $courselogs{$env{'request.course.id'}}) {
 2514: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
 2515:     } else {
 2516: 	$courselogs{$env{'request.course.id'}}.=$what;
 2517:     }
 2518:     if (length($courselogs{$env{'request.course.id'}})>4048) {
 2519: 	&flushcourselogs();
 2520:     }
 2521: }
 2522: 
 2523: sub courseacclog {
 2524:     my $fnsymb=shift;
 2525:     unless ($env{'request.course.id'}) { return ''; }
 2526:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
 2527:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
 2528:         $what.=':POST';
 2529:         # FIXME: Probably ought to escape things....
 2530: 	foreach my $key (keys(%env)) {
 2531:             if ($key=~/^form\.(.*)/) {
 2532:                 my $formitem = $1;
 2533:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
 2534:                     $what.=':'.$formitem.'='.$env{$key};
 2535:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
 2536:                     $what.=':'.$formitem.'='.$env{$key};
 2537:                 }
 2538:             }
 2539:         }
 2540:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
 2541:         # FIXME: We should not be depending on a form parameter that someone
 2542:         # editing lonsearchcat.pm might change in the future.
 2543:         if ($env{'form.phase'} eq 'course_search') {
 2544:             $what.= ':POST';
 2545:             # FIXME: Probably ought to escape things....
 2546:             foreach my $element ('courseexp','crsfulltext','crsrelated',
 2547:                                  'crsdiscuss') {
 2548:                 $what.=':'.$element.'='.$env{'form.'.$element};
 2549:             }
 2550:         }
 2551:     }
 2552:     &courselog($what);
 2553: }
 2554: 
 2555: sub countacc {
 2556:     my $url=&declutter(shift);
 2557:     return if (! defined($url) || $url eq '');
 2558:     unless ($env{'request.course.id'}) { return ''; }
 2559:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
 2560:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
 2561:     $accesshash{$key}++;
 2562: }
 2563: 
 2564: sub linklog {
 2565:     my ($from,$to)=@_;
 2566:     $from=&declutter($from);
 2567:     $to=&declutter($to);
 2568:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
 2569:     $accesshash{$to.'___'.$from.'___goto'}=1;
 2570: }
 2571:   
 2572: sub userrolelog {
 2573:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
 2574:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
 2575:         ($trole=~/^in/) || ($trole=~/^cc/) ||
 2576:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
 2577:         ($trole=~/^ta/)) {
 2578:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2579:        $userrolehash
 2580:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2581:                     =$tend.':'.$tstart;
 2582:     }
 2583:     if (($env{'request.role'} =~ /dc\./) &&
 2584: 	(($trole=~/^au/) || ($trole=~/^in/) ||
 2585: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
 2586: 	 ($trole=~/^cr/) || ($trole=~/^ta/))) {
 2587:        $userrolehash
 2588:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
 2589:                     =$tend.':'.$tstart;
 2590:     }
 2591:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
 2592:         ($trole=~/^li/) || ($trole=~/^li/) ||
 2593:         ($trole=~/^au/) || ($trole=~/^dg/) ||
 2594:         ($trole=~/^sc/)) {
 2595:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
 2596:        $domainrolehash
 2597:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
 2598:                     = $tend.':'.$tstart;
 2599:     }
 2600: }
 2601: 
 2602: sub courserolelog {
 2603:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
 2604:     if (($trole eq 'cc') || ($trole eq 'in') ||
 2605:         ($trole eq 'ep') || ($trole eq 'ad') ||
 2606:         ($trole eq 'ta') || ($trole eq 'st') ||
 2607:         ($trole=~/^cr/) || ($trole eq 'gr')) {
 2608:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
 2609:             my $cdom = $1;
 2610:             my $cnum = $2;
 2611:             my $sec = $3;
 2612:             my $namespace = 'rolelog';
 2613:             my %storehash = (
 2614:                                role    => $trole,
 2615:                                start   => $tstart,
 2616:                                end     => $tend,
 2617:                                selfenroll => $selfenroll,
 2618:                                context    => $context,
 2619:                             );
 2620:             if ($trole eq 'gr') {
 2621:                 $namespace = 'groupslog';
 2622:                 $storehash{'group'} = $sec;
 2623:             } else {
 2624:                 $storehash{'section'} = $sec;
 2625:             }
 2626:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
 2627:         }
 2628:     }
 2629:     return;
 2630: }
 2631: 
 2632: sub get_course_adv_roles {
 2633:     my ($cid,$codes) = @_;
 2634:     $cid=$env{'request.course.id'} unless (defined($cid));
 2635:     my %coursehash=&coursedescription($cid);
 2636:     my %nothide=();
 2637:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2638:         if ($user !~ /:/) {
 2639: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
 2640:         } else {
 2641:             $nothide{$user}=1;
 2642:         }
 2643:     }
 2644:     my %returnhash=();
 2645:     my %dumphash=
 2646:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
 2647:     my $now=time;
 2648:     foreach my $entry (keys %dumphash) {
 2649: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2650:         if (($tstart) && ($tstart<0)) { next; }
 2651:         if (($tend) && ($tend<$now)) { next; }
 2652:         if (($tstart) && ($now<$tstart)) { next; }
 2653:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
 2654: 	if ($username eq '' || $domain eq '') { next; }
 2655: 	if ((&privileged($username,$domain)) && 
 2656: 	    (!$nothide{$username.':'.$domain})) { next; }
 2657: 	if ($role eq 'cr') { next; }
 2658:         if ($codes) {
 2659:             if ($section) { $role .= ':'.$section; }
 2660:             if ($returnhash{$role}) {
 2661:                 $returnhash{$role}.=','.$username.':'.$domain;
 2662:             } else {
 2663:                 $returnhash{$role}=$username.':'.$domain;
 2664:             }
 2665:         } else {
 2666:             my $key=&plaintext($role);
 2667:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
 2668:             if ($returnhash{$key}) {
 2669: 	        $returnhash{$key}.=','.$username.':'.$domain;
 2670:             } else {
 2671:                 $returnhash{$key}=$username.':'.$domain;
 2672:             }
 2673:         }
 2674:     }
 2675:     return %returnhash;
 2676: }
 2677: 
 2678: sub get_my_roles {
 2679:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
 2680:     unless (defined($uname)) { $uname=$env{'user.name'}; }
 2681:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
 2682:     my (%dumphash,%nothide);
 2683:     if ($context eq 'userroles') { 
 2684:         %dumphash = &dump('roles',$udom,$uname);
 2685:     } else {
 2686:         %dumphash=
 2687:             &dump('nohist_userroles',$udom,$uname);
 2688:         if ($hidepriv) {
 2689:             my %coursehash=&coursedescription($udom.'_'.$uname);
 2690:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
 2691:                 if ($user !~ /:/) {
 2692:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
 2693:                 } else {
 2694:                     $nothide{$user} = 1;
 2695:                 }
 2696:             }
 2697:         }
 2698:     }
 2699:     my %returnhash=();
 2700:     my $now=time;
 2701:     foreach my $entry (keys(%dumphash)) {
 2702:         my ($role,$tend,$tstart);
 2703:         if ($context eq 'userroles') {
 2704: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
 2705:         } else {
 2706:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
 2707:         }
 2708:         if (($tstart) && ($tstart<0)) { next; }
 2709:         my $status = 'active';
 2710:         if (($tend) && ($tend<=$now)) {
 2711:             $status = 'previous';
 2712:         } 
 2713:         if (($tstart) && ($now<$tstart)) {
 2714:             $status = 'future';
 2715:         }
 2716:         if (ref($types) eq 'ARRAY') {
 2717:             if (!grep(/^\Q$status\E$/,@{$types})) {
 2718:                 next;
 2719:             } 
 2720:         } else {
 2721:             if ($status ne 'active') {
 2722:                 next;
 2723:             }
 2724:         }
 2725:         my ($rolecode,$username,$domain,$section,$area);
 2726:         if ($context eq 'userroles') {
 2727:             ($area,$rolecode) = split(/_/,$entry);
 2728:             (undef,$domain,$username,$section) = split(/\//,$area);
 2729:         } else {
 2730:             ($role,$username,$domain,$section) = split(/\:/,$entry);
 2731:         }
 2732:         if (ref($roledoms) eq 'ARRAY') {
 2733:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
 2734:                 next;
 2735:             }
 2736:         }
 2737:         if (ref($roles) eq 'ARRAY') {
 2738:             if (!grep(/^\Q$role\E$/,@{$roles})) {
 2739:                 if ($role =~ /^cr\//) {
 2740:                     if (!grep(/^cr$/,@{$roles})) {
 2741:                         next;
 2742:                     }
 2743:                 } else {
 2744:                     next;
 2745:                 }
 2746:             }
 2747:         }
 2748:         if ($hidepriv) {
 2749:             if ((&privileged($username,$domain)) &&
 2750:                 (!$nothide{$username.':'.$domain})) { 
 2751:                 next;
 2752:             }
 2753:         }
 2754:         if ($withsec) {
 2755:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
 2756:                 $tstart.':'.$tend;
 2757:         } else {
 2758:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
 2759:         }
 2760:     }
 2761:     return %returnhash;
 2762: }
 2763: 
 2764: # ----------------------------------------------------- Frontpage Announcements
 2765: #
 2766: #
 2767: 
 2768: sub postannounce {
 2769:     my ($server,$text)=@_;
 2770:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
 2771:     unless ($text=~/\w/) { $text=''; }
 2772:     return &reply('setannounce:'.&escape($text),$server);
 2773: }
 2774: 
 2775: sub getannounce {
 2776: 
 2777:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
 2778: 	my $announcement='';
 2779: 	while (my $line = <$fh>) { $announcement .= $line; }
 2780: 	close($fh);
 2781: 	if ($announcement=~/\w/) { 
 2782: 	    return 
 2783:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
 2784:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
 2785: 	} else {
 2786: 	    return '';
 2787: 	}
 2788:     } else {
 2789: 	return '';
 2790:     }
 2791: }
 2792: 
 2793: # ---------------------------------------------------------- Course ID routines
 2794: # Deal with domain's nohist_courseid.db files
 2795: #
 2796: 
 2797: sub courseidput {
 2798:     my ($domain,$storehash,$coursehome,$caller) = @_;
 2799:     my $outcome;
 2800:     if ($caller eq 'timeonly') {
 2801:         my $cids = '';
 2802:         foreach my $item (keys(%$storehash)) {
 2803:             $cids.=&escape($item).'&';
 2804:         }
 2805:         $cids=~s/\&$//;
 2806:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
 2807:                           $coursehome);       
 2808:     } else {
 2809:         my $items = '';
 2810:         foreach my $item (keys(%$storehash)) {
 2811:             $items.= &escape($item).'='.
 2812:                      &freeze_escape($$storehash{$item}).'&';
 2813:         }
 2814:         $items=~s/\&$//;
 2815:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
 2816:                           $coursehome);
 2817:     }
 2818:     if ($outcome eq 'unknown_cmd') {
 2819:         my $what;
 2820:         foreach my $cid (keys(%$storehash)) {
 2821:             $what .= &escape($cid).'=';
 2822:             foreach my $item ('description','inst_code','owner','type') {
 2823:                 $what .= &escape($storehash->{$cid}{$item}).':';
 2824:             }
 2825:             $what =~ s/\:$/&/;
 2826:         }
 2827:         $what =~ s/\&$//;  
 2828:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
 2829:     } else {
 2830:         return $outcome;
 2831:     }
 2832: }
 2833: 
 2834: sub courseiddump {
 2835:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
 2836:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
 2837:         $selfenrollonly,$catfilter,$showhidden,$caller)=@_;
 2838:     my $as_hash = 1;
 2839:     my %returnhash;
 2840:     if (!$domfilter) { $domfilter=''; }
 2841:     my %libserv = &all_library();
 2842:     foreach my $tryserver (keys(%libserv)) {
 2843:         if ( (  $hostidflag == 1 
 2844: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
 2845: 	     || (!defined($hostidflag)) ) {
 2846: 
 2847: 	    if (($domfilter eq '') ||
 2848: 		(&host_domain($tryserver) eq $domfilter)) {
 2849:                 my $rep = 
 2850:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
 2851:                          $sincefilter.':'.&escape($descfilter).':'.
 2852:                          &escape($instcodefilter).':'.&escape($ownerfilter).
 2853:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
 2854:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
 2855:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
 2856:                          $showhidden.':'.$caller,$tryserver);
 2857:                 my @pairs=split(/\&/,$rep);
 2858:                 foreach my $item (@pairs) {
 2859:                     my ($key,$value)=split(/\=/,$item,2);
 2860:                     $key = &unescape($key);
 2861:                     next if ($key =~ /^error: 2 /);
 2862:                     my $result = &thaw_unescape($value);
 2863:                     if (ref($result) eq 'HASH') {
 2864:                         $returnhash{$key}=$result;
 2865:                     } else {
 2866:                         my @responses = split(/:/,$value);
 2867:                         my @items = ('description','inst_code','owner','type');
 2868:                         for (my $i=0; $i<@responses; $i++) {
 2869:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
 2870:                         }
 2871:                     } 
 2872:                 }
 2873:             }
 2874:         }
 2875:     }
 2876:     return %returnhash;
 2877: }
 2878: 
 2879: # ---------------------------------------------------------- DC e-mail
 2880: 
 2881: sub dcmailput {
 2882:     my ($domain,$msgid,$message,$server)=@_;
 2883:     my $status = &Apache::lonnet::critical(
 2884:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
 2885:        &escape($message),$server);
 2886:     return $status;
 2887: }
 2888: 
 2889: sub dcmaildump {
 2890:     my ($dom,$startdate,$enddate,$senders) = @_;
 2891:     my %returnhash=();
 2892: 
 2893:     if (defined(&domain($dom,'primary'))) {
 2894:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
 2895:                                                          &escape($enddate).':';
 2896: 	my @esc_senders=map { &escape($_)} @$senders;
 2897: 	$cmd.=&escape(join('&',@esc_senders));
 2898: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
 2899:             my ($key,$value) = split(/\=/,$line,2);
 2900:             if (($key) && ($value)) {
 2901:                 $returnhash{&unescape($key)} = &unescape($value);
 2902:             }
 2903:         }
 2904:     }
 2905:     return %returnhash;
 2906: }
 2907: # ---------------------------------------------------------- Domain roles
 2908: 
 2909: sub get_domain_roles {
 2910:     my ($dom,$roles,$startdate,$enddate)=@_;
 2911:     if (undef($startdate) || $startdate eq '') {
 2912:         $startdate = '.';
 2913:     }
 2914:     if (undef($enddate) || $enddate eq '') {
 2915:         $enddate = '.';
 2916:     }
 2917:     my $rolelist;
 2918:     if (ref($roles) eq 'ARRAY') {
 2919:         $rolelist = join(':',@{$roles});
 2920:     }
 2921:     my %personnel = ();
 2922: 
 2923:     my %servers = &get_servers($dom,'library');
 2924:     foreach my $tryserver (keys(%servers)) {
 2925: 	%{$personnel{$tryserver}}=();
 2926: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
 2927: 					    &escape($startdate).':'.
 2928: 					    &escape($enddate).':'.
 2929: 					    &escape($rolelist), $tryserver))) {
 2930: 	    my ($key,$value) = split(/\=/,$line,2);
 2931: 	    if (($key) && ($value)) {
 2932: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
 2933: 	    }
 2934: 	}
 2935:     }
 2936:     return %personnel;
 2937: }
 2938: 
 2939: # ----------------------------------------------------------- Check out an item
 2940: 
 2941: sub get_first_access {
 2942:     my ($type,$argsymb)=@_;
 2943:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2944:     if ($argsymb) { $symb=$argsymb; }
 2945:     my ($map,$id,$res)=&decode_symb($symb);
 2946:     if ($type eq 'course') {
 2947: 	$res='course';
 2948:     } elsif ($type eq 'map') {
 2949: 	$res=&symbread($map);
 2950:     } else {
 2951: 	$res=$symb;
 2952:     }
 2953:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
 2954:     return $times{"$courseid\0$res"};
 2955: }
 2956: 
 2957: sub set_first_access {
 2958:     my ($type)=@_;
 2959:     my ($symb,$courseid,$udom,$uname)=&whichuser();
 2960:     my ($map,$id,$res)=&decode_symb($symb);
 2961:     if ($type eq 'course') {
 2962: 	$res='course';
 2963:     } elsif ($type eq 'map') {
 2964: 	$res=&symbread($map);
 2965:     } else {
 2966: 	$res=$symb;
 2967:     }
 2968:     my $firstaccess=&get_first_access($type,$symb);
 2969:     if (!$firstaccess) {
 2970: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
 2971:     }
 2972:     return 'already_set';
 2973: }
 2974: 
 2975: sub checkout {
 2976:     my ($symb,$tuname,$tudom,$tcrsid)=@_;
 2977:     my $now=time;
 2978:     my $lonhost=$perlvar{'lonHostID'};
 2979:     my $infostr=&escape(
 2980:                  'CHECKOUTTOKEN&'.
 2981:                  $tuname.'&'.
 2982:                  $tudom.'&'.
 2983:                  $tcrsid.'&'.
 2984:                  $symb.'&'.
 2985: 		 $now.'&'.$ENV{'REMOTE_ADDR'});
 2986:     my $token=&reply('tmpput:'.$infostr,$lonhost);
 2987:     if ($token=~/^error\:/) { 
 2988:         &logthis("<font color=\"blue\">WARNING: ".
 2989:                 "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
 2990:                  "</font>");
 2991:         return ''; 
 2992:     }
 2993: 
 2994:     $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
 2995:     $token=~tr/a-z/A-Z/;
 2996: 
 2997:     my %infohash=('resource.0.outtoken' => $token,
 2998:                   'resource.0.checkouttime' => $now,
 2999:                   'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
 3000: 
 3001:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 3002:        return '';
 3003:     } else {
 3004:         &logthis("<font color=\"blue\">WARNING: ".
 3005:                 "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
 3006:                  "</font>");
 3007:     }    
 3008: 
 3009:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 3010:                          &escape('Checkout '.$infostr.' - '.
 3011:                                                  $token)) ne 'ok') {
 3012: 	return '';
 3013:     } else {
 3014:         &logthis("<font color=\"blue\">WARNING: ".
 3015:                 "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
 3016:                  "</font>");
 3017:     }
 3018:     return $token;
 3019: }
 3020: 
 3021: # ------------------------------------------------------------ Check in an item
 3022: 
 3023: sub checkin {
 3024:     my $token=shift;
 3025:     my $now=time;
 3026:     my ($ta,$tb,$lonhost)=split(/\*/,$token);
 3027:     $lonhost=~tr/A-Z/a-z/;
 3028:     my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
 3029:     $dtoken=~s/\W/\_/g;
 3030:     my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
 3031:                  split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
 3032: 
 3033:     unless (($tuname) && ($tudom)) {
 3034:         &logthis('Check in '.$token.' ('.$dtoken.') failed');
 3035:         return '';
 3036:     }
 3037:     
 3038:     unless (&allowed('mgr',$tcrsid)) {
 3039:         &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
 3040:                  $env{'user.name'}.' - '.$env{'user.domain'});
 3041:         return '';
 3042:     }
 3043: 
 3044:     my %infohash=('resource.0.intoken' => $token,
 3045:                   'resource.0.checkintime' => $now,
 3046:                   'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
 3047: 
 3048:     unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
 3049:        return '';
 3050:     }    
 3051: 
 3052:     if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
 3053:                          &escape('Checkin - '.$token)) ne 'ok') {
 3054: 	return '';
 3055:     }
 3056: 
 3057:     return ($symb,$tuname,$tudom,$tcrsid);    
 3058: }
 3059: 
 3060: # --------------------------------------------- Set Expire Date for Spreadsheet
 3061: 
 3062: sub expirespread {
 3063:     my ($uname,$udom,$stype,$usymb)=@_;
 3064:     my $cid=$env{'request.course.id'}; 
 3065:     if ($cid) {
 3066:        my $now=time;
 3067:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
 3068:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
 3069:                             $env{'course.'.$cid.'.num'}.
 3070: 	        	    ':nohist_expirationdates:'.
 3071:                             &escape($key).'='.$now,
 3072:                             $env{'course.'.$cid.'.home'})
 3073:     }
 3074:     return 'ok';
 3075: }
 3076: 
 3077: # ----------------------------------------------------- Devalidate Spreadsheets
 3078: 
 3079: sub devalidate {
 3080:     my ($symb,$uname,$udom)=@_;
 3081:     my $cid=$env{'request.course.id'}; 
 3082:     if ($cid) {
 3083:         # delete the stored spreadsheets for
 3084:         # - the student level sheet of this user in course's homespace
 3085:         # - the assessment level sheet for this resource 
 3086:         #   for this user in user's homespace
 3087: 	# - current conditional state info
 3088: 	my $key=$uname.':'.$udom.':';
 3089:         my $status=
 3090: 	    &del('nohist_calculatedsheets',
 3091: 		 [$key.'studentcalc:'],
 3092: 		 $env{'course.'.$cid.'.domain'},
 3093: 		 $env{'course.'.$cid.'.num'})
 3094: 		.' '.
 3095: 	    &del('nohist_calculatedsheets_'.$cid,
 3096: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
 3097:         unless ($status eq 'ok ok') {
 3098:            &logthis('Could not devalidate spreadsheet '.
 3099:                     $uname.' at '.$udom.' for '.
 3100: 		    $symb.': '.$status);
 3101:         }
 3102: 	&delenv('user.state.'.$cid);
 3103:     }
 3104: }
 3105: 
 3106: sub get_scalar {
 3107:     my ($string,$end) = @_;
 3108:     my $value;
 3109:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
 3110: 	$value = $1;
 3111:     } elsif ($$string =~ s/^([^&]*?)&//) {
 3112: 	$value = $1;
 3113:     }
 3114:     return &unescape($value);
 3115: }
 3116: 
 3117: sub array2str {
 3118:   my (@array) = @_;
 3119:   my $result=&arrayref2str(\@array);
 3120:   $result=~s/^__ARRAY_REF__//;
 3121:   $result=~s/__END_ARRAY_REF__$//;
 3122:   return $result;
 3123: }
 3124: 
 3125: sub arrayref2str {
 3126:   my ($arrayref) = @_;
 3127:   my $result='__ARRAY_REF__';
 3128:   foreach my $elem (@$arrayref) {
 3129:     if(ref($elem) eq 'ARRAY') {
 3130:       $result.=&arrayref2str($elem).'&';
 3131:     } elsif(ref($elem) eq 'HASH') {
 3132:       $result.=&hashref2str($elem).'&';
 3133:     } elsif(ref($elem)) {
 3134:       #print("Got a ref of ".(ref($elem))." skipping.");
 3135:     } else {
 3136:       $result.=&escape($elem).'&';
 3137:     }
 3138:   }
 3139:   $result=~s/\&$//;
 3140:   $result .= '__END_ARRAY_REF__';
 3141:   return $result;
 3142: }
 3143: 
 3144: sub hash2str {
 3145:   my (%hash) = @_;
 3146:   my $result=&hashref2str(\%hash);
 3147:   $result=~s/^__HASH_REF__//;
 3148:   $result=~s/__END_HASH_REF__$//;
 3149:   return $result;
 3150: }
 3151: 
 3152: sub hashref2str {
 3153:   my ($hashref)=@_;
 3154:   my $result='__HASH_REF__';
 3155:   foreach my $key (sort(keys(%$hashref))) {
 3156:     if (ref($key) eq 'ARRAY') {
 3157:       $result.=&arrayref2str($key).'=';
 3158:     } elsif (ref($key) eq 'HASH') {
 3159:       $result.=&hashref2str($key).'=';
 3160:     } elsif (ref($key)) {
 3161:       $result.='=';
 3162:       #print("Got a ref of ".(ref($key))." skipping.");
 3163:     } else {
 3164: 	if ($key) {$result.=&escape($key).'=';} else { last; }
 3165:     }
 3166: 
 3167:     if(ref($hashref->{$key}) eq 'ARRAY') {
 3168:       $result.=&arrayref2str($hashref->{$key}).'&';
 3169:     } elsif(ref($hashref->{$key}) eq 'HASH') {
 3170:       $result.=&hashref2str($hashref->{$key}).'&';
 3171:     } elsif(ref($hashref->{$key})) {
 3172:        $result.='&';
 3173:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
 3174:     } else {
 3175:       $result.=&escape($hashref->{$key}).'&';
 3176:     }
 3177:   }
 3178:   $result=~s/\&$//;
 3179:   $result .= '__END_HASH_REF__';
 3180:   return $result;
 3181: }
 3182: 
 3183: sub str2hash {
 3184:     my ($string)=@_;
 3185:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
 3186:     return %$hash;
 3187: }
 3188: 
 3189: sub str2hashref {
 3190:   my ($string) = @_;
 3191: 
 3192:   my %hash;
 3193: 
 3194:   if($string !~ /^__HASH_REF__/) {
 3195:       if (! ($string eq '' || !defined($string))) {
 3196: 	  $hash{'error'}='Not hash reference';
 3197:       }
 3198:       return (\%hash, $string);
 3199:   }
 3200: 
 3201:   $string =~ s/^__HASH_REF__//;
 3202: 
 3203:   while($string !~ /^__END_HASH_REF__/) {
 3204:       #key
 3205:       my $key='';
 3206:       if($string =~ /^__HASH_REF__/) {
 3207:           ($key, $string)=&str2hashref($string);
 3208:           if(defined($key->{'error'})) {
 3209:               $hash{'error'}='Bad data';
 3210:               return (\%hash, $string);
 3211:           }
 3212:       } elsif($string =~ /^__ARRAY_REF__/) {
 3213:           ($key, $string)=&str2arrayref($string);
 3214:           if($key->[0] eq 'Array reference error') {
 3215:               $hash{'error'}='Bad data';
 3216:               return (\%hash, $string);
 3217:           }
 3218:       } else {
 3219:           $string =~ s/^(.*?)=//;
 3220: 	  $key=&unescape($1);
 3221:       }
 3222:       $string =~ s/^=//;
 3223: 
 3224:       #value
 3225:       my $value='';
 3226:       if($string =~ /^__HASH_REF__/) {
 3227:           ($value, $string)=&str2hashref($string);
 3228:           if(defined($value->{'error'})) {
 3229:               $hash{'error'}='Bad data';
 3230:               return (\%hash, $string);
 3231:           }
 3232:       } elsif($string =~ /^__ARRAY_REF__/) {
 3233:           ($value, $string)=&str2arrayref($string);
 3234:           if($value->[0] eq 'Array reference error') {
 3235:               $hash{'error'}='Bad data';
 3236:               return (\%hash, $string);
 3237:           }
 3238:       } else {
 3239: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
 3240:       }
 3241:       $string =~ s/^&//;
 3242: 
 3243:       $hash{$key}=$value;
 3244:   }
 3245: 
 3246:   $string =~ s/^__END_HASH_REF__//;
 3247: 
 3248:   return (\%hash, $string);
 3249: }
 3250: 
 3251: sub str2array {
 3252:     my ($string)=@_;
 3253:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
 3254:     return @$array;
 3255: }
 3256: 
 3257: sub str2arrayref {
 3258:   my ($string) = @_;
 3259:   my @array;
 3260: 
 3261:   if($string !~ /^__ARRAY_REF__/) {
 3262:       if (! ($string eq '' || !defined($string))) {
 3263: 	  $array[0]='Array reference error';
 3264:       }
 3265:       return (\@array, $string);
 3266:   }
 3267: 
 3268:   $string =~ s/^__ARRAY_REF__//;
 3269: 
 3270:   while($string !~ /^__END_ARRAY_REF__/) {
 3271:       my $value='';
 3272:       if($string =~ /^__HASH_REF__/) {
 3273:           ($value, $string)=&str2hashref($string);
 3274:           if(defined($value->{'error'})) {
 3275:               $array[0] ='Array reference error';
 3276:               return (\@array, $string);
 3277:           }
 3278:       } elsif($string =~ /^__ARRAY_REF__/) {
 3279:           ($value, $string)=&str2arrayref($string);
 3280:           if($value->[0] eq 'Array reference error') {
 3281:               $array[0] ='Array reference error';
 3282:               return (\@array, $string);
 3283:           }
 3284:       } else {
 3285: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
 3286:       }
 3287:       $string =~ s/^&//;
 3288: 
 3289:       push(@array, $value);
 3290:   }
 3291: 
 3292:   $string =~ s/^__END_ARRAY_REF__//;
 3293: 
 3294:   return (\@array, $string);
 3295: }
 3296: 
 3297: # -------------------------------------------------------------------Temp Store
 3298: 
 3299: sub tmpreset {
 3300:   my ($symb,$namespace,$domain,$stuname) = @_;
 3301:   if (!$symb) {
 3302:     $symb=&symbread();
 3303:     if (!$symb) { $symb= $env{'request.url'}; }
 3304:   }
 3305:   $symb=escape($symb);
 3306: 
 3307:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3308:   $namespace=~s/\//\_/g;
 3309:   $namespace=~s/\W//g;
 3310: 
 3311:   if (!$domain) { $domain=$env{'user.domain'}; }
 3312:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3313:   if ($domain eq 'public' && $stuname eq 'public') {
 3314:       $stuname=$ENV{'REMOTE_ADDR'};
 3315:   }
 3316:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3317:   my %hash;
 3318:   if (tie(%hash,'GDBM_File',
 3319: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3320: 	  &GDBM_WRCREAT(),0640)) {
 3321:     foreach my $key (keys %hash) {
 3322:       if ($key=~ /:$symb/) {
 3323: 	delete($hash{$key});
 3324:       }
 3325:     }
 3326:   }
 3327: }
 3328: 
 3329: sub tmpstore {
 3330:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3331: 
 3332:   if (!$symb) {
 3333:     $symb=&symbread();
 3334:     if (!$symb) { $symb= $env{'request.url'}; }
 3335:   }
 3336:   $symb=escape($symb);
 3337: 
 3338:   if (!$namespace) {
 3339:     # I don't think we would ever want to store this for a course.
 3340:     # it seems this will only be used if we don't have a course.
 3341:     #$namespace=$env{'request.course.id'};
 3342:     #if (!$namespace) {
 3343:       $namespace=$env{'request.state'};
 3344:     #}
 3345:   }
 3346:   $namespace=~s/\//\_/g;
 3347:   $namespace=~s/\W//g;
 3348:   if (!$domain) { $domain=$env{'user.domain'}; }
 3349:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3350:   if ($domain eq 'public' && $stuname eq 'public') {
 3351:       $stuname=$ENV{'REMOTE_ADDR'};
 3352:   }
 3353:   my $now=time;
 3354:   my %hash;
 3355:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3356:   if (tie(%hash,'GDBM_File',
 3357: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3358: 	  &GDBM_WRCREAT(),0640)) {
 3359:     $hash{"version:$symb"}++;
 3360:     my $version=$hash{"version:$symb"};
 3361:     my $allkeys=''; 
 3362:     foreach my $key (keys(%$storehash)) {
 3363:       $allkeys.=$key.':';
 3364:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
 3365:     }
 3366:     $hash{"$version:$symb:timestamp"}=$now;
 3367:     $allkeys.='timestamp';
 3368:     $hash{"$version:keys:$symb"}=$allkeys;
 3369:     if (untie(%hash)) {
 3370:       return 'ok';
 3371:     } else {
 3372:       return "error:$!";
 3373:     }
 3374:   } else {
 3375:     return "error:$!";
 3376:   }
 3377: }
 3378: 
 3379: # -----------------------------------------------------------------Temp Restore
 3380: 
 3381: sub tmprestore {
 3382:   my ($symb,$namespace,$domain,$stuname) = @_;
 3383: 
 3384:   if (!$symb) {
 3385:     $symb=&symbread();
 3386:     if (!$symb) { $symb= $env{'request.url'}; }
 3387:   }
 3388:   $symb=escape($symb);
 3389: 
 3390:   if (!$namespace) { $namespace=$env{'request.state'}; }
 3391: 
 3392:   if (!$domain) { $domain=$env{'user.domain'}; }
 3393:   if (!$stuname) { $stuname=$env{'user.name'}; }
 3394:   if ($domain eq 'public' && $stuname eq 'public') {
 3395:       $stuname=$ENV{'REMOTE_ADDR'};
 3396:   }
 3397:   my %returnhash;
 3398:   $namespace=~s/\//\_/g;
 3399:   $namespace=~s/\W//g;
 3400:   my %hash;
 3401:   my $path=$perlvar{'lonDaemons'}.'/tmp';
 3402:   if (tie(%hash,'GDBM_File',
 3403: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
 3404: 	  &GDBM_READER(),0640)) {
 3405:     my $version=$hash{"version:$symb"};
 3406:     $returnhash{'version'}=$version;
 3407:     my $scope;
 3408:     for ($scope=1;$scope<=$version;$scope++) {
 3409:       my $vkeys=$hash{"$scope:keys:$symb"};
 3410:       my @keys=split(/:/,$vkeys);
 3411:       my $key;
 3412:       $returnhash{"$scope:keys"}=$vkeys;
 3413:       foreach $key (@keys) {
 3414: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3415: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
 3416:       }
 3417:     }
 3418:     if (!(untie(%hash))) {
 3419:       return "error:$!";
 3420:     }
 3421:   } else {
 3422:     return "error:$!";
 3423:   }
 3424:   return %returnhash;
 3425: }
 3426: 
 3427: # ----------------------------------------------------------------------- Store
 3428: 
 3429: sub store {
 3430:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3431:     my $home='';
 3432: 
 3433:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3434: 
 3435:     $symb=&symbclean($symb);
 3436:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3437: 
 3438:     if (!$domain) { $domain=$env{'user.domain'}; }
 3439:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3440: 
 3441:     &devalidate($symb,$stuname,$domain);
 3442: 
 3443:     $symb=escape($symb);
 3444:     if (!$namespace) { 
 3445:        unless ($namespace=$env{'request.course.id'}) { 
 3446:           return ''; 
 3447:        } 
 3448:     }
 3449:     if (!$home) { $home=$env{'user.home'}; }
 3450: 
 3451:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3452:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3453: 
 3454:     my $namevalue='';
 3455:     foreach my $key (keys(%$storehash)) {
 3456:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3457:     }
 3458:     $namevalue=~s/\&$//;
 3459:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
 3460:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3461: }
 3462: 
 3463: # -------------------------------------------------------------- Critical Store
 3464: 
 3465: sub cstore {
 3466:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
 3467:     my $home='';
 3468: 
 3469:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3470: 
 3471:     $symb=&symbclean($symb);
 3472:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
 3473: 
 3474:     if (!$domain) { $domain=$env{'user.domain'}; }
 3475:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3476: 
 3477:     &devalidate($symb,$stuname,$domain);
 3478: 
 3479:     $symb=escape($symb);
 3480:     if (!$namespace) { 
 3481:        unless ($namespace=$env{'request.course.id'}) { 
 3482:           return ''; 
 3483:        } 
 3484:     }
 3485:     if (!$home) { $home=$env{'user.home'}; }
 3486: 
 3487:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
 3488:     $$storehash{'host'}=$perlvar{'lonHostID'};
 3489: 
 3490:     my $namevalue='';
 3491:     foreach my $key (keys(%$storehash)) {
 3492:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 3493:     }
 3494:     $namevalue=~s/\&$//;
 3495:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
 3496:     return critical
 3497:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
 3498: }
 3499: 
 3500: # --------------------------------------------------------------------- Restore
 3501: 
 3502: sub restore {
 3503:     my ($symb,$namespace,$domain,$stuname) = @_;
 3504:     my $home='';
 3505: 
 3506:     if ($stuname) { $home=&homeserver($stuname,$domain); }
 3507: 
 3508:     if (!$symb) {
 3509:       unless ($symb=escape(&symbread())) { return ''; }
 3510:     } else {
 3511:       $symb=&escape(&symbclean($symb));
 3512:     }
 3513:     if (!$namespace) { 
 3514:        unless ($namespace=$env{'request.course.id'}) { 
 3515:           return ''; 
 3516:        } 
 3517:     }
 3518:     if (!$domain) { $domain=$env{'user.domain'}; }
 3519:     if (!$stuname) { $stuname=$env{'user.name'}; }
 3520:     if (!$home) { $home=$env{'user.home'}; }
 3521:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
 3522: 
 3523:     my %returnhash=();
 3524:     foreach my $line (split(/\&/,$answer)) {
 3525: 	my ($name,$value)=split(/\=/,$line);
 3526:         $returnhash{&unescape($name)}=&thaw_unescape($value);
 3527:     }
 3528:     my $version;
 3529:     for ($version=1;$version<=$returnhash{'version'};$version++) {
 3530:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
 3531:           $returnhash{$item}=$returnhash{$version.':'.$item};
 3532:        }
 3533:     }
 3534:     return %returnhash;
 3535: }
 3536: 
 3537: # ---------------------------------------------------------- Course Description
 3538: 
 3539: sub coursedescription {
 3540:     my ($courseid,$args)=@_;
 3541:     $courseid=~s/^\///;
 3542:     $courseid=~s/\_/\//g;
 3543:     my ($cdomain,$cnum)=split(/\//,$courseid);
 3544:     my $chome=&homeserver($cnum,$cdomain);
 3545:     my $normalid=$cdomain.'_'.$cnum;
 3546:     # need to always cache even if we get errors otherwise we keep 
 3547:     # trying and trying and trying to get the course description.
 3548:     my %envhash=();
 3549:     my %returnhash=();
 3550:     
 3551:     my $expiretime=600;
 3552:     if ($env{'request.course.id'} eq $normalid) {
 3553: 	$expiretime=120;
 3554:     }
 3555: 
 3556:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
 3557:     if (!$args->{'freshen_cache'}
 3558: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
 3559: 	foreach my $key (keys(%env)) {
 3560: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
 3561: 	    my ($setting) = $1;
 3562: 	    $returnhash{$setting} = $env{$key};
 3563: 	}
 3564: 	return %returnhash;
 3565:     }
 3566: 
 3567:     # get the data agin
 3568:     if (!$args->{'one_time'}) {
 3569: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
 3570:     }
 3571: 
 3572:     if ($chome ne 'no_host') {
 3573:        %returnhash=&dump('environment',$cdomain,$cnum);
 3574:        if (!exists($returnhash{'con_lost'})) {
 3575:            $returnhash{'home'}= $chome;
 3576: 	   $returnhash{'domain'} = $cdomain;
 3577: 	   $returnhash{'num'} = $cnum;
 3578:            if (!defined($returnhash{'type'})) {
 3579:                $returnhash{'type'} = 'Course';
 3580:            }
 3581:            while (my ($name,$value) = each %returnhash) {
 3582:                $envhash{'course.'.$normalid.'.'.$name}=$value;
 3583:            }
 3584:            $returnhash{'url'}=&clutter($returnhash{'url'});
 3585:            $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
 3586: 	       $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
 3587:            $envhash{'course.'.$normalid.'.home'}=$chome;
 3588:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
 3589:            $envhash{'course.'.$normalid.'.num'}=$cnum;
 3590:        }
 3591:     }
 3592:     if (!$args->{'one_time'}) {
 3593: 	&appenv(\%envhash);
 3594:     }
 3595:     return %returnhash;
 3596: }
 3597: 
 3598: # -------------------------------------------------See if a user is privileged
 3599: 
 3600: sub privileged {
 3601:     my ($username,$domain)=@_;
 3602:     my $rolesdump=&reply("dump:$domain:$username:roles",
 3603: 			&homeserver($username,$domain));
 3604:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
 3605:     my $now=time;
 3606:     if ($rolesdump ne '') {
 3607:         foreach my $entry (split(/&/,$rolesdump)) {
 3608: 	    if ($entry!~/^rolesdef_/) {
 3609: 		my ($area,$role)=split(/=/,$entry);
 3610: 		$area=~s/\_\w\w$//;
 3611: 		my ($trole,$tend,$tstart)=split(/_/,$role);
 3612: 		if (($trole eq 'dc') || ($trole eq 'su')) {
 3613: 		    my $active=1;
 3614: 		    if ($tend) {
 3615: 			if ($tend<$now) { $active=0; }
 3616: 		    }
 3617: 		    if ($tstart) {
 3618: 			if ($tstart>$now) { $active=0; }
 3619: 		    }
 3620: 		    if ($active) { return 1; }
 3621: 		}
 3622: 	    }
 3623: 	}
 3624:     }
 3625:     return 0;
 3626: }
 3627: 
 3628: # -------------------------------------------------------- Get user privileges
 3629: 
 3630: sub rolesinit {
 3631:     my ($domain,$username,$authhost)=@_;
 3632:     my %userroles;
 3633:     my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
 3634:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return \%userroles; }
 3635:     my %allroles=();
 3636:     my %allgroups=();   
 3637:     my $now=time;
 3638:     %userroles = ('user.login.time' => $now);
 3639:     my $group_privs;
 3640: 
 3641:     if ($rolesdump ne '') {
 3642:         foreach my $entry (split(/&/,$rolesdump)) {
 3643: 	  if ($entry!~/^rolesdef_/) {
 3644:             my ($area,$role)=split(/=/,$entry);
 3645: 	    $area=~s/\_\w\w$//;
 3646:             my ($trole,$tend,$tstart,$group_privs);
 3647: 	    if ($role=~/^cr/) { 
 3648: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
 3649: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
 3650: 		    ($tend,$tstart)=split('_',$trest);
 3651: 		} else {
 3652: 		    $trole=$role;
 3653: 		}
 3654:             } elsif ($role =~ m|^gr/|) {
 3655:                 ($trole,$tend,$tstart) = split(/_/,$role);
 3656:                 ($trole,$group_privs) = split(/\//,$trole);
 3657:                 $group_privs = &unescape($group_privs);
 3658: 	    } else {
 3659: 		($trole,$tend,$tstart)=split(/_/,$role);
 3660: 	    }
 3661: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
 3662: 					 $username);
 3663: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
 3664:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
 3665:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
 3666:             if (($area ne '') && ($trole ne '')) {
 3667: 		my $spec=$trole.'.'.$area;
 3668: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
 3669: 		if ($trole =~ /^cr\//) {
 3670:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 3671:                 } elsif ($trole eq 'gr') {
 3672:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
 3673: 		} else {
 3674:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 3675: 		}
 3676:             }
 3677:           }
 3678:         }
 3679:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
 3680:         $userroles{'user.adv'}    = $adv;
 3681: 	$userroles{'user.author'} = $author;
 3682:         $env{'user.adv'}=$adv;
 3683:     }
 3684:     return \%userroles;  
 3685: }
 3686: 
 3687: sub set_arearole {
 3688:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
 3689: # log the associated role with the area
 3690:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
 3691:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
 3692: }
 3693: 
 3694: sub custom_roleprivs {
 3695:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
 3696:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
 3697:     my $homsvr=homeserver($rauthor,$rdomain);
 3698:     if (&hostname($homsvr) ne '') {
 3699:         my ($rdummy,$roledef)=
 3700:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
 3701:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
 3702:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
 3703:             if (defined($syspriv)) {
 3704:                 $$allroles{'cm./'}.=':'.$syspriv;
 3705:                 $$allroles{$spec.'./'}.=':'.$syspriv;
 3706:             }
 3707:             if ($tdomain ne '') {
 3708:                 if (defined($dompriv)) {
 3709:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
 3710:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
 3711:                 }
 3712:                 if (($trest ne '') && (defined($coursepriv))) {
 3713:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
 3714:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
 3715:                 }
 3716:             }
 3717:         }
 3718:     }
 3719: }
 3720: 
 3721: sub group_roleprivs {
 3722:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
 3723:     my $access = 1;
 3724:     my $now = time;
 3725:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
 3726:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
 3727:     if ($access) {
 3728:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
 3729:         $$allgroups{$course}{$group} .=':'.$group_privs;
 3730:     }
 3731: }
 3732: 
 3733: sub standard_roleprivs {
 3734:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
 3735:     if (defined($pr{$trole.':s'})) {
 3736:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
 3737:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
 3738:     }
 3739:     if ($tdomain ne '') {
 3740:         if (defined($pr{$trole.':d'})) {
 3741:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3742:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
 3743:         }
 3744:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
 3745:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
 3746:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
 3747:         }
 3748:     }
 3749: }
 3750: 
 3751: sub set_userprivs {
 3752:     my ($userroles,$allroles,$allgroups) = @_; 
 3753:     my $author=0;
 3754:     my $adv=0;
 3755:     my %grouproles = ();
 3756:     if (keys(%{$allgroups}) > 0) {
 3757:         foreach my $role (keys %{$allroles}) {
 3758:             my ($trole,$area,$sec,$extendedarea);
 3759:             if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
 3760:                 $trole = $1;
 3761:                 $area = $2;
 3762:                 $sec = $3;
 3763:                 $extendedarea = $area.$sec;
 3764:                 if (exists($$allgroups{$area})) {
 3765:                     foreach my $group (keys(%{$$allgroups{$area}})) {
 3766:                         my $spec = $trole.'.'.$extendedarea;
 3767:                         $grouproles{$spec.'.'.$area.'/'.$group} = 
 3768:                                                 $$allgroups{$area}{$group};
 3769:                     }
 3770:                 }
 3771:             }
 3772:         }
 3773:     }
 3774:     foreach my $group (keys(%grouproles)) {
 3775:         $$allroles{$group} = $grouproles{$group};
 3776:     }
 3777:     foreach my $role (keys(%{$allroles})) {
 3778:         my %thesepriv;
 3779:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
 3780:         foreach my $item (split(/:/,$$allroles{$role})) {
 3781:             if ($item ne '') {
 3782:                 my ($privilege,$restrictions)=split(/&/,$item);
 3783:                 if ($restrictions eq '') {
 3784:                     $thesepriv{$privilege}='F';
 3785:                 } elsif ($thesepriv{$privilege} ne 'F') {
 3786:                     $thesepriv{$privilege}.=$restrictions;
 3787:                 }
 3788:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
 3789:             }
 3790:         }
 3791:         my $thesestr='';
 3792:         foreach my $priv (keys(%thesepriv)) {
 3793: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
 3794: 	}
 3795:         $userroles->{'user.priv.'.$role} = $thesestr;
 3796:     }
 3797:     return ($author,$adv);
 3798: }
 3799: 
 3800: # --------------------------------------------------------------- get interface
 3801: 
 3802: sub get {
 3803:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3804:    my $items='';
 3805:    foreach my $item (@$storearr) {
 3806:        $items.=&escape($item).'&';
 3807:    }
 3808:    $items=~s/\&$//;
 3809:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3810:    if (!$uname) { $uname=$env{'user.name'}; }
 3811:    my $uhome=&homeserver($uname,$udomain);
 3812: 
 3813:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
 3814:    my @pairs=split(/\&/,$rep);
 3815:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
 3816:      return @pairs;
 3817:    }
 3818:    my %returnhash=();
 3819:    my $i=0;
 3820:    foreach my $item (@$storearr) {
 3821:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 3822:       $i++;
 3823:    }
 3824:    return %returnhash;
 3825: }
 3826: 
 3827: # --------------------------------------------------------------- del interface
 3828: 
 3829: sub del {
 3830:    my ($namespace,$storearr,$udomain,$uname)=@_;
 3831:    my $items='';
 3832:    foreach my $item (@$storearr) {
 3833:        $items.=&escape($item).'&';
 3834:    }
 3835:    $items=~s/\&$//;
 3836:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3837:    if (!$uname) { $uname=$env{'user.name'}; }
 3838:    my $uhome=&homeserver($uname,$udomain);
 3839: 
 3840:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
 3841: }
 3842: 
 3843: # -------------------------------------------------------------- dump interface
 3844: 
 3845: sub dump {
 3846:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3847:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3848:     if (!$uname) { $uname=$env{'user.name'}; }
 3849:     my $uhome=&homeserver($uname,$udomain);
 3850:     if ($regexp) {
 3851: 	$regexp=&escape($regexp);
 3852:     } else {
 3853: 	$regexp='.';
 3854:     }
 3855:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3856:     my @pairs=split(/\&/,$rep);
 3857:     my %returnhash=();
 3858:     foreach my $item (@pairs) {
 3859: 	my ($key,$value)=split(/=/,$item,2);
 3860: 	$key = &unescape($key);
 3861: 	next if ($key =~ /^error: 2 /);
 3862: 	$returnhash{$key}=&thaw_unescape($value);
 3863:     }
 3864:     return %returnhash;
 3865: }
 3866: 
 3867: # --------------------------------------------------------- dumpstore interface
 3868: 
 3869: sub dumpstore {
 3870:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
 3871:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3872:    if (!$uname) { $uname=$env{'user.name'}; }
 3873:    my $uhome=&homeserver($uname,$udomain);
 3874:    if ($regexp) {
 3875:        $regexp=&escape($regexp);
 3876:    } else {
 3877:        $regexp='.';
 3878:    }
 3879:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
 3880:    my @pairs=split(/\&/,$rep);
 3881:    my %returnhash=();
 3882:    foreach my $item (@pairs) {
 3883:        my ($key,$value)=split(/=/,$item,2);
 3884:        next if ($key =~ /^error: 2 /);
 3885:        $returnhash{$key}=&thaw_unescape($value);
 3886:    }
 3887:    return %returnhash;
 3888: }
 3889: 
 3890: # -------------------------------------------------------------- keys interface
 3891: 
 3892: sub getkeys {
 3893:    my ($namespace,$udomain,$uname)=@_;
 3894:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 3895:    if (!$uname) { $uname=$env{'user.name'}; }
 3896:    my $uhome=&homeserver($uname,$udomain);
 3897:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
 3898:    my @keyarray=();
 3899:    foreach my $key (split(/\&/,$rep)) {
 3900:       next if ($key =~ /^error: 2 /);
 3901:       push(@keyarray,&unescape($key));
 3902:    }
 3903:    return @keyarray;
 3904: }
 3905: 
 3906: # --------------------------------------------------------------- currentdump
 3907: sub currentdump {
 3908:    my ($courseid,$sdom,$sname)=@_;
 3909:    $courseid = $env{'request.course.id'} if (! defined($courseid));
 3910:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
 3911:    $sname    = $env{'user.name'}         if (! defined($sname));
 3912:    my $uhome = &homeserver($sname,$sdom);
 3913:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
 3914:    return if ($rep =~ /^(error:|no_such_host)/);
 3915:    #
 3916:    my %returnhash=();
 3917:    #
 3918:    if ($rep eq "unknown_cmd") { 
 3919:        # an old lond will not know currentdump
 3920:        # Do a dump and make it look like a currentdump
 3921:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
 3922:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
 3923:        my %hash = @tmp;
 3924:        @tmp=();
 3925:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
 3926:    } else {
 3927:        my @pairs=split(/\&/,$rep);
 3928:        foreach my $pair (@pairs) {
 3929:            my ($key,$value)=split(/=/,$pair,2);
 3930:            my ($symb,$param) = split(/:/,$key);
 3931:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
 3932:                                                         &thaw_unescape($value);
 3933:        }
 3934:    }
 3935:    return %returnhash;
 3936: }
 3937: 
 3938: sub convert_dump_to_currentdump{
 3939:     my %hash = %{shift()};
 3940:     my %returnhash;
 3941:     # Code ripped from lond, essentially.  The only difference
 3942:     # here is the unescaping done by lonnet::dump().  Conceivably
 3943:     # we might run in to problems with parameter names =~ /^v\./
 3944:     while (my ($key,$value) = each(%hash)) {
 3945:         my ($v,$symb,$param) = split(/:/,$key);
 3946: 	$symb  = &unescape($symb);
 3947: 	$param = &unescape($param);
 3948:         next if ($v eq 'version' || $symb eq 'keys');
 3949:         next if (exists($returnhash{$symb}) &&
 3950:                  exists($returnhash{$symb}->{$param}) &&
 3951:                  $returnhash{$symb}->{'v.'.$param} > $v);
 3952:         $returnhash{$symb}->{$param}=$value;
 3953:         $returnhash{$symb}->{'v.'.$param}=$v;
 3954:     }
 3955:     #
 3956:     # Remove all of the keys in the hashes which keep track of
 3957:     # the version of the parameter.
 3958:     while (my ($symb,$param_hash) = each(%returnhash)) {
 3959:         # use a foreach because we are going to delete from the hash.
 3960:         foreach my $key (keys(%$param_hash)) {
 3961:             delete($param_hash->{$key}) if ($key =~ /^v\./);
 3962:         }
 3963:     }
 3964:     return \%returnhash;
 3965: }
 3966: 
 3967: # ------------------------------------------------------ critical inc interface
 3968: 
 3969: sub cinc {
 3970:     return &inc(@_,'critical');
 3971: }
 3972: 
 3973: # --------------------------------------------------------------- inc interface
 3974: 
 3975: sub inc {
 3976:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
 3977:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 3978:     if (!$uname) { $uname=$env{'user.name'}; }
 3979:     my $uhome=&homeserver($uname,$udomain);
 3980:     my $items='';
 3981:     if (! ref($store)) {
 3982:         # got a single value, so use that instead
 3983:         $items = &escape($store).'=&';
 3984:     } elsif (ref($store) eq 'SCALAR') {
 3985:         $items = &escape($$store).'=&';        
 3986:     } elsif (ref($store) eq 'ARRAY') {
 3987:         $items = join('=&',map {&escape($_);} @{$store});
 3988:     } elsif (ref($store) eq 'HASH') {
 3989:         while (my($key,$value) = each(%{$store})) {
 3990:             $items.= &escape($key).'='.&escape($value).'&';
 3991:         }
 3992:     }
 3993:     $items=~s/\&$//;
 3994:     if ($critical) {
 3995: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
 3996:     } else {
 3997: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
 3998:     }
 3999: }
 4000: 
 4001: # --------------------------------------------------------------- put interface
 4002: 
 4003: sub put {
 4004:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4005:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4006:    if (!$uname) { $uname=$env{'user.name'}; }
 4007:    my $uhome=&homeserver($uname,$udomain);
 4008:    my $items='';
 4009:    foreach my $item (keys(%$storehash)) {
 4010:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4011:    }
 4012:    $items=~s/\&$//;
 4013:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 4014: }
 4015: 
 4016: # ------------------------------------------------------------ newput interface
 4017: 
 4018: sub newput {
 4019:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4020:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4021:    if (!$uname) { $uname=$env{'user.name'}; }
 4022:    my $uhome=&homeserver($uname,$udomain);
 4023:    my $items='';
 4024:    foreach my $key (keys(%$storehash)) {
 4025:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
 4026:    }
 4027:    $items=~s/\&$//;
 4028:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
 4029: }
 4030: 
 4031: # ---------------------------------------------------------  putstore interface
 4032: 
 4033: sub putstore {
 4034:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 4035:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4036:    if (!$uname) { $uname=$env{'user.name'}; }
 4037:    my $uhome=&homeserver($uname,$udomain);
 4038:    my $items='';
 4039:    foreach my $key (keys(%$storehash)) {
 4040:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
 4041:    }
 4042:    $items=~s/\&$//;
 4043:    my $esc_symb=&escape($symb);
 4044:    my $esc_v=&escape($version);
 4045:    my $reply =
 4046:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
 4047: 	      $uhome);
 4048:    if ($reply eq 'unknown_cmd') {
 4049:        # gfall back to way things use to be done
 4050:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
 4051: 			    $uname);
 4052:    }
 4053:    return $reply;
 4054: }
 4055: 
 4056: sub old_putstore {
 4057:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
 4058:     if (!$udomain) { $udomain=$env{'user.domain'}; }
 4059:     if (!$uname) { $uname=$env{'user.name'}; }
 4060:     my $uhome=&homeserver($uname,$udomain);
 4061:     my %newstorehash;
 4062:     foreach my $item (keys(%$storehash)) {
 4063: 	my $key = $version.':'.&escape($symb).':'.$item;
 4064: 	$newstorehash{$key} = $storehash->{$item};
 4065:     }
 4066:     my $items='';
 4067:     my %allitems = ();
 4068:     foreach my $item (keys(%newstorehash)) {
 4069: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
 4070: 	    my $key = $1.':keys:'.$2;
 4071: 	    $allitems{$key} .= $3.':';
 4072: 	}
 4073: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
 4074:     }
 4075:     foreach my $item (keys(%allitems)) {
 4076: 	$allitems{$item} =~ s/\:$//;
 4077: 	$items.= $item.'='.$allitems{$item}.'&';
 4078:     }
 4079:     $items=~s/\&$//;
 4080:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
 4081: }
 4082: 
 4083: # ------------------------------------------------------ critical put interface
 4084: 
 4085: sub cput {
 4086:    my ($namespace,$storehash,$udomain,$uname)=@_;
 4087:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4088:    if (!$uname) { $uname=$env{'user.name'}; }
 4089:    my $uhome=&homeserver($uname,$udomain);
 4090:    my $items='';
 4091:    foreach my $item (keys(%$storehash)) {
 4092:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4093:    }
 4094:    $items=~s/\&$//;
 4095:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
 4096: }
 4097: 
 4098: # -------------------------------------------------------------- eget interface
 4099: 
 4100: sub eget {
 4101:    my ($namespace,$storearr,$udomain,$uname)=@_;
 4102:    my $items='';
 4103:    foreach my $item (@$storearr) {
 4104:        $items.=&escape($item).'&';
 4105:    }
 4106:    $items=~s/\&$//;
 4107:    if (!$udomain) { $udomain=$env{'user.domain'}; }
 4108:    if (!$uname) { $uname=$env{'user.name'}; }
 4109:    my $uhome=&homeserver($uname,$udomain);
 4110:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
 4111:    my @pairs=split(/\&/,$rep);
 4112:    my %returnhash=();
 4113:    my $i=0;
 4114:    foreach my $item (@$storearr) {
 4115:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
 4116:       $i++;
 4117:    }
 4118:    return %returnhash;
 4119: }
 4120: 
 4121: # ------------------------------------------------------------ tmpput interface
 4122: sub tmpput {
 4123:     my ($storehash,$server,$context)=@_;
 4124:     my $items='';
 4125:     foreach my $item (keys(%$storehash)) {
 4126: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
 4127:     }
 4128:     $items=~s/\&$//;
 4129:     if (defined($context)) {
 4130:         $items .= ':'.&escape($context);
 4131:     }
 4132:     return &reply("tmpput:$items",$server);
 4133: }
 4134: 
 4135: # ------------------------------------------------------------ tmpget interface
 4136: sub tmpget {
 4137:     my ($token,$server)=@_;
 4138:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 4139:     my $rep=&reply("tmpget:$token",$server);
 4140:     my %returnhash;
 4141:     foreach my $item (split(/\&/,$rep)) {
 4142: 	my ($key,$value)=split(/=/,$item);
 4143:         next if ($key =~ /^error: 2 /);
 4144: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
 4145:     }
 4146:     return %returnhash;
 4147: }
 4148: 
 4149: # ------------------------------------------------------------ tmpget interface
 4150: sub tmpdel {
 4151:     my ($token,$server)=@_;
 4152:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
 4153:     return &reply("tmpdel:$token",$server);
 4154: }
 4155: 
 4156: # -------------------------------------------------- portfolio access checking
 4157: 
 4158: sub portfolio_access {
 4159:     my ($requrl) = @_;
 4160:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
 4161:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
 4162:     if ($result) {
 4163:         my %setters;
 4164:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4165:             my ($startblock,$endblock) =
 4166:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
 4167:             if ($startblock && $endblock) {
 4168:                 return 'B';
 4169:             }
 4170:         } else {
 4171:             my ($startblock,$endblock) =
 4172:                 &Apache::loncommon::blockcheck(\%setters,'port');
 4173:             if ($startblock && $endblock) {
 4174:                 return 'B';
 4175:             }
 4176:         }
 4177:     }
 4178:     if ($result eq 'ok') {
 4179:        return 'F';
 4180:     } elsif ($result =~ /^[^:]+:guest_/) {
 4181:        return 'A';
 4182:     }
 4183:     return '';
 4184: }
 4185: 
 4186: sub get_portfolio_access {
 4187:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
 4188: 
 4189:     if (!ref($access_hash)) {
 4190: 	my $current_perms = &get_portfile_permissions($udom,$unum);
 4191: 	my %access_controls = &get_access_controls($current_perms,$group,
 4192: 						   $file_name);
 4193: 	$access_hash = $access_controls{$file_name};
 4194:     }
 4195: 
 4196:     my ($public,$guest,@domains,@users,@courses,@groups);
 4197:     my $now = time;
 4198:     if (ref($access_hash) eq 'HASH') {
 4199:         foreach my $key (keys(%{$access_hash})) {
 4200:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 4201:             if ($start > $now) {
 4202:                 next;
 4203:             }
 4204:             if ($end && $end<$now) {
 4205:                 next;
 4206:             }
 4207:             if ($scope eq 'public') {
 4208:                 $public = $key;
 4209:                 last;
 4210:             } elsif ($scope eq 'guest') {
 4211:                 $guest = $key;
 4212:             } elsif ($scope eq 'domains') {
 4213:                 push(@domains,$key);
 4214:             } elsif ($scope eq 'users') {
 4215:                 push(@users,$key);
 4216:             } elsif ($scope eq 'course') {
 4217:                 push(@courses,$key);
 4218:             } elsif ($scope eq 'group') {
 4219:                 push(@groups,$key);
 4220:             }
 4221:         }
 4222:         if ($public) {
 4223:             return 'ok';
 4224:         }
 4225:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
 4226:             if ($guest) {
 4227:                 return $guest;
 4228:             }
 4229:         } else {
 4230:             if (@domains > 0) {
 4231:                 foreach my $domkey (@domains) {
 4232:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
 4233:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
 4234:                             return 'ok';
 4235:                         }
 4236:                     }
 4237:                 }
 4238:             }
 4239:             if (@users > 0) {
 4240:                 foreach my $userkey (@users) {
 4241:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
 4242:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
 4243:                             if (ref($item) eq 'HASH') {
 4244:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
 4245:                                     ($item->{'udom'} eq $env{'user.domain'})) {
 4246:                                     return 'ok';
 4247:                                 }
 4248:                             }
 4249:                         }
 4250:                     } 
 4251:                 }
 4252:             }
 4253:             my %roleshash;
 4254:             my @courses_and_groups = @courses;
 4255:             push(@courses_and_groups,@groups); 
 4256:             if (@courses_and_groups > 0) {
 4257:                 my (%allgroups,%allroles); 
 4258:                 my ($start,$end,$role,$sec,$group);
 4259:                 foreach my $envkey (%env) {
 4260:                     if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4261:                         my $cid = $2.'_'.$3; 
 4262:                         if ($1 eq 'gr') {
 4263:                             $group = $4;
 4264:                             $allgroups{$cid}{$group} = $env{$envkey};
 4265:                         } else {
 4266:                             if ($4 eq '') {
 4267:                                 $sec = 'none';
 4268:                             } else {
 4269:                                 $sec = $4;
 4270:                             }
 4271:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4272:                         }
 4273:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
 4274:                         my $cid = $2.'_'.$3;
 4275:                         if ($4 eq '') {
 4276:                             $sec = 'none';
 4277:                         } else {
 4278:                             $sec = $4;
 4279:                         }
 4280:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
 4281:                     }
 4282:                 }
 4283:                 if (keys(%allroles) == 0) {
 4284:                     return;
 4285:                 }
 4286:                 foreach my $key (@courses_and_groups) {
 4287:                     my %content = %{$$access_hash{$key}};
 4288:                     my $cnum = $content{'number'};
 4289:                     my $cdom = $content{'domain'};
 4290:                     my $cid = $cdom.'_'.$cnum;
 4291:                     if (!exists($allroles{$cid})) {
 4292:                         next;
 4293:                     }    
 4294:                     foreach my $role_id (keys(%{$content{'roles'}})) {
 4295:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
 4296:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
 4297:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
 4298:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
 4299:                         foreach my $role (keys(%{$allroles{$cid}})) {
 4300:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
 4301:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
 4302:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
 4303:                                         if (grep/^all$/,@sections) {
 4304:                                             return 'ok';
 4305:                                         } else {
 4306:                                             if (grep/^$sec$/,@sections) {
 4307:                                                 return 'ok';
 4308:                                             }
 4309:                                         }
 4310:                                     }
 4311:                                 }
 4312:                                 if (keys(%{$allgroups{$cid}}) == 0) {
 4313:                                     if (grep/^none$/,@groups) {
 4314:                                         return 'ok';
 4315:                                     }
 4316:                                 } else {
 4317:                                     if (grep/^all$/,@groups) {
 4318:                                         return 'ok';
 4319:                                     } 
 4320:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
 4321:                                         if (grep/^$group$/,@groups) {
 4322:                                             return 'ok';
 4323:                                         }
 4324:                                     }
 4325:                                 } 
 4326:                             }
 4327:                         }
 4328:                     }
 4329:                 }
 4330:             }
 4331:             if ($guest) {
 4332:                 return $guest;
 4333:             }
 4334:         }
 4335:     }
 4336:     return;
 4337: }
 4338: 
 4339: sub course_group_datechecker {
 4340:     my ($dates,$now,$status) = @_;
 4341:     my ($start,$end) = split(/\./,$dates);
 4342:     if (!$start && !$end) {
 4343:         return 'ok';
 4344:     }
 4345:     if (grep/^active$/,@{$status}) {
 4346:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
 4347:             return 'ok';
 4348:         }
 4349:     }
 4350:     if (grep/^previous$/,@{$status}) {
 4351:         if ($end > $now ) {
 4352:             return 'ok';
 4353:         }
 4354:     }
 4355:     if (grep/^future$/,@{$status}) {
 4356:         if ($start > $now) {
 4357:             return 'ok';
 4358:         }
 4359:     }
 4360:     return; 
 4361: }
 4362: 
 4363: sub parse_portfolio_url {
 4364:     my ($url) = @_;
 4365: 
 4366:     my ($type,$udom,$unum,$group,$file_name);
 4367:     
 4368:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
 4369: 	$type = 1;
 4370:         $udom = $1;
 4371:         $unum = $2;
 4372:         $file_name = $3;
 4373:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
 4374: 	$type = 2;
 4375:         $udom = $1;
 4376:         $unum = $2;
 4377:         $group = $3;
 4378:         $file_name = $3.'/'.$4;
 4379:     }
 4380:     if (wantarray) {
 4381: 	return ($type,$udom,$unum,$file_name,$group);
 4382:     }
 4383:     return $type;
 4384: }
 4385: 
 4386: sub is_portfolio_url {
 4387:     my ($url) = @_;
 4388:     return scalar(&parse_portfolio_url($url));
 4389: }
 4390: 
 4391: sub is_portfolio_file {
 4392:     my ($file) = @_;
 4393:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
 4394:         return 1;
 4395:     }
 4396:     return;
 4397: }
 4398: 
 4399: sub usertools_access {
 4400:     my ($uname,$udom,$tool,$action) = @_;
 4401:     my $access;
 4402:     my %tools = (
 4403:                   aboutme   => 1,
 4404:                   blog      => 1,
 4405:                   portfolio => 1,
 4406:                 );
 4407:     return if (!defined($tools{$tool}));
 4408: 
 4409:     if ((!defined($udom)) || (!defined($uname))) {
 4410:         $udom = $env{'user.domain'};
 4411:         $uname = $env{'user.name'};
 4412:     }
 4413: 
 4414:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 4415:         if ($action ne 'reload') {
 4416:             return $env{'environment.availabletools.'.$tool};
 4417:         }
 4418:     }
 4419: 
 4420:     my ($toolstatus,$inststatus);
 4421: 
 4422:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 4423:         $toolstatus = $env{'environment.tools.'.$tool};
 4424:         $inststatus = $env{'environment.inststatus'};
 4425:     } else {
 4426:         my %userenv = &userenvironment($udom,$uname,'tools.'.$tool);
 4427:         $toolstatus = $userenv{'tools.'.$tool};
 4428:         $inststatus = $userenv{'inststatus'};
 4429:     }
 4430: 
 4431:     if ($toolstatus ne '') {
 4432:         if ($toolstatus) {
 4433:             $access = 1;
 4434:         } else {
 4435:             $access = 0;
 4436:         }
 4437:         return $access;
 4438:     }
 4439: 
 4440:     my $is_adv = &is_advanced_user($udom,$uname);
 4441:     my %domdef = &get_domain_defaults($udom);
 4442:     if (ref($domdef{$tool}) eq 'HASH') {
 4443:         if ($is_adv) {
 4444:             if ($domdef{$tool}{'_LC_adv'} ne '') {
 4445:                 if ($domdef{$tool}{'_LC_adv'}) { 
 4446:                     $access = 1;
 4447:                 } else {
 4448:                     $access = 0;
 4449:                 }
 4450:                 return $access;
 4451:             }
 4452:         }
 4453:         if ($inststatus ne '') {
 4454:             my ($hasaccess,$hasnoaccess);
 4455:             foreach my $affiliation (split(/:/,$inststatus)) {
 4456:                 if ($domdef{$tool}{$affiliation} ne '') { 
 4457:                     if ($domdef{$tool}{$affiliation}) {
 4458:                         $hasaccess = 1;
 4459:                     } else {
 4460:                         $hasnoaccess = 1;
 4461:                     }
 4462:                 }
 4463:             }
 4464:             if ($hasaccess || $hasnoaccess) {
 4465:                 if ($hasaccess) {
 4466:                     $access = 1;
 4467:                 } elsif ($hasnoaccess) {
 4468:                     $access = 0; 
 4469:                 }
 4470:                 return $access;
 4471:             }
 4472:         } else {
 4473:             if ($domdef{$tool}{'default'} ne '') {
 4474:                 if ($domdef{$tool}{'default'}) {
 4475:                     $access = 1;
 4476:                 } elsif ($domdef{$tool}{'default'} == 0) {
 4477:                     $access = 0;
 4478:                 }
 4479:                 return $access;
 4480:             }
 4481:         }
 4482:     } else {
 4483:         $access = 1;
 4484:         return $access;
 4485:     }
 4486: }
 4487: 
 4488: sub is_advanced_user {
 4489:     my ($udom,$uname) = @_;
 4490:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
 4491:     my %allroles;
 4492:     my $is_adv;
 4493:     foreach my $role (keys(%roleshash)) {
 4494:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
 4495:         my $area = '/'.$tdomain.'/'.$trest;
 4496:         if ($sec ne '') {
 4497:             $area .= '/'.$sec;
 4498:         }
 4499:         if (($area ne '') && ($trole ne '')) {
 4500:             my $spec=$trole.'.'.$area;
 4501:             if ($trole =~ /^cr\//) {
 4502:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
 4503:             } elsif ($trole ne 'gr') {
 4504:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
 4505:             }
 4506:         }
 4507:     }
 4508:     foreach my $role (keys(%allroles)) {
 4509:         last if ($is_adv);
 4510:         foreach my $item (split(/:/,$allroles{$role})) {
 4511:             if ($item ne '') {
 4512:                 my ($privilege,$restrictions)=split(/&/,$item);
 4513:                 if ($privilege eq 'adv') {
 4514:                     $is_adv = 1;
 4515:                     last;
 4516:                 }
 4517:             }
 4518:         }
 4519:     }
 4520:     return $is_adv;
 4521: }
 4522: 
 4523: # ---------------------------------------------- Custom access rule evaluation
 4524: 
 4525: sub customaccess {
 4526:     my ($priv,$uri)=@_;
 4527:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
 4528:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
 4529:     $udom = &LONCAPA::clean_domain($udom);
 4530:     $ucrs = &LONCAPA::clean_username($ucrs);
 4531:     my $access=0;
 4532:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
 4533: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
 4534: 	if ($type eq 'user') {
 4535: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4536: 		my ($tdom,$tuname)=split(m{/},$scope);
 4537: 		if ($tdom) {
 4538: 		    if ($tdom ne $env{'user.domain'}) { next; }
 4539: 		}
 4540: 		if ($tuname) {
 4541: 		    if ($tuname ne $env{'user.name'}) { next; }
 4542: 		}
 4543: 		$access=($effect eq 'allow');
 4544: 		last;
 4545: 	    }
 4546: 	} else {
 4547: 	    if ($role) {
 4548: 		if ($role ne $urole) { next; }
 4549: 	    }
 4550: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
 4551: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
 4552: 		if ($tdom) {
 4553: 		    if ($tdom ne $udom) { next; }
 4554: 		}
 4555: 		if ($tcrs) {
 4556: 		    if ($tcrs ne $ucrs) { next; }
 4557: 		}
 4558: 		if ($tsec) {
 4559: 		    if ($tsec ne $usec) { next; }
 4560: 		}
 4561: 		$access=($effect eq 'allow');
 4562: 		last;
 4563: 	    }
 4564: 	    if ($realm eq '' && $role eq '') {
 4565: 		$access=($effect eq 'allow');
 4566: 	    }
 4567: 	}
 4568:     }
 4569:     return $access;
 4570: }
 4571: 
 4572: # ------------------------------------------------- Check for a user privilege
 4573: 
 4574: sub allowed {
 4575:     my ($priv,$uri,$symb,$role)=@_;
 4576:     my $ver_orguri=$uri;
 4577:     $uri=&deversion($uri);
 4578:     my $orguri=$uri;
 4579:     $uri=&declutter($uri);
 4580: 
 4581:     if ($priv eq 'evb') {
 4582: # Evade communication block restrictions for specified role in a course
 4583:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
 4584:             return $1;
 4585:         } else {
 4586:             return;
 4587:         }
 4588:     }
 4589: 
 4590:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
 4591: # Free bre access to adm and meta resources
 4592:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
 4593: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
 4594: 	&& ($priv eq 'bre')) {
 4595: 	return 'F';
 4596:     }
 4597: 
 4598: # Free bre access to user's own portfolio contents
 4599:     my ($space,$domain,$name,@dir)=split('/',$uri);
 4600:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
 4601: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
 4602:         my %setters;
 4603:         my ($startblock,$endblock) = 
 4604:             &Apache::loncommon::blockcheck(\%setters,'port');
 4605:         if ($startblock && $endblock) {
 4606:             return 'B';
 4607:         } else {
 4608:             return 'F';
 4609:         }
 4610:     }
 4611: 
 4612: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
 4613:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
 4614:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
 4615:         if (exists($env{'request.course.id'})) {
 4616:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
 4617:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
 4618:             if (($domain eq $cdom) && ($name eq $cnum)) {
 4619:                 my $courseprivid=$env{'request.course.id'};
 4620:                 $courseprivid=~s/\_/\//;
 4621:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
 4622:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
 4623:                     return $1; 
 4624:                 } else {
 4625:                     if ($env{'request.course.sec'}) {
 4626:                         $courseprivid.='/'.$env{'request.course.sec'};
 4627:                     }
 4628:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
 4629:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
 4630:                         return $2;
 4631:                     }
 4632:                 }
 4633:             }
 4634:         }
 4635:     }
 4636: 
 4637: # Free bre to public access
 4638: 
 4639:     if ($priv eq 'bre') {
 4640:         my $copyright=&metadata($uri,'copyright');
 4641: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
 4642:            return 'F'; 
 4643:         }
 4644:         if ($copyright eq 'priv') {
 4645:             $uri=~/([^\/]+)\/([^\/]+)\//;
 4646: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
 4647: 		return '';
 4648:             }
 4649:         }
 4650:         if ($copyright eq 'domain') {
 4651:             $uri=~/([^\/]+)\/([^\/]+)\//;
 4652: 	    unless (($env{'user.domain'} eq $1) ||
 4653:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
 4654: 		return '';
 4655:             }
 4656:         }
 4657:         if ($env{'request.role'}=~ /li\.\//) {
 4658:             # Library role, so allow browsing of resources in this domain.
 4659:             return 'F';
 4660:         }
 4661:         if ($copyright eq 'custom') {
 4662: 	    unless (&customaccess($priv,$uri)) { return ''; }
 4663:         }
 4664:     }
 4665:     # Domain coordinator is trying to create a course
 4666:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
 4667:         # uri is the requested domain in this case.
 4668:         # comparison to 'request.role.domain' shows if the user has selected
 4669:         # a role of dc for the domain in question.
 4670:         return 'F' if ($uri eq $env{'request.role.domain'});
 4671:     }
 4672: 
 4673:     my $thisallowed='';
 4674:     my $statecond=0;
 4675:     my $courseprivid='';
 4676: 
 4677: # Course
 4678: 
 4679:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
 4680:        $thisallowed.=$1;
 4681:     }
 4682: 
 4683: # Domain
 4684: 
 4685:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
 4686:        =~/\Q$priv\E\&([^\:]*)/) {
 4687:        $thisallowed.=$1;
 4688:     }
 4689: 
 4690: # Course: uri itself is a course
 4691:     my $courseuri=$uri;
 4692:     $courseuri=~s/\_(\d)/\/$1/;
 4693:     $courseuri=~s/^([^\/])/\/$1/;
 4694: 
 4695:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
 4696:        =~/\Q$priv\E\&([^\:]*)/) {
 4697:        $thisallowed.=$1;
 4698:     }
 4699: 
 4700: # URI is an uploaded document for this course, default permissions don't matter
 4701: # not allowing 'edit' access (editupload) to uploaded course docs
 4702:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
 4703: 	$thisallowed='';
 4704:         my ($match)=&is_on_map($uri);
 4705:         if ($match) {
 4706:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
 4707:                   =~/\Q$priv\E\&([^\:]*)/) {
 4708:                 $thisallowed.=$1;
 4709:             }
 4710:         } else {
 4711:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
 4712:             if ($refuri) {
 4713:                 if ($refuri =~ m|^/adm/|) {
 4714:                     $thisallowed='F';
 4715:                 } else {
 4716:                     $refuri=&declutter($refuri);
 4717:                     my ($match) = &is_on_map($refuri);
 4718:                     if ($match) {
 4719:                         $thisallowed='F';
 4720:                     }
 4721:                 }
 4722:             }
 4723:         }
 4724:     }
 4725: 
 4726:     if ($priv eq 'bre'
 4727: 	&& $thisallowed ne 'F' 
 4728: 	&& $thisallowed ne '2'
 4729: 	&& &is_portfolio_url($uri)) {
 4730: 	$thisallowed = &portfolio_access($uri);
 4731:     }
 4732:     
 4733: # Full access at system, domain or course-wide level? Exit.
 4734:     if ($thisallowed=~/F/) {
 4735: 	return 'F';
 4736:     }
 4737: 
 4738: # If this is generating or modifying users, exit with special codes
 4739: 
 4740:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
 4741: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
 4742: 	    my ($audom,$auname)=split('/',$uri);
 4743: # no author name given, so this just checks on the general right to make a co-author in this domain
 4744: 	    unless ($auname) { return $thisallowed; }
 4745: # an author name is given, so we are about to actually make a co-author for a certain account
 4746: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
 4747: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
 4748: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
 4749: 	}
 4750: 	return $thisallowed;
 4751:     }
 4752: #
 4753: # Gathered so far: system, domain and course wide privileges
 4754: #
 4755: # Course: See if uri or referer is an individual resource that is part of 
 4756: # the course
 4757: 
 4758:     if ($env{'request.course.id'}) {
 4759: 
 4760:        $courseprivid=$env{'request.course.id'};
 4761:        if ($env{'request.course.sec'}) {
 4762:           $courseprivid.='/'.$env{'request.course.sec'};
 4763:        }
 4764:        $courseprivid=~s/\_/\//;
 4765:        my $checkreferer=1;
 4766:        my ($match,$cond)=&is_on_map($uri);
 4767:        if ($match) {
 4768:            $statecond=$cond;
 4769:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4770:                =~/\Q$priv\E\&([^\:]*)/) {
 4771:                $thisallowed.=$1;
 4772:                $checkreferer=0;
 4773:            }
 4774:        }
 4775:        
 4776:        if ($checkreferer) {
 4777: 	  my $refuri=$env{'httpref.'.$orguri};
 4778:             unless ($refuri) {
 4779:                 foreach my $key (keys(%env)) {
 4780: 		    if ($key=~/^httpref\..*\*/) {
 4781: 			my $pattern=$key;
 4782:                         $pattern=~s/^httpref\.\/res\///;
 4783:                         $pattern=~s/\*/\[\^\/\]\+/g;
 4784:                         $pattern=~s/\//\\\//g;
 4785:                         if ($orguri=~/$pattern/) {
 4786: 			    $refuri=$env{$key};
 4787:                         }
 4788:                     }
 4789:                 }
 4790:             }
 4791: 
 4792:          if ($refuri) { 
 4793: 	  $refuri=&declutter($refuri);
 4794:           my ($match,$cond)=&is_on_map($refuri);
 4795:             if ($match) {
 4796:               my $refstatecond=$cond;
 4797:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
 4798:                   =~/\Q$priv\E\&([^\:]*)/) {
 4799:                   $thisallowed.=$1;
 4800:                   $uri=$refuri;
 4801:                   $statecond=$refstatecond;
 4802:               }
 4803:           }
 4804:         }
 4805:        }
 4806:    }
 4807: 
 4808: #
 4809: # Gathered now: all privileges that could apply, and condition number
 4810: # 
 4811: #
 4812: # Full or no access?
 4813: #
 4814: 
 4815:     if ($thisallowed=~/F/) {
 4816: 	return 'F';
 4817:     }
 4818: 
 4819:     unless ($thisallowed) {
 4820:         return '';
 4821:     }
 4822: 
 4823: # Restrictions exist, deal with them
 4824: #
 4825: #   C:according to course preferences
 4826: #   R:according to resource settings
 4827: #   L:unless locked
 4828: #   X:according to user session state
 4829: #
 4830: 
 4831: # Possibly locked functionality, check all courses
 4832: # Locks might take effect only after 10 minutes cache expiration for other
 4833: # courses, and 2 minutes for current course
 4834: 
 4835:     my $envkey;
 4836:     if ($thisallowed=~/L/) {
 4837:         foreach $envkey (keys %env) {
 4838:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
 4839:                my $courseid=$2;
 4840:                my $roleid=$1.'.'.$2;
 4841:                $courseid=~s/^\///;
 4842:                my $expiretime=600;
 4843:                if ($env{'request.role'} eq $roleid) {
 4844: 		  $expiretime=120;
 4845:                }
 4846: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
 4847:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
 4848:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
 4849: 		   &coursedescription($courseid,{'freshen_cache' => 1});
 4850:                }
 4851:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
 4852:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
 4853: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
 4854:                        &log($env{'user.domain'},$env{'user.name'},
 4855:                             $env{'user.home'},
 4856:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
 4857:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 4858:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 4859: 		       return '';
 4860:                    }
 4861:                }
 4862:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
 4863:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
 4864: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
 4865:                        &log($env{'user.domain'},$env{'user.name'},
 4866:                             $env{'user.home'},
 4867:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
 4868:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
 4869:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
 4870: 		       return '';
 4871:                    }
 4872:                }
 4873: 	   }
 4874:        }
 4875:     }
 4876:    
 4877: #
 4878: # Rest of the restrictions depend on selected course
 4879: #
 4880: 
 4881:     unless ($env{'request.course.id'}) {
 4882: 	if ($thisallowed eq 'A') {
 4883: 	    return 'A';
 4884:         } elsif ($thisallowed eq 'B') {
 4885:             return 'B';
 4886: 	} else {
 4887: 	    return '1';
 4888: 	}
 4889:     }
 4890: 
 4891: #
 4892: # Now user is definitely in a course
 4893: #
 4894: 
 4895: 
 4896: # Course preferences
 4897: 
 4898:    if ($thisallowed=~/C/) {
 4899:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4900:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
 4901:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
 4902: 	   =~/\Q$rolecode\E/) {
 4903: 	   if ($priv ne 'pch') { 
 4904: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4905: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
 4906: 			$env{'request.course.id'});
 4907: 	   }
 4908:            return '';
 4909:        }
 4910: 
 4911:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
 4912: 	   =~/\Q$unamedom\E/) {
 4913: 	   if ($priv ne 'pch') { 
 4914: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
 4915: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
 4916: 			$env{'request.course.id'});
 4917: 	   }
 4918:            return '';
 4919:        }
 4920:    }
 4921: 
 4922: # Resource preferences
 4923: 
 4924:    if ($thisallowed=~/R/) {
 4925:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
 4926:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
 4927: 	   if ($priv ne 'pch') { 
 4928: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
 4929: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
 4930: 	   }
 4931: 	   return '';
 4932:        }
 4933:    }
 4934: 
 4935: # Restricted by state or randomout?
 4936: 
 4937:    if ($thisallowed=~/X/) {
 4938:       if ($env{'acc.randomout'}) {
 4939: 	 if (!$symb) { $symb=&symbread($uri,1); }
 4940:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
 4941:             return ''; 
 4942:          }
 4943:       }
 4944:       if (&condval($statecond)) {
 4945: 	 return '2';
 4946:       } else {
 4947:          return '';
 4948:       }
 4949:    }
 4950: 
 4951:     if ($thisallowed eq 'A') {
 4952: 	return 'A';
 4953:     } elsif ($thisallowed eq 'B') {
 4954:         return 'B';
 4955:     }
 4956:    return 'F';
 4957: }
 4958: 
 4959: sub split_uri_for_cond {
 4960:     my $uri=&deversion(&declutter(shift));
 4961:     my @uriparts=split(/\//,$uri);
 4962:     my $filename=pop(@uriparts);
 4963:     my $pathname=join('/',@uriparts);
 4964:     return ($pathname,$filename);
 4965: }
 4966: # --------------------------------------------------- Is a resource on the map?
 4967: 
 4968: sub is_on_map {
 4969:     my ($pathname,$filename) = &split_uri_for_cond(shift);
 4970:     #Trying to find the conditional for the file
 4971:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
 4972: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
 4973:     if ($match) {
 4974: 	return (1,$1);
 4975:     } else {
 4976: 	return (0,0);
 4977:     }
 4978: }
 4979: 
 4980: # --------------------------------------------------------- Get symb from alias
 4981: 
 4982: sub get_symb_from_alias {
 4983:     my $symb=shift;
 4984:     my ($map,$resid,$url)=&decode_symb($symb);
 4985: # Already is a symb
 4986:     if ($url) { return $symb; }
 4987: # Must be an alias
 4988:     my $aliassymb='';
 4989:     my %bighash;
 4990:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 4991:                             &GDBM_READER(),0640)) {
 4992:         my $rid=$bighash{'mapalias_'.$symb};
 4993: 	if ($rid) {
 4994: 	    my ($mapid,$resid)=split(/\./,$rid);
 4995: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
 4996: 				    $resid,$bighash{'src_'.$rid});
 4997: 	}
 4998:         untie %bighash;
 4999:     }
 5000:     return $aliassymb;
 5001: }
 5002: 
 5003: # ----------------------------------------------------------------- Define Role
 5004: 
 5005: sub definerole {
 5006:   if (allowed('mcr','/')) {
 5007:     my ($rolename,$sysrole,$domrole,$courole)=@_;
 5008:     foreach my $role (split(':',$sysrole)) {
 5009: 	my ($crole,$cqual)=split(/\&/,$role);
 5010:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
 5011:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
 5012: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 5013:                return "refused:s:$crole&$cqual"; 
 5014:             }
 5015:         }
 5016:     }
 5017:     foreach my $role (split(':',$domrole)) {
 5018: 	my ($crole,$cqual)=split(/\&/,$role);
 5019:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
 5020:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
 5021: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
 5022:                return "refused:d:$crole&$cqual"; 
 5023:             }
 5024:         }
 5025:     }
 5026:     foreach my $role (split(':',$courole)) {
 5027: 	my ($crole,$cqual)=split(/\&/,$role);
 5028:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
 5029:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
 5030: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
 5031:                return "refused:c:$crole&$cqual"; 
 5032:             }
 5033:         }
 5034:     }
 5035:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 5036:                 "$env{'user.domain'}:$env{'user.name'}:".
 5037: 	        "rolesdef_$rolename=".
 5038:                 escape($sysrole.'_'.$domrole.'_'.$courole);
 5039:     return reply($command,$env{'user.home'});
 5040:   } else {
 5041:     return 'refused';
 5042:   }
 5043: }
 5044: 
 5045: # ---------------- Make a metadata query against the network of library servers
 5046: 
 5047: sub metadata_query {
 5048:     my ($query,$custom,$customshow,$server_array)=@_;
 5049:     my %rhash;
 5050:     my %libserv = &all_library();
 5051:     my @server_list = (defined($server_array) ? @$server_array
 5052:                                               : keys(%libserv) );
 5053:     for my $server (@server_list) {
 5054: 	unless ($custom or $customshow) {
 5055: 	    my $reply=&reply("querysend:".&escape($query),$server);
 5056: 	    $rhash{$server}=$reply;
 5057: 	}
 5058: 	else {
 5059: 	    my $reply=&reply("querysend:".&escape($query).':'.
 5060: 			     &escape($custom).':'.&escape($customshow),
 5061: 			     $server);
 5062: 	    $rhash{$server}=$reply;
 5063: 	}
 5064:     }
 5065:     return \%rhash;
 5066: }
 5067: 
 5068: # ----------------------------------------- Send log queries and wait for reply
 5069: 
 5070: sub log_query {
 5071:     my ($uname,$udom,$query,%filters)=@_;
 5072:     my $uhome=&homeserver($uname,$udom);
 5073:     if ($uhome eq 'no_host') { return 'error: no_host'; }
 5074:     my $uhost=&hostname($uhome);
 5075:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
 5076:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
 5077:                        $uhome);
 5078:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
 5079:     return get_query_reply($queryid);
 5080: }
 5081: 
 5082: # -------------------------- Update MySQL table for portfolio file
 5083: 
 5084: sub update_portfolio_table {
 5085:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
 5086:     if ($group ne '') {
 5087:         $file_name =~s /^\Q$group\E//;
 5088:     }
 5089:     my $homeserver = &homeserver($uname,$udom);
 5090:     my $queryid=
 5091:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
 5092:                ':'.&escape($file_name).':'.$action,$homeserver);
 5093:     my $reply = &get_query_reply($queryid);
 5094:     return $reply;
 5095: }
 5096: 
 5097: # -------------------------- Update MySQL allusers table
 5098: 
 5099: sub update_allusers_table {
 5100:     my ($uname,$udom,$names) = @_;
 5101:     my $homeserver = &homeserver($uname,$udom);
 5102:     my $queryid=
 5103:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
 5104:                'lastname='.&escape($names->{'lastname'}).'%%'.
 5105:                'firstname='.&escape($names->{'firstname'}).'%%'.
 5106:                'middlename='.&escape($names->{'middlename'}).'%%'.
 5107:                'generation='.&escape($names->{'generation'}).'%%'.
 5108:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
 5109:                'id='.&escape($names->{'id'}),$homeserver);
 5110:     my $reply = &get_query_reply($queryid);
 5111:     return $reply;
 5112: }
 5113: 
 5114: # ------- Request retrieval of institutional classlists for course(s)
 5115: 
 5116: sub fetch_enrollment_query {
 5117:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
 5118:     my $homeserver;
 5119:     my $maxtries = 1;
 5120:     if ($context eq 'automated') {
 5121:         $homeserver = $perlvar{'lonHostID'};
 5122:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
 5123:     } else {
 5124:         $homeserver = &homeserver($cnum,$dom);
 5125:     }
 5126:     my $host=&hostname($homeserver);
 5127:     my $cmd = '';
 5128:     foreach my $affiliate (keys %{$affiliatesref}) {
 5129:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5130:     }
 5131:     $cmd =~ s/%%$//;
 5132:     $cmd = &escape($cmd);
 5133:     my $query = 'fetchenrollment';
 5134:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
 5135:     unless ($queryid=~/^\Q$host\E\_/) { 
 5136:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
 5137:         return 'error: '.$queryid;
 5138:     }
 5139:     my $reply = &get_query_reply($queryid);
 5140:     my $tries = 1;
 5141:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5142:         $reply = &get_query_reply($queryid);
 5143:         $tries ++;
 5144:     }
 5145:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5146:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5147:     } else {
 5148:         my @responses = split(/:/,$reply);
 5149:         if ($homeserver eq $perlvar{'lonHostID'}) {
 5150:             foreach my $line (@responses) {
 5151:                 my ($key,$value) = split(/=/,$line,2);
 5152:                 $$replyref{$key} = $value;
 5153:             }
 5154:         } else {
 5155:             my $pathname = $perlvar{'lonDaemons'}.'/tmp';
 5156:             foreach my $line (@responses) {
 5157:                 my ($key,$value) = split(/=/,$line);
 5158:                 $$replyref{$key} = $value;
 5159:                 if ($value > 0) {
 5160:                     foreach my $item (@{$$affiliatesref{$key}}) {
 5161:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
 5162:                         my $destname = $pathname.'/'.$filename;
 5163:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
 5164:                         if ($xml_classlist =~ /^error/) {
 5165:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
 5166:                         } else {
 5167:                             if ( open(FILE,">$destname") ) {
 5168:                                 print FILE &unescape($xml_classlist);
 5169:                                 close(FILE);
 5170:                             } else {
 5171:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
 5172:                             }
 5173:                         }
 5174:                     }
 5175:                 }
 5176:             }
 5177:         }
 5178:         return 'ok';
 5179:     }
 5180:     return 'error';
 5181: }
 5182: 
 5183: sub get_query_reply {
 5184:     my $queryid=shift;
 5185:     my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
 5186:     my $reply='';
 5187:     for (1..100) {
 5188: 	sleep 2;
 5189:         if (-e $replyfile.'.end') {
 5190: 	    if (open(my $fh,$replyfile)) {
 5191: 		$reply = join('',<$fh>);
 5192: 		close($fh);
 5193: 	   } else { return 'error: reply_file_error'; }
 5194:            return &unescape($reply);
 5195: 	}
 5196:     }
 5197:     return 'timeout:'.$queryid;
 5198: }
 5199: 
 5200: sub courselog_query {
 5201: #
 5202: # possible filters:
 5203: # url: url or symb
 5204: # username
 5205: # domain
 5206: # action: view, submit, grade
 5207: # start: timestamp
 5208: # end: timestamp
 5209: #
 5210:     my (%filters)=@_;
 5211:     unless ($env{'request.course.id'}) { return 'no_course'; }
 5212:     if ($filters{'url'}) {
 5213: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
 5214:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
 5215:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
 5216:     }
 5217:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
 5218:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
 5219:     return &log_query($cname,$cdom,'courselog',%filters);
 5220: }
 5221: 
 5222: sub userlog_query {
 5223: #
 5224: # possible filters:
 5225: # action: log check role
 5226: # start: timestamp
 5227: # end: timestamp
 5228: #
 5229:     my ($uname,$udom,%filters)=@_;
 5230:     return &log_query($uname,$udom,'userlog',%filters);
 5231: }
 5232: 
 5233: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
 5234: 
 5235: sub auto_run {
 5236:     my ($cnum,$cdom) = @_;
 5237:     my $response = 0;
 5238:     my $settings;
 5239:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
 5240:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
 5241:         $settings = $domconfig{'autoenroll'};
 5242:         if ($settings->{'run'} eq '1') {
 5243:             $response = 1;
 5244:         }
 5245:     } else {
 5246:         my $homeserver;
 5247:         if (&is_course($cdom,$cnum)) {
 5248:             $homeserver = &homeserver($cnum,$cdom);
 5249:         } else {
 5250:             $homeserver = &domain($cdom,'primary');
 5251:         }
 5252:         if ($homeserver ne 'no_host') {
 5253:             $response = &reply('autorun:'.$cdom,$homeserver);
 5254:         }
 5255:     }
 5256:     return $response;
 5257: }
 5258: 
 5259: sub auto_get_sections {
 5260:     my ($cnum,$cdom,$inst_coursecode) = @_;
 5261:     my $homeserver = &homeserver($cnum,$cdom);
 5262:     my @secs = ();
 5263:     my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
 5264:     unless ($response eq 'refused') {
 5265:         @secs = split(/:/,$response);
 5266:     }
 5267:     return @secs;
 5268: }
 5269: 
 5270: sub auto_new_course {
 5271:     my ($cnum,$cdom,$inst_course_id,$owner) = @_;
 5272:     my $homeserver = &homeserver($cnum,$cdom);
 5273:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
 5274:     return $response;
 5275: }
 5276: 
 5277: sub auto_validate_courseID {
 5278:     my ($cnum,$cdom,$inst_course_id) = @_;
 5279:     my $homeserver = &homeserver($cnum,$cdom);
 5280:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
 5281:     return $response;
 5282: }
 5283: 
 5284: sub auto_create_password {
 5285:     my ($cnum,$cdom,$authparam,$udom) = @_;
 5286:     my ($homeserver,$response);
 5287:     my $create_passwd = 0;
 5288:     my $authchk = '';
 5289:     if ($udom =~ /^$match_domain$/) {
 5290:         $homeserver = &domain($udom,'primary');
 5291:     }
 5292:     if ($homeserver eq '') {
 5293:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
 5294:             $homeserver = &homeserver($cnum,$cdom);
 5295:         }
 5296:     }
 5297:     if ($homeserver eq '') {
 5298:         $authchk = 'nodomain';
 5299:     } else {
 5300:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
 5301:         if ($response eq 'refused') {
 5302:             $authchk = 'refused';
 5303:         } else {
 5304:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
 5305:         }
 5306:     }
 5307:     return ($authparam,$create_passwd,$authchk);
 5308: }
 5309: 
 5310: sub auto_photo_permission {
 5311:     my ($cnum,$cdom,$students) = @_;
 5312:     my $homeserver = &homeserver($cnum,$cdom);
 5313:     my ($outcome,$perm_reqd,$conditions) = 
 5314: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
 5315:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5316: 	return (undef,undef);
 5317:     }
 5318:     return ($outcome,$perm_reqd,$conditions);
 5319: }
 5320: 
 5321: sub auto_checkphotos {
 5322:     my ($uname,$udom,$pid) = @_;
 5323:     my $homeserver = &homeserver($uname,$udom);
 5324:     my ($result,$resulttype);
 5325:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
 5326: 				   &escape($uname).':'.&escape($pid),
 5327: 				   $homeserver));
 5328:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5329: 	return (undef,undef);
 5330:     }
 5331:     if ($outcome) {
 5332:         ($result,$resulttype) = split(/:/,$outcome);
 5333:     } 
 5334:     return ($result,$resulttype);
 5335: }
 5336: 
 5337: sub auto_photochoice {
 5338:     my ($cnum,$cdom) = @_;
 5339:     my $homeserver = &homeserver($cnum,$cdom);
 5340:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
 5341: 						       &escape($cdom),
 5342: 						       $homeserver)));
 5343:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
 5344: 	return (undef,undef);
 5345:     }
 5346:     return ($update,$comment);
 5347: }
 5348: 
 5349: sub auto_photoupdate {
 5350:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
 5351:     my $homeserver = &homeserver($cnum,$dom);
 5352:     my $host=&hostname($homeserver);
 5353:     my $cmd = '';
 5354:     my $maxtries = 1;
 5355:     foreach my $affiliate (keys(%{$affiliatesref})) {
 5356:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
 5357:     }
 5358:     $cmd =~ s/%%$//;
 5359:     $cmd = &escape($cmd);
 5360:     my $query = 'institutionalphotos';
 5361:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
 5362:     unless ($queryid=~/^\Q$host\E\_/) {
 5363:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
 5364:         return 'error: '.$queryid;
 5365:     }
 5366:     my $reply = &get_query_reply($queryid);
 5367:     my $tries = 1;
 5368:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
 5369:         $reply = &get_query_reply($queryid);
 5370:         $tries ++;
 5371:     }
 5372:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
 5373:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
 5374:     } else {
 5375:         my @responses = split(/:/,$reply);
 5376:         my $outcome = shift(@responses); 
 5377:         foreach my $item (@responses) {
 5378:             my ($key,$value) = split(/=/,$item);
 5379:             $$photo{$key} = $value;
 5380:         }
 5381:         return $outcome;
 5382:     }
 5383:     return 'error';
 5384: }
 5385: 
 5386: sub auto_instcode_format {
 5387:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
 5388: 	$cat_order) = @_;
 5389:     my $courses = '';
 5390:     my @homeservers;
 5391:     if ($caller eq 'global') {
 5392: 	my %servers = &get_servers($codedom,'library');
 5393: 	foreach my $tryserver (keys(%servers)) {
 5394: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5395: 		push(@homeservers,$tryserver);
 5396: 	    }
 5397:         }
 5398:     } else {
 5399:         push(@homeservers,&homeserver($caller,$codedom));
 5400:     }
 5401:     foreach my $code (keys(%{$instcodes})) {
 5402:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
 5403:     }
 5404:     chop($courses);
 5405:     my $ok_response = 0;
 5406:     my $response;
 5407:     while (@homeservers > 0 && $ok_response == 0) {
 5408:         my $server = shift(@homeservers); 
 5409:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
 5410:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
 5411:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
 5412: 		split(/:/,$response);
 5413:             %{$codes} = (%{$codes},&str2hash($codes_str));
 5414:             push(@{$codetitles},&str2array($codetitles_str));
 5415:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
 5416:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
 5417:             $ok_response = 1;
 5418:         }
 5419:     }
 5420:     if ($ok_response) {
 5421:         return 'ok';
 5422:     } else {
 5423:         return $response;
 5424:     }
 5425: }
 5426: 
 5427: sub auto_instcode_defaults {
 5428:     my ($domain,$returnhash,$code_order) = @_;
 5429:     my @homeservers;
 5430: 
 5431:     my %servers = &get_servers($domain,'library');
 5432:     foreach my $tryserver (keys(%servers)) {
 5433: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
 5434: 	    push(@homeservers,$tryserver);
 5435: 	}
 5436:     }
 5437: 
 5438:     my $response;
 5439:     foreach my $server (@homeservers) {
 5440:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
 5441:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
 5442: 	
 5443: 	foreach my $pair (split(/\&/,$response)) {
 5444: 	    my ($name,$value)=split(/\=/,$pair);
 5445: 	    if ($name eq 'code_order') {
 5446: 		@{$code_order} = split(/\&/,&unescape($value));
 5447: 	    } else {
 5448: 		$returnhash->{&unescape($name)}=&unescape($value);
 5449: 	    }
 5450: 	}
 5451: 	return 'ok';
 5452:     }
 5453: 
 5454:     return $response;
 5455: } 
 5456: 
 5457: sub auto_validate_class_sec {
 5458:     my ($cdom,$cnum,$owners,$inst_class) = @_;
 5459:     my $homeserver = &homeserver($cnum,$cdom);
 5460:     my $ownerlist;
 5461:     if (ref($owners) eq 'ARRAY') {
 5462:         $ownerlist = join(',',@{$owners});
 5463:     } else {
 5464:         $ownerlist = $owners;
 5465:     }
 5466:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
 5467:                         &escape($ownerlist).':'.$cdom,$homeserver);
 5468:     return $response;
 5469: }
 5470: 
 5471: # ------------------------------------------------------- Course Group routines
 5472: 
 5473: sub get_coursegroups {
 5474:     my ($cdom,$cnum,$group,$namespace) = @_;
 5475:     return(&dump($namespace,$cdom,$cnum,$group));
 5476: }
 5477: 
 5478: sub modify_coursegroup {
 5479:     my ($cdom,$cnum,$groupsettings) = @_;
 5480:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
 5481: }
 5482: 
 5483: sub toggle_coursegroup_status {
 5484:     my ($cdom,$cnum,$group,$action) = @_;
 5485:     my ($from_namespace,$to_namespace);
 5486:     if ($action eq 'delete') {
 5487:         $from_namespace = 'coursegroups';
 5488:         $to_namespace = 'deleted_groups';
 5489:     } else {
 5490:         $from_namespace = 'deleted_groups';
 5491:         $to_namespace = 'coursegroups';
 5492:     }
 5493:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
 5494:     if (my $tmp = &error(%curr_group)) {
 5495:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
 5496:         return ('read error',$tmp);
 5497:     } else {
 5498:         my %savedsettings = %curr_group; 
 5499:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
 5500:         my $deloutcome;
 5501:         if ($result eq 'ok') {
 5502:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
 5503:         } else {
 5504:             return ('write error',$result);
 5505:         }
 5506:         if ($deloutcome eq 'ok') {
 5507:             return 'ok';
 5508:         } else {
 5509:             return ('delete error',$deloutcome);
 5510:         }
 5511:     }
 5512: }
 5513: 
 5514: sub modify_group_roles {
 5515:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
 5516:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
 5517:     my $role = 'gr/'.&escape($userprivs);
 5518:     my ($uname,$udom) = split(/:/,$user);
 5519:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
 5520:     if ($result eq 'ok') {
 5521:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
 5522:     }
 5523:     return $result;
 5524: }
 5525: 
 5526: sub modify_coursegroup_membership {
 5527:     my ($cdom,$cnum,$membership) = @_;
 5528:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
 5529:     return $result;
 5530: }
 5531: 
 5532: sub get_active_groups {
 5533:     my ($udom,$uname,$cdom,$cnum) = @_;
 5534:     my $now = time;
 5535:     my %groups = ();
 5536:     foreach my $key (keys(%env)) {
 5537:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
 5538:             my ($start,$end) = split(/\./,$env{$key});
 5539:             if (($end!=0) && ($end<$now)) { next; }
 5540:             if (($start!=0) && ($start>$now)) { next; }
 5541:             if ($1 eq $cdom && $2 eq $cnum) {
 5542:                 $groups{$3} = $env{$key} ;
 5543:             }
 5544:         }
 5545:     }
 5546:     return %groups;
 5547: }
 5548: 
 5549: sub get_group_membership {
 5550:     my ($cdom,$cnum,$group) = @_;
 5551:     return(&dump('groupmembership',$cdom,$cnum,$group));
 5552: }
 5553: 
 5554: sub get_users_groups {
 5555:     my ($udom,$uname,$courseid) = @_;
 5556:     my @usersgroups;
 5557:     my $cachetime=1800;
 5558: 
 5559:     my $hashid="$udom:$uname:$courseid";
 5560:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
 5561:     if (defined($cached)) {
 5562:         @usersgroups = split(/:/,$grouplist);
 5563:     } else {  
 5564:         $grouplist = '';
 5565:         my $courseurl = &courseid_to_courseurl($courseid);
 5566:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
 5567:         my $access_end = $env{'course.'.$courseid.
 5568:                               '.default_enrollment_end_date'};
 5569:         my $now = time;
 5570:         foreach my $key (keys(%roleshash)) {
 5571:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
 5572:                 my $group = $1;
 5573:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
 5574:                     my $start = $2;
 5575:                     my $end = $1;
 5576:                     if ($start == -1) { next; } # deleted from group
 5577:                     if (($start!=0) && ($start>$now)) { next; }
 5578:                     if (($end!=0) && ($end<$now)) {
 5579:                         if ($access_end && $access_end < $now) {
 5580:                             if ($access_end - $end < 86400) {
 5581:                                 push(@usersgroups,$group);
 5582:                             }
 5583:                         }
 5584:                         next;
 5585:                     }
 5586:                     push(@usersgroups,$group);
 5587:                 }
 5588:             }
 5589:         }
 5590:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
 5591:         $grouplist = join(':',@usersgroups);
 5592:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
 5593:     }
 5594:     return @usersgroups;
 5595: }
 5596: 
 5597: sub devalidate_getgroups_cache {
 5598:     my ($udom,$uname,$cdom,$cnum)=@_;
 5599:     my $courseid = $cdom.'_'.$cnum;
 5600: 
 5601:     my $hashid="$udom:$uname:$courseid";
 5602:     &devalidate_cache_new('getgroups',$hashid);
 5603: }
 5604: 
 5605: # ------------------------------------------------------------------ Plain Text
 5606: 
 5607: sub plaintext {
 5608:     my ($short,$type,$cid) = @_;
 5609:     if ($short =~ /^cr/) {
 5610: 	return (split('/',$short))[-1];
 5611:     }
 5612:     if (!defined($cid)) {
 5613:         $cid = $env{'request.course.id'};
 5614:     }
 5615:     if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
 5616:         return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
 5617:                                           '.plaintext'});
 5618:     }
 5619:     my %rolenames = (
 5620:                       Course => 'std',
 5621:                       Group => 'alt1',
 5622:                     );
 5623:     if (defined($type) && 
 5624:          defined($rolenames{$type}) && 
 5625:          defined($prp{$short}{$rolenames{$type}})) {
 5626:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
 5627:     } else {
 5628:         return &Apache::lonlocal::mt($prp{$short}{'std'});
 5629:     }
 5630: }
 5631: 
 5632: # ----------------------------------------------------------------- Assign Role
 5633: 
 5634: sub assignrole {
 5635:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
 5636:         $context)=@_;
 5637:     my $mrole;
 5638:     if ($role =~ /^cr\//) {
 5639:         my $cwosec=$url;
 5640:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 5641: 	unless (&allowed('ccr',$cwosec)) {
 5642:            &logthis('Refused custom assignrole: '.
 5643:              $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 5644: 		    $env{'user.name'}.' at '.$env{'user.domain'});
 5645:            return 'refused'; 
 5646:         }
 5647:         $mrole='cr';
 5648:     } elsif ($role =~ /^gr\//) {
 5649:         my $cwogrp=$url;
 5650:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
 5651:         unless (&allowed('mdg',$cwogrp)) {
 5652:             &logthis('Refused group assignrole: '.
 5653:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
 5654:                     $env{'user.name'}.' at '.$env{'user.domain'});
 5655:             return 'refused';
 5656:         }
 5657:         $mrole='gr';
 5658:     } else {
 5659:         my $cwosec=$url;
 5660:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
 5661:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
 5662:             my $refused;
 5663:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
 5664:                 if (!(&allowed('c'.$role,$url))) {
 5665:                     $refused = 1;
 5666:                 }
 5667:             } else {
 5668:                 $refused = 1;
 5669:             }
 5670:             if ($refused) {
 5671:                 if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
 5672:                     $refused = '';
 5673:                 } else {
 5674:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
 5675:                              ' '.$role.' '.$end.' '.$start.' by '.
 5676: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
 5677:                     return 'refused';
 5678:                 }
 5679:             }
 5680:         }
 5681:         $mrole=$role;
 5682:     }
 5683:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
 5684:                 "$udom:$uname:$url".'_'."$mrole=$role";
 5685:     if ($end) { $command.='_'.$end; }
 5686:     if ($start) {
 5687: 	if ($end) { 
 5688:            $command.='_'.$start; 
 5689:         } else {
 5690:            $command.='_0_'.$start;
 5691:         }
 5692:     }
 5693:     my $origstart = $start;
 5694:     my $origend = $end;
 5695:     my $delflag;
 5696: # actually delete
 5697:     if ($deleteflag) {
 5698: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
 5699: # modify command to delete the role
 5700:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
 5701:                 "$udom:$uname:$url".'_'."$mrole";
 5702: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
 5703: # set start and finish to negative values for userrolelog
 5704:            $start=-1;
 5705:            $end=-1;
 5706:            $delflag = 1;
 5707:         }
 5708:     }
 5709: # send command
 5710:     my $answer=&reply($command,&homeserver($uname,$udom));
 5711: # log new user role if status is ok
 5712:     if ($answer eq 'ok') {
 5713: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
 5714: # for course roles, perform group memberships changes triggered by role change.
 5715:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
 5716:         unless ($role =~ /^gr/) {
 5717:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
 5718:                                              $origstart,$selfenroll,$context);
 5719:         }
 5720:     }
 5721:     return $answer;
 5722: }
 5723: 
 5724: # -------------------------------------------------- Modify user authentication
 5725: # Overrides without validation
 5726: 
 5727: sub modifyuserauth {
 5728:     my ($udom,$uname,$umode,$upass)=@_;
 5729:     my $uhome=&homeserver($uname,$udom);
 5730:     unless (&allowed('mau',$udom)) { return 'refused'; }
 5731:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
 5732:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 5733:              ' in domain '.$env{'request.role.domain'});  
 5734:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
 5735: 		     &escape($upass),$uhome);
 5736:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
 5737:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
 5738:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 5739:     &log($udom,,$uname,$uhome,
 5740:         'Authentication changed by '.$env{'user.domain'}.', '.
 5741:                                      $env{'user.name'}.', '.$umode.
 5742:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
 5743:     unless ($reply eq 'ok') {
 5744:         &logthis('Authentication mode error: '.$reply);
 5745: 	return 'error: '.$reply;
 5746:     }   
 5747:     return 'ok';
 5748: }
 5749: 
 5750: # --------------------------------------------------------------- Modify a user
 5751: 
 5752: sub modifyuser {
 5753:     my ($udom,    $uname, $uid,
 5754:         $umode,   $upass, $first,
 5755:         $middle,  $last,  $gene,
 5756:         $forceid, $desiredhome, $email, $inststatus)=@_;
 5757:     $udom= &LONCAPA::clean_domain($udom);
 5758:     $uname=&LONCAPA::clean_username($uname);
 5759:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
 5760:              $umode.', '.$first.', '.$middle.', '.
 5761: 	     $last.', '.$gene.'(forceid: '.$forceid.')'.
 5762:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
 5763:                                      ' desiredhome not specified'). 
 5764:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
 5765:              ' in domain '.$env{'request.role.domain'});
 5766:     my $uhome=&homeserver($uname,$udom,'true');
 5767: # ----------------------------------------------------------------- Create User
 5768:     if (($uhome eq 'no_host') && 
 5769: 	(($umode && $upass) || ($umode eq 'localauth'))) {
 5770:         my $unhome='';
 5771:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
 5772:             $unhome = $desiredhome;
 5773: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
 5774: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
 5775:         } else { # load balancing routine for determining $unhome
 5776:             my $loadm=10000000;
 5777: 	    my %servers = &get_servers($udom,'library');
 5778: 	    foreach my $tryserver (keys(%servers)) {
 5779: 		my $answer=reply('load',$tryserver);
 5780: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
 5781: 		    $loadm=$answer;
 5782: 		    $unhome=$tryserver;
 5783: 		}
 5784: 	    }
 5785:         }
 5786:         if (($unhome eq '') || ($unhome eq 'no_host')) {
 5787: 	    return 'error: unable to find a home server for '.$uname.
 5788:                    ' in domain '.$udom;
 5789:         }
 5790:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
 5791:                          &escape($upass),$unhome);
 5792: 	unless ($reply eq 'ok') {
 5793:             return 'error: '.$reply;
 5794:         }   
 5795:         $uhome=&homeserver($uname,$udom,'true');
 5796:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
 5797: 	    return 'error: unable verify users home machine.';
 5798:         }
 5799:     }   # End of creation of new user
 5800: # ---------------------------------------------------------------------- Add ID
 5801:     if ($uid) {
 5802:        $uid=~tr/A-Z/a-z/;
 5803:        my %uidhash=&idrget($udom,$uname);
 5804:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
 5805:          && (!$forceid)) {
 5806: 	  unless ($uid eq $uidhash{$uname}) {
 5807: 	      return 'error: user id "'.$uid.'" does not match '.
 5808:                   'current user id "'.$uidhash{$uname}.'".';
 5809:           }
 5810:        } else {
 5811: 	  &idput($udom,($uname => $uid));
 5812:        }
 5813:     }
 5814: # -------------------------------------------------------------- Add names, etc
 5815:     my @tmp=&get('environment',
 5816: 		   ['firstname','middlename','lastname','generation','id',
 5817:                     'permanentemail','inststatus'],
 5818: 		   $udom,$uname);
 5819:     my %names;
 5820:     if ($tmp[0] =~ m/^error:.*/) { 
 5821:         %names=(); 
 5822:     } else {
 5823:         %names = @tmp;
 5824:     }
 5825: #
 5826: # Make sure to not trash student environment if instructor does not bother
 5827: # to supply name and email information
 5828: #
 5829:     if ($first)  { $names{'firstname'}  = $first; }
 5830:     if (defined($middle)) { $names{'middlename'} = $middle; }
 5831:     if ($last)   { $names{'lastname'}   = $last; }
 5832:     if (defined($gene))   { $names{'generation'} = $gene; }
 5833:     if ($email) {
 5834:        $email=~s/[^\w\@\.\-\,]//gs;
 5835:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
 5836:     }
 5837:     if ($uid) { $names{'id'}  = $uid; }
 5838:     if (defined($inststatus)) { $names{'inststatus'} = $inststatus; } 
 5839:     my $reply = &put('environment', \%names, $udom,$uname);
 5840:     if ($reply ne 'ok') { return 'error: '.$reply; }
 5841:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
 5842:     &devalidate_cache_new('namescache',$uname.':'.$udom);
 5843:     my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
 5844:                  $umode.', '.$first.', '.$middle.', '.
 5845: 	         $last.', '.$gene.', '.$email.', '.$inststatus;
 5846:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
 5847:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
 5848:     } else {
 5849:         $logmsg .= ' during self creation';
 5850:     }
 5851:     &logthis($logmsg);
 5852:     return 'ok';
 5853: }
 5854: 
 5855: # -------------------------------------------------------------- Modify student
 5856: 
 5857: sub modifystudent {
 5858:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
 5859:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
 5860:         $selfenroll,$context)=@_;
 5861:     if (!$cid) {
 5862: 	unless ($cid=$env{'request.course.id'}) {
 5863: 	    return 'not_in_class';
 5864: 	}
 5865:     }
 5866: # --------------------------------------------------------------- Make the user
 5867:     my $reply=&modifyuser
 5868: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
 5869:          $desiredhome,$email);
 5870:     unless ($reply eq 'ok') { return $reply; }
 5871:     # This will cause &modify_student_enrollment to get the uid from the
 5872:     # students environment
 5873:     $uid = undef if (!$forceid);
 5874:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
 5875: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
 5876:     return $reply;
 5877: }
 5878: 
 5879: sub modify_student_enrollment {
 5880:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
 5881:     my ($cdom,$cnum,$chome);
 5882:     if (!$cid) {
 5883: 	unless ($cid=$env{'request.course.id'}) {
 5884: 	    return 'not_in_class';
 5885: 	}
 5886: 	$cdom=$env{'course.'.$cid.'.domain'};
 5887: 	$cnum=$env{'course.'.$cid.'.num'};
 5888:     } else {
 5889: 	($cdom,$cnum)=split(/_/,$cid);
 5890:     }
 5891:     $chome=$env{'course.'.$cid.'.home'};
 5892:     if (!$chome) {
 5893: 	$chome=&homeserver($cnum,$cdom);
 5894:     }
 5895:     if (!$chome) { return 'unknown_course'; }
 5896:     # Make sure the user exists
 5897:     my $uhome=&homeserver($uname,$udom);
 5898:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 5899: 	return 'error: no such user';
 5900:     }
 5901:     # Get student data if we were not given enough information
 5902:     if (!defined($first)  || $first  eq '' || 
 5903:         !defined($last)   || $last   eq '' || 
 5904:         !defined($uid)    || $uid    eq '' || 
 5905:         !defined($middle) || $middle eq '' || 
 5906:         !defined($gene)   || $gene   eq '') {
 5907:         # They did not supply us with enough data to enroll the student, so
 5908:         # we need to pick up more information.
 5909:         my %tmp = &get('environment',
 5910:                        ['firstname','middlename','lastname', 'generation','id']
 5911:                        ,$udom,$uname);
 5912: 
 5913:         #foreach my $key (keys(%tmp)) {
 5914:         #    &logthis("key $key = ".$tmp{$key});
 5915:         #}
 5916:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
 5917:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
 5918:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
 5919:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
 5920:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
 5921:     }
 5922:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
 5923:     my $reply=cput('classlist',
 5924: 		   {"$uname:$udom" => 
 5925: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
 5926: 		   $cdom,$cnum);
 5927:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
 5928: 	return 'error: '.$reply;
 5929:     } else {
 5930: 	&devalidate_getsection_cache($udom,$uname,$cid);
 5931:     }
 5932:     # Add student role to user
 5933:     my $uurl='/'.$cid;
 5934:     $uurl=~s/\_/\//g;
 5935:     if ($usec) {
 5936: 	$uurl.='/'.$usec;
 5937:     }
 5938:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
 5939: }
 5940: 
 5941: sub format_name {
 5942:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
 5943:     my $name;
 5944:     if ($first ne 'lastname') {
 5945: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
 5946:     } else {
 5947: 	if ($lastname=~/\S/) {
 5948: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
 5949: 	    $name=~s/\s+,/,/;
 5950: 	} else {
 5951: 	    $name.= $firstname.' '.$middlename.' '.$generation;
 5952: 	}
 5953:     }
 5954:     $name=~s/^\s+//;
 5955:     $name=~s/\s+$//;
 5956:     $name=~s/\s+/ /g;
 5957:     return $name;
 5958: }
 5959: 
 5960: # ------------------------------------------------- Write to course preferences
 5961: 
 5962: sub writecoursepref {
 5963:     my ($courseid,%prefs)=@_;
 5964:     $courseid=~s/^\///;
 5965:     $courseid=~s/\_/\//g;
 5966:     my ($cdomain,$cnum)=split(/\//,$courseid);
 5967:     my $chome=homeserver($cnum,$cdomain);
 5968:     if (($chome eq '') || ($chome eq 'no_host')) { 
 5969: 	return 'error: no such course';
 5970:     }
 5971:     my $cstring='';
 5972:     foreach my $pref (keys(%prefs)) {
 5973: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
 5974:     }
 5975:     $cstring=~s/\&$//;
 5976:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
 5977: }
 5978: 
 5979: # ---------------------------------------------------------- Make/modify course
 5980: 
 5981: sub createcourse {
 5982:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
 5983:         $course_owner,$crstype)=@_;
 5984:     $url=&declutter($url);
 5985:     my $cid='';
 5986:     unless (&allowed('ccc',$udom)) {
 5987:         return 'refused';
 5988:     }
 5989: # ------------------------------------------------------------------- Create ID
 5990:    my $uname=int(1+rand(9)).
 5991:        ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
 5992:        substr($$.time,0,5).unpack("H8",pack("I32",time)).
 5993:        unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 5994: # ----------------------------------------------- Make sure that does not exist
 5995:    my $uhome=&homeserver($uname,$udom,'true');
 5996:    unless (($uhome eq '') || ($uhome eq 'no_host')) {
 5997:        $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
 5998:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
 5999:        $uhome=&homeserver($uname,$udom,'true');       
 6000:        unless (($uhome eq '') || ($uhome eq 'no_host')) {
 6001:            return 'error: unable to generate unique course-ID';
 6002:        } 
 6003:    }
 6004: # ------------------------------------------------ Check supplied server name
 6005:     $course_server = $env{'user.homeserver'} if (! defined($course_server));
 6006:     if (! &is_library($course_server)) {
 6007:         return 'error:bad server name '.$course_server;
 6008:     }
 6009: # ------------------------------------------------------------- Make the course
 6010:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
 6011:                       $course_server);
 6012:     unless ($reply eq 'ok') { return 'error: '.$reply; }
 6013:     $uhome=&homeserver($uname,$udom,'true');
 6014:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
 6015: 	return 'error: no such course';
 6016:     }
 6017: # ----------------------------------------------------------------- Course made
 6018: # log existence
 6019:     my $newcourse = {
 6020:                     $udom.'_'.$uname => {
 6021:                                      description => $description,
 6022:                                      inst_code   => $inst_code,
 6023:                                      owner       => $course_owner,
 6024:                                      type        => $crstype,
 6025:                                                 },
 6026:                     };
 6027:     &courseidput($udom,$newcourse,$uhome,'notime');
 6028: # set toplevel url
 6029:     my $topurl=$url;
 6030:     unless ($nonstandard) {
 6031: # ------------------------------------------ For standard courses, make top url
 6032:         my $mapurl=&clutter($url);
 6033:         if ($mapurl eq '/res/') { $mapurl=''; }
 6034:         $env{'form.initmap'}=(<<ENDINITMAP);
 6035: <map>
 6036: <resource id="1" type="start"></resource>
 6037: <resource id="2" src="$mapurl"></resource>
 6038: <resource id="3" type="finish"></resource>
 6039: <link index="1" from="1" to="2"></link>
 6040: <link index="2" from="2" to="3"></link>
 6041: </map>
 6042: ENDINITMAP
 6043:         $topurl=&declutter(
 6044:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
 6045:                           );
 6046:     }
 6047: # ----------------------------------------------------------- Write preferences
 6048:     &writecoursepref($udom.'_'.$uname,
 6049:                      ('description' => $description,
 6050:                       'url'         => $topurl));
 6051:     return '/'.$udom.'/'.$uname;
 6052: }
 6053: 
 6054: sub is_course {
 6055:     my ($cdom,$cnum) = @_;
 6056:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
 6057: 				undef,'.');
 6058:     if (exists($courses{$cdom.'_'.$cnum})) {
 6059:         return 1;
 6060:     }
 6061:     return 0;
 6062: }
 6063: 
 6064: # ---------------------------------------------------------- Assign Custom Role
 6065: 
 6066: sub assigncustomrole {
 6067:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
 6068:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
 6069:                        $end,$start,$deleteflag,$selfenroll,$context);
 6070: }
 6071: 
 6072: # ----------------------------------------------------------------- Revoke Role
 6073: 
 6074: sub revokerole {
 6075:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
 6076:     my $now=time;
 6077:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
 6078: }
 6079: 
 6080: # ---------------------------------------------------------- Revoke Custom Role
 6081: 
 6082: sub revokecustomrole {
 6083:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
 6084:     my $now=time;
 6085:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
 6086:            $deleteflag,$selfenroll,$context);
 6087: }
 6088: 
 6089: # ------------------------------------------------------------ Disk usage
 6090: sub diskusage {
 6091:     my ($udom,$uname,$directorypath,$getpropath)=@_;
 6092:     $directorypath =~ s/\/$//;
 6093:     my $listing=&reply('du2:'.&escape($directorypath).':'
 6094:                        .&escape($getpropath).':'.&escape($uname).':'
 6095:                        .&escape($udom),homeserver($uname,$udom));
 6096:     if ($listing eq 'unknown_cmd') {
 6097:         if ($getpropath) {
 6098:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
 6099:         }
 6100:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
 6101:     }
 6102:     return $listing;
 6103: }
 6104: 
 6105: sub is_locked {
 6106:     my ($file_name, $domain, $user) = @_;
 6107:     my @check;
 6108:     my $is_locked;
 6109:     push @check, $file_name;
 6110:     my %locked = &get('file_permissions',\@check,
 6111: 		      $env{'user.domain'},$env{'user.name'});
 6112:     my ($tmp)=keys(%locked);
 6113:     if ($tmp=~/^error:/) { undef(%locked); }
 6114:     
 6115:     if (ref($locked{$file_name}) eq 'ARRAY') {
 6116:         $is_locked = 'false';
 6117:         foreach my $entry (@{$locked{$file_name}}) {
 6118:            if (ref($entry) eq 'ARRAY') { 
 6119:                $is_locked = 'true';
 6120:                last;
 6121:            }
 6122:        }
 6123:     } else {
 6124:         $is_locked = 'false';
 6125:     }
 6126: }
 6127: 
 6128: sub declutter_portfile {
 6129:     my ($file) = @_;
 6130:     $file =~ s{^(/portfolio/|portfolio/)}{/};
 6131:     return $file;
 6132: }
 6133: 
 6134: # ------------------------------------------------------------- Mark as Read Only
 6135: 
 6136: sub mark_as_readonly {
 6137:     my ($domain,$user,$files,$what) = @_;
 6138:     my %current_permissions = &dump('file_permissions',$domain,$user);
 6139:     my ($tmp)=keys(%current_permissions);
 6140:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6141:     foreach my $file (@{$files}) {
 6142: 	$file = &declutter_portfile($file);
 6143:         push(@{$current_permissions{$file}},$what);
 6144:     }
 6145:     &put('file_permissions',\%current_permissions,$domain,$user);
 6146:     return;
 6147: }
 6148: 
 6149: # ------------------------------------------------------------Save Selected Files
 6150: 
 6151: sub save_selected_files {
 6152:     my ($user, $path, @files) = @_;
 6153:     my $filename = $user."savedfiles";
 6154:     my @other_files = &files_not_in_path($user, $path);
 6155:     open (OUT, '>'.$tmpdir.$filename);
 6156:     foreach my $file (@files) {
 6157:         print (OUT $env{'form.currentpath'}.$file."\n");
 6158:     }
 6159:     foreach my $file (@other_files) {
 6160:         print (OUT $file."\n");
 6161:     }
 6162:     close (OUT);
 6163:     return 'ok';
 6164: }
 6165: 
 6166: sub clear_selected_files {
 6167:     my ($user) = @_;
 6168:     my $filename = $user."savedfiles";
 6169:     open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6170:     print (OUT undef);
 6171:     close (OUT);
 6172:     return ("ok");    
 6173: }
 6174: 
 6175: sub files_in_path {
 6176:     my ($user, $path) = @_;
 6177:     my $filename = $user."savedfiles";
 6178:     my %return_files;
 6179:     open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6180:     while (my $line_in = <IN>) {
 6181:         chomp ($line_in);
 6182:         my @paths_and_file = split (m!/!, $line_in);
 6183:         my $file_part = pop (@paths_and_file);
 6184:         my $path_part = join ('/', @paths_and_file);
 6185:         $path_part.='/';
 6186:         my $path_and_file = $path_part.$file_part;
 6187:         if ($path_part eq $path) {
 6188:             $return_files{$file_part}= 'selected';
 6189:         }
 6190:     }
 6191:     close (IN);
 6192:     return (\%return_files);
 6193: }
 6194: 
 6195: # called in portfolio select mode, to show files selected NOT in current directory
 6196: sub files_not_in_path {
 6197:     my ($user, $path) = @_;
 6198:     my $filename = $user."savedfiles";
 6199:     my @return_files;
 6200:     my $path_part;
 6201:     open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
 6202:     while (my $line = <IN>) {
 6203:         #ok, I know it's clunky, but I want it to work
 6204:         my @paths_and_file = split(m|/|, $line);
 6205:         my $file_part = pop(@paths_and_file);
 6206:         chomp($file_part);
 6207:         my $path_part = join('/', @paths_and_file);
 6208:         $path_part .= '/';
 6209:         my $path_and_file = $path_part.$file_part;
 6210:         if ($path_part ne $path) {
 6211:             push(@return_files, ($path_and_file));
 6212:         }
 6213:     }
 6214:     close(OUT);
 6215:     return (@return_files);
 6216: }
 6217: 
 6218: #----------------------------------------------Get portfolio file permissions
 6219: 
 6220: sub get_portfile_permissions {
 6221:     my ($domain,$user) = @_;
 6222:     my %current_permissions = &dump('file_permissions',$domain,$user);
 6223:     my ($tmp)=keys(%current_permissions);
 6224:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6225:     return \%current_permissions;
 6226: }
 6227: 
 6228: #---------------------------------------------Get portfolio file access controls
 6229: 
 6230: sub get_access_controls {
 6231:     my ($current_permissions,$group,$file) = @_;
 6232:     my %access;
 6233:     my $real_file = $file;
 6234:     $file =~ s/\.meta$//;
 6235:     if (defined($file)) {
 6236:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
 6237:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
 6238:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
 6239:             }
 6240:         }
 6241:     } else {
 6242:         foreach my $key (keys(%{$current_permissions})) {
 6243:             if ($key =~ /\0accesscontrol$/) {
 6244:                 if (defined($group)) {
 6245:                     if ($key !~ m-^\Q$group\E/-) {
 6246:                         next;
 6247:                     }
 6248:                 }
 6249:                 my ($fullpath) = split(/\0/,$key);
 6250:                 if (ref($$current_permissions{$key}) eq 'HASH') {
 6251:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
 6252:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
 6253:                     }
 6254:                 }
 6255:             }
 6256:         }
 6257:     }
 6258:     return %access;
 6259: }
 6260: 
 6261: sub modify_access_controls {
 6262:     my ($file_name,$changes,$domain,$user)=@_;
 6263:     my ($outcome,$deloutcome);
 6264:     my %store_permissions;
 6265:     my %new_values;
 6266:     my %new_control;
 6267:     my %translation;
 6268:     my @deletions = ();
 6269:     my $now = time;
 6270:     if (exists($$changes{'activate'})) {
 6271:         if (ref($$changes{'activate'}) eq 'HASH') {
 6272:             my @newitems = sort(keys(%{$$changes{'activate'}}));
 6273:             my $numnew = scalar(@newitems);
 6274:             for (my $i=0; $i<$numnew; $i++) {
 6275:                 my $newkey = $newitems[$i];
 6276:                 my $newid = &Apache::loncommon::get_cgi_id();
 6277:                 if ($newkey =~ /^\d+:/) { 
 6278:                     $newkey =~ s/^(\d+)/$newid/;
 6279:                     $translation{$1} = $newid;
 6280:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
 6281:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
 6282:                     $translation{$1} = $newid;
 6283:                 }
 6284:                 $new_values{$file_name."\0".$newkey} = 
 6285:                                           $$changes{'activate'}{$newitems[$i]};
 6286:                 $new_control{$newkey} = $now;
 6287:             }
 6288:         }
 6289:     }
 6290:     my %todelete;
 6291:     my %changed_items;
 6292:     foreach my $action ('delete','update') {
 6293:         if (exists($$changes{$action})) {
 6294:             if (ref($$changes{$action}) eq 'HASH') {
 6295:                 foreach my $key (keys(%{$$changes{$action}})) {
 6296:                     my ($itemnum) = ($key =~ /^([^:]+):/);
 6297:                     if ($action eq 'delete') { 
 6298:                         $todelete{$itemnum} = 1;
 6299:                     } else {
 6300:                         $changed_items{$itemnum} = $key;
 6301:                     }
 6302:                 }
 6303:             }
 6304:         }
 6305:     }
 6306:     # get lock on access controls for file.
 6307:     my $lockhash = {
 6308:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
 6309:                                                        ':'.$env{'user.domain'},
 6310:                    }; 
 6311:     my $tries = 0;
 6312:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 6313:    
 6314:     while (($gotlock ne 'ok') && $tries <3) {
 6315:         $tries ++;
 6316:         sleep 1;
 6317:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
 6318:     }
 6319:     if ($gotlock eq 'ok') {
 6320:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
 6321:         my ($tmp)=keys(%curr_permissions);
 6322:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
 6323:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
 6324:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
 6325:             if (ref($curr_controls) eq 'HASH') {
 6326:                 foreach my $control_item (keys(%{$curr_controls})) {
 6327:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
 6328:                     if (defined($todelete{$itemnum})) {
 6329:                         push(@deletions,$file_name."\0".$control_item);
 6330:                     } else {
 6331:                         if (defined($changed_items{$itemnum})) {
 6332:                             $new_control{$changed_items{$itemnum}} = $now;
 6333:                             push(@deletions,$file_name."\0".$control_item);
 6334:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
 6335:                         } else {
 6336:                             $new_control{$control_item} = $$curr_controls{$control_item};
 6337:                         }
 6338:                     }
 6339:                 }
 6340:             }
 6341:         }
 6342:         my ($group);
 6343:         if (&is_course($domain,$user)) {
 6344:             ($group,my $file) = split(/\//,$file_name,2);
 6345:         }
 6346:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
 6347:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
 6348:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
 6349:         #  remove lock
 6350:         my @del_lock = ($file_name."\0".'locked_access_records');
 6351:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
 6352:         my $sqlresult =
 6353:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
 6354:                                     $group);
 6355:     } else {
 6356:         $outcome = "error: could not obtain lockfile\n";  
 6357:     }
 6358:     return ($outcome,$deloutcome,\%new_values,\%translation);
 6359: }
 6360: 
 6361: sub make_public_indefinitely {
 6362:     my ($requrl) = @_;
 6363:     my $now = time;
 6364:     my $action = 'activate';
 6365:     my $aclnum = 0;
 6366:     if (&is_portfolio_url($requrl)) {
 6367:         my (undef,$udom,$unum,$file_name,$group) =
 6368:             &parse_portfolio_url($requrl);
 6369:         my $current_perms = &get_portfile_permissions($udom,$unum);
 6370:         my %access_controls = &get_access_controls($current_perms,
 6371:                                                    $group,$file_name);
 6372:         foreach my $key (keys(%{$access_controls{$file_name}})) {
 6373:             my ($num,$scope,$end,$start) = 
 6374:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
 6375:             if ($scope eq 'public') {
 6376:                 if ($start <= $now && $end == 0) {
 6377:                     $action = 'none';
 6378:                 } else {
 6379:                     $action = 'update';
 6380:                     $aclnum = $num;
 6381:                 }
 6382:                 last;
 6383:             }
 6384:         }
 6385:         if ($action eq 'none') {
 6386:              return 'ok';
 6387:         } else {
 6388:             my %changes;
 6389:             my $newend = 0;
 6390:             my $newstart = $now;
 6391:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
 6392:             $changes{$action}{$newkey} = {
 6393:                 type => 'public',
 6394:                 time => {
 6395:                     start => $newstart,
 6396:                     end   => $newend,
 6397:                 },
 6398:             };
 6399:             my ($outcome,$deloutcome,$new_values,$translation) =
 6400:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
 6401:             return $outcome;
 6402:         }
 6403:     } else {
 6404:         return 'invalid';
 6405:     }
 6406: }
 6407: 
 6408: #------------------------------------------------------Get Marked as Read Only
 6409: 
 6410: sub get_marked_as_readonly {
 6411:     my ($domain,$user,$what,$group) = @_;
 6412:     my $current_permissions = &get_portfile_permissions($domain,$user);
 6413:     my @readonly_files;
 6414:     my $cmp1=$what;
 6415:     if (ref($what)) { $cmp1=join('',@{$what}) };
 6416:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 6417:         if (defined($group)) {
 6418:             if ($file_name !~ m-^\Q$group\E/-) {
 6419:                 next;
 6420:             }
 6421:         }
 6422:         if (ref($value) eq "ARRAY"){
 6423:             foreach my $stored_what (@{$value}) {
 6424:                 my $cmp2=$stored_what;
 6425:                 if (ref($stored_what) eq 'ARRAY') {
 6426:                     $cmp2=join('',@{$stored_what});
 6427:                 }
 6428:                 if ($cmp1 eq $cmp2) {
 6429:                     push(@readonly_files, $file_name);
 6430:                     last;
 6431:                 } elsif (!defined($what)) {
 6432:                     push(@readonly_files, $file_name);
 6433:                     last;
 6434:                 }
 6435:             }
 6436:         }
 6437:     }
 6438:     return @readonly_files;
 6439: }
 6440: #-----------------------------------------------------------Get Marked as Read Only Hash
 6441: 
 6442: sub get_marked_as_readonly_hash {
 6443:     my ($current_permissions,$group,$what) = @_;
 6444:     my %readonly_files;
 6445:     while (my ($file_name,$value) = each(%{$current_permissions})) {
 6446:         if (defined($group)) {
 6447:             if ($file_name !~ m-^\Q$group\E/-) {
 6448:                 next;
 6449:             }
 6450:         }
 6451:         if (ref($value) eq "ARRAY"){
 6452:             foreach my $stored_what (@{$value}) {
 6453:                 if (ref($stored_what) eq 'ARRAY') {
 6454:                     foreach my $lock_descriptor(@{$stored_what}) {
 6455:                         if ($lock_descriptor eq 'graded') {
 6456:                             $readonly_files{$file_name} = 'graded';
 6457:                         } elsif ($lock_descriptor eq 'handback') {
 6458:                             $readonly_files{$file_name} = 'handback';
 6459:                         } else {
 6460:                             if (!exists($readonly_files{$file_name})) {
 6461:                                 $readonly_files{$file_name} = 'locked';
 6462:                             }
 6463:                         }
 6464:                     }
 6465:                 } 
 6466:             }
 6467:         } 
 6468:     }
 6469:     return %readonly_files;
 6470: }
 6471: # ------------------------------------------------------------ Unmark as Read Only
 6472: 
 6473: sub unmark_as_readonly {
 6474:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
 6475:     # for portfolio submissions, $what contains [$symb,$crsid] 
 6476:     my ($domain,$user,$what,$file_name,$group) = @_;
 6477:     $file_name = &declutter_portfile($file_name);
 6478:     my $symb_crs = $what;
 6479:     if (ref($what)) { $symb_crs=join('',@$what); }
 6480:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
 6481:     my ($tmp)=keys(%current_permissions);
 6482:     if ($tmp=~/^error:/) { undef(%current_permissions); }
 6483:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
 6484:     foreach my $file (@readonly_files) {
 6485: 	my $clean_file = &declutter_portfile($file);
 6486: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
 6487: 	my $current_locks = $current_permissions{$file};
 6488:         my @new_locks;
 6489:         my @del_keys;
 6490:         if (ref($current_locks) eq "ARRAY"){
 6491:             foreach my $locker (@{$current_locks}) {
 6492:                 my $compare=$locker;
 6493:                 if (ref($locker) eq 'ARRAY') {
 6494:                     $compare=join('',@{$locker});
 6495:                     if ($compare ne $symb_crs) {
 6496:                         push(@new_locks, $locker);
 6497:                     }
 6498:                 }
 6499:             }
 6500:             if (scalar(@new_locks) > 0) {
 6501:                 $current_permissions{$file} = \@new_locks;
 6502:             } else {
 6503:                 push(@del_keys, $file);
 6504:                 &del('file_permissions',\@del_keys, $domain, $user);
 6505:                 delete($current_permissions{$file});
 6506:             }
 6507:         }
 6508:     }
 6509:     &put('file_permissions',\%current_permissions,$domain,$user);
 6510:     return;
 6511: }
 6512: 
 6513: # ------------------------------------------------------------ Directory lister
 6514: 
 6515: sub dirlist {
 6516:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
 6517:     $uri=~s/^\///;
 6518:     $uri=~s/\/$//;
 6519:     my ($udom, $uname);
 6520:     if ($getuserdir) {
 6521:         $udom = $userdomain;
 6522:         $uname = $username;
 6523:     } else {
 6524:         (undef,$udom,$uname)=split(/\//,$uri);
 6525:         if(defined($userdomain)) {
 6526:             $udom = $userdomain;
 6527:         }
 6528:         if(defined($username)) {
 6529:             $uname = $username;
 6530:         }
 6531:     }
 6532:     my ($dirRoot,$listing,@listing_results);
 6533: 
 6534:     $dirRoot = $perlvar{'lonDocRoot'};
 6535:     if (defined($getpropath)) {
 6536:         $dirRoot = &propath($udom,$uname);
 6537:         $dirRoot =~ s/\/$//;
 6538:     } elsif (defined($getuserdir)) {
 6539:         my $subdir=$uname.'__';
 6540:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
 6541:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
 6542:                    ."/$udom/$subdir/$uname";
 6543:     } elsif (defined($alternateRoot)) {
 6544:         $dirRoot = $alternateRoot;
 6545:     }
 6546: 
 6547:     if($udom) {
 6548:         if($uname) {
 6549:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
 6550:                               .$getuserdir.':'.&escape($dirRoot)
 6551:                               .':'.&escape($uname).':'.&escape($udom),
 6552:                               &homeserver($uname,$udom));
 6553:             if ($listing eq 'unknown_cmd') {
 6554:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
 6555:                                   &homeserver($uname,$udom));
 6556:             } else {
 6557:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 6558:             }
 6559:             if ($listing eq 'unknown_cmd') {
 6560:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
 6561: 				  &homeserver($uname,$udom));
 6562:                 @listing_results = split(/:/,$listing);
 6563:             } else {
 6564:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
 6565:             }
 6566:             return @listing_results;
 6567:         } elsif(!$alternateRoot) {
 6568:             my %allusers;
 6569: 	    my %servers = &get_servers($udom,'library');
 6570:  	    foreach my $tryserver (keys(%servers)) {
 6571:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
 6572:                                   &escape($udom),$tryserver);
 6573:                 if ($listing eq 'unknown_cmd') {
 6574: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
 6575: 				      $udom, $tryserver);
 6576:                 } else {
 6577:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
 6578:                 }
 6579: 		if ($listing eq 'unknown_cmd') {
 6580: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
 6581: 				      $udom, $tryserver);
 6582: 		    @listing_results = split(/:/,$listing);
 6583: 		} else {
 6584: 		    @listing_results =
 6585: 			map { &unescape($_); } split(/:/,$listing);
 6586: 		}
 6587: 		if ($listing_results[0] ne 'no_such_dir' && 
 6588: 		    $listing_results[0] ne 'empty'       &&
 6589: 		    $listing_results[0] ne 'con_lost') {
 6590: 		    foreach my $line (@listing_results) {
 6591: 			my ($entry) = split(/&/,$line,2);
 6592: 			$allusers{$entry} = 1;
 6593: 		    }
 6594: 		}
 6595:             }
 6596:             my $alluserstr='';
 6597:             foreach my $user (sort(keys(%allusers))) {
 6598:                 $alluserstr.=$user.'&user:';
 6599:             }
 6600:             $alluserstr=~s/:$//;
 6601:             return split(/:/,$alluserstr);
 6602:         } else {
 6603:             return ('missing user name');
 6604:         }
 6605:     } elsif(!defined($getpropath)) {
 6606:         my @all_domains = sort(&all_domains());
 6607:         foreach my $domain (@all_domains) {
 6608:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
 6609:         }
 6610:         return @all_domains;
 6611:     } else {
 6612:         return ('missing domain');
 6613:     }
 6614: }
 6615: 
 6616: # --------------------------------------------- GetFileTimestamp
 6617: # This function utilizes dirlist and returns the date stamp for
 6618: # when it was last modified.  It will also return an error of -1
 6619: # if an error occurs
 6620: 
 6621: sub GetFileTimestamp {
 6622:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
 6623:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
 6624:     $studentName   = &LONCAPA::clean_username($studentName);
 6625:     my ($fileStat) = 
 6626:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
 6627:                                  undef,$getuserdir);
 6628:     my @stats = split('&', $fileStat);
 6629:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 6630:         # @stats contains first the filename, then the stat output
 6631:         return $stats[10]; # so this is 10 instead of 9.
 6632:     } else {
 6633:         return -1;
 6634:     }
 6635: }
 6636: 
 6637: sub stat_file {
 6638:     my ($uri) = @_;
 6639:     $uri = &clutter_with_no_wrapper($uri);
 6640: 
 6641:     my ($udom,$uname,$file);
 6642:     if ($uri =~ m-^/(uploaded|editupload)/-) {
 6643: 	($udom,$uname,$file) =
 6644: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
 6645: 	$file = 'userfiles/'.$file;
 6646:     }
 6647:     if ($uri =~ m-^/res/-) {
 6648: 	($udom,$uname) = 
 6649: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
 6650: 	$file = $uri;
 6651:     }
 6652: 
 6653:     if (!$udom || !$uname || !$file) {
 6654: 	# unable to handle the uri
 6655: 	return ();
 6656:     }
 6657:     my $getpropath;
 6658:     if ($file =~ /^userfiles\//) {
 6659:         $getpropath = 1;
 6660:     }
 6661:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
 6662:     my @stats = split('&', $result);
 6663:     
 6664:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
 6665: 	shift(@stats); #filename is first
 6666: 	return @stats;
 6667:     }
 6668:     return ();
 6669: }
 6670: 
 6671: # -------------------------------------------------------- Value of a Condition
 6672: 
 6673: # gets the value of a specific preevaluated condition
 6674: #    stored in the string  $env{user.state.<cid>}
 6675: # or looks up a condition reference in the bighash and if if hasn't
 6676: # already been evaluated recurses into docondval to get the value of
 6677: # the condition, then memoizing it to 
 6678: #   $env{user.state.<cid>.<condition>}
 6679: sub directcondval {
 6680:     my $number=shift;
 6681:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
 6682: 	&Apache::lonuserstate::evalstate();
 6683:     }
 6684:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
 6685: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
 6686:     } elsif ($number =~ /^_/) {
 6687: 	my $sub_condition;
 6688: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 6689: 		&GDBM_READER(),0640)) {
 6690: 	    $sub_condition=$bighash{'conditions'.$number};
 6691: 	    untie(%bighash);
 6692: 	}
 6693: 	my $value = &docondval($sub_condition);
 6694: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
 6695: 	return $value;
 6696:     }
 6697:     if ($env{'user.state.'.$env{'request.course.id'}}) {
 6698:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
 6699:     } else {
 6700:        return 2;
 6701:     }
 6702: }
 6703: 
 6704: # get the collection of conditions for this resource
 6705: sub condval {
 6706:     my $condidx=shift;
 6707:     my $allpathcond='';
 6708:     foreach my $cond (split(/\|/,$condidx)) {
 6709: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
 6710: 	    $allpathcond.=
 6711: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
 6712: 	}
 6713:     }
 6714:     $allpathcond=~s/\|$//;
 6715:     return &docondval($allpathcond);
 6716: }
 6717: 
 6718: #evaluates an expression of conditions
 6719: sub docondval {
 6720:     my ($allpathcond) = @_;
 6721:     my $result=0;
 6722:     if ($env{'request.course.id'}
 6723: 	&& defined($allpathcond)) {
 6724: 	my $operand='|';
 6725: 	my @stack;
 6726: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
 6727: 	    if ($chunk eq '(') {
 6728: 		push @stack,($operand,$result);
 6729: 	    } elsif ($chunk eq ')') {
 6730: 		my $before=pop @stack;
 6731: 		if (pop @stack eq '&') {
 6732: 		    $result=$result>$before?$before:$result;
 6733: 		} else {
 6734: 		    $result=$result>$before?$result:$before;
 6735: 		}
 6736: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
 6737: 		$operand=$chunk;
 6738: 	    } else {
 6739: 		my $new=directcondval($chunk);
 6740: 		if ($operand eq '&') {
 6741: 		    $result=$result>$new?$new:$result;
 6742: 		} else {
 6743: 		    $result=$result>$new?$result:$new;
 6744: 		}
 6745: 	    }
 6746: 	}
 6747:     }
 6748:     return $result;
 6749: }
 6750: 
 6751: # ---------------------------------------------------- Devalidate courseresdata
 6752: 
 6753: sub devalidatecourseresdata {
 6754:     my ($coursenum,$coursedomain)=@_;
 6755:     my $hashid=$coursenum.':'.$coursedomain;
 6756:     &devalidate_cache_new('courseres',$hashid);
 6757: }
 6758: 
 6759: 
 6760: # --------------------------------------------------- Course Resourcedata Query
 6761: #
 6762: #  Parameters:
 6763: #      $coursenum    - Number of the course.
 6764: #      $coursedomain - Domain at which the course was created.
 6765: #  Returns:
 6766: #     A hash of the course parameters along (I think) with timestamps
 6767: #     and version info.
 6768: 
 6769: sub get_courseresdata {
 6770:     my ($coursenum,$coursedomain)=@_;
 6771:     my $coursehom=&homeserver($coursenum,$coursedomain);
 6772:     my $hashid=$coursenum.':'.$coursedomain;
 6773:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
 6774:     my %dumpreply;
 6775:     unless (defined($cached)) {
 6776: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
 6777: 	$result=\%dumpreply;
 6778: 	my ($tmp) = keys(%dumpreply);
 6779: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
 6780: 	    &do_cache_new('courseres',$hashid,$result,600);
 6781: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
 6782: 	    return $tmp;
 6783: 	} elsif ($tmp =~ /^(error)/) {
 6784: 	    $result=undef;
 6785: 	    &do_cache_new('courseres',$hashid,$result,600);
 6786: 	}
 6787:     }
 6788:     return $result;
 6789: }
 6790: 
 6791: sub devalidateuserresdata {
 6792:     my ($uname,$udom)=@_;
 6793:     my $hashid="$udom:$uname";
 6794:     &devalidate_cache_new('userres',$hashid);
 6795: }
 6796: 
 6797: sub get_userresdata {
 6798:     my ($uname,$udom)=@_;
 6799:     #most student don\'t have any data set, check if there is some data
 6800:     if (&EXT_cache_status($udom,$uname)) { return undef; }
 6801: 
 6802:     my $hashid="$udom:$uname";
 6803:     my ($result,$cached)=&is_cached_new('userres',$hashid);
 6804:     if (!defined($cached)) {
 6805: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
 6806: 	$result=\%resourcedata;
 6807: 	&do_cache_new('userres',$hashid,$result,600);
 6808:     }
 6809:     my ($tmp)=keys(%$result);
 6810:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
 6811: 	return $result;
 6812:     }
 6813:     #error 2 occurs when the .db doesn't exist
 6814:     if ($tmp!~/error: 2 /) {
 6815: 	&logthis("<font color=\"blue\">WARNING:".
 6816: 		 " Trying to get resource data for ".
 6817: 		 $uname." at ".$udom.": ".
 6818: 		 $tmp."</font>");
 6819:     } elsif ($tmp=~/error: 2 /) {
 6820: 	#&EXT_cache_set($udom,$uname);
 6821: 	&do_cache_new('userres',$hashid,undef,600);
 6822: 	undef($tmp); # not really an error so don't send it back
 6823:     }
 6824:     return $tmp;
 6825: }
 6826: #----------------------------------------------- resdata - return resource data
 6827: #  Purpose:
 6828: #    Return resource data for either users or for a course.
 6829: #  Parameters:
 6830: #     $name      - Course/user name.
 6831: #     $domain    - Name of the domain the user/course is registered on.
 6832: #     $type      - Type of thing $name is (must be 'course' or 'user'
 6833: #     @which     - Array of names of resources desired.
 6834: #  Returns:
 6835: #     The value of the first reasource in @which that is found in the
 6836: #     resource hash.
 6837: #  Exceptional Conditions:
 6838: #     If the $type passed in is not valid (not the string 'course' or 
 6839: #     'user', an undefined  reference is returned.
 6840: #     If none of the resources are found, an undef is returned
 6841: sub resdata {
 6842:     my ($name,$domain,$type,@which)=@_;
 6843:     my $result;
 6844:     if ($type eq 'course') {
 6845: 	$result=&get_courseresdata($name,$domain);
 6846:     } elsif ($type eq 'user') {
 6847: 	$result=&get_userresdata($name,$domain);
 6848:     }
 6849:     if (!ref($result)) { return $result; }    
 6850:     foreach my $item (@which) {
 6851: 	if (defined($result->{$item->[0]})) {
 6852: 	    return [$result->{$item->[0]},$item->[1]];
 6853: 	}
 6854:     }
 6855:     return undef;
 6856: }
 6857: 
 6858: #
 6859: # EXT resource caching routines
 6860: #
 6861: 
 6862: sub clear_EXT_cache_status {
 6863:     &delenv('cache.EXT.');
 6864: }
 6865: 
 6866: sub EXT_cache_status {
 6867:     my ($target_domain,$target_user) = @_;
 6868:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 6869:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
 6870:         # We know already the user has no data
 6871:         return 1;
 6872:     } else {
 6873:         return 0;
 6874:     }
 6875: }
 6876: 
 6877: sub EXT_cache_set {
 6878:     my ($target_domain,$target_user) = @_;
 6879:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
 6880:     #&appenv({$cachename => time});
 6881: }
 6882: 
 6883: # --------------------------------------------------------- Value of a Variable
 6884: sub EXT {
 6885: 
 6886:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
 6887:     unless ($varname) { return ''; }
 6888:     #get real user name/domain, courseid and symb
 6889:     my $courseid;
 6890:     my $publicuser;
 6891:     if ($symbparm) {
 6892: 	$symbparm=&get_symb_from_alias($symbparm);
 6893:     }
 6894:     if (!($uname && $udom)) {
 6895:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
 6896:       if (!$symbparm) {	$symbparm=$cursymb; }
 6897:     } else {
 6898: 	$courseid=$env{'request.course.id'};
 6899:     }
 6900:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
 6901:     my $rest;
 6902:     if (defined($therest[0])) {
 6903:        $rest=join('.',@therest);
 6904:     } else {
 6905:        $rest='';
 6906:     }
 6907: 
 6908:     my $qualifierrest=$qualifier;
 6909:     if ($rest) { $qualifierrest.='.'.$rest; }
 6910:     my $spacequalifierrest=$space;
 6911:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
 6912:     if ($realm eq 'user') {
 6913: # --------------------------------------------------------------- user.resource
 6914: 	if ($space eq 'resource') {
 6915: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
 6916: 		  || defined($Apache::lonhomework::parsing_a_task))
 6917: 		 &&
 6918: 		 ($symbparm eq &symbread()) ) {	
 6919: 		# if we are in the middle of processing the resource the
 6920: 		# get the value we are planning on committing
 6921:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
 6922:                     return $Apache::lonhomework::results{$qualifierrest};
 6923:                 } else {
 6924:                     return $Apache::lonhomework::history{$qualifierrest};
 6925:                 }
 6926: 	    } else {
 6927: 		my %restored;
 6928: 		if ($publicuser || $env{'request.state'} eq 'construct') {
 6929: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
 6930: 		} else {
 6931: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
 6932: 		}
 6933: 		return $restored{$qualifierrest};
 6934: 	    }
 6935: # ----------------------------------------------------------------- user.access
 6936:         } elsif ($space eq 'access') {
 6937: 	    # FIXME - not supporting calls for a specific user
 6938:             return &allowed($qualifier,$rest);
 6939: # ------------------------------------------ user.preferences, user.environment
 6940:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
 6941: 	    if (($uname eq $env{'user.name'}) &&
 6942: 		($udom eq $env{'user.domain'})) {
 6943: 		return $env{join('.',('environment',$qualifierrest))};
 6944: 	    } else {
 6945: 		my %returnhash;
 6946: 		if (!$publicuser) {
 6947: 		    %returnhash=&userenvironment($udom,$uname,
 6948: 						 $qualifierrest);
 6949: 		}
 6950: 		return $returnhash{$qualifierrest};
 6951: 	    }
 6952: # ----------------------------------------------------------------- user.course
 6953:         } elsif ($space eq 'course') {
 6954: 	    # FIXME - not supporting calls for a specific user
 6955:             return $env{join('.',('request.course',$qualifier))};
 6956: # ------------------------------------------------------------------- user.role
 6957:         } elsif ($space eq 'role') {
 6958: 	    # FIXME - not supporting calls for a specific user
 6959:             my ($role,$where)=split(/\./,$env{'request.role'});
 6960:             if ($qualifier eq 'value') {
 6961: 		return $role;
 6962:             } elsif ($qualifier eq 'extent') {
 6963:                 return $where;
 6964:             }
 6965: # ----------------------------------------------------------------- user.domain
 6966:         } elsif ($space eq 'domain') {
 6967:             return $udom;
 6968: # ------------------------------------------------------------------- user.name
 6969:         } elsif ($space eq 'name') {
 6970:             return $uname;
 6971: # ---------------------------------------------------- Any other user namespace
 6972:         } else {
 6973: 	    my %reply;
 6974: 	    if (!$publicuser) {
 6975: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
 6976: 	    }
 6977: 	    return $reply{$qualifierrest};
 6978:         }
 6979:     } elsif ($realm eq 'query') {
 6980: # ---------------------------------------------- pull stuff out of query string
 6981:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
 6982: 						[$spacequalifierrest]);
 6983: 	return $env{'form.'.$spacequalifierrest}; 
 6984:    } elsif ($realm eq 'request') {
 6985: # ------------------------------------------------------------- request.browser
 6986:         if ($space eq 'browser') {
 6987: 	    if ($qualifier eq 'textremote') {
 6988: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
 6989: 		    return 1;
 6990: 		} else {
 6991: 		    return 0;
 6992: 		}
 6993: 	    } else {
 6994: 		return $env{'browser.'.$qualifier};
 6995: 	    }
 6996: # ------------------------------------------------------------ request.filename
 6997:         } else {
 6998:             return $env{'request.'.$spacequalifierrest};
 6999:         }
 7000:     } elsif ($realm eq 'course') {
 7001: # ---------------------------------------------------------- course.description
 7002:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
 7003:     } elsif ($realm eq 'resource') {
 7004: 
 7005: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
 7006: 	    if (!$symbparm) { $symbparm=&symbread(); }
 7007: 	}
 7008: 
 7009: 	if ($space eq 'title') {
 7010: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
 7011: 	    return &gettitle($symbparm);
 7012: 	}
 7013: 	
 7014: 	if ($space eq 'map') {
 7015: 	    my ($map) = &decode_symb($symbparm);
 7016: 	    return &symbread($map);
 7017: 	}
 7018: 	if ($space eq 'filename') {
 7019: 	    if ($symbparm) {
 7020: 		return &clutter((&decode_symb($symbparm))[2]);
 7021: 	    }
 7022: 	    return &hreflocation('',$env{'request.filename'});
 7023: 	}
 7024: 
 7025: 	my ($section, $group, @groups);
 7026: 	my ($courselevelm,$courselevel);
 7027: 	if ($symbparm && defined($courseid) && 
 7028: 	    $courseid eq $env{'request.course.id'}) {
 7029: 
 7030: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
 7031: 
 7032: # ----------------------------------------------------- Cascading lookup scheme
 7033: 	    my $symbp=$symbparm;
 7034: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
 7035: 
 7036: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
 7037: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
 7038: 
 7039: 	    if (($env{'user.name'} eq $uname) &&
 7040: 		($env{'user.domain'} eq $udom)) {
 7041: 		$section=$env{'request.course.sec'};
 7042:                 @groups = split(/:/,$env{'request.course.groups'});  
 7043:                 @groups=&sort_course_groups($courseid,@groups); 
 7044: 	    } else {
 7045: 		if (! defined($usection)) {
 7046: 		    $section=&getsection($udom,$uname,$courseid);
 7047: 		} else {
 7048: 		    $section = $usection;
 7049: 		}
 7050:                 @groups = &get_users_groups($udom,$uname,$courseid);
 7051: 	    }
 7052: 
 7053: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
 7054: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
 7055: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
 7056: 
 7057: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
 7058: 	    my $courselevelr=$courseid.'.'.$symbparm;
 7059: 	    $courselevelm=$courseid.'.'.$mapparm;
 7060: 
 7061: # ----------------------------------------------------------- first, check user
 7062: 
 7063: 	    my $userreply=&resdata($uname,$udom,'user',
 7064: 				       ([$courselevelr,'resource'],
 7065: 					[$courselevelm,'map'     ],
 7066: 					[$courselevel, 'course'  ]));
 7067: 	    if (defined($userreply)) { return &get_reply($userreply); }
 7068: 
 7069: # ------------------------------------------------ second, check some of course
 7070:             my $coursereply;
 7071:             if (@groups > 0) {
 7072:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
 7073:                                        $mapparm,$spacequalifierrest);
 7074:                 if (defined($coursereply)) { return &get_reply($coursereply); }
 7075:             }
 7076: 
 7077: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 7078: 				  $env{'course.'.$courseid.'.domain'},
 7079: 				  'course',
 7080: 				  ([$seclevelr,   'resource'],
 7081: 				   [$seclevelm,   'map'     ],
 7082: 				   [$seclevel,    'course'  ],
 7083: 				   [$courselevelr,'resource']));
 7084: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 7085: 
 7086: # ------------------------------------------------------ third, check map parms
 7087: 	    my %parmhash=();
 7088: 	    my $thisparm='';
 7089: 	    if (tie(%parmhash,'GDBM_File',
 7090: 		    $env{'request.course.fn'}.'_parms.db',
 7091: 		    &GDBM_READER(),0640)) {
 7092: 		$thisparm=$parmhash{$symbparm};
 7093: 		untie(%parmhash);
 7094: 	    }
 7095: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
 7096: 	}
 7097: # ------------------------------------------ fourth, look in resource metadata
 7098: 
 7099: 	$spacequalifierrest=~s/\./\_/;
 7100: 	my $filename;
 7101: 	if (!$symbparm) { $symbparm=&symbread(); }
 7102: 	if ($symbparm) {
 7103: 	    $filename=(&decode_symb($symbparm))[2];
 7104: 	} else {
 7105: 	    $filename=$env{'request.filename'};
 7106: 	}
 7107: 	my $metadata=&metadata($filename,$spacequalifierrest);
 7108: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 7109: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
 7110: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
 7111: 
 7112: # ---------------------------------------------- fourth, look in rest of course
 7113: 	if ($symbparm && defined($courseid) && 
 7114: 	    $courseid eq $env{'request.course.id'}) {
 7115: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
 7116: 				     $env{'course.'.$courseid.'.domain'},
 7117: 				     'course',
 7118: 				     ([$courselevelm,'map'   ],
 7119: 				      [$courselevel, 'course']));
 7120: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
 7121: 	}
 7122: # ------------------------------------------------------------------ Cascade up
 7123: 	unless ($space eq '0') {
 7124: 	    my @parts=split(/_/,$space);
 7125: 	    my $id=pop(@parts);
 7126: 	    my $part=join('_',@parts);
 7127: 	    if ($part eq '') { $part='0'; }
 7128: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
 7129: 				 $symbparm,$udom,$uname,$section,1);
 7130: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
 7131: 	}
 7132: 	if ($recurse) { return undef; }
 7133: 	my $pack_def=&packages_tab_default($filename,$varname);
 7134: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
 7135: # ---------------------------------------------------- Any other user namespace
 7136:     } elsif ($realm eq 'environment') {
 7137: # ----------------------------------------------------------------- environment
 7138: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
 7139: 	    return $env{'environment.'.$spacequalifierrest};
 7140: 	} else {
 7141: 	    if ($uname eq 'anonymous' && $udom eq '') {
 7142: 		return '';
 7143: 	    }
 7144: 	    my %returnhash=&userenvironment($udom,$uname,
 7145: 					    $spacequalifierrest);
 7146: 	    return $returnhash{$spacequalifierrest};
 7147: 	}
 7148:     } elsif ($realm eq 'system') {
 7149: # ----------------------------------------------------------------- system.time
 7150: 	if ($space eq 'time') {
 7151: 	    return time;
 7152:         }
 7153:     } elsif ($realm eq 'server') {
 7154: # ----------------------------------------------------------------- system.time
 7155: 	if ($space eq 'name') {
 7156: 	    return $ENV{'SERVER_NAME'};
 7157:         }
 7158:     }
 7159:     return '';
 7160: }
 7161: 
 7162: sub get_reply {
 7163:     my ($reply_value) = @_;
 7164:     if (ref($reply_value) eq 'ARRAY') {
 7165:         if (wantarray) {
 7166: 	    return @$reply_value;
 7167:         }
 7168:         return $reply_value->[0];
 7169:     } else {
 7170:         return $reply_value;
 7171:     }
 7172: }
 7173: 
 7174: sub check_group_parms {
 7175:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
 7176:     my @groupitems = ();
 7177:     my $resultitem;
 7178:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
 7179:     foreach my $group (@{$groups}) {
 7180:         foreach my $level (@levels) {
 7181:              my $item = $courseid.'.['.$group.'].'.$level->[0];
 7182:              push(@groupitems,[$item,$level->[1]]);
 7183:         }
 7184:     }
 7185:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
 7186:                             $env{'course.'.$courseid.'.domain'},
 7187:                                      'course',@groupitems);
 7188:     return $coursereply;
 7189: }
 7190: 
 7191: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
 7192:     my ($courseid,@groups) = @_;
 7193:     @groups = sort(@groups);
 7194:     return @groups;
 7195: }
 7196: 
 7197: sub packages_tab_default {
 7198:     my ($uri,$varname)=@_;
 7199:     my (undef,$part,$name)=split(/\./,$varname);
 7200: 
 7201:     my (@extension,@specifics,$do_default);
 7202:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
 7203: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
 7204: 	if ($pack_type eq 'default') {
 7205: 	    $do_default=1;
 7206: 	} elsif ($pack_type eq 'extension') {
 7207: 	    push(@extension,[$package,$pack_type,$pack_part]);
 7208: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
 7209: 	    # only look at packages defaults for packages that this id is
 7210: 	    push(@specifics,[$package,$pack_type,$pack_part]);
 7211: 	}
 7212:     }
 7213:     # first look for a package that matches the requested part id
 7214:     foreach my $package (@specifics) {
 7215: 	my (undef,$pack_type,$pack_part)=@{$package};
 7216: 	next if ($pack_part ne $part);
 7217: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7218: 	    return $packagetab{"$pack_type&$name&default"};
 7219: 	}
 7220:     }
 7221:     # look for any possible matching non extension_ package
 7222:     foreach my $package (@specifics) {
 7223: 	my (undef,$pack_type,$pack_part)=@{$package};
 7224: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7225: 	    return $packagetab{"$pack_type&$name&default"};
 7226: 	}
 7227: 	if ($pack_type eq 'part') { $pack_part='0'; }
 7228: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
 7229: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
 7230: 	}
 7231:     }
 7232:     # look for any posible extension_ match
 7233:     foreach my $package (@extension) {
 7234: 	my ($package,$pack_type)=@{$package};
 7235: 	if (defined($packagetab{"$pack_type&$name&default"})) {
 7236: 	    return $packagetab{"$pack_type&$name&default"};
 7237: 	}
 7238: 	if (defined($packagetab{$package."&$name&default"})) {
 7239: 	    return $packagetab{$package."&$name&default"};
 7240: 	}
 7241:     }
 7242:     # look for a global default setting
 7243:     if ($do_default && defined($packagetab{"default&$name&default"})) {
 7244: 	return $packagetab{"default&$name&default"};
 7245:     }
 7246:     return undef;
 7247: }
 7248: 
 7249: sub add_prefix_and_part {
 7250:     my ($prefix,$part)=@_;
 7251:     my $keyroot;
 7252:     if (defined($prefix) && $prefix !~ /^__/) {
 7253: 	# prefix that has a part already
 7254: 	$keyroot=$prefix;
 7255:     } elsif (defined($prefix)) {
 7256: 	# prefix that is missing a part
 7257: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
 7258:     } else {
 7259: 	# no prefix at all
 7260: 	if (defined($part)) { $keyroot='_'.$part; }
 7261:     }
 7262:     return $keyroot;
 7263: }
 7264: 
 7265: # ---------------------------------------------------------------- Get metadata
 7266: 
 7267: my %metaentry;
 7268: sub metadata {
 7269:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
 7270:     $uri=&declutter($uri);
 7271:     # if it is a non metadata possible uri return quickly
 7272:     if (($uri eq '') || 
 7273: 	(($uri =~ m|^/*adm/|) && 
 7274: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
 7275:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
 7276: 	return undef;
 7277:     }
 7278:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
 7279: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
 7280: 	return undef;
 7281:     }
 7282:     my $filename=$uri;
 7283:     $uri=~s/\.meta$//;
 7284: #
 7285: # Is the metadata already cached?
 7286: # Look at timestamp of caching
 7287: # Everything is cached by the main uri, libraries are never directly cached
 7288: #
 7289:     if (!defined($liburi)) {
 7290: 	my ($result,$cached)=&is_cached_new('meta',$uri);
 7291: 	if (defined($cached)) { return $result->{':'.$what}; }
 7292:     }
 7293:     {
 7294: #
 7295: # Is this a recursive call for a library?
 7296: #
 7297: #	if (! exists($metacache{$uri})) {
 7298: #	    $metacache{$uri}={};
 7299: #	}
 7300: 	my $cachetime = 60*60;
 7301:         if ($liburi) {
 7302: 	    $liburi=&declutter($liburi);
 7303:             $filename=$liburi;
 7304:         } else {
 7305: 	    &devalidate_cache_new('meta',$uri);
 7306: 	    undef(%metaentry);
 7307: 	}
 7308:         my %metathesekeys=();
 7309:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
 7310: 	my $metastring;
 7311: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
 7312: 	    my $which = &hreflocation('','/'.($liburi || $uri));
 7313: 	    $metastring = 
 7314: 		&Apache::lonnet::ssi_body($which,
 7315: 					  ('grade_target' => 'meta'));
 7316: 	    $cachetime = 1; # only want this cached in the child not long term
 7317: 	} elsif ($uri !~ m -^(editupload)/-) {
 7318: 	    my $file=&filelocation('',&clutter($filename));
 7319: 	    #push(@{$metaentry{$uri.'.file'}},$file);
 7320: 	    $metastring=&getfile($file);
 7321: 	}
 7322:         my $parser=HTML::LCParser->new(\$metastring);
 7323:         my $token;
 7324:         undef %metathesekeys;
 7325:         while ($token=$parser->get_token) {
 7326: 	    if ($token->[0] eq 'S') {
 7327: 		if (defined($token->[2]->{'package'})) {
 7328: #
 7329: # This is a package - get package info
 7330: #
 7331: 		    my $package=$token->[2]->{'package'};
 7332: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 7333: 		    if (defined($token->[2]->{'id'})) { 
 7334: 			$keyroot.='_'.$token->[2]->{'id'}; 
 7335: 		    }
 7336: 		    if ($metaentry{':packages'}) {
 7337: 			$metaentry{':packages'}.=','.$package.$keyroot;
 7338: 		    } else {
 7339: 			$metaentry{':packages'}=$package.$keyroot;
 7340: 		    }
 7341: 		    foreach my $pack_entry (keys(%packagetab)) {
 7342: 			my $part=$keyroot;
 7343: 			$part=~s/^\_//;
 7344: 			if ($pack_entry=~/^\Q$package\E\&/ || 
 7345: 			    $pack_entry=~/^\Q$package\E_0\&/) {
 7346: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
 7347: 			    # ignore package.tab specified default values
 7348:                             # here &package_tab_default() will fetch those
 7349: 			    if ($subp eq 'default') { next; }
 7350: 			    my $value=$packagetab{$pack_entry};
 7351: 			    my $unikey;
 7352: 			    if ($pack =~ /_0$/) {
 7353: 				$unikey='parameter_0_'.$name;
 7354: 				$part=0;
 7355: 			    } else {
 7356: 				$unikey='parameter'.$keyroot.'_'.$name;
 7357: 			    }
 7358: 			    if ($subp eq 'display') {
 7359: 				$value.=' [Part: '.$part.']';
 7360: 			    }
 7361: 			    $metaentry{':'.$unikey.'.part'}=$part;
 7362: 			    $metathesekeys{$unikey}=1;
 7363: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 7364: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
 7365: 			    }
 7366: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
 7367: 				$metaentry{':'.$unikey}=
 7368: 				    $metaentry{':'.$unikey.'.default'};
 7369: 			    }
 7370: 			}
 7371: 		    }
 7372: 		} else {
 7373: #
 7374: # This is not a package - some other kind of start tag
 7375: #
 7376: 		    my $entry=$token->[1];
 7377: 		    my $unikey;
 7378: 		    if ($entry eq 'import') {
 7379: 			$unikey='';
 7380: 		    } else {
 7381: 			$unikey=$entry;
 7382: 		    }
 7383: 		    $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
 7384: 
 7385: 		    if (defined($token->[2]->{'id'})) { 
 7386: 			$unikey.='_'.$token->[2]->{'id'}; 
 7387: 		    }
 7388: 
 7389: 		    if ($entry eq 'import') {
 7390: #
 7391: # Importing a library here
 7392: #
 7393: 			if ($depthcount<20) {
 7394: 			    my $location=$parser->get_text('/import');
 7395: 			    my $dir=$filename;
 7396: 			    $dir=~s|[^/]*$||;
 7397: 			    $location=&filelocation($dir,$location);
 7398: 			    my $metadata = 
 7399: 				&metadata($uri,'keys', $location,$unikey,
 7400: 					  $depthcount+1);
 7401: 			    foreach my $meta (split(',',$metadata)) {
 7402: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
 7403: 				$metathesekeys{$meta}=1;
 7404: 			    }
 7405: 			}
 7406: 		    } else { 
 7407: 			
 7408: 			if (defined($token->[2]->{'name'})) { 
 7409: 			    $unikey.='_'.$token->[2]->{'name'}; 
 7410: 			}
 7411: 			$metathesekeys{$unikey}=1;
 7412: 			foreach my $param (@{$token->[3]}) {
 7413: 			    $metaentry{':'.$unikey.'.'.$param} =
 7414: 				$token->[2]->{$param};
 7415: 			}
 7416: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
 7417: 			my $default=$metaentry{':'.$unikey.'.default'};
 7418: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
 7419: 		 # only ws inside the tag, and not in default, so use default
 7420: 		 # as value
 7421: 			    $metaentry{':'.$unikey}=$default;
 7422: 			} elsif ( $internaltext =~ /\S/ ) {
 7423: 		  # something interesting inside the tag
 7424: 			    $metaentry{':'.$unikey}=$internaltext;
 7425: 			} else {
 7426: 		  # no interesting values, don't set a default
 7427: 			}
 7428: # end of not-a-package not-a-library import
 7429: 		    }
 7430: # end of not-a-package start tag
 7431: 		}
 7432: # the next is the end of "start tag"
 7433: 	    }
 7434: 	}
 7435: 	my ($extension) = ($uri =~ /\.(\w+)$/);
 7436: 	$extension = lc($extension);
 7437: 	if ($extension eq 'htm') { $extension='html'; }
 7438: 
 7439: 	foreach my $key (keys(%packagetab)) {
 7440: 	    #no specific packages #how's our extension
 7441: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
 7442: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
 7443: 					 \%metathesekeys);
 7444: 	}
 7445: 
 7446: 	if (!exists($metaentry{':packages'})
 7447: 	    || $packagetab{"import_defaults&extension_$extension"}) {
 7448: 	    foreach my $key (keys(%packagetab)) {
 7449: 		#no specific packages well let's get default then
 7450: 		if ($key!~/^default&/) { next; }
 7451: 		&metadata_create_package_def($uri,$key,'default',
 7452: 					     \%metathesekeys);
 7453: 	    }
 7454: 	}
 7455: # are there custom rights to evaluate
 7456: 	if ($metaentry{':copyright'} eq 'custom') {
 7457: 
 7458:     #
 7459:     # Importing a rights file here
 7460:     #
 7461: 	    unless ($depthcount) {
 7462: 		my $location=$metaentry{':customdistributionfile'};
 7463: 		my $dir=$filename;
 7464: 		$dir=~s|[^/]*$||;
 7465: 		$location=&filelocation($dir,$location);
 7466: 		my $rights_metadata =
 7467: 		    &metadata($uri,'keys',$location,'_rights',
 7468: 			      $depthcount+1);
 7469: 		foreach my $rights (split(',',$rights_metadata)) {
 7470: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
 7471: 		    $metathesekeys{$rights}=1;
 7472: 		}
 7473: 	    }
 7474: 	}
 7475: 	# uniqifiy package listing
 7476: 	my %seen;
 7477: 	my @uniq_packages =
 7478: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
 7479: 	$metaentry{':packages'} = join(',',@uniq_packages);
 7480: 
 7481: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
 7482: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
 7483: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
 7484: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
 7485: # this is the end of "was not already recently cached
 7486:     }
 7487:     return $metaentry{':'.$what};
 7488: }
 7489: 
 7490: sub metadata_create_package_def {
 7491:     my ($uri,$key,$package,$metathesekeys)=@_;
 7492:     my ($pack,$name,$subp)=split(/\&/,$key);
 7493:     if ($subp eq 'default') { next; }
 7494:     
 7495:     if (defined($metaentry{':packages'})) {
 7496: 	$metaentry{':packages'}.=','.$package;
 7497:     } else {
 7498: 	$metaentry{':packages'}=$package;
 7499:     }
 7500:     my $value=$packagetab{$key};
 7501:     my $unikey;
 7502:     $unikey='parameter_0_'.$name;
 7503:     $metaentry{':'.$unikey.'.part'}=0;
 7504:     $$metathesekeys{$unikey}=1;
 7505:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
 7506: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
 7507:     }
 7508:     if (defined($metaentry{':'.$unikey.'.default'})) {
 7509: 	$metaentry{':'.$unikey}=
 7510: 	    $metaentry{':'.$unikey.'.default'};
 7511:     }
 7512: }
 7513: 
 7514: sub metadata_generate_part0 {
 7515:     my ($metadata,$metacache,$uri) = @_;
 7516:     my %allnames;
 7517:     foreach my $metakey (keys(%$metadata)) {
 7518: 	if ($metakey=~/^parameter\_(.*)/) {
 7519: 	  my $part=$$metacache{':'.$metakey.'.part'};
 7520: 	  my $name=$$metacache{':'.$metakey.'.name'};
 7521: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
 7522: 	    $allnames{$name}=$part;
 7523: 	  }
 7524: 	}
 7525:     }
 7526:     foreach my $name (keys(%allnames)) {
 7527:       $$metadata{"parameter_0_$name"}=1;
 7528:       my $key=":parameter_0_$name";
 7529:       $$metacache{"$key.part"}='0';
 7530:       $$metacache{"$key.name"}=$name;
 7531:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
 7532: 					   $allnames{$name}.'_'.$name.
 7533: 					   '.type'};
 7534:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
 7535: 			     '.display'};
 7536:       my $expr='[Part: '.$allnames{$name}.']';
 7537:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
 7538:       $$metacache{"$key.display"}=$olddis;
 7539:     }
 7540: }
 7541: 
 7542: # ------------------------------------------------------ Devalidate title cache
 7543: 
 7544: sub devalidate_title_cache {
 7545:     my ($url)=@_;
 7546:     if (!$env{'request.course.id'}) { return; }
 7547:     my $symb=&symbread($url);
 7548:     if (!$symb) { return; }
 7549:     my $key=$env{'request.course.id'}."\0".$symb;
 7550:     &devalidate_cache_new('title',$key);
 7551: }
 7552: 
 7553: # ------------------------------------------------- Get the title of a resource
 7554: 
 7555: sub gettitle {
 7556:     my $urlsymb=shift;
 7557:     my $symb=&symbread($urlsymb);
 7558:     if ($symb) {
 7559: 	my $key=$env{'request.course.id'}."\0".$symb;
 7560: 	my ($result,$cached)=&is_cached_new('title',$key);
 7561: 	if (defined($cached)) { 
 7562: 	    return $result;
 7563: 	}
 7564: 	my ($map,$resid,$url)=&decode_symb($symb);
 7565: 	my $title='';
 7566: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
 7567: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
 7568: 	} else {
 7569: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7570: 		    &GDBM_READER(),0640)) {
 7571: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
 7572: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
 7573: 		untie(%bighash);
 7574: 	    }
 7575: 	}
 7576: 	$title=~s/\&colon\;/\:/gs;
 7577: 	if ($title) {
 7578: 	    return &do_cache_new('title',$key,$title,600);
 7579: 	}
 7580: 	$urlsymb=$url;
 7581:     }
 7582:     my $title=&metadata($urlsymb,'title');
 7583:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
 7584:     return $title;
 7585: }
 7586: 
 7587: sub get_slot {
 7588:     my ($which,$cnum,$cdom)=@_;
 7589:     if (!$cnum || !$cdom) {
 7590: 	(undef,my $courseid)=&whichuser();
 7591: 	$cdom=$env{'course.'.$courseid.'.domain'};
 7592: 	$cnum=$env{'course.'.$courseid.'.num'};
 7593:     }
 7594:     my $key=join("\0",'slots',$cdom,$cnum,$which);
 7595:     my %slotinfo;
 7596:     if (exists($remembered{$key})) {
 7597: 	$slotinfo{$which} = $remembered{$key};
 7598:     } else {
 7599: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
 7600: 	&Apache::lonhomework::showhash(%slotinfo);
 7601: 	my ($tmp)=keys(%slotinfo);
 7602: 	if ($tmp=~/^error:/) { return (); }
 7603: 	$remembered{$key} = $slotinfo{$which};
 7604:     }
 7605:     if (ref($slotinfo{$which}) eq 'HASH') {
 7606: 	return %{$slotinfo{$which}};
 7607:     }
 7608:     return $slotinfo{$which};
 7609: }
 7610: # ------------------------------------------------- Update symbolic store links
 7611: 
 7612: sub symblist {
 7613:     my ($mapname,%newhash)=@_;
 7614:     $mapname=&deversion(&declutter($mapname));
 7615:     my %hash;
 7616:     if (($env{'request.course.fn'}) && (%newhash)) {
 7617:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 7618:                       &GDBM_WRCREAT(),0640)) {
 7619: 	    foreach my $url (keys %newhash) {
 7620: 		next if ($url eq 'last_known'
 7621: 			 && $env{'form.no_update_last_known'});
 7622: 		$hash{declutter($url)}=&encode_symb($mapname,
 7623: 						    $newhash{$url}->[1],
 7624: 						    $newhash{$url}->[0]);
 7625:             }
 7626:             if (untie(%hash)) {
 7627: 		return 'ok';
 7628:             }
 7629:         }
 7630:     }
 7631:     return 'error';
 7632: }
 7633: 
 7634: # --------------------------------------------------------------- Verify a symb
 7635: 
 7636: sub symbverify {
 7637:     my ($symb,$thisurl)=@_;
 7638:     my $thisfn=$thisurl;
 7639:     $thisfn=&declutter($thisfn);
 7640: # direct jump to resource in page or to a sequence - will construct own symbs
 7641:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
 7642: # check URL part
 7643:     my ($map,$resid,$url)=&decode_symb($symb);
 7644: 
 7645:     unless ($url eq $thisfn) { return 0; }
 7646: 
 7647:     $symb=&symbclean($symb);
 7648:     $thisurl=&deversion($thisurl);
 7649:     $thisfn=&deversion($thisfn);
 7650: 
 7651:     my %bighash;
 7652:     my $okay=0;
 7653: 
 7654:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7655:                             &GDBM_READER(),0640)) {
 7656:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
 7657:         unless ($ids) { 
 7658:            $ids=$bighash{'ids_/'.$thisurl};
 7659:         }
 7660:         if ($ids) {
 7661: # ------------------------------------------------------------------- Has ID(s)
 7662: 	    foreach my $id (split(/\,/,$ids)) {
 7663: 	       my ($mapid,$resid)=split(/\./,$id);
 7664:                if (
 7665:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
 7666:    eq $symb) { 
 7667: 		   if (($env{'request.role.adv'}) ||
 7668: 		       $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
 7669: 		       $okay=1; 
 7670: 		   }
 7671: 	       }
 7672: 	   }
 7673:         }
 7674: 	untie(%bighash);
 7675:     }
 7676:     return $okay;
 7677: }
 7678: 
 7679: # --------------------------------------------------------------- Clean-up symb
 7680: 
 7681: sub symbclean {
 7682:     my $symb=shift;
 7683:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 7684: # remove version from map
 7685:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
 7686: 
 7687: # remove version from URL
 7688:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
 7689: 
 7690: # remove wrapper
 7691: 
 7692:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
 7693:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
 7694:     return $symb;
 7695: }
 7696: 
 7697: # ---------------------------------------------- Split symb to find map and url
 7698: 
 7699: sub encode_symb {
 7700:     my ($map,$resid,$url)=@_;
 7701:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
 7702: }
 7703: 
 7704: sub decode_symb {
 7705:     my $symb=shift;
 7706:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
 7707:     my ($map,$resid,$url)=split(/___/,$symb);
 7708:     return (&fixversion($map),$resid,&fixversion($url));
 7709: }
 7710: 
 7711: sub fixversion {
 7712:     my $fn=shift;
 7713:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
 7714:     my %bighash;
 7715:     my $uri=&clutter($fn);
 7716:     my $key=$env{'request.course.id'}.'_'.$uri;
 7717: # is this cached?
 7718:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
 7719:     if (defined($cached)) { return $result; }
 7720: # unfortunately not cached, or expired
 7721:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7722: 	    &GDBM_READER(),0640)) {
 7723:  	if ($bighash{'version_'.$uri}) {
 7724:  	    my $version=$bighash{'version_'.$uri};
 7725:  	    unless (($version eq 'mostrecent') || 
 7726: 		    ($version==&getversion($uri))) {
 7727:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
 7728:  	    }
 7729:  	}
 7730:  	untie %bighash;
 7731:     }
 7732:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
 7733: }
 7734: 
 7735: sub deversion {
 7736:     my $url=shift;
 7737:     $url=~s/\.\d+\.(\w+)$/\.$1/;
 7738:     return $url;
 7739: }
 7740: 
 7741: # ------------------------------------------------------ Return symb list entry
 7742: 
 7743: sub symbread {
 7744:     my ($thisfn,$donotrecurse)=@_;
 7745:     my $cache_str='request.symbread.cached.'.$thisfn;
 7746:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
 7747: # no filename provided? try from environment
 7748:     unless ($thisfn) {
 7749:         if ($env{'request.symb'}) {
 7750: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
 7751: 	}
 7752: 	$thisfn=$env{'request.filename'};
 7753:     }
 7754:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 7755: # is that filename actually a symb? Verify, clean, and return
 7756:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
 7757: 	if (&symbverify($thisfn,$1)) {
 7758: 	    return $env{$cache_str}=&symbclean($thisfn);
 7759: 	}
 7760:     }
 7761:     $thisfn=declutter($thisfn);
 7762:     my %hash;
 7763:     my %bighash;
 7764:     my $syval='';
 7765:     if (($env{'request.course.fn'}) && ($thisfn)) {
 7766:         my $targetfn = $thisfn;
 7767:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
 7768:             $targetfn = 'adm/wrapper/'.$thisfn;
 7769:         }
 7770: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
 7771: 	    $targetfn=$1;
 7772: 	}
 7773:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
 7774:                       &GDBM_READER(),0640)) {
 7775: 	    $syval=$hash{$targetfn};
 7776:             untie(%hash);
 7777:         }
 7778: # ---------------------------------------------------------- There was an entry
 7779:         if ($syval) {
 7780: 	    #unless ($syval=~/\_\d+$/) {
 7781: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
 7782: 		    #&appenv({'request.ambiguous' => $thisfn});
 7783: 		    #return $env{$cache_str}='';
 7784: 		#}    
 7785: 		#$syval.=$1;
 7786: 	    #}
 7787:         } else {
 7788: # ------------------------------------------------------- Was not in symb table
 7789:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
 7790:                             &GDBM_READER(),0640)) {
 7791: # ---------------------------------------------- Get ID(s) for current resource
 7792:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
 7793:               unless ($ids) { 
 7794:                  $ids=$bighash{'ids_/'.$thisfn};
 7795:               }
 7796:               unless ($ids) {
 7797: # alias?
 7798: 		  $ids=$bighash{'mapalias_'.$thisfn};
 7799:               }
 7800:               if ($ids) {
 7801: # ------------------------------------------------------------------- Has ID(s)
 7802:                  my @possibilities=split(/\,/,$ids);
 7803:                  if ($#possibilities==0) {
 7804: # ----------------------------------------------- There is only one possibility
 7805: 		     my ($mapid,$resid)=split(/\./,$ids);
 7806: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
 7807: 						    $resid,$thisfn);
 7808:                  } elsif (!$donotrecurse) {
 7809: # ------------------------------------------ There is more than one possibility
 7810:                      my $realpossible=0;
 7811:                      foreach my $id (@possibilities) {
 7812: 			 my $file=$bighash{'src_'.$id};
 7813:                          if (&allowed('bre',$file)) {
 7814:          		    my ($mapid,$resid)=split(/\./,$id);
 7815:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
 7816: 				$realpossible++;
 7817:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
 7818: 						    $resid,$thisfn);
 7819:                             }
 7820: 			 }
 7821:                      }
 7822: 		     if ($realpossible!=1) { $syval=''; }
 7823:                  } else {
 7824:                      $syval='';
 7825:                  }
 7826: 	      }
 7827:               untie(%bighash)
 7828:            }
 7829:         }
 7830:         if ($syval) {
 7831: 	    return $env{$cache_str}=$syval;
 7832:         }
 7833:     }
 7834:     &appenv({'request.ambiguous' => $thisfn});
 7835:     return $env{$cache_str}='';
 7836: }
 7837: 
 7838: # ---------------------------------------------------------- Return random seed
 7839: 
 7840: sub numval {
 7841:     my $txt=shift;
 7842:     $txt=~tr/A-J/0-9/;
 7843:     $txt=~tr/a-j/0-9/;
 7844:     $txt=~tr/K-T/0-9/;
 7845:     $txt=~tr/k-t/0-9/;
 7846:     $txt=~tr/U-Z/0-5/;
 7847:     $txt=~tr/u-z/0-5/;
 7848:     $txt=~s/\D//g;
 7849:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
 7850:     return int($txt);
 7851: }
 7852: 
 7853: sub numval2 {
 7854:     my $txt=shift;
 7855:     $txt=~tr/A-J/0-9/;
 7856:     $txt=~tr/a-j/0-9/;
 7857:     $txt=~tr/K-T/0-9/;
 7858:     $txt=~tr/k-t/0-9/;
 7859:     $txt=~tr/U-Z/0-5/;
 7860:     $txt=~tr/u-z/0-5/;
 7861:     $txt=~s/\D//g;
 7862:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 7863:     my $total;
 7864:     foreach my $val (@txts) { $total+=$val; }
 7865:     if ($_64bit) { if ($total > 2**32) { return -1; } }
 7866:     return int($total);
 7867: }
 7868: 
 7869: sub numval3 {
 7870:     use integer;
 7871:     my $txt=shift;
 7872:     $txt=~tr/A-J/0-9/;
 7873:     $txt=~tr/a-j/0-9/;
 7874:     $txt=~tr/K-T/0-9/;
 7875:     $txt=~tr/k-t/0-9/;
 7876:     $txt=~tr/U-Z/0-5/;
 7877:     $txt=~tr/u-z/0-5/;
 7878:     $txt=~s/\D//g;
 7879:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
 7880:     my $total;
 7881:     foreach my $val (@txts) { $total+=$val; }
 7882:     if ($_64bit) { $total=(($total<<32)>>32); }
 7883:     return $total;
 7884: }
 7885: 
 7886: sub digest {
 7887:     my ($data)=@_;
 7888:     my $digest=&Digest::MD5::md5($data);
 7889:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
 7890:     my ($e,$f);
 7891:     {
 7892:         use integer;
 7893:         $e=($a+$b);
 7894:         $f=($c+$d);
 7895:         if ($_64bit) {
 7896:             $e=(($e<<32)>>32);
 7897:             $f=(($f<<32)>>32);
 7898:         }
 7899:     }
 7900:     if (wantarray) {
 7901: 	return ($e,$f);
 7902:     } else {
 7903: 	my $g;
 7904: 	{
 7905: 	    use integer;
 7906: 	    $g=($e+$f);
 7907: 	    if ($_64bit) {
 7908: 		$g=(($g<<32)>>32);
 7909: 	    }
 7910: 	}
 7911: 	return $g;
 7912:     }
 7913: }
 7914: 
 7915: sub latest_rnd_algorithm_id {
 7916:     return '64bit5';
 7917: }
 7918: 
 7919: sub get_rand_alg {
 7920:     my ($courseid)=@_;
 7921:     if (!$courseid) { $courseid=(&whichuser())[1]; }
 7922:     if ($courseid) {
 7923: 	return $env{"course.$courseid.rndseed"};
 7924:     }
 7925:     return &latest_rnd_algorithm_id();
 7926: }
 7927: 
 7928: sub validCODE {
 7929:     my ($CODE)=@_;
 7930:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
 7931:     return 0;
 7932: }
 7933: 
 7934: sub getCODE {
 7935:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
 7936:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
 7937: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
 7938: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
 7939: 	return $Apache::lonhomework::history{'resource.CODE'};
 7940:     }
 7941:     return undef;
 7942: }
 7943: 
 7944: sub rndseed {
 7945:     my ($symb,$courseid,$domain,$username)=@_;
 7946:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
 7947:     if (!defined($symb)) {
 7948: 	unless ($symb=$wsymb) { return time; }
 7949:     }
 7950:     if (!$courseid) { $courseid=$wcourseid; }
 7951:     if (!$domain) { $domain=$wdomain; }
 7952:     if (!$username) { $username=$wusername }
 7953:     my $which=&get_rand_alg();
 7954: 
 7955:     if (defined(&getCODE())) {
 7956: 	if ($which eq '64bit5') {
 7957: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
 7958: 	} elsif ($which eq '64bit4') {
 7959: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
 7960: 	} else {
 7961: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
 7962: 	}
 7963:     } elsif ($which eq '64bit5') {
 7964: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
 7965:     } elsif ($which eq '64bit4') {
 7966: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
 7967:     } elsif ($which eq '64bit3') {
 7968: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
 7969:     } elsif ($which eq '64bit2') {
 7970: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
 7971:     } elsif ($which eq '64bit') {
 7972: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
 7973:     }
 7974:     return &rndseed_32bit($symb,$courseid,$domain,$username);
 7975: }
 7976: 
 7977: sub rndseed_32bit {
 7978:     my ($symb,$courseid,$domain,$username)=@_;
 7979:     {
 7980: 	use integer;
 7981: 	my $symbchck=unpack("%32C*",$symb) << 27;
 7982: 	my $symbseed=numval($symb) << 22;
 7983: 	my $namechck=unpack("%32C*",$username) << 17;
 7984: 	my $nameseed=numval($username) << 12;
 7985: 	my $domainseed=unpack("%32C*",$domain) << 7;
 7986: 	my $courseseed=unpack("%32C*",$courseid);
 7987: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
 7988: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 7989: 	#&logthis("rndseed :$num:$symb");
 7990: 	if ($_64bit) { $num=(($num<<32)>>32); }
 7991: 	return $num;
 7992:     }
 7993: }
 7994: 
 7995: sub rndseed_64bit {
 7996:     my ($symb,$courseid,$domain,$username)=@_;
 7997:     {
 7998: 	use integer;
 7999: 	my $symbchck=unpack("%32S*",$symb) << 21;
 8000: 	my $symbseed=numval($symb) << 10;
 8001: 	my $namechck=unpack("%32S*",$username);
 8002: 	
 8003: 	my $nameseed=numval($username) << 21;
 8004: 	my $domainseed=unpack("%32S*",$domain) << 10;
 8005: 	my $courseseed=unpack("%32S*",$courseid);
 8006: 	
 8007: 	my $num1=$symbchck+$symbseed+$namechck;
 8008: 	my $num2=$nameseed+$domainseed+$courseseed;
 8009: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8010: 	#&logthis("rndseed :$num:$symb");
 8011: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8012: 	return "$num1,$num2";
 8013:     }
 8014: }
 8015: 
 8016: sub rndseed_64bit2 {
 8017:     my ($symb,$courseid,$domain,$username)=@_;
 8018:     {
 8019: 	use integer;
 8020: 	# strings need to be an even # of cahracters long, it it is odd the
 8021:         # last characters gets thrown away
 8022: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8023: 	my $symbseed=numval($symb) << 10;
 8024: 	my $namechck=unpack("%32S*",$username.' ');
 8025: 	
 8026: 	my $nameseed=numval($username) << 21;
 8027: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8028: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8029: 	
 8030: 	my $num1=$symbchck+$symbseed+$namechck;
 8031: 	my $num2=$nameseed+$domainseed+$courseseed;
 8032: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8033: 	#&logthis("rndseed :$num:$symb");
 8034: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8035: 	return "$num1,$num2";
 8036:     }
 8037: }
 8038: 
 8039: sub rndseed_64bit3 {
 8040:     my ($symb,$courseid,$domain,$username)=@_;
 8041:     {
 8042: 	use integer;
 8043: 	# strings need to be an even # of cahracters long, it it is odd the
 8044:         # last characters gets thrown away
 8045: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8046: 	my $symbseed=numval2($symb) << 10;
 8047: 	my $namechck=unpack("%32S*",$username.' ');
 8048: 	
 8049: 	my $nameseed=numval2($username) << 21;
 8050: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8051: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8052: 	
 8053: 	my $num1=$symbchck+$symbseed+$namechck;
 8054: 	my $num2=$nameseed+$domainseed+$courseseed;
 8055: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8056: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 8057: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8058: 	
 8059: 	return "$num1:$num2";
 8060:     }
 8061: }
 8062: 
 8063: sub rndseed_64bit4 {
 8064:     my ($symb,$courseid,$domain,$username)=@_;
 8065:     {
 8066: 	use integer;
 8067: 	# strings need to be an even # of cahracters long, it it is odd the
 8068:         # last characters gets thrown away
 8069: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
 8070: 	my $symbseed=numval3($symb) << 10;
 8071: 	my $namechck=unpack("%32S*",$username.' ');
 8072: 	
 8073: 	my $nameseed=numval3($username) << 21;
 8074: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
 8075: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8076: 	
 8077: 	my $num1=$symbchck+$symbseed+$namechck;
 8078: 	my $num2=$nameseed+$domainseed+$courseseed;
 8079: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
 8080: 	#&logthis("rndseed :$num1:$num2:$_64bit");
 8081: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
 8082: 	
 8083: 	return "$num1:$num2";
 8084:     }
 8085: }
 8086: 
 8087: sub rndseed_64bit5 {
 8088:     my ($symb,$courseid,$domain,$username)=@_;
 8089:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
 8090:     return "$num1:$num2";
 8091: }
 8092: 
 8093: sub rndseed_CODE_64bit {
 8094:     my ($symb,$courseid,$domain,$username)=@_;
 8095:     {
 8096: 	use integer;
 8097: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 8098: 	my $symbseed=numval2($symb);
 8099: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 8100: 	my $CODEseed=numval(&getCODE());
 8101: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8102: 	my $num1=$symbseed+$CODEchck;
 8103: 	my $num2=$CODEseed+$courseseed+$symbchck;
 8104: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 8105: 	#&logthis("rndseed :$num1:$num2:$symb");
 8106: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 8107: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 8108: 	return "$num1:$num2";
 8109:     }
 8110: }
 8111: 
 8112: sub rndseed_CODE_64bit4 {
 8113:     my ($symb,$courseid,$domain,$username)=@_;
 8114:     {
 8115: 	use integer;
 8116: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
 8117: 	my $symbseed=numval3($symb);
 8118: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
 8119: 	my $CODEseed=numval3(&getCODE());
 8120: 	my $courseseed=unpack("%32S*",$courseid.' ');
 8121: 	my $num1=$symbseed+$CODEchck;
 8122: 	my $num2=$CODEseed+$courseseed+$symbchck;
 8123: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
 8124: 	#&logthis("rndseed :$num1:$num2:$symb");
 8125: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
 8126: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
 8127: 	return "$num1:$num2";
 8128:     }
 8129: }
 8130: 
 8131: sub rndseed_CODE_64bit5 {
 8132:     my ($symb,$courseid,$domain,$username)=@_;
 8133:     my $code = &getCODE();
 8134:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
 8135:     return "$num1:$num2";
 8136: }
 8137: 
 8138: sub setup_random_from_rndseed {
 8139:     my ($rndseed)=@_;
 8140:     if ($rndseed =~/([,:])/) {
 8141: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
 8142: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
 8143:     } else {
 8144: 	&Math::Random::random_set_seed_from_phrase($rndseed);
 8145:     }
 8146: }
 8147: 
 8148: sub latest_receipt_algorithm_id {
 8149:     return 'receipt3';
 8150: }
 8151: 
 8152: sub recunique {
 8153:     my $fucourseid=shift;
 8154:     my $unique;
 8155:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
 8156: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 8157: 	$unique=$env{"course.$fucourseid.internal.encseed"};
 8158:     } else {
 8159: 	$unique=$perlvar{'lonReceipt'};
 8160:     }
 8161:     return unpack("%32C*",$unique);
 8162: }
 8163: 
 8164: sub recprefix {
 8165:     my $fucourseid=shift;
 8166:     my $prefix;
 8167:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
 8168: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
 8169: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
 8170:     } else {
 8171: 	$prefix=$perlvar{'lonHostID'};
 8172:     }
 8173:     return unpack("%32C*",$prefix);
 8174: }
 8175: 
 8176: sub ireceipt {
 8177:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
 8178: 
 8179:     my $return =&recprefix($fucourseid).'-';
 8180: 
 8181:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
 8182: 	$env{'request.state'} eq 'construct') {
 8183: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
 8184: 	return $return;
 8185:     }
 8186: 
 8187:     my $cuname=unpack("%32C*",$funame);
 8188:     my $cudom=unpack("%32C*",$fudom);
 8189:     my $cucourseid=unpack("%32C*",$fucourseid);
 8190:     my $cusymb=unpack("%32C*",$fusymb);
 8191:     my $cunique=&recunique($fucourseid);
 8192:     my $cpart=unpack("%32S*",$part);
 8193:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
 8194: 
 8195: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
 8196: 			       
 8197: 	$return.= ($cunique%$cuname+
 8198: 		   $cunique%$cudom+
 8199: 		   $cusymb%$cuname+
 8200: 		   $cusymb%$cudom+
 8201: 		   $cucourseid%$cuname+
 8202: 		   $cucourseid%$cudom+
 8203: 		   $cpart%$cuname+
 8204: 		   $cpart%$cudom);
 8205:     } else {
 8206: 	$return.= ($cunique%$cuname+
 8207: 		   $cunique%$cudom+
 8208: 		   $cusymb%$cuname+
 8209: 		   $cusymb%$cudom+
 8210: 		   $cucourseid%$cuname+
 8211: 		   $cucourseid%$cudom);
 8212:     }
 8213:     return $return;
 8214: }
 8215: 
 8216: sub receipt {
 8217:     my ($part)=@_;
 8218:     my ($symb,$courseid,$domain,$name) = &whichuser();
 8219:     return &ireceipt($name,$domain,$courseid,$symb,$part);
 8220: }
 8221: 
 8222: sub whichuser {
 8223:     my ($passedsymb)=@_;
 8224:     my ($symb,$courseid,$domain,$name,$publicuser);
 8225:     if (defined($env{'form.grade_symb'})) {
 8226: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
 8227: 	my $allowed=&allowed('vgr',$tmp_courseid);
 8228: 	if (!$allowed &&
 8229: 	    exists($env{'request.course.sec'}) &&
 8230: 	    $env{'request.course.sec'} !~ /^\s*$/) {
 8231: 	    $allowed=&allowed('vgr',$tmp_courseid.
 8232: 			      '/'.$env{'request.course.sec'});
 8233: 	}
 8234: 	if ($allowed) {
 8235: 	    ($symb)=&get_env_multiple('form.grade_symb');
 8236: 	    $courseid=$tmp_courseid;
 8237: 	    ($domain)=&get_env_multiple('form.grade_domain');
 8238: 	    ($name)=&get_env_multiple('form.grade_username');
 8239: 	    return ($symb,$courseid,$domain,$name,$publicuser);
 8240: 	}
 8241:     }
 8242:     if (!$passedsymb) {
 8243: 	$symb=&symbread();
 8244:     } else {
 8245: 	$symb=$passedsymb;
 8246:     }
 8247:     $courseid=$env{'request.course.id'};
 8248:     $domain=$env{'user.domain'};
 8249:     $name=$env{'user.name'};
 8250:     if ($name eq 'public' && $domain eq 'public') {
 8251: 	if (!defined($env{'form.username'})) {
 8252: 	    $env{'form.username'}.=time.rand(10000000);
 8253: 	}
 8254: 	$name.=$env{'form.username'};
 8255:     }
 8256:     return ($symb,$courseid,$domain,$name,$publicuser);
 8257: 
 8258: }
 8259: 
 8260: # ------------------------------------------------------------ Serves up a file
 8261: # returns either the contents of the file or 
 8262: # -1 if the file doesn't exist
 8263: #
 8264: # if the target is a file that was uploaded via DOCS, 
 8265: # a check will be made to see if a current copy exists on the local server,
 8266: # if it does this will be served, otherwise a copy will be retrieved from
 8267: # the home server for the course and stored in /home/httpd/html/userfiles on
 8268: # the local server.   
 8269: 
 8270: sub getfile {
 8271:     my ($file) = @_;
 8272:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 8273:     &repcopy($file);
 8274:     return &readfile($file);
 8275: }
 8276: 
 8277: sub repcopy_userfile {
 8278:     my ($file)=@_;
 8279:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
 8280:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
 8281:     my ($cdom,$cnum,$filename) = 
 8282: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
 8283:     my $uri="/uploaded/$cdom/$cnum/$filename";
 8284:     if (-e "$file") {
 8285: # we already have a local copy, check it out
 8286: 	my @fileinfo = stat($file);
 8287: 	my $rtncode;
 8288: 	my $info;
 8289: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
 8290: 	if ($lwpresp ne 'ok') {
 8291: # there is no such file anymore, even though we had a local copy
 8292: 	    if ($rtncode eq '404') {
 8293: 		unlink($file);
 8294: 	    }
 8295: 	    return -1;
 8296: 	}
 8297: 	if ($info < $fileinfo[9]) {
 8298: # nice, the file we have is up-to-date, just say okay
 8299: 	    return 'ok';
 8300: 	} else {
 8301: # the file is outdated, get rid of it
 8302: 	    unlink($file);
 8303: 	}
 8304:     }
 8305: # one way or the other, at this point, we don't have the file
 8306: # construct the correct path for the file
 8307:     my @parts = ($cdom,$cnum); 
 8308:     if ($filename =~ m|^(.+)/[^/]+$|) {
 8309: 	push @parts, split(/\//,$1);
 8310:     }
 8311:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
 8312:     foreach my $part (@parts) {
 8313: 	$path .= '/'.$part;
 8314: 	if (!-e $path) {
 8315: 	    mkdir($path,0770);
 8316: 	}
 8317:     }
 8318: # now the path exists for sure
 8319: # get a user agent
 8320:     my $ua=new LWP::UserAgent;
 8321:     my $transferfile=$file.'.in.transfer';
 8322: # FIXME: this should flock
 8323:     if (-e $transferfile) { return 'ok'; }
 8324:     my $request;
 8325:     $uri=~s/^\///;
 8326:     my $homeserver = &homeserver($cnum,$cdom);
 8327:     my $protocol = $protocol{$homeserver};
 8328:     $protocol = 'http' if ($protocol ne 'https');
 8329:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
 8330:     my $response=$ua->request($request,$transferfile);
 8331: # did it work?
 8332:     if ($response->is_error()) {
 8333: 	unlink($transferfile);
 8334: 	&logthis("Userfile repcopy failed for $uri");
 8335: 	return -1;
 8336:     }
 8337: # worked, rename the transfer file
 8338:     rename($transferfile,$file);
 8339:     return 'ok';
 8340: }
 8341: 
 8342: sub tokenwrapper {
 8343:     my $uri=shift;
 8344:     $uri=~s|^https?\://([^/]+)||;
 8345:     $uri=~s|^/||;
 8346:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
 8347:     my $token=$1;
 8348:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
 8349:     if ($udom && $uname && $file) {
 8350: 	$file=~s|(\?\.*)*$||;
 8351:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
 8352:         my $homeserver = &homeserver($uname,$udom);
 8353:         my $protocol = $protocol{$homeserver};
 8354:         $protocol = 'http' if ($protocol ne 'https');
 8355:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
 8356:                (($uri=~/\?/)?'&':'?').'token='.$token.
 8357:                                '&tokenissued='.$perlvar{'lonHostID'};
 8358:     } else {
 8359:         return '/adm/notfound.html';
 8360:     }
 8361: }
 8362: 
 8363: # call with reqtype HEAD: get last modification time
 8364: # call with reqtype GET: get the file contents
 8365: # Do not call this with reqtype GET for large files! It loads everything into memory
 8366: #
 8367: sub getuploaded {
 8368:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
 8369:     $uri=~s/^\///;
 8370:     my $homeserver = &homeserver($cnum,$cdom);
 8371:     my $protocol = $protocol{$homeserver};
 8372:     $protocol = 'http' if ($protocol ne 'https');
 8373:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
 8374:     my $ua=new LWP::UserAgent;
 8375:     my $request=new HTTP::Request($reqtype,$uri);
 8376:     my $response=$ua->request($request);
 8377:     $$rtncode = $response->code;
 8378:     if (! $response->is_success()) {
 8379: 	return 'failed';
 8380:     }      
 8381:     if ($reqtype eq 'HEAD') {
 8382: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
 8383:     } elsif ($reqtype eq 'GET') {
 8384: 	$$info = $response->content;
 8385:     }
 8386:     return 'ok';
 8387: }
 8388: 
 8389: sub readfile {
 8390:     my $file = shift;
 8391:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
 8392:     my $fh;
 8393:     open($fh,"<$file");
 8394:     my $a='';
 8395:     while (my $line = <$fh>) { $a .= $line; }
 8396:     return $a;
 8397: }
 8398: 
 8399: sub filelocation {
 8400:     my ($dir,$file) = @_;
 8401:     my $location;
 8402:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
 8403: 
 8404:     if ($file =~ m-^/adm/-) {
 8405: 	$file=~s-^/adm/wrapper/-/-;
 8406: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 8407:     }
 8408: 
 8409:     if ($file=~m:^/~:) { # is a contruction space reference
 8410:         $location = $file;
 8411:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
 8412:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
 8413: 	# is a correct contruction space reference
 8414:         $location = $file;
 8415:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
 8416:         $location = $file;
 8417:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
 8418:         my ($udom,$uname,$filename)=
 8419:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
 8420:         my $home=&homeserver($uname,$udom);
 8421:         my $is_me=0;
 8422:         my @ids=&current_machine_ids();
 8423:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
 8424:         if ($is_me) {
 8425:   	    $location=&propath($udom,$uname).'/userfiles/'.$filename;
 8426:         } else {
 8427:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
 8428:   	      $udom.'/'.$uname.'/'.$filename;
 8429:         }
 8430:     } elsif ($file =~ m-^/adm/-) {
 8431: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
 8432:     } else {
 8433:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 8434:         $file=~s:^/res/:/:;
 8435:         if ( !( $file =~ m:^/:) ) {
 8436:             $location = $dir. '/'.$file;
 8437:         } else {
 8438:             $location = '/home/httpd/html/res'.$file;
 8439:         }
 8440:     }
 8441:     $location=~s://+:/:g; # remove duplicate /
 8442:     while ($location=~m{/\.\./}) {
 8443: 	if ($location =~ m{/[^/]+/\.\./}) {
 8444: 	    $location=~ s{/[^/]+/\.\./}{/}g;
 8445: 	} else {
 8446: 	    $location=~ s{/\.\./}{/}g;
 8447: 	}
 8448:     } #remove dir/..
 8449:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
 8450:     return $location;
 8451: }
 8452: 
 8453: sub hreflocation {
 8454:     my ($dir,$file)=@_;
 8455:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
 8456: 	$file=filelocation($dir,$file);
 8457:     } elsif ($file=~m-^/adm/-) {
 8458: 	$file=~s-^/adm/wrapper/-/-;
 8459: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
 8460:     }
 8461:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
 8462: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
 8463:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
 8464: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
 8465:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
 8466: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
 8467: 	    -/uploaded/$1/$2/-x;
 8468:     }
 8469:     if ($file=~ m{^/userfiles/}) {
 8470: 	$file =~ s{^/userfiles/}{/uploaded/};
 8471:     }
 8472:     return $file;
 8473: }
 8474: 
 8475: sub current_machine_domains {
 8476:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
 8477: }
 8478: 
 8479: sub machine_domains {
 8480:     my ($hostname) = @_;
 8481:     my @domains;
 8482:     my %hostname = &all_hostnames();
 8483:     while( my($id, $name) = each(%hostname)) {
 8484: #	&logthis("-$id-$name-$hostname-");
 8485: 	if ($hostname eq $name) {
 8486: 	    push(@domains,&host_domain($id));
 8487: 	}
 8488:     }
 8489:     return @domains;
 8490: }
 8491: 
 8492: sub current_machine_ids {
 8493:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
 8494: }
 8495: 
 8496: sub machine_ids {
 8497:     my ($hostname) = @_;
 8498:     $hostname ||= &hostname($perlvar{'lonHostID'});
 8499:     my @ids;
 8500:     my %name_to_host = &all_names();
 8501:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
 8502: 	return @{ $name_to_host{$hostname} };
 8503:     }
 8504:     return;
 8505: }
 8506: 
 8507: sub additional_machine_domains {
 8508:     my @domains;
 8509:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
 8510:     while( my $line = <$fh>) {
 8511:         $line =~ s/\s//g;
 8512:         push(@domains,$line);
 8513:     }
 8514:     return @domains;
 8515: }
 8516: 
 8517: sub default_login_domain {
 8518:     my $domain = $perlvar{'lonDefDomain'};
 8519:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
 8520:     foreach my $posdom (&current_machine_domains(),
 8521:                         &additional_machine_domains()) {
 8522:         if (lc($posdom) eq lc($testdomain)) {
 8523:             $domain=$posdom;
 8524:             last;
 8525:         }
 8526:     }
 8527:     return $domain;
 8528: }
 8529: 
 8530: # ------------------------------------------------------------- Declutters URLs
 8531: 
 8532: sub declutter {
 8533:     my $thisfn=shift;
 8534:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
 8535:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
 8536:     $thisfn=~s/^\///;
 8537:     $thisfn=~s|^adm/wrapper/||;
 8538:     $thisfn=~s|^adm/coursedocs/showdoc/||;
 8539:     $thisfn=~s/^res\///;
 8540:     $thisfn=~s/\?.+$//;
 8541:     return $thisfn;
 8542: }
 8543: 
 8544: # ------------------------------------------------------------- Clutter up URLs
 8545: 
 8546: sub clutter {
 8547:     my $thisfn='/'.&declutter(shift);
 8548:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
 8549: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
 8550:        $thisfn='/res'.$thisfn; 
 8551:     }
 8552:     if ($thisfn !~m|/adm|) {
 8553: 	if ($thisfn =~ m|/ext/|) {
 8554: 	    $thisfn='/adm/wrapper'.$thisfn;
 8555: 	} else {
 8556: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
 8557: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
 8558: 	    if ($embstyle eq 'ssi'
 8559: 		|| ($embstyle eq 'hdn')
 8560: 		|| ($embstyle eq 'rat')
 8561: 		|| ($embstyle eq 'prv')
 8562: 		|| ($embstyle eq 'ign')) {
 8563: 		#do nothing with these
 8564: 	    } elsif (($embstyle eq 'img') 
 8565: 		|| ($embstyle eq 'emb')
 8566: 		|| ($embstyle eq 'wrp')) {
 8567: 		$thisfn='/adm/wrapper'.$thisfn;
 8568: 	    } elsif ($embstyle eq 'unk'
 8569: 		     && $thisfn!~/\.(sequence|page)$/) {
 8570: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
 8571: 	    } else {
 8572: #		&logthis("Got a blank emb style");
 8573: 	    }
 8574: 	}
 8575:     }
 8576:     return $thisfn;
 8577: }
 8578: 
 8579: sub clutter_with_no_wrapper {
 8580:     my $uri = &clutter(shift);
 8581:     if ($uri =~ m-^/adm/-) {
 8582: 	$uri =~ s-^/adm/wrapper/-/-;
 8583: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
 8584:     }
 8585:     return $uri;
 8586: }
 8587: 
 8588: sub freeze_escape {
 8589:     my ($value)=@_;
 8590:     if (ref($value)) {
 8591: 	$value=&nfreeze($value);
 8592: 	return '__FROZEN__'.&escape($value);
 8593:     }
 8594:     return &escape($value);
 8595: }
 8596: 
 8597: 
 8598: sub thaw_unescape {
 8599:     my ($value)=@_;
 8600:     if ($value =~ /^__FROZEN__/) {
 8601: 	substr($value,0,10,undef);
 8602: 	$value=&unescape($value);
 8603: 	return &thaw($value);
 8604:     }
 8605:     return &unescape($value);
 8606: }
 8607: 
 8608: sub correct_line_ends {
 8609:     my ($result)=@_;
 8610:     $$result =~s/\r\n/\n/mg;
 8611:     $$result =~s/\r/\n/mg;
 8612: }
 8613: # ================================================================ Main Program
 8614: 
 8615: sub goodbye {
 8616:    &logthis("Starting Shut down");
 8617: #not converted to using infrastruture and probably shouldn't be
 8618:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
 8619: #converted
 8620: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
 8621:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
 8622: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
 8623: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
 8624: #1.1 only
 8625: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
 8626: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
 8627: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
 8628: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
 8629:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
 8630:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
 8631:    &logthis(sprintf("%-20s is %s",'hits',$hits));
 8632:    &flushcourselogs();
 8633:    &logthis("Shutting down");
 8634: }
 8635: 
 8636: sub get_dns {
 8637:     my ($url,$func,$ignore_cache) = @_;
 8638:     if (!$ignore_cache) {
 8639: 	my ($content,$cached)=
 8640: 	    &Apache::lonnet::is_cached_new('dns',$url);
 8641: 	if ($cached) {
 8642: 	    &$func($content);
 8643: 	    return;
 8644: 	}
 8645:     }
 8646: 
 8647:     my %alldns;
 8648:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 8649:     foreach my $dns (<$config>) {
 8650: 	next if ($dns !~ /^\^(\S*)/x);
 8651:         my $line = $1;
 8652:         my ($host,$protocol) = split(/:/,$line);
 8653:         if ($protocol ne 'https') {
 8654:             $protocol = 'http';
 8655:         }
 8656: 	$alldns{$host} = $protocol;
 8657:     }
 8658:     while (%alldns) {
 8659: 	my ($dns) = keys(%alldns);
 8660: 	my $ua=new LWP::UserAgent;
 8661: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
 8662: 	my $response=$ua->request($request);
 8663:         delete($alldns{$dns});
 8664: 	next if ($response->is_error());
 8665: 	my @content = split("\n",$response->content);
 8666: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
 8667: 	&$func(\@content);
 8668: 	return;
 8669:     }
 8670:     close($config);
 8671:     my $which = (split('/',$url))[3];
 8672:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
 8673:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
 8674:     my @content = <$config>;
 8675:     &$func(\@content);
 8676:     return;
 8677: }
 8678: # ------------------------------------------------------------ Read domain file
 8679: {
 8680:     my $loaded;
 8681:     my %domain;
 8682: 
 8683:     sub parse_domain_tab {
 8684: 	my ($lines) = @_;
 8685: 	foreach my $line (@$lines) {
 8686: 	    next if ($line =~ /^(\#|\s*$ )/x);
 8687: 
 8688: 	    chomp($line);
 8689: 	    my ($name,@elements) = split(/:/,$line,9);
 8690: 	    my %this_domain;
 8691: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
 8692: 			       'lang_def', 'city', 'longi', 'lati',
 8693: 			       'primary') {
 8694: 		$this_domain{$field} = shift(@elements);
 8695: 	    }
 8696: 	    $domain{$name} = \%this_domain;
 8697: 	}
 8698:     }
 8699: 
 8700:     sub reset_domain_info {
 8701: 	undef($loaded);
 8702: 	undef(%domain);
 8703:     }
 8704: 
 8705:     sub load_domain_tab {
 8706: 	my ($ignore_cache) = @_;
 8707: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
 8708: 	my $fh;
 8709: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
 8710: 	    my @lines = <$fh>;
 8711: 	    &parse_domain_tab(\@lines);
 8712: 	}
 8713: 	close($fh);
 8714: 	$loaded = 1;
 8715:     }
 8716: 
 8717:     sub domain {
 8718: 	&load_domain_tab() if (!$loaded);
 8719: 
 8720: 	my ($name,$what) = @_;
 8721: 	return if ( !exists($domain{$name}) );
 8722: 
 8723: 	if (!$what) {
 8724: 	    return $domain{$name}{'description'};
 8725: 	}
 8726: 	return $domain{$name}{$what};
 8727:     }
 8728: 
 8729:     sub domain_info {
 8730:         &load_domain_tab() if (!$loaded);
 8731:         return %domain;
 8732:     }
 8733: 
 8734: }
 8735: 
 8736: 
 8737: # ------------------------------------------------------------- Read hosts file
 8738: {
 8739:     my %hostname;
 8740:     my %hostdom;
 8741:     my %libserv;
 8742:     my $loaded;
 8743:     my %name_to_host;
 8744: 
 8745:     sub parse_hosts_tab {
 8746: 	my ($file) = @_;
 8747: 	foreach my $configline (@$file) {
 8748: 	    next if ($configline =~ /^(\#|\s*$ )/x);
 8749: 	    next if ($configline =~ /^\^/);
 8750: 	    chomp($configline);
 8751: 	    my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
 8752: 	    $name=~s/\s//g;
 8753: 	    if ($id && $domain && $role && $name) {
 8754: 		$hostname{$id}=$name;
 8755: 		push(@{$name_to_host{$name}}, $id);
 8756: 		$hostdom{$id}=$domain;
 8757: 		if ($role eq 'library') { $libserv{$id}=$name; }
 8758:                 if (defined($protocol)) {
 8759:                     if ($protocol eq 'https') {
 8760:                         $protocol{$id} = $protocol;
 8761:                     } else {
 8762:                         $protocol{$id} = 'http'; 
 8763:                     }
 8764:                 } else {
 8765:                     $protocol{$id} = 'http';
 8766:                 }
 8767: 	    }
 8768: 	}
 8769:     }
 8770:     
 8771:     sub reset_hosts_info {
 8772: 	&purge_remembered();
 8773: 	&reset_domain_info();
 8774: 	&reset_hosts_ip_info();
 8775: 	undef(%name_to_host);
 8776: 	undef(%hostname);
 8777: 	undef(%hostdom);
 8778: 	undef(%libserv);
 8779: 	undef($loaded);
 8780:     }
 8781: 
 8782:     sub load_hosts_tab {
 8783: 	my ($ignore_cache) = @_;
 8784: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
 8785: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
 8786: 	my @config = <$config>;
 8787: 	&parse_hosts_tab(\@config);
 8788: 	close($config);
 8789: 	$loaded=1;
 8790:     }
 8791: 
 8792:     sub hostname {
 8793: 	&load_hosts_tab() if (!$loaded);
 8794: 
 8795: 	my ($lonid) = @_;
 8796: 	return $hostname{$lonid};
 8797:     }
 8798: 
 8799:     sub all_hostnames {
 8800: 	&load_hosts_tab() if (!$loaded);
 8801: 
 8802: 	return %hostname;
 8803:     }
 8804: 
 8805:     sub all_names {
 8806: 	&load_hosts_tab() if (!$loaded);
 8807: 
 8808: 	return %name_to_host;
 8809:     }
 8810: 
 8811:     sub all_host_domain {
 8812:         &load_hosts_tab() if (!$loaded);
 8813:         return %hostdom;
 8814:     }
 8815: 
 8816:     sub is_library {
 8817: 	&load_hosts_tab() if (!$loaded);
 8818: 
 8819: 	return exists($libserv{$_[0]});
 8820:     }
 8821: 
 8822:     sub all_library {
 8823: 	&load_hosts_tab() if (!$loaded);
 8824: 
 8825: 	return %libserv;
 8826:     }
 8827: 
 8828:     sub get_servers {
 8829: 	&load_hosts_tab() if (!$loaded);
 8830: 
 8831: 	my ($domain,$type) = @_;
 8832: 	my %possible_hosts = ($type eq 'library') ? %libserv
 8833: 	                                          : %hostname;
 8834: 	my %result;
 8835: 	if (ref($domain) eq 'ARRAY') {
 8836: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 8837: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
 8838: 		    $result{$host} = $hostname;
 8839: 		}
 8840: 	    }
 8841: 	} else {
 8842: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
 8843: 		if ($hostdom{$host} eq $domain) {
 8844: 		    $result{$host} = $hostname;
 8845: 		}
 8846: 	    }
 8847: 	}
 8848: 	return %result;
 8849:     }
 8850: 
 8851:     sub host_domain {
 8852: 	&load_hosts_tab() if (!$loaded);
 8853: 
 8854: 	my ($lonid) = @_;
 8855: 	return $hostdom{$lonid};
 8856:     }
 8857: 
 8858:     sub all_domains {
 8859: 	&load_hosts_tab() if (!$loaded);
 8860: 
 8861: 	my %seen;
 8862: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
 8863: 	return @uniq;
 8864:     }
 8865: }
 8866: 
 8867: { 
 8868:     my %iphost;
 8869:     my %name_to_ip;
 8870:     my %lonid_to_ip;
 8871: 
 8872:     sub get_hosts_from_ip {
 8873: 	my ($ip) = @_;
 8874: 	my %iphosts = &get_iphost();
 8875: 	if (ref($iphosts{$ip})) {
 8876: 	    return @{$iphosts{$ip}};
 8877: 	}
 8878: 	return;
 8879:     }
 8880:     
 8881:     sub reset_hosts_ip_info {
 8882: 	undef(%iphost);
 8883: 	undef(%name_to_ip);
 8884: 	undef(%lonid_to_ip);
 8885:     }
 8886: 
 8887:     sub get_host_ip {
 8888: 	my ($lonid) = @_;
 8889: 	if (exists($lonid_to_ip{$lonid})) {
 8890: 	    return $lonid_to_ip{$lonid};
 8891: 	}
 8892: 	my $name=&hostname($lonid);
 8893:    	my $ip = gethostbyname($name);
 8894: 	return if (!$ip || length($ip) ne 4);
 8895: 	$ip=inet_ntoa($ip);
 8896: 	$name_to_ip{$name}   = $ip;
 8897: 	$lonid_to_ip{$lonid} = $ip;
 8898: 	return $ip;
 8899:     }
 8900:     
 8901:     sub get_iphost {
 8902: 	my ($ignore_cache) = @_;
 8903: 
 8904: 	if (!$ignore_cache) {
 8905: 	    if (%iphost) {
 8906: 		return %iphost;
 8907: 	    }
 8908: 	    my ($ip_info,$cached)=
 8909: 		&Apache::lonnet::is_cached_new('iphost','iphost');
 8910: 	    if ($cached) {
 8911: 		%iphost      = %{$ip_info->[0]};
 8912: 		%name_to_ip  = %{$ip_info->[1]};
 8913: 		%lonid_to_ip = %{$ip_info->[2]};
 8914: 		return %iphost;
 8915: 	    }
 8916: 	}
 8917: 
 8918: 	# get yesterday's info for fallback
 8919: 	my %old_name_to_ip;
 8920: 	my ($ip_info,$cached)=
 8921: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
 8922: 	if ($cached) {
 8923: 	    %old_name_to_ip = %{$ip_info->[1]};
 8924: 	}
 8925: 
 8926: 	my %name_to_host = &all_names();
 8927: 	foreach my $name (keys(%name_to_host)) {
 8928: 	    my $ip;
 8929: 	    if (!exists($name_to_ip{$name})) {
 8930: 		$ip = gethostbyname($name);
 8931: 		if (!$ip || length($ip) ne 4) {
 8932: 		    if (defined($old_name_to_ip{$name})) {
 8933: 			$ip = $old_name_to_ip{$name};
 8934: 			&logthis("Can't find $name defaulting to old $ip");
 8935: 		    } else {
 8936: 			&logthis("Name $name no IP found");
 8937: 			next;
 8938: 		    }
 8939: 		} else {
 8940: 		    $ip=inet_ntoa($ip);
 8941: 		}
 8942: 		$name_to_ip{$name} = $ip;
 8943: 	    } else {
 8944: 		$ip = $name_to_ip{$name};
 8945: 	    }
 8946: 	    foreach my $id (@{ $name_to_host{$name} }) {
 8947: 		$lonid_to_ip{$id} = $ip;
 8948: 	    }
 8949: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
 8950: 	}
 8951: 	&Apache::lonnet::do_cache_new('iphost','iphost',
 8952: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
 8953: 				      48*60*60);
 8954: 
 8955: 	return %iphost;
 8956:     }
 8957: }
 8958: 
 8959: BEGIN {
 8960: 
 8961: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
 8962:     unless ($readit) {
 8963: {
 8964:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
 8965:     %perlvar = (%perlvar,%{$configvars});
 8966: }
 8967: 
 8968: 
 8969: # ------------------------------------------------------ Read spare server file
 8970: {
 8971:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
 8972: 
 8973:     while (my $configline=<$config>) {
 8974:        chomp($configline);
 8975:        if ($configline) {
 8976: 	   my ($host,$type) = split(':',$configline,2);
 8977: 	   if (!defined($type) || $type eq '') { $type = 'default' };
 8978: 	   push(@{ $spareid{$type} }, $host);
 8979:        }
 8980:     }
 8981:     close($config);
 8982: }
 8983: # ------------------------------------------------------------ Read permissions
 8984: {
 8985:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
 8986: 
 8987:     while (my $configline=<$config>) {
 8988: 	chomp($configline);
 8989: 	if ($configline) {
 8990: 	    my ($role,$perm)=split(/ /,$configline);
 8991: 	    if ($perm ne '') { $pr{$role}=$perm; }
 8992: 	}
 8993:     }
 8994:     close($config);
 8995: }
 8996: 
 8997: # -------------------------------------------- Read plain texts for permissions
 8998: {
 8999:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
 9000: 
 9001:     while (my $configline=<$config>) {
 9002: 	chomp($configline);
 9003: 	if ($configline) {
 9004: 	    my ($short,@plain)=split(/:/,$configline);
 9005:             %{$prp{$short}} = ();
 9006: 	    if (@plain > 0) {
 9007:                 $prp{$short}{'std'} = $plain[0];
 9008:                 for (my $i=1; $i<@plain; $i++) {
 9009:                     $prp{$short}{'alt'.$i} = $plain[$i];  
 9010:                 }
 9011:             }
 9012: 	}
 9013:     }
 9014:     close($config);
 9015: }
 9016: 
 9017: # ---------------------------------------------------------- Read package table
 9018: {
 9019:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
 9020: 
 9021:     while (my $configline=<$config>) {
 9022: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
 9023: 	chomp($configline);
 9024: 	my ($short,$plain)=split(/:/,$configline);
 9025: 	my ($pack,$name)=split(/\&/,$short);
 9026: 	if ($plain ne '') {
 9027: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
 9028: 	    $packagetab{$short}=$plain; 
 9029: 	}
 9030:     }
 9031:     close($config);
 9032: }
 9033: 
 9034: # ------------- set up temporary directory
 9035: {
 9036:     $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
 9037: 
 9038: }
 9039: 
 9040: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
 9041: 				'compress_threshold'=> 20_000,
 9042:  			        });
 9043: 
 9044: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
 9045: $dumpcount=0;
 9046: $locknum=0;
 9047: 
 9048: &logtouch();
 9049: &logthis('<font color="yellow">INFO: Read configuration</font>');
 9050: $readit=1;
 9051:     {
 9052: 	use integer;
 9053: 	my $test=(2**32)+1;
 9054: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
 9055: 	&logthis(" Detected 64bit platform ($_64bit)");
 9056:     }
 9057: }
 9058: }
 9059: 
 9060: 1;
 9061: __END__
 9062: 
 9063: =pod
 9064: 
 9065: =head1 NAME
 9066: 
 9067: Apache::lonnet - Subroutines to ask questions about things in the network.
 9068: 
 9069: =head1 SYNOPSIS
 9070: 
 9071: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
 9072: 
 9073:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
 9074: 
 9075: Common parameters:
 9076: 
 9077: =over 4
 9078: 
 9079: =item *
 9080: 
 9081: $uname : an internal username (if $cname expecting a course Id specifically)
 9082: 
 9083: =item *
 9084: 
 9085: $udom : a domain (if $cdom expecting a course's domain specifically)
 9086: 
 9087: =item *
 9088: 
 9089: $symb : a resource instance identifier
 9090: 
 9091: =item *
 9092: 
 9093: $namespace : the name of a .db file that contains the data needed or
 9094: being set.
 9095: 
 9096: =back
 9097: 
 9098: =head1 OVERVIEW
 9099: 
 9100: lonnet provides subroutines which interact with the
 9101: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
 9102: about classes, users, and resources.
 9103: 
 9104: For many of these objects you can also use this to store data about
 9105: them or modify them in various ways.
 9106: 
 9107: =head2 Symbs
 9108: 
 9109: To identify a specific instance of a resource, LON-CAPA uses symbols
 9110: or "symbs"X<symb>. These identifiers are built from the URL of the
 9111: map, the resource number of the resource in the map, and the URL of
 9112: the resource itself. The latter is somewhat redundant, but might help
 9113: if maps change.
 9114: 
 9115: An example is
 9116: 
 9117:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
 9118: 
 9119: The respective map entry is
 9120: 
 9121:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
 9122:   title="Problem 2">
 9123:  </resource>
 9124: 
 9125: Symbs are used by the random number generator, as well as to store and
 9126: restore data specific to a certain instance of for example a problem.
 9127: 
 9128: =head2 Storing And Retrieving Data
 9129: 
 9130: X<store()>X<cstore()>X<restore()>Three of the most important functions
 9131: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
 9132: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
 9133: is is the non-critical message twin of cstore. These functions are for
 9134: handlers to store a perl hash to a user's permanent data space in an
 9135: easy manner, and to retrieve it again on another call. It is expected
 9136: that a handler would use this once at the beginning to retrieve data,
 9137: and then again once at the end to send only the new data back.
 9138: 
 9139: The data is stored in the user's data directory on the user's
 9140: homeserver under the ID of the course.
 9141: 
 9142: The hash that is returned by restore will have all of the previous
 9143: value for all of the elements of the hash.
 9144: 
 9145: Example:
 9146: 
 9147:  #creating a hash
 9148:  my %hash;
 9149:  $hash{'foo'}='bar';
 9150: 
 9151:  #storing it
 9152:  &Apache::lonnet::cstore(\%hash);
 9153: 
 9154:  #changing a value
 9155:  $hash{'foo'}='notbar';
 9156: 
 9157:  #adding a new value
 9158:  $hash{'bar'}='foo';
 9159:  &Apache::lonnet::cstore(\%hash);
 9160: 
 9161:  #retrieving the hash
 9162:  my %history=&Apache::lonnet::restore();
 9163: 
 9164:  #print the hash
 9165:  foreach my $key (sort(keys(%history))) {
 9166:    print("\%history{$key} = $history{$key}");
 9167:  }
 9168: 
 9169: Will print out:
 9170: 
 9171:  %history{1:foo} = bar
 9172:  %history{1:keys} = foo:timestamp
 9173:  %history{1:timestamp} = 990455579
 9174:  %history{2:bar} = foo
 9175:  %history{2:foo} = notbar
 9176:  %history{2:keys} = foo:bar:timestamp
 9177:  %history{2:timestamp} = 990455580
 9178:  %history{bar} = foo
 9179:  %history{foo} = notbar
 9180:  %history{timestamp} = 990455580
 9181:  %history{version} = 2
 9182: 
 9183: Note that the special hash entries C<keys>, C<version> and
 9184: C<timestamp> were added to the hash. C<version> will be equal to the
 9185: total number of versions of the data that have been stored. The
 9186: C<timestamp> attribute will be the UNIX time the hash was
 9187: stored. C<keys> is available in every historical section to list which
 9188: keys were added or changed at a specific historical revision of a
 9189: hash.
 9190: 
 9191: B<Warning>: do not store the hash that restore returns directly. This
 9192: will cause a mess since it will restore the historical keys as if the
 9193: were new keys. I.E. 1:foo will become 1:1:foo etc.
 9194: 
 9195: Calling convention:
 9196: 
 9197:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
 9198:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
 9199: 
 9200: For more detailed information, see lonnet specific documentation.
 9201: 
 9202: =head1 RETURN MESSAGES
 9203: 
 9204: =over 4
 9205: 
 9206: =item * B<con_lost>: unable to contact remote host
 9207: 
 9208: =item * B<con_delayed>: unable to contact remote host, message will be delivered
 9209: when the connection is brought back up
 9210: 
 9211: =item * B<con_failed>: unable to contact remote host and unable to save message
 9212: for later delivery
 9213: 
 9214: =item * B<error:>: an error a occurred, a description of the error follows the :
 9215: 
 9216: =item * B<no_such_host>: unable to fund a host associated with the user/domain
 9217: that was requested
 9218: 
 9219: =back
 9220: 
 9221: =head1 PUBLIC SUBROUTINES
 9222: 
 9223: =head2 Session Environment Functions
 9224: 
 9225: =over 4
 9226: 
 9227: =item * 
 9228: X<appenv()>
 9229: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
 9230: the user envirnoment file, and will be restored for each access this
 9231: user makes during this session, also modifies the %env for the current
 9232: process. Optional rolesarrayref - if defined contains a reference to an array
 9233: of roles which are exempt from the restriction on modifying user.role entries 
 9234: in the user's environment.db and in %env.    
 9235: 
 9236: =item *
 9237: X<delenv()>
 9238: B<delenv($delthis,$regexp)>: removes all items from the session
 9239: environment file that begin with $delthis. If the
 9240: optional second arg - $regexp - is true, $delthis is treated as a
 9241: regular expression, otherwise \Q$delthis\E is used.
 9242: The values are also deleted from the current processes %env.
 9243: 
 9244: =item * get_env_multiple($name) 
 9245: 
 9246: gets $name from the %env hash, it seemlessly handles the cases where multiple
 9247: values may be defined and end up as an array ref.
 9248: 
 9249: returns an array of values
 9250: 
 9251: =back
 9252: 
 9253: =head2 User Information
 9254: 
 9255: =over 4
 9256: 
 9257: =item *
 9258: X<queryauthenticate()>
 9259: B<queryauthenticate($uname,$udom)>: try to determine user's current 
 9260: authentication scheme
 9261: 
 9262: =item *
 9263: X<authenticate()>
 9264: B<authenticate($uname,$upass,$udom)>: try to
 9265: authenticate user from domain's lib servers (first use the current
 9266: one). C<$upass> should be the users password.
 9267: 
 9268: =item *
 9269: X<homeserver()>
 9270: B<homeserver($uname,$udom)>: find the server which has
 9271: the user's directory and files (there must be only one), this caches
 9272: the answer, and also caches if there is a borken connection.
 9273: 
 9274: =item *
 9275: X<idget()>
 9276: B<idget($udom,@ids)>: find the usernames behind a list of IDs
 9277: (IDs are a unique resource in a domain, there must be only 1 ID per
 9278: username, and only 1 username per ID in a specific domain) (returns
 9279: hash: id=>name,id=>name)
 9280: 
 9281: =item *
 9282: X<idrget()>
 9283: B<idrget($udom,@unames)>: find the IDs behind a list of
 9284: usernames (returns hash: name=>id,name=>id)
 9285: 
 9286: =item *
 9287: X<idput()>
 9288: B<idput($udom,%ids)>: store away a list of names and associated IDs
 9289: 
 9290: =item *
 9291: X<rolesinit()>
 9292: B<rolesinit($udom,$username,$authhost)>: get user privileges
 9293: 
 9294: =item *
 9295: X<getsection()>
 9296: B<getsection($udom,$uname,$cname)>: finds the section of student in the
 9297: course $cname, return section name/number or '' for "not in course"
 9298: and '-1' for "no section"
 9299: 
 9300: =item *
 9301: X<userenvironment()>
 9302: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
 9303: passed in @what from the requested user's environment, returns a hash
 9304: 
 9305: =item * 
 9306: X<userlog_query()>
 9307: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
 9308: activity.log file. %filters defines filters applied when parsing the
 9309: log file. These can be start or end timestamps, or the type of action
 9310: - log to look for Login or Logout events, check for Checkin or
 9311: Checkout, role for role selection. The response is in the form
 9312: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
 9313: escaped strings of the action recorded in the activity.log file.
 9314: 
 9315: =back
 9316: 
 9317: =head2 User Roles
 9318: 
 9319: =over 4
 9320: 
 9321: =item *
 9322: 
 9323: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
 9324:  F: full access
 9325:  U,I,K: authentication modes (cxx only)
 9326:  '': forbidden
 9327:  1: user needs to choose course
 9328:  2: browse allowed
 9329:  A: passphrase authentication needed
 9330: 
 9331: =item *
 9332: 
 9333: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
 9334: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
 9335: and course level
 9336: 
 9337: =item *
 9338: 
 9339: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
 9340: explanation of a user role term
 9341: 
 9342: =item *
 9343: 
 9344: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
 9345: All arguments are optional. Returns a hash of a roles, either for
 9346: co-author/assistant author roles for a user's Construction Space
 9347: (default), or if $context is 'userroles', roles for the user himself,
 9348: In the hash, keys are set to colon-separated $uname,$udom,$role, and
 9349: (optionally) if $withsec is true, a fourth colon-separated item - $section.
 9350: For each key, value is set to colon-separated start and end times for
 9351: the role.  If no username and domain are specified, will default to
 9352: current user/domain. Types, roles, and roledoms are references to arrays
 9353: of role statuses (active, future or previous), roles 
 9354: (e.g., cc,in, st etc.) and domains of the roles which can be used
 9355: to restrict the list of roles reported. If no array ref is 
 9356: provided for types, will default to return only active roles.
 9357: 
 9358: =back
 9359: 
 9360: =head2 User Modification
 9361: 
 9362: =over 4
 9363: 
 9364: =item *
 9365: 
 9366: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
 9367: user for the level given by URL.  Optional start and end dates (leave empty
 9368: string or zero for "no date")
 9369: 
 9370: =item *
 9371: 
 9372: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
 9373: change a users, password, possible return values are: ok,
 9374: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
 9375: refused
 9376: 
 9377: =item *
 9378: 
 9379: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
 9380: 
 9381: =item *
 9382: 
 9383: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
 9384:            $forceid,$desiredhome,$email,$inststatus) : 
 9385: modify user
 9386: 
 9387: =item *
 9388: 
 9389: modifystudent
 9390: 
 9391: modify a student's enrollment and identification information.
 9392: The course id is resolved based on the current users environment.  
 9393: This means the envoking user must be a course coordinator or otherwise
 9394: associated with a course.
 9395: 
 9396: This call is essentially a wrapper for lonnet::modifyuser and
 9397: lonnet::modify_student_enrollment
 9398: 
 9399: Inputs: 
 9400: 
 9401: =over 4
 9402: 
 9403: =item B<$udom> Student's loncapa domain
 9404: 
 9405: =item B<$uname> Student's loncapa login name
 9406: 
 9407: =item B<$uid> Student/Employee ID
 9408: 
 9409: =item B<$umode> Student's authentication mode
 9410: 
 9411: =item B<$upass> Student's password
 9412: 
 9413: =item B<$first> Student's first name
 9414: 
 9415: =item B<$middle> Student's middle name
 9416: 
 9417: =item B<$last> Student's last name
 9418: 
 9419: =item B<$gene> Student's generation
 9420: 
 9421: =item B<$usec> Student's section in course
 9422: 
 9423: =item B<$end> Unix time of the roles expiration
 9424: 
 9425: =item B<$start> Unix time of the roles start date
 9426: 
 9427: =item B<$forceid> If defined, allow $uid to be changed
 9428: 
 9429: =item B<$desiredhome> server to use as home server for student
 9430: 
 9431: =item B<$email> Student's permanent e-mail address
 9432: 
 9433: =item B<$type> Type of enrollment (auto or manual)
 9434: 
 9435: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
 9436: 
 9437: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
 9438: 
 9439: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
 9440: 
 9441: =item B<$context> role change context (shown in User Management Logs display in a course)
 9442: 
 9443: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
 9444: 
 9445: =back
 9446: 
 9447: =item *
 9448: 
 9449: modify_student_enrollment
 9450: 
 9451: Change a students enrollment status in a class.  The environment variable
 9452: 'role.request.course' must be defined for this function to proceed.
 9453: 
 9454: Inputs:
 9455: 
 9456: =over 4
 9457: 
 9458: =item $udom, students domain
 9459: 
 9460: =item $uname, students name
 9461: 
 9462: =item $uid, students user id
 9463: 
 9464: =item $first, students first name
 9465: 
 9466: =item $middle
 9467: 
 9468: =item $last
 9469: 
 9470: =item $gene
 9471: 
 9472: =item $usec
 9473: 
 9474: =item $end
 9475: 
 9476: =item $start
 9477: 
 9478: =item $type
 9479: 
 9480: =item $locktype
 9481: 
 9482: =item $cid
 9483: 
 9484: =item $selfenroll
 9485: 
 9486: =item $context
 9487: 
 9488: =back
 9489: 
 9490: 
 9491: =item *
 9492: 
 9493: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
 9494: custom role; give a custom role to a user for the level given by URL.  Specify
 9495: name and domain of role author, and role name
 9496: 
 9497: =item *
 9498: 
 9499: revokerole($udom,$uname,$url,$role) : revoke a role for url
 9500: 
 9501: =item *
 9502: 
 9503: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
 9504: 
 9505: =back
 9506: 
 9507: =head2 Course Infomation
 9508: 
 9509: =over 4
 9510: 
 9511: =item *
 9512: 
 9513: coursedescription($courseid) : returns a hash of information about the
 9514: specified course id, including all environment settings for the
 9515: course, the description of the course will be in the hash under the
 9516: key 'description'
 9517: 
 9518: =item *
 9519: 
 9520: resdata($name,$domain,$type,@which) : request for current parameter
 9521: setting for a specific $type, where $type is either 'course' or 'user',
 9522: @what should be a list of parameters to ask about. This routine caches
 9523: answers for 5 minutes.
 9524: 
 9525: =item *
 9526: 
 9527: get_courseresdata($courseid, $domain) : dump the entire course resource
 9528: data base, returning a hash that is keyed by the resource name and has
 9529: values that are the resource value.  I believe that the timestamps and
 9530: versions are also returned.
 9531: 
 9532: 
 9533: =back
 9534: 
 9535: =head2 Course Modification
 9536: 
 9537: =over 4
 9538: 
 9539: =item *
 9540: 
 9541: writecoursepref($courseid,%prefs) : write preferences (environment
 9542: database) for a course
 9543: 
 9544: =item *
 9545: 
 9546: createcourse($udom,$description,$url) : make/modify course
 9547: 
 9548: =back
 9549: 
 9550: =head2 Resource Subroutines
 9551: 
 9552: =over 4
 9553: 
 9554: =item *
 9555: 
 9556: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
 9557: 
 9558: =item *
 9559: 
 9560: repcopy($filename) : subscribes to the requested file, and attempts to
 9561: replicate from the owning library server, Might return
 9562: 'unavailable', 'not_found', 'forbidden', 'ok', or
 9563: 'bad_request', also attempts to grab the metadata for the
 9564: resource. Expects the local filesystem pathname
 9565: (/home/httpd/html/res/....)
 9566: 
 9567: =back
 9568: 
 9569: =head2 Resource Information
 9570: 
 9571: =over 4
 9572: 
 9573: =item *
 9574: 
 9575: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
 9576: a vairety of different possible values, $varname should be a request
 9577: string, and the other parameters can be used to specify who and what
 9578: one is asking about.
 9579: 
 9580: Possible values for $varname are environment.lastname (or other item
 9581: from the envirnment hash), user.name (or someother aspect about the
 9582: user), resource.0.maxtries (or some other part and parameter of a
 9583: resource)
 9584: 
 9585: =item *
 9586: 
 9587: directcondval($number) : get current value of a condition; reads from a state
 9588: string
 9589: 
 9590: =item *
 9591: 
 9592: condval($condidx) : value of condition index based on state
 9593: 
 9594: =item *
 9595: 
 9596: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
 9597: resource's metadata, $what should be either a specific key, or either
 9598: 'keys' (to get a list of possible keys) or 'packages' to get a list of
 9599: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
 9600: 
 9601: this function automatically caches all requests
 9602: 
 9603: =item *
 9604: 
 9605: metadata_query($query,$custom,$customshow) : make a metadata query against the
 9606: network of library servers; returns file handle of where SQL and regex results
 9607: will be stored for query
 9608: 
 9609: =item *
 9610: 
 9611: symbread($filename) : return symbolic list entry (filename argument optional);
 9612: returns the data handle
 9613: 
 9614: =item *
 9615: 
 9616: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
 9617: a possible symb for the URL in $thisfn, and if is an encryypted
 9618: resource that the user accessed using /enc/ returns a 1 on success, 0
 9619: on failure, user must be in a course, as it assumes the existance of
 9620: the course initial hash, and uses $env('request.course.id'}
 9621: 
 9622: 
 9623: =item *
 9624: 
 9625: symbclean($symb) : removes versions numbers from a symb, returns the
 9626: cleaned symb
 9627: 
 9628: =item *
 9629: 
 9630: is_on_map($uri) : checks if the $uri is somewhere on the current
 9631: course map, user must be in a course for it to work.
 9632: 
 9633: =item *
 9634: 
 9635: numval($salt) : return random seed value (addend for rndseed)
 9636: 
 9637: =item *
 9638: 
 9639: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
 9640: a random seed, all arguments are optional, if they aren't sent it uses the
 9641: environment to derive them. Note: if symb isn't sent and it can't get one
 9642: from &symbread it will use the current time as its return value
 9643: 
 9644: =item *
 9645: 
 9646: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
 9647: unfakeable, receipt
 9648: 
 9649: =item *
 9650: 
 9651: receipt() : API to ireceipt working off of env values; given out to users
 9652: 
 9653: =item *
 9654: 
 9655: countacc($url) : count the number of accesses to a given URL
 9656: 
 9657: =item *
 9658: 
 9659: 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
 9660: 
 9661: =item *
 9662: 
 9663: 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)
 9664: 
 9665: =item *
 9666: 
 9667: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
 9668: 
 9669: =item *
 9670: 
 9671: devalidate($symb) : devalidate temporary spreadsheet calculations,
 9672: forcing spreadsheet to reevaluate the resource scores next time.
 9673: 
 9674: =back
 9675: 
 9676: =head2 Storing/Retreiving Data
 9677: 
 9678: =over 4
 9679: 
 9680: =item *
 9681: 
 9682: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
 9683: for this url; hashref needs to be given and should be a \%hashname; the
 9684: remaining args aren't required and if they aren't passed or are '' they will
 9685: be derived from the env
 9686: 
 9687: =item *
 9688: 
 9689: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
 9690: uses critical subroutine
 9691: 
 9692: =item *
 9693: 
 9694: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
 9695: all args are optional
 9696: 
 9697: =item *
 9698: 
 9699: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
 9700: dumps the complete (or key matching regexp) namespace into a hash
 9701: ($udom, $uname, $regexp, $range are optional) for a namespace that is
 9702: normally &store()ed into
 9703: 
 9704: $range should be either an integer '100' (give me the first 100
 9705:                                            matching records)
 9706:               or be  two integers sperated by a - with no spaces
 9707:                  '30-50' (give me the 30th through the 50th matching
 9708:                           records)
 9709: 
 9710: 
 9711: =item *
 9712: 
 9713: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
 9714: replaces a &store() version of data with a replacement set of data
 9715: for a particular resource in a namespace passed in the $storehash hash 
 9716: reference
 9717: 
 9718: =item *
 9719: 
 9720: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
 9721: works very similar to store/cstore, but all data is stored in a
 9722: temporary location and can be reset using tmpreset, $storehash should
 9723: be a hash reference, returns nothing on success
 9724: 
 9725: =item *
 9726: 
 9727: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
 9728: similar to restore, but all data is stored in a temporary location and
 9729: can be reset using tmpreset. Returns a hash of values on success,
 9730: error string otherwise.
 9731: 
 9732: =item *
 9733: 
 9734: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
 9735: deltes all keys for $symb form the temporary storage hash.
 9736: 
 9737: =item *
 9738: 
 9739: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 9740: reference filled in from namesp ($udom and $uname are optional)
 9741: 
 9742: =item *
 9743: 
 9744: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
 9745: namesp ($udom and $uname are optional)
 9746: 
 9747: =item *
 9748: 
 9749: dump($namespace,$udom,$uname,$regexp,$range) : 
 9750: dumps the complete (or key matching regexp) namespace into a hash
 9751: ($udom, $uname, $regexp, $range are optional)
 9752: 
 9753: $range should be either an integer '100' (give me the first 100
 9754:                                            matching records)
 9755:               or be  two integers sperated by a - with no spaces
 9756:                  '30-50' (give me the 30th through the 50th matching
 9757:                           records)
 9758: =item *
 9759: 
 9760: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
 9761: $store can be a scalar, an array reference, or if the amount to be 
 9762: incremented is > 1, a hash reference.
 9763: 
 9764: ($udom and $uname are optional)
 9765: 
 9766: =item *
 9767: 
 9768: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
 9769: ($udom and $uname are optional)
 9770: 
 9771: =item *
 9772: 
 9773: cput($namespace,$storehash,$udom,$uname) : critical put
 9774: ($udom and $uname are optional)
 9775: 
 9776: =item *
 9777: 
 9778: newput($namespace,$storehash,$udom,$uname) :
 9779: 
 9780: Attempts to store the items in the $storehash, but only if they don't
 9781: currently exist, if this succeeds you can be certain that you have 
 9782: successfully created a new key value pair in the $namespace db.
 9783: 
 9784: 
 9785: Args:
 9786:  $namespace: name of database to store values to
 9787:  $storehash: hashref to store to the db
 9788:  $udom: (optional) domain of user containing the db
 9789:  $uname: (optional) name of user caontaining the db
 9790: 
 9791: Returns:
 9792:  'ok' -> succeeded in storing all keys of $storehash
 9793:  'key_exists: <key>' -> failed to anything out of $storehash, as at
 9794:                         least <key> already existed in the db (other
 9795:                         requested keys may also already exist)
 9796:  'error: <msg>' -> unable to tie the DB or other error occurred
 9797:  'con_lost' -> unable to contact request server
 9798:  'refused' -> action was not allowed by remote machine
 9799: 
 9800: 
 9801: =item *
 9802: 
 9803: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
 9804: reference filled in from namesp (encrypts the return communication)
 9805: ($udom and $uname are optional)
 9806: 
 9807: =item *
 9808: 
 9809: log($udom,$name,$home,$message) : write to permanent log for user; use
 9810: critical subroutine
 9811: 
 9812: =item *
 9813: 
 9814: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
 9815: array reference filled in from namespace found in domain level on either
 9816: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
 9817: 
 9818: =item *
 9819: 
 9820: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
 9821: domain level either on specified domain server ($uhome) or primary domain 
 9822: server ($udom and $uhome are optional)
 9823: 
 9824: =item * 
 9825: 
 9826: get_domain_defaults($target_domain) : returns hash with defaults for
 9827: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
 9828: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
 9829: or localauth), initial password or a kerberos realm, language (e.g., en-us).
 9830: Values are retrieved from cache (if current), or from domain's configuration.db
 9831: (if available), or lastly from values in lonTabs/dns_domain,tab, 
 9832: or lonTabs/domain.tab. 
 9833: 
 9834: %domdefaults = &get_auth_defaults($target_domain);
 9835: 
 9836: =back
 9837: 
 9838: =head2 Network Status Functions
 9839: 
 9840: =over 4
 9841: 
 9842: =item *
 9843: 
 9844: dirlist($uri) : return directory list based on URI
 9845: 
 9846: =item *
 9847: 
 9848: spareserver() : find server with least workload from spare.tab
 9849: 
 9850: =back
 9851: 
 9852: =head2 Apache Request
 9853: 
 9854: =over 4
 9855: 
 9856: =item *
 9857: 
 9858: ssi($url,%hash) : server side include, does a complete request cycle on url to
 9859: localhost, posts hash
 9860: 
 9861: =back
 9862: 
 9863: =head2 Data to String to Data
 9864: 
 9865: =over 4
 9866: 
 9867: =item *
 9868: 
 9869: hash2str(%hash) : convert a hash into a string complete with escaping and '='
 9870: and '&' separators, supports elements that are arrayrefs and hashrefs
 9871: 
 9872: =item *
 9873: 
 9874: hashref2str($hashref) : convert a hashref into a string complete with
 9875: escaping and '=' and '&' separators, supports elements that are
 9876: arrayrefs and hashrefs
 9877: 
 9878: =item *
 9879: 
 9880: arrayref2str($arrayref) : convert an arrayref into a string complete
 9881: with escaping and '&' separators, supports elements that are arrayrefs
 9882: and hashrefs
 9883: 
 9884: =item *
 9885: 
 9886: str2hash($string) : convert string to hash using unescaping and
 9887: splitting on '=' and '&', supports elements that are arrayrefs and
 9888: hashrefs
 9889: 
 9890: =item *
 9891: 
 9892: str2array($string) : convert string to hash using unescaping and
 9893: splitting on '&', supports elements that are arrayrefs and hashrefs
 9894: 
 9895: =back
 9896: 
 9897: =head2 Logging Routines
 9898: 
 9899: =over 4
 9900: 
 9901: These routines allow one to make log messages in the lonnet.log and
 9902: lonnet.perm logfiles.
 9903: 
 9904: =item *
 9905: 
 9906: logtouch() : make sure the logfile, lonnet.log, exists
 9907: 
 9908: =item *
 9909: 
 9910: logthis() : append message to the normal lonnet.log file, it gets
 9911: preiodically rolled over and deleted.
 9912: 
 9913: =item *
 9914: 
 9915: logperm() : append a permanent message to lonnet.perm.log, this log
 9916: file never gets deleted by any automated portion of the system, only
 9917: messages of critical importance should go in here.
 9918: 
 9919: =back
 9920: 
 9921: =head2 General File Helper Routines
 9922: 
 9923: =over 4
 9924: 
 9925: =item *
 9926: 
 9927: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
 9928: (a) files in /uploaded
 9929:   (i) If a local copy of the file exists - 
 9930:       compares modification date of local copy with last-modified date for 
 9931:       definitive version stored on home server for course. If local copy is 
 9932:       stale, requests a new version from the home server and stores it. 
 9933:       If the original has been removed from the home server, then local copy 
 9934:       is unlinked.
 9935:   (ii) If local copy does not exist -
 9936:       requests the file from the home server and stores it. 
 9937:   
 9938:   If $caller is 'uploadrep':  
 9939:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
 9940:     for request for files originally uploaded via DOCS. 
 9941:      - returns 'ok' if fresh local copy now available, -1 otherwise.
 9942:   
 9943:   Otherwise:
 9944:      This indicates a call from the content generation phase of the request.
 9945:      -  returns the entire contents of the file or -1.
 9946:      
 9947: (b) files in /res
 9948:    - returns the entire contents of a file or -1; 
 9949:    it properly subscribes to and replicates the file if neccessary.
 9950: 
 9951: 
 9952: =item *
 9953: 
 9954: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
 9955:                   reference
 9956: 
 9957: returns either a stat() list of data about the file or an empty list
 9958: if the file doesn't exist or couldn't find out about it (connection
 9959: problems or user unknown)
 9960: 
 9961: =item *
 9962: 
 9963: filelocation($dir,$file) : returns file system location of a file
 9964: based on URI; meant to be "fairly clean" absolute reference, $dir is a
 9965: directory that relative $file lookups are to looked in ($dir of /a/dir
 9966: and a file of ../bob will become /a/bob)
 9967: 
 9968: =item *
 9969: 
 9970: hreflocation($dir,$file) : returns file system location or a URL; same as
 9971: filelocation except for hrefs
 9972: 
 9973: =item *
 9974: 
 9975: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
 9976: 
 9977: =back
 9978: 
 9979: =head2 Usererfile file routines (/uploaded*)
 9980: 
 9981: =over 4
 9982: 
 9983: =item *
 9984: 
 9985: userfileupload(): main rotine for putting a file in a user or course's
 9986:                   filespace, arguments are,
 9987: 
 9988:  formname - required - this is the name of the element in $env where the
 9989:            filename, and the contents of the file to create/modifed exist
 9990:            the filename is in $env{'form.'.$formname.'.filename'} and the
 9991:            contents of the file is located in $env{'form.'.$formname}
 9992:  coursedoc - if true, store the file in the course of the active role
 9993:              of the current user
 9994:  subdir - required - subdirectory to put the file in under ../userfiles/
 9995:          if undefined, it will be placed in "unknown"
 9996: 
 9997:  (This routine calls clean_filename() to remove any dangerous
 9998:  characters from the filename, and then calls finuserfileupload() to
 9999:  complete the transaction)
10000: 
10001:  returns either the url of the uploaded file (/uploaded/....) if successful
10002:  and /adm/notfound.html if unsuccessful
10003: 
10004: =item *
10005: 
10006: clean_filename(): routine for cleaing a filename up for storage in
10007:                  userfile space, argument is:
10008: 
10009:  filename - proposed filename
10010: 
10011: returns: the new clean filename
10012: 
10013: =item *
10014: 
10015: finishuserfileupload(): routine that creaes and sends the file to
10016: userspace, probably shouldn't be called directly
10017: 
10018:   docuname: username or courseid of destination for the file
10019:   docudom: domain of user/course of destination for the file
10020:   formname: same as for userfileupload()
10021:   fname: filename (inculding subdirectories) for the file
10022: 
10023:  returns either the url of the uploaded file (/uploaded/....) if successful
10024:  and /adm/notfound.html if unsuccessful
10025: 
10026: =item *
10027: 
10028: renameuserfile(): renames an existing userfile to a new name
10029: 
10030:   Args:
10031:    docuname: username or courseid of destination for the file
10032:    docudom: domain of user/course of destination for the file
10033:    old: current file name (including any subdirs under userfiles)
10034:    new: desired file name (including any subdirs under userfiles)
10035: 
10036: =item *
10037: 
10038: mkdiruserfile(): creates a directory is a userfiles dir
10039: 
10040:   Args:
10041:    docuname: username or courseid of destination for the file
10042:    docudom: domain of user/course of destination for the file
10043:    dir: dir to create (including any subdirs under userfiles)
10044: 
10045: =item *
10046: 
10047: removeuserfile(): removes a file that exists in userfiles
10048: 
10049:   Args:
10050:    docuname: username or courseid of destination for the file
10051:    docudom: domain of user/course of destination for the file
10052:    fname: filname to delete (including any subdirs under userfiles)
10053: 
10054: =item *
10055: 
10056: removeuploadedurl(): convience function for removeuserfile()
10057: 
10058:   Args:
10059:    url:  a full /uploaded/... url to delete
10060: 
10061: =item * 
10062: 
10063: get_portfile_permissions():
10064:   Args:
10065:     domain: domain of user or course contain the portfolio files
10066:     user: name of user or num of course contain the portfolio files
10067:   Returns:
10068:     hashref of a dump of the proper file_permissions.db
10069:    
10070: 
10071: =item * 
10072: 
10073: get_access_controls():
10074: 
10075: Args:
10076:   current_permissions: the hash ref returned from get_portfile_permissions()
10077:   group: (optional) the group you want the files associated with
10078:   file: (optional) the file you want access info on
10079: 
10080: Returns:
10081:     a hash (keys are file names) of hashes containing
10082:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
10083:         values are XML containing access control settings (see below) 
10084: 
10085: Internal notes:
10086: 
10087:  access controls are stored in file_permissions.db as key=value pairs.
10088:     key -> path to file/file_name\0uniqueID:scope_end_start
10089:         where scope -> public,guest,course,group,domains or users.
10090:               end -> UNIX time for end of access (0 -> no end date)
10091:               start -> UNIX time for start of access
10092: 
10093:     value -> XML description of access control
10094:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
10095:             <start></start>
10096:             <end></end>
10097: 
10098:             <password></password>  for scope type = guest
10099: 
10100:             <domain></domain>     for scope type = course or group
10101:             <number></number>
10102:             <roles id="">
10103:              <role></role>
10104:              <access></access>
10105:              <section></section>
10106:              <group></group>
10107:             </roles>
10108: 
10109:             <dom></dom>         for scope type = domains
10110: 
10111:             <users>             for scope type = users
10112:              <user>
10113:               <uname></uname>
10114:               <udom></udom>
10115:              </user>
10116:             </users>
10117:            </scope> 
10118:               
10119:  Access data is also aggregated for each file in an additional key=value pair:
10120:  key -> path to file/file_name\0accesscontrol 
10121:  value -> reference to hash
10122:           hash contains key = value pairs
10123:           where key = uniqueID:scope_end_start
10124:                 value = UNIX time record was last updated
10125: 
10126:           Used to improve speed of look-ups of access controls for each file.  
10127:  
10128:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
10129: 
10130: modify_access_controls():
10131: 
10132: Modifies access controls for a portfolio file
10133: Args
10134: 1. file name
10135: 2. reference to hash of required changes,
10136: 3. domain
10137: 4. username
10138:   where domain,username are the domain of the portfolio owner 
10139:   (either a user or a course) 
10140: 
10141: Returns:
10142: 1. result of additions or updates ('ok' or 'error', with error message). 
10143: 2. result of deletions ('ok' or 'error', with error message).
10144: 3. reference to hash of any new or updated access controls.
10145: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
10146:    key = integer (inbound ID)
10147:    value = uniqueID  
10148: 
10149: =back
10150: 
10151: =head2 HTTP Helper Routines
10152: 
10153: =over 4
10154: 
10155: =item *
10156: 
10157: escape() : unpack non-word characters into CGI-compatible hex codes
10158: 
10159: =item *
10160: 
10161: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
10162: 
10163: =back
10164: 
10165: =head1 PRIVATE SUBROUTINES
10166: 
10167: =head2 Underlying communication routines (Shouldn't call)
10168: 
10169: =over 4
10170: 
10171: =item *
10172: 
10173: subreply() : tries to pass a message to lonc, returns con_lost if incapable
10174: 
10175: =item *
10176: 
10177: reply() : uses subreply to send a message to remote machine, logs all failures
10178: 
10179: =item *
10180: 
10181: critical() : passes a critical message to another server; if cannot
10182: get through then place message in connection buffer directory and
10183: returns con_delayed, if incapable of saving message, returns
10184: con_failed
10185: 
10186: =item *
10187: 
10188: reconlonc() : tries to reconnect lonc client processes.
10189: 
10190: =back
10191: 
10192: =head2 Resource Access Logging
10193: 
10194: =over 4
10195: 
10196: =item *
10197: 
10198: flushcourselogs() : flush (save) buffer logs and access logs
10199: 
10200: =item *
10201: 
10202: courselog($what) : save message for course in hash
10203: 
10204: =item *
10205: 
10206: courseacclog($what) : save message for course using &courselog().  Perform
10207: special processing for specific resource types (problems, exams, quizzes, etc).
10208: 
10209: =item *
10210: 
10211: goodbye() : flush course logs and log shutting down; it is called in srm.conf
10212: as a PerlChildExitHandler
10213: 
10214: =back
10215: 
10216: =head2 Other
10217: 
10218: =over 4
10219: 
10220: =item *
10221: 
10222: symblist($mapname,%newhash) : update symbolic storage links
10223: 
10224: =back
10225: 
10226: =cut
10227: 

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